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 |
|---|---|---|---|---|---|---|---|---|
namespace Disqord
{
public static class LocalInteractionResponseExtensions
{
public static TResponse WithType<TResponse>(this TResponse response, InteractionResponseType type)
where TResponse : LocalInteractionResponse
{
response.Type = type;
return response;
}
public static TResponse WithIsEphemeral<TResponse>(this TResponse response, bool isEphemeral = true)
where TResponse : LocalInteractionResponse
{
response.IsEphemeral = true;
return response;
}
}
}
| 30.65 | 109 | 0.621533 | [
"MIT"
] | Neuheit/Diqnod | src/Disqord.Core/Entities/Local/Interaction/LocalInteractionResponseExtensions.cs | 615 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.Versioning;
using NuGet;
namespace Microsoft.Dnx.Runtime.Helpers
{
public static class FrameworkNameHelper
{
public static FrameworkName ParseFrameworkName(string targetFramework)
{
if (targetFramework.Contains("+"))
{
var portableProfile = NetPortableProfile.Parse(targetFramework);
if (portableProfile != null &&
portableProfile.FrameworkName.Profile != targetFramework)
{
return portableProfile.FrameworkName;
}
return VersionUtility.UnsupportedFrameworkName;
}
if (targetFramework.IndexOf(',') != -1)
{
// Assume it's a framework name if it contains commas
// e.g. .NETPortable,Version=v4.5,Profile=Profile78
return new FrameworkName(targetFramework);
}
return VersionUtility.ParseFrameworkName(targetFramework);
}
public static string MakeDefaultTargetFrameworkDefine(Tuple<string, FrameworkName> frameworkDefinition)
{
var shortName = frameworkDefinition.Item1;
var targetFramework = frameworkDefinition.Item2;
if (VersionUtility.IsPortableFramework(targetFramework))
{
return null;
}
return shortName.ToUpperInvariant();
}
}
} | 32.88 | 111 | 0.607664 | [
"Apache-2.0"
] | cemoses/aspnet | dnx-dev/src/Microsoft.Dnx.Runtime/Helpers/FrameworkNameHelper.cs | 1,644 | C# |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using Autodesk.Revit.DB;
using Point = System.Drawing.Point;
namespace Revit.SDK.Samples.NewOpenings.CS
{
/// <summary>
/// Main form used to display the profile of Wall or Floor and draw the opening profiles.
/// </summary>
public partial class NewOpeningsForm : System.Windows.Forms.Form
{
#region class members
private Profile m_profile; //save the profile date (ProfileFloor or ProfileWall)
private Matrix4 m_to2DMatrix; //save the matrix use to transform 3D to 2D
private Matrix4 m_moveToCenterMatrix; //save the matrix use to move point to origin
private Matrix4 m_scaleMatrix; //save the matrix use to scale
private ITool m_tool = null; //current using tool
private Queue<ITool> m_tools = new Queue<ITool>(); //all tool can use in pictureBox
#endregion
/// <summary>
/// default constructor
/// </summary>
public NewOpeningsForm()
{
InitializeComponent();
}
/// <summary>
/// constructor
/// </summary>
/// <param name="profile">ProfileWall or ProfileFloor</param>
public NewOpeningsForm(Profile profile)
:this()
{
m_profile = profile;
m_to2DMatrix = m_profile.To2DMatrix();
m_moveToCenterMatrix = m_profile.ToCenterMatrix();
InitTools();
}
/// <summary>
/// add tools, then use can draw by these tools in picture box
/// </summary>
private void InitTools()
{
//wall
if(m_profile is ProfileWall)
{
m_tool = new RectTool();
m_tools.Enqueue(m_tool);
m_tools.Enqueue(new EmptyTool());
}
//floor
else
{
m_tool = new LineTool();
m_tools.Enqueue(m_tool);
m_tools.Enqueue(new RectTool());
m_tools.Enqueue(new CircleTool());
m_tools.Enqueue(new ArcTool());
m_tools.Enqueue(new EmptyTool());
}
}
/// <summary>
/// use matrix to transform point
/// </summary>
/// <param name="pts">contain the points to be transform</param>
private void TransFormPoints(Point[] pts)
{
System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix(
1, 0, 0, 1, this.openingPictureBox.Width / 2, this.openingPictureBox.Height / 2);
matrix.Invert();
matrix.TransformPoints(pts);
}
/// <summary>
/// get four points on circle by center and one point on circle
/// </summary>
/// <param name="points">contain the center and one point on circle</param>
private List<Vector4> GenerateCircle4Point(List<Point> points)
{
Matrix rotation = new Matrix();
//get the circle center and bound point
Point center = points[0];
Point bound = points[1];
rotation.RotateAt(90, (PointF)center);
Point[] circle = new Point[4];
circle[0] = points[1];
for(int i = 1; i < 4; i++)
{
Point[] ps = new Point[1] { bound };
rotation.TransformPoints(ps);
circle[i] = ps[0];
bound = ps[0];
}
return TransForm2DTo3D(circle);
}
/// <summary>
/// Transform the point on Form to 3d world coordinate of Revit
/// </summary>
/// <param name="ps">contain the points to be transform</param>
private List<Vector4> TransForm2DTo3D(Point[] ps)
{
List<Vector4> result = new List<Vector4>();
TransFormPoints(ps);
Matrix4 transFormMatrix = Matrix4.Multiply(
m_scaleMatrix.Inverse(),m_moveToCenterMatrix);
transFormMatrix = Matrix4.Multiply(transFormMatrix, m_to2DMatrix);
foreach (Point point in ps)
{
Vector4 v = new Vector4(point.X, point.Y, 0);
v = transFormMatrix.TransForm(v);
result.Add(v);
}
return result;
}
/// <summary>
/// calculate the matrix use to scale
/// </summary>
/// <param name="size">pictureBox size</param>
private Matrix4 ComputerScaleMatrix(Size size)
{
PointF[] boundPoints = m_profile.GetFaceBounds();
float width = ((float)size.Width) / (boundPoints[1].X - boundPoints[0].X);
float hight = ((float)size.Height) / (boundPoints[1].Y - boundPoints[0].Y);
float factor = width <= hight ? width : hight;
return new Matrix4(factor);
}
/// <summary>
/// Calculate the matrix use to transform 3D to 2D
/// </summary>
private Matrix4 Comuter3DTo2DMatrix()
{
Matrix4 result = Matrix4.Multiply(
m_to2DMatrix.Inverse(), m_moveToCenterMatrix.Inverse());
result = Matrix4.Multiply(result, m_scaleMatrix);
return result;
}
private void OkButton_Click(object sender, EventArgs e)
{
foreach (ITool tool in m_tools)
{
List<List<Point>> curcves = tool.GetLines();
foreach (List<Point> curve in curcves)
{
List<Vector4> ps3D;
if (tool.ToolType == ToolType.Circle)
{
ps3D = GenerateCircle4Point(curve);
}
else if (tool.ToolType == ToolType.Rectangle)
{
Point[] ps = new Point[4] { curve[0], new Point(curve[0].X, curve[1].Y),
curve[1], new Point(curve[1].X, curve[0].Y) };
ps3D = TransForm2DTo3D(ps);
}
else
{
ps3D = TransForm2DTo3D(curve.ToArray());
}
m_profile.DrawOpening(ps3D, tool.ToolType);
}
}
this.Close();
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void openingPictureBox_Paint(object sender, PaintEventArgs e)
{
//Draw the pictures in the m_tools list
foreach (ITool tool in m_tools)
{
tool.Draw(e.Graphics);
}
//draw the tips string
e.Graphics.DrawString(m_tool.ToolType.ToString(),
SystemFonts.DefaultFont, SystemBrushes.Highlight, 2, 5);
//move the origin to the picture center
Size size = this.openingPictureBox.Size;
e.Graphics.Transform = new System.Drawing.Drawing2D.Matrix(
1, 0, 0, 1, size.Width / 2, size.Height / 2);
//draw profile
Size scaleSize = new Size((int)(0.85 * size.Width), (int)(0.85 * size.Height));
m_scaleMatrix = ComputerScaleMatrix(scaleSize);
Matrix4 trans = Comuter3DTo2DMatrix();
m_profile.Draw2D(e.Graphics, Pens.Blue, trans);
}
/// <summary>
/// mouse event handle
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openingPictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (MouseButtons.Left == e.Button || MouseButtons.Right == e.Button)
{
Graphics g = openingPictureBox.CreateGraphics();
m_tool.OnMouseDown(g, e);
m_tool.OnRightMouseClick(g, e);
}
else if (MouseButtons.Middle == e.Button)
{
m_tool.OnMidMouseDown(null, null);
m_tool = m_tools.Peek();
m_tools.Enqueue(m_tool);
m_tools.Dequeue();
Graphics graphic = openingPictureBox.CreateGraphics();
graphic.DrawString(m_tool.ToolType.ToString(),
SystemFonts.DefaultFont, SystemBrushes.Highlight, 2, 5);
this.Refresh();
}
}
/// <summary>
/// Mouse event handle
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openingPictureBox_MouseUp(object sender, MouseEventArgs e)
{
Graphics g = openingPictureBox.CreateGraphics();
m_tool.OnMouseUp(g, e);
}
/// <summary>
/// Mouse event handle
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openingPictureBox_MouseMove(object sender, MouseEventArgs e)
{
Graphics graphics = openingPictureBox.CreateGraphics();
m_tool.OnMouseMove(graphics, e);
PaintEventArgs paintArg = new PaintEventArgs(graphics, new System.Drawing.Rectangle());
openingPictureBox_Paint(null, paintArg);
}
}
} | 36.873684 | 99 | 0.550956 | [
"BSD-3-Clause"
] | AMEE/rev | samples/Revit 2012 SDK/Samples/NewOpenings/CS/NewOpeningsForm.cs | 10,509 | C# |
using DpdtInject.Tests.Properties;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DpdtInject.Injector.Src.Excp;
namespace DpdtInject.Tests.Unsorted.CircularDependency3
{
[TestClass]
public class UnsortedCircularDependency3_Fixture
{
public TestContext TestContext
{
get;
set;
}
[TestMethod]
public void Test()
{
var preparation = new Preparator(
TestContext,
nameof(UnsortedCircularDependency3_Cluster.UnsortedCircularDependency3Cluster_Tester),
nameof(TestResources.UnsortedCircularDependency3_Cluster),
TestResources.UnsortedCircularDependency3_Cluster
);
preparation.Check();
//no check for warning because here is a lot of warnings due to circular dependency
Assert.AreEqual(1, preparation.DiagnosticReporter.Exceptions.Count, "Error count");
Assert.AreEqual(DpdtExceptionTypeEnum.CircularDependency, preparation.DiagnosticReporter.GetDpdtException().Type);
}
}
}
| 32.911765 | 126 | 0.666667 | [
"MIT"
] | lsoft/DpDtInject | DpdtInject.Tests/Unsorted/CircularDependency3/UnsortedCircularDependency3_Fixture.cs | 1,119 | C# |
using Eaf.Dependency;
using Eaf.Extensions;
using System.Linq;
namespace Eaf.Middleware.Auditing
{
public class NamespaceStripper : INamespaceStripper, ITransientDependency
{
public string StripNameSpace(string serviceName)
{
if (serviceName.IsNullOrEmpty() || !serviceName.Contains("."))
{
return serviceName;
}
if (serviceName.Contains("["))
{
return StripGenericNamespace(serviceName);
}
return GetTextAfterLastDot(serviceName);
}
private static string GetTextAfterLastDot(string text)
{
var lastDotIndex = text.LastIndexOf('.');
return text.Substring(lastDotIndex + 1);
}
private static string StripGenericNamespace(string serviceName)
{
var serviceNameParts = serviceName.Split('[').Where(s => !s.IsNullOrEmpty()).ToList();
var genericServiceName = "";
var openBracketCount = 0;
for (var i = 0; i < serviceNameParts.Count; i++)
{
var serviceNamePart = serviceNameParts[i];
if (serviceNamePart.Contains("`"))
{
genericServiceName += GetTextAfterLastDot(serviceNamePart.Substring(0, serviceNamePart.IndexOf('`'))) + "<";
openBracketCount++;
}
if (serviceNamePart.Contains(","))
{
genericServiceName += GetTextAfterLastDot(serviceNamePart.Substring(0, serviceNamePart.IndexOf(',')));
if (i + 1 < serviceNameParts.Count && serviceNameParts[i + 1].Contains(","))
{
genericServiceName += ", ";
}
else
{
genericServiceName += ">";
openBracketCount--;
}
}
}
for (int i = 0; i < openBracketCount; i++)
{
genericServiceName += ">";
}
return genericServiceName;
}
}
} | 32.264706 | 128 | 0.497265 | [
"MIT"
] | afonsoft/EAF | src/Eaf.Middleware.Application/Auditing/NamespaceStripper.cs | 2,194 | C# |
// Copyright (c) 2008-2021, Hazelcast, Inc. 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.Reflection;
using System;
namespace Hazelcast.Core
{
/// <summary>
/// Represents the version of this client.
/// </summary>
internal static class ClientVersion
{
private static string _clientVersion;
/// <summary>
/// Gets the version of this assembly.
/// </summary>
internal static string Version
{
get
{
if (_clientVersion != null) return _clientVersion;
var type = typeof (ClientVersion);
var assembly = type.Assembly;
var attribute = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
if (attribute != null)
{
var version = attribute.InformationalVersion;
var pos = version.IndexOf('+', StringComparison.OrdinalIgnoreCase);
if (pos > 0 && version.Length > pos + 7)
version = version.Substring(0, pos + 7);
_clientVersion = version;
}
else
{
var v = assembly.GetCustomAttribute<AssemblyVersionAttribute>();
_clientVersion = v != null ? v.Version : "0.0.0";
}
return _clientVersion;
}
}
}
}
| 34.275862 | 101 | 0.578974 | [
"Apache-2.0"
] | alexb5dh/hazelcast-csharp-client | src/Hazelcast.Net/Core/ClientVersion.cs | 1,990 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace PrecizeSoft.IO.Wcf.MessageContracts.ConversionStatistics.V1
{
[MessageContract]
public class GetStatByFileCategoriesMessage
{
}
}
| 20.066667 | 69 | 0.787375 | [
"Apache-2.0"
] | precizeman/precizesoft-io | src/PrecizeSoft.IO.WcfClients/Wcf/MessageContracts/ConversionStatistics/V1/GetStatByFileCategoriesMessage.cs | 303 | C# |
using System;
using Microsoft.EntityFrameworkCore;
namespace Indice.Oba.AspNetCore.Features.EF
{
/// <summary>
/// Options for configuring the CertificatesStore context.
/// </summary>
public class CertificatesStoreOptions
{
/// <summary>
/// Callback to configure the EF DbContext.
/// </summary>
/// <value>
/// The configure database context.
/// </value>
public Action<DbContextOptionsBuilder> ConfigureDbContext { get; set; }
/// <summary>
/// Callback in DI to resolve the EF DbContextOptions. If set, ConfigureDbContext will not be used.
/// </summary>
/// <value>
/// The configure database context.
/// </value>
public Action<IServiceProvider, DbContextOptionsBuilder> ResolveDbContextOptions { get; set; }
/// <summary>
/// Gets or sets the default schema.
/// </summary>
/// <value>
/// The default schema.
/// </value>
public string DefaultSchema { get; set; } = null;
}
}
| 31.735294 | 107 | 0.585728 | [
"MIT"
] | dkarkanas/Indice.Psd2 | src/Indice.Oba.AspNetCore/Features/EF/CertificatesStoreOptions.cs | 1,081 | 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 Microsoft.ML.Probabilistic.Compiler.Attributes;
using Microsoft.ML.Probabilistic.Compiler;
using Microsoft.ML.Probabilistic.Factors;
using Microsoft.ML.Probabilistic.Compiler.CodeModel;
using Microsoft.ML.Probabilistic.Models.Attributes;
namespace Microsoft.ML.Probabilistic.Compiler.Transforms
{
/// <summary>
/// This transform clones variables that are derived in some contexts and non-derived in others. This is needed for VMP to function correctly with deterministic gates.
/// PREREQUISITE:
/// A variable with at least one derived definition must have DerivedVariable attribute set.
/// </summary>
internal class DerivedVariableTransform : ShallowCopyTransform
{
public override string Name
{
get { return "DerivedVariableTransform"; }
}
/// <summary>
/// Counter used to generate variable names.
/// </summary>
protected int Count;
/// <summary>
/// Convert random assignments to derived variables
/// </summary>
/// <param name="iae"></param>
/// <returns></returns>
protected override IExpression ConvertAssign(IAssignExpression iae)
{
iae = (IAssignExpression) base.ConvertAssign(iae);
IStatement ist = context.FindAncestor<IStatement>();
if (!context.InputAttributes.Has<Models.Constraint>(ist) &&
(iae.Expression is IMethodInvokeExpression))
{
IMethodInvokeExpression imie = (IMethodInvokeExpression) iae.Expression;
IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(iae.Target);
if (ivd != null)
{
bool isDerived = context.InputAttributes.Has<DerivedVariable>(ivd);
if (isDerived)
{
FactorManager.FactorInfo info = CodeRecognizer.GetFactorInfo(context, imie);
if (!info.IsDeterministicFactor)
{
// The variable is derived, but this definition is not derived.
// Thus we must convert
// y = sample()
// into
// y_random = sample()
// y = Copy(y_random)
// where y_random is not derived.
VariableInformation varInfo = VariableInformation.GetVariableInformation(context, ivd);
IList<IStatement> stmts = Builder.StmtCollection();
string name = ivd.Name + "_random" + (Count++);
List<IList<IExpression>> indices = Recognizer.GetIndices(iae.Target);
IVariableDeclaration cloneVar = varInfo.DeriveIndexedVariable(stmts, context, name, indices, copyInitializer: true);
context.OutputAttributes.Remove<DerivedVariable>(cloneVar);
stmts.Add(Builder.AssignStmt(Builder.VarRefExpr(cloneVar), iae.Expression));
int ancIndex = context.FindAncestorIndex<IStatement>();
context.AddStatementsBeforeAncestorIndex(ancIndex, stmts);
Type tp = iae.Target.GetExpressionType();
if (tp == null)
{
Error("Could not determine type of expression: " + iae.Target);
return iae;
}
IExpression copy = Builder.StaticGenericMethod(new Func<PlaceHolder, PlaceHolder>(Clone.Copy), new Type[] {tp},
Builder.VarRefExpr(cloneVar));
iae = Builder.AssignExpr(iae.Target, copy);
}
}
}
}
return iae;
}
}
} | 50.232558 | 172 | 0.55 | [
"MIT"
] | Bruugs/infer | src/Compiler/Infer/Transforms/DerivedVariableTransform.cs | 4,320 | C# |
using System;
using System.Reflection;
using System.Xml.XPath;
using Microsoft.OpenApi.Models;
namespace Surging.Core.Swagger_V5.SwaggerGen
{
public class XmlCommentsOperationFilter : IOperationFilter
{
private readonly XPathNavigator _xmlNavigator;
public XmlCommentsOperationFilter(XPathDocument xmlDoc)
{
_xmlNavigator = xmlDoc.CreateNavigator();
}
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (context.MethodInfo == null) return;
// If method is from a constructed generic type, look for comments from the generic type method
var targetMethod = context.MethodInfo.DeclaringType.IsConstructedGenericType
? context.MethodInfo.GetUnderlyingGenericTypeMethod()
: context.MethodInfo;
if (targetMethod == null) return;
ApplyControllerTags(operation, targetMethod.DeclaringType);
ApplyMethodTags(operation, targetMethod);
}
private void ApplyControllerTags(OpenApiOperation operation, Type controllerType)
{
var typeMemberName = XmlCommentsNodeNameHelper.GetMemberNameForType(controllerType);
var responseNodes = _xmlNavigator.Select($"/doc/members/member[@name='{typeMemberName}']/response");
ApplyResponseTags(operation, responseNodes);
}
private void ApplyMethodTags(OpenApiOperation operation, MethodInfo methodInfo)
{
var methodMemberName = XmlCommentsNodeNameHelper.GetMemberNameForMethod(methodInfo);
var methodNode = _xmlNavigator.SelectSingleNode($"/doc/members/member[@name='{methodMemberName}']");
if (methodNode == null) return;
var summaryNode = methodNode.SelectSingleNode("summary");
if (summaryNode != null)
operation.Summary = XmlCommentsTextHelper.Humanize(summaryNode.InnerXml);
var remarksNode = methodNode.SelectSingleNode("remarks");
if (remarksNode != null)
operation.Description = XmlCommentsTextHelper.Humanize(remarksNode.InnerXml);
var responseNodes = methodNode.Select("response");
ApplyResponseTags(operation, responseNodes);
}
private void ApplyResponseTags(OpenApiOperation operation, XPathNodeIterator responseNodes)
{
while (responseNodes.MoveNext())
{
var code = responseNodes.Current.GetAttribute("code", "");
var response = operation.Responses.ContainsKey(code)
? operation.Responses[code]
: operation.Responses[code] = new OpenApiResponse();
response.Description = XmlCommentsTextHelper.Humanize(responseNodes.Current.InnerXml);
}
}
}
} | 40.549296 | 112 | 0.660993 | [
"MIT"
] | JohnZhaoXiaoHu/surging | src/Surging.Core/Surging.Core.Swagger_V5/SwaggerGen/XmlComments/XmlCommentsOperationFilter.cs | 2,881 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Swan.Collections
{
/// <summary>
/// A thread-safe collection cache repository for types.
/// </summary>
/// <typeparam name="TValue">The type of member to cache.</typeparam>
public class CollectionCacheRepository<TValue>
{
private readonly Lazy<ConcurrentDictionary<Type, IEnumerable<TValue>>> _data =
new Lazy<ConcurrentDictionary<Type, IEnumerable<TValue>>>(() =>
new ConcurrentDictionary<Type, IEnumerable<TValue>>(), true);
/// <summary>
/// Determines whether the cache contains the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns><c>true</c> if the cache contains the key, otherwise <c>false</c>.</returns>
public bool ContainsKey(Type key) => _data.Value.ContainsKey(key);
/// <summary>
/// Retrieves the properties stored for the specified type.
/// If the properties are not available, it calls the factory method to retrieve them
/// and returns them as an array of PropertyInfo.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="factory">The factory.</param>
/// <returns>
/// An array of the properties stored for the specified type.
/// </returns>
/// <exception cref="ArgumentNullException">
/// key
/// or
/// factory.
/// </exception>
/// <exception cref="System.ArgumentNullException">type.</exception>
public IEnumerable<TValue> Retrieve(Type key, Func<Type, IEnumerable<TValue>> factory)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (factory == null)
throw new ArgumentNullException(nameof(factory));
return _data.Value.GetOrAdd(key, k => factory.Invoke(k).Where(item => item != null));
}
}
}
| 38.54717 | 97 | 0.605972 | [
"MIT"
] | pgrawehr/swan | src/Swan.Lite/Collections/CollectionCacheRepository.cs | 2,045 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AutomatedComponentTestWriter.Models
{
public class ComponentTestDTO
{
public ComponentTestDTO()
{
Properties = new List<Property>();
}
public APIAction APIAction { get; set; }
public string APIEndpointURL { get; set; }
public string DTOName { get; set; }
public List<Property> Properties { get; set; }
}
public class Property
{
public string PropertyName { get; set; }
public string DataType { get; set; }
public string Required { get; set; }
public string DefaultValue { get; set; }
public ComplexObject ComplexType { get; set; }
public List<Parameter> Parameters { get; set; }
public Property()
{
Parameters = new List<Parameter>();
ComplexType = new ComplexObject();
Required = "False";
}
}
public class Parameter
{
public string ComplexMemberSpecifier { get; set; }
public string ExpectedMessage { get; set; }
public string HTTPResponse { get; set; }
public string RandomParam { get; set; }
public string NullParam { get; set; }
public string BlankParam { get; set; }
public string ValueLength { get; set; }
public string TestName { get; set; }
public Parameter()
{
ComplexMemberSpecifier = "";
NullParam = "false";
BlankParam = "false";
RandomParam = "False";
ValueLength = "0";
}
}
public class ComplexObject
{
public string ObjectName { get; set; }
public List<ComplexObjectMember> ComplexMembers { get; set; }
public List<Parameter> Parameters { get; set; }
public ComplexObject()
{
ComplexMembers = new List<ComplexObjectMember>();
Parameters = new List<Parameter>();
}
}
public class ComplexObjectMember
{
public string Key { get; set; }
public string Value { get; set; }
public string DataType { get; set; }
}
public enum APIAction
{
Post,
Put
}
public enum HTTPResponse
{
BadRequest,
Unauthorized,
NotFound,
OK,
InternalServerError
}
} | 26.347826 | 69 | 0.563119 | [
"MIT"
] | cltalmadge/AutomatedComponentTestWriter | AutomatedComponentTestWriter/Models/ComponentTestDTO.cs | 2,426 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SIL.DblBundle.Tests.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", "4.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("SIL.DblBundle.Tests.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;
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] English_lds {
get {
object obj = ResourceManager.GetObject("English_lds", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized string similar to <?xml version="1.0" encoding="utf-8"?>
///<ldml>
/// <identity>
/// <version number="" />
/// <generation date="2015-07-09T20:55:53Z" />
/// <language type="qaa" />
/// </identity>
/// <delimiters>
/// <quotationStart>“</quotationStart>
/// <quotationEnd>”</quotationEnd>
/// <alternateQuotationStart>‘</alternateQuotationStart>
/// <alternateQuotationEnd>’</alternateQuotationEnd>
/// <special xmlns:sil="urn://www.sil.org/ldml/0.1">
/// <sil:quotation-marks>
/// <sil:quotationContinue>“</sil:quotationContinue>
/// <sil:alt [rest of string was truncated]";.
/// </summary>
internal static string ldml_xml {
get {
return ResourceManager.GetString("ldml_xml", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] MAT_usx {
get {
object obj = ResourceManager.GetObject("MAT_usx", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized string similar to <?xml version="1.0" encoding="utf-8"?>
///<DBLMetadata type="text" typeVersion="1.4" id="ce61dd3decd6b8a8" revision="0">
/// <identification>
/// <name>Test Bundle Publication</name>
/// <nameLocal></nameLocal>
/// <abbreviation></abbreviation>
/// <abbreviationLocal></abbreviationLocal>
/// <scope></scope>
/// <description></description>
/// <dateCompleted></dateCompleted>
/// <systemId type="gbc"></systemId>
/// <systemId type="tms"></systemId>
/// <systemId type="reap"></systemId>
/// <systemId t [rest of string was truncated]";.
/// </summary>
internal static string metadata_xml {
get {
return ResourceManager.GetString("metadata_xml", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <?xml version="1.0" encoding="utf-8"?>
///<stylesheet>
/// <property name="font-family">Cambria</property>
/// <property name="font-size" unit="pt">14</property>
/// <style id="id" publishable="false" versetext="false">
/// <name>id - File - Identification</name>
/// <description>File identification information (BOOKID, FILENAME, EDITOR, MODIFICATION DATE)</description>
/// <property name="text-align">left</property>
/// </style>
/// <style id="h" publishable="true" versetext="false">
/// <name>h - File - Head [rest of string was truncated]";.
/// </summary>
internal static string styles_xml {
get {
return ResourceManager.GetString("styles_xml", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] versification_vrs {
get {
object obj = ResourceManager.GetObject("versification_vrs", resourceCulture);
return ((byte[])(obj));
}
}
}
}
| 45.918239 | 185 | 0.572387 | [
"MIT"
] | andrew-polk/libpalaso | SIL.DblBundle.Tests/Properties/Resources.Designer.cs | 7,313 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
#pragma warning disable 1591
namespace Silk.NET.OpenGLES.Extensions.MESA
{
public enum MESA
{
FramebufferFlipYMesa = 0x8BBB,
ProgramBinaryFormatMesa = 0x875F,
}
}
| 19.052632 | 57 | 0.696133 | [
"MIT"
] | AzyIsCool/Silk.NET | src/OpenGL/Extensions/Silk.NET.OpenGLES.Extensions.MESA/Enums/MESA.gen.cs | 362 | C# |
namespace FlaUI.Core.Definitions
{
/// <summary>
/// Contains values that specify whether data in a table should be read primarily by row or by column.
/// </summary>
public enum RowOrColumnMajor
{
/// <summary>
/// Specifies that data in the table should be read row by row.
/// </summary>
RowMajor = 0,
/// <summary>
/// Specifies that data in the table should be read column by column
/// </summary>
ColumnMajor = 1,
/// <summary>
/// Specifies that the best way to present the data is indeterminate.
/// </summary>
Indeterminate = 2
}
}
| 30.090909 | 106 | 0.574018 | [
"MIT"
] | work-flower/FlaUI | src/FlaUI.Core/Definitions/RowOrColumnMajor.cs | 664 | C# |
// Copyright (C) 2019 Singapore ETH Centre, Future Cities Laboratory
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
// Author: Michael Joos (joos@arch.ethz.ch)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using UnityEngine;
public static class MultiGridDataIO
{
public static readonly string FileSufix = "multi";
private static readonly LoadPatchData<MultiGridPatch, MultiGridData>[] headerLoader =
{
LoadCsv,
LoadBinHeader
};
public static LoadPatchData<MultiGridPatch, MultiGridData> GetPatchHeaderLoader(PatchDataFormat format)
{
return headerLoader[(int)format];
}
public static IEnumerator LoadCsv(string filename, PatchDataLoadedCallback<MultiGridData> callback)
{
yield return FileRequest.GetText(filename, (sr) => PatchDataIO.ParseAsync(sr, filename, ParseCsv, callback));
}
private static void ReadValues(StreamReader sr, MultiGridData multigrid, string filename)
{
int categoriesCount = multigrid.categories == null? 0 : multigrid.categories.Length;
if (categoriesCount == 0)
return;
List<float>[] data = new List<float>[categoriesCount];
for (int i = 0; i < categoriesCount; i++)
{
data[i] = new List<float>();
}
string line;
string[] cells;
float value;
var cultureInfo = CultureInfo.InvariantCulture;
// Read each data row at a time with value
while ((line = sr.ReadLine()) != null)
{
cells = line.Split(',');
for (int i = 0; i < categoriesCount; i++)
{
value = float.Parse(cells[i], cultureInfo);
data[i].Add(value);
var g = multigrid.categories[i].grid;
g.minValue = Mathf.Min(g.minValue, value);
g.maxValue = Mathf.Max(g.maxValue, value);
}
}
for (int i = 0; i < categoriesCount; i++)
{
multigrid.categories[i].grid.values = data[i].ToArray();
}
}
public static IEnumerator LoadBinHeader(string filename, PatchDataLoadedCallback<MultiGridData> callback)
{
#if UNITY_WEBGL
callback(ParseBinHeader(PatchDataIO.brHeaders, filename));
yield break;
#else
yield return FileRequest.GetBinary(filename, (br) => callback(ParseBinHeader(br, filename)));
#endif
}
public static MultiGridData ParseBinHeader(BinaryReader br, string filename)
{
return ParseBinHeader(br, filename, new MultiGridData());
}
public static IEnumerator LoadBin(this MultiGridData mulyigrid, string filename, PatchDataLoadedCallback<MultiGridData> callback)
{
yield return FileRequest.GetBinary(filename, (br) => callback(ParseBin(br, filename, mulyigrid)));
}
private static void ParseCsv(ParseTaskData data)
{
GridDataIO.Parameter parameter = null;
bool[] found = new bool[GridDataIO.Parameters.Length];
string line = null;
string[] cells = null;
bool skipLineRead = false;
GridData grid = new GridData();
MultiGridData multigrid = null;
while (true)
{
if (!skipLineRead)
line = data.sr.ReadLine();
else
skipLineRead = false;
if (line == null)
break;
cells = line.Split(',');
parameter = GridDataIO.CheckParameter(cells[0], cells[1], GridDataIO.Parameters, out bool hasData);
if (parameter == null)
{
#if UNITY_EDITOR
Debug.LogWarning("File " + data.filename + " has unrecognized header parameter " + cells[0] + ". Should it go to the metadata?");
#endif
if (grid.metadata != null)
{
grid.metadata.Add(cells[0], cells[1]);
}
continue;
}
#if UNITY_EDITOR
if (found[(int)parameter.id])
{
Debug.LogWarning("File " + data.filename + " has duplicate metadata entry: " + parameter.label);
}
#endif
found[(int)parameter.id] = true;
switch (parameter.id)
{
case GridDataIO.ParamId.Metadata:
if (hasData)
{
grid.metadata = PatchDataIO.ReadCsvMetadata(data.sr, GridDataIO.CsvTokens, ref line);
skipLineRead = line != null;
}
break;
//case GridDataIO.ParamId.NameToValue:
// if (hasData)
// {
// nameToValues = GridDataIO.ReadCsvNameToValues(sr, CsvTokens, ref line);
// skipLineRead = line != null;
// }
// break;
case GridDataIO.ParamId.Categories:
if (hasData)
{
grid.categories = GridDataIO.ReadCsvCategories(data.sr, data.filename, GridDataIO.CsvTokens, ref line);
skipLineRead = line != null;
}
break;
case GridDataIO.ParamId.Coloring:
case GridDataIO.ParamId.Colouring:
try
{
grid.coloring = (GridData.Coloring)Enum.Parse(typeof(GridData.Coloring), cells[1], true);
}
catch (Exception)
{
grid.coloring = GridData.Coloring.Single;
}
break;
case GridDataIO.ParamId.West:
grid.west = double.Parse(cells[1], CultureInfo.InvariantCulture);
break;
case GridDataIO.ParamId.North:
grid.north = double.Parse(cells[1], CultureInfo.InvariantCulture);
if (grid.north > GeoCalculator.MaxLatitude)
Debug.LogWarning("File " + data.filename + " has north above " + GeoCalculator.MaxLatitude + ": " + grid.north);
break;
case GridDataIO.ParamId.East:
grid.east = double.Parse(cells[1], CultureInfo.InvariantCulture);
break;
case GridDataIO.ParamId.South:
grid.south = double.Parse(cells[1], CultureInfo.InvariantCulture);
if (grid.south < GeoCalculator.MinLatitude)
Debug.LogWarning("File " + data.filename + " has south below " + GeoCalculator.MinLatitude + ": " + grid.south);
break;
case GridDataIO.ParamId.CountX:
grid.countX = int.Parse(cells[1]);
break;
case GridDataIO.ParamId.CountY:
grid.countY = int.Parse(cells[1]);
break;
case GridDataIO.ParamId.Units:
grid.units = cells[1];
break;
case GridDataIO.ParamId.Values:
multigrid = new MultiGridData(grid);
ReadValues(data.sr, multigrid, data.filename);
break;
default:
#if UNITY_EDITOR
Debug.Log("File " + data.filename + " will ignore row: " + line);
#endif
skipLineRead = false;
break;
}
}
#if UNITY_EDITOR
foreach (var p in GridDataIO.Parameters)
{
if (p.isRequired && !found[(int)p.id])
{
Debug.LogError("Didn't find " + p.label + " in " + data.filename);
}
}
#endif
data.patch = multigrid;
}
private static MultiGridData ParseBin(BinaryReader br, string filename, MultiGridData multigrid)
{
ParseBinHeader(br, filename, multigrid);
ParseBinProperties(br, multigrid);
ParseBinGrids(br, filename, multigrid);
return multigrid;
}
public static MultiGridData ParseBinHeader(BinaryReader br, string filename, MultiGridData multigrid)
{
// Read header
PatchDataIO.SkipBinVersion(br);
PatchDataIO.ReadBinBoundsHeader(br, filename, multigrid);
return multigrid;
}
public static void ParseBinProperties(BinaryReader br, MultiGridData multigrid)
{
// Read Metadata (if available)
multigrid.metadata = PatchDataIO.ReadBinMetadata(br);
// Read coloring
multigrid.coloring = (GridData.Coloring)br.ReadByte();
// Read categories (without values)
int gridCount = br.ReadInt32();
if (gridCount > 0)
{
multigrid.categories = new GridCategory[gridCount];
for (int i = 0; i < gridCount; i++)
{
multigrid.categories[i] = new GridCategory(br.ReadString(), null, Color.white);
}
}
}
public static void ParseBinGrids(BinaryReader br, string filename, MultiGridData multigrid)
{
if (multigrid.categories != null)
{
int count = multigrid.categories.Length;
for (int i = 0; i < count; i++)
{
var grid = new GridData(multigrid);
GridDataIO.ParseBinProperties(br, filename, grid);
GridDataIO.ParseBinValues(br, grid);
grid.patch = multigrid.patch;
multigrid.categories[i].grid = grid;
}
}
}
public static void SaveBin(this MultiGridData multigrid, string filename)
{
using (var bw = new BinaryWriter(File.Open(filename, FileMode.Create)))
{
PatchDataIO.WriteBinVersion(bw);
PatchDataIO.WriteBinBoundsHeader(bw, multigrid);
// Write Metadata (if available)
PatchDataIO.WriteBinMetadata(bw, multigrid.metadata);
bw.Write((byte)multigrid.coloring);
int categoriesCount = multigrid.categories == null ? 0 : multigrid.categories.Length;
bw.Write(categoriesCount);
if (multigrid.categories != null)
{
// Write categories (without values)
foreach (var c in multigrid.categories)
{
bw.Write(c.name);
}
// Write Grids
foreach (var c in multigrid.categories)
{
GridDataIO.WriteBinProperties(bw, c.grid);
GridDataIO.WriteBinValues(bw, c.grid);
}
}
}
}
}
| 28.66879 | 145 | 0.657965 | [
"MIT"
] | RebeccaRossellini/ur-scape | Assets/DataLayers/Scripts/MultiGridDataIO.cs | 9,004 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Relational.Tests.TestUtilities;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Update;
using Xunit;
namespace Microsoft.EntityFrameworkCore.Relational.Tests.Update
{
public class ModificationCommandTest
{
[Fact]
public void ModificationCommand_initialized_correctly_for_added_entities_with_temp_generated_key()
{
var entry = CreateEntry(EntityState.Added, generateKeyValues: true);
entry.MarkAsTemporary(entry.EntityType.FindPrimaryKey().Properties[0]);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.Equal("T1", command.TableName);
Assert.Null(command.Schema);
Assert.Equal(EntityState.Added, command.EntityState);
Assert.Equal(2, command.ColumnModifications.Count);
var columnMod = command.ColumnModifications[0];
Assert.Equal("Col1", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Id", columnMod.Property.Name);
Assert.False(columnMod.IsCondition);
Assert.True(columnMod.IsKey);
Assert.True(columnMod.IsRead);
Assert.False(columnMod.IsWrite);
columnMod = command.ColumnModifications[1];
Assert.Equal("Col2", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Name", columnMod.Property.Name);
Assert.False(columnMod.IsCondition);
Assert.False(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.True(columnMod.IsWrite);
}
[Fact]
public void ModificationCommand_initialized_correctly_for_added_entities_with_non_temp_generated_key()
{
var entry = CreateEntry(EntityState.Added, generateKeyValues: true);
entry.MarkAsTemporary(entry.EntityType.FindPrimaryKey().Properties[0], isTemporary: false);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.Equal("T1", command.TableName);
Assert.Null(command.Schema);
Assert.Equal(EntityState.Added, command.EntityState);
Assert.Equal(2, command.ColumnModifications.Count);
var columnMod = command.ColumnModifications[0];
Assert.Equal("Col1", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Id", columnMod.Property.Name);
Assert.False(columnMod.IsCondition);
Assert.True(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.True(columnMod.IsWrite);
columnMod = command.ColumnModifications[1];
Assert.Equal("Col2", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Name", columnMod.Property.Name);
Assert.False(columnMod.IsCondition);
Assert.False(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.True(columnMod.IsWrite);
}
[Fact]
public void ModificationCommand_initialized_correctly_for_added_entities_with_explicitly_specified_key_value()
{
var entry = CreateEntry(EntityState.Added);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.Equal("T1", command.TableName);
Assert.Null(command.Schema);
Assert.Equal(EntityState.Added, command.EntityState);
Assert.Equal(2, command.ColumnModifications.Count);
var columnMod = command.ColumnModifications[0];
Assert.Equal("Col1", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Id", columnMod.Property.Name);
Assert.False(columnMod.IsCondition);
Assert.True(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.True(columnMod.IsWrite);
columnMod = command.ColumnModifications[1];
Assert.Equal("Col2", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Name", columnMod.Property.Name);
Assert.False(columnMod.IsCondition);
Assert.False(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.True(columnMod.IsWrite);
}
[Fact]
public void ModificationCommand_initialized_correctly_for_modified_entities_with_identity_key()
{
var entry = CreateEntry(EntityState.Modified, generateKeyValues: true);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.Equal("T1", command.TableName);
Assert.Null(command.Schema);
Assert.Equal(EntityState.Modified, command.EntityState);
Assert.Equal(2, command.ColumnModifications.Count);
var columnMod = command.ColumnModifications[0];
Assert.Equal("Col1", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Id", columnMod.Property.Name);
Assert.True(columnMod.IsCondition);
Assert.True(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.False(columnMod.IsWrite);
columnMod = command.ColumnModifications[1];
Assert.Equal("Col2", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Name", columnMod.Property.Name);
Assert.False(columnMod.IsCondition);
Assert.False(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.True(columnMod.IsWrite);
}
[Fact]
public void ModificationCommand_initialized_correctly_for_modified_entities_with_client_generated_key()
{
var entry = CreateEntry(EntityState.Modified);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.Equal("T1", command.TableName);
Assert.Null(command.Schema);
Assert.Equal(EntityState.Modified, command.EntityState);
Assert.Equal(2, command.ColumnModifications.Count);
var columnMod = command.ColumnModifications[0];
Assert.Equal("Col1", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Id", columnMod.Property.Name);
Assert.True(columnMod.IsCondition);
Assert.True(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.False(columnMod.IsWrite);
columnMod = command.ColumnModifications[1];
Assert.Equal("Col2", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Name", columnMod.Property.Name);
Assert.False(columnMod.IsCondition);
Assert.False(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.True(columnMod.IsWrite);
}
[Fact]
public void ModificationCommand_initialized_correctly_for_modified_entities_with_concurrency_token()
{
var entry = CreateEntry(EntityState.Modified, computeNonKeyValue: true);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.Equal("T1", command.TableName);
Assert.Null(command.Schema);
Assert.Equal(EntityState.Modified, command.EntityState);
Assert.Equal(2, command.ColumnModifications.Count);
var columnMod = command.ColumnModifications[0];
Assert.Equal("Col1", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Id", columnMod.Property.Name);
Assert.True(columnMod.IsCondition);
Assert.True(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.False(columnMod.IsWrite);
columnMod = command.ColumnModifications[1];
Assert.Equal("Col2", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Name", columnMod.Property.Name);
Assert.True(columnMod.IsCondition);
Assert.False(columnMod.IsKey);
Assert.True(columnMod.IsRead);
Assert.False(columnMod.IsWrite);
}
[Fact]
public void ModificationCommand_initialized_correctly_for_deleted_entities()
{
var entry = CreateEntry(EntityState.Deleted);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.Equal("T1", command.TableName);
Assert.Null(command.Schema);
Assert.Equal(EntityState.Deleted, command.EntityState);
Assert.Equal(1, command.ColumnModifications.Count);
var columnMod = command.ColumnModifications[0];
Assert.Equal("Col1", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Id", columnMod.Property.Name);
Assert.True(columnMod.IsCondition);
Assert.True(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.False(columnMod.IsWrite);
}
[Fact]
public void ModificationCommand_initialized_correctly_for_deleted_entities_with_concurrency_token()
{
var entry = CreateEntry(EntityState.Deleted, computeNonKeyValue: true);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.Equal("T1", command.TableName);
Assert.Null(command.Schema);
Assert.Equal(EntityState.Deleted, command.EntityState);
Assert.Equal(2, command.ColumnModifications.Count);
var columnMod = command.ColumnModifications[0];
Assert.Equal("Col1", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Id", columnMod.Property.Name);
Assert.True(columnMod.IsCondition);
Assert.True(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.False(columnMod.IsWrite);
columnMod = command.ColumnModifications[1];
Assert.Equal("Col2", columnMod.ColumnName);
Assert.Same(entry, columnMod.Entry);
Assert.Equal("Name", columnMod.Property.Name);
Assert.True(columnMod.IsCondition);
Assert.False(columnMod.IsKey);
Assert.False(columnMod.IsRead);
Assert.False(columnMod.IsWrite);
}
[Fact]
public void ModificationCommand_throws_for_unchanged_entities()
{
var entry = CreateEntry(EntityState.Unchanged);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
Assert.Equal(
RelationalStrings.ModificationFunctionInvalidEntityState(EntityState.Unchanged),
Assert.Throws<ArgumentException>(() => command.AddEntry(entry)).Message);
}
[Fact]
public void ModificationCommand_throws_for_unknown_entities()
{
var entry = CreateEntry(EntityState.Detached);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
Assert.Equal(
RelationalStrings.ModificationFunctionInvalidEntityState(EntityState.Detached),
Assert.Throws<ArgumentException>(() => command.AddEntry(entry)).Message);
}
[Fact]
public void RequiresResultPropagation_false_for_Delete_operation()
{
var entry = CreateEntry(
EntityState.Deleted, generateKeyValues: true, computeNonKeyValue: true);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.False(command.RequiresResultPropagation);
}
[Fact]
public void RequiresResultPropagation_true_for_Insert_operation_if_store_generated_columns_exist()
{
var entry = CreateEntry(
EntityState.Added, generateKeyValues: true, computeNonKeyValue: true);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.True(command.RequiresResultPropagation);
}
[Fact]
public void RequiresResultPropagation_false_for_Insert_operation_if_no_store_generated_columns_exist()
{
var entry = CreateEntry(EntityState.Added);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.False(command.RequiresResultPropagation);
}
[Fact]
public void RequiresResultPropagation_true_for_Update_operation_if_non_key_store_generated_columns_exist()
{
var entry = CreateEntry(
EntityState.Modified, generateKeyValues: true, computeNonKeyValue: true);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.True(command.RequiresResultPropagation);
}
[Fact]
public void RequiresResultPropagation_false_for_Update_operation_if_no_non_key_store_generated_columns_exist()
{
var entry = CreateEntry(EntityState.Modified, generateKeyValues: true);
var command = new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, p => p.TestProvider());
command.AddEntry(entry);
Assert.False(command.RequiresResultPropagation);
}
private class T1
{
public int Id { get; set; }
public string Name { get; set; }
}
private static IModel BuildModel(bool generateKeyValues, bool computeNonKeyValue)
{
var model = new Model();
var entityType = model.AddEntityType(typeof(T1));
var key = entityType.AddProperty("Id", typeof(int));
key.ValueGenerated = generateKeyValues ? ValueGenerated.OnAdd : ValueGenerated.Never;
key.Relational().ColumnName = "Col1";
entityType.GetOrSetPrimaryKey(key);
var nonKey = entityType.AddProperty("Name", typeof(string));
nonKey.IsConcurrencyToken = computeNonKeyValue;
nonKey.Relational().ColumnName = "Col2";
nonKey.ValueGenerated = computeNonKeyValue ? ValueGenerated.OnAddOrUpdate : ValueGenerated.Never;
return model;
}
private static InternalEntityEntry CreateEntry(
EntityState entityState,
bool generateKeyValues = false,
bool computeNonKeyValue = false)
{
var model = BuildModel(generateKeyValues, computeNonKeyValue);
return RelationalTestHelpers.Instance.CreateInternalEntry(model, entityState, new T1 { Id = 1, Name = computeNonKeyValue ? null : "Test" });
}
}
}
| 41.2925 | 152 | 0.642368 | [
"Apache-2.0"
] | Mattlk13/EntityFramework | test/Microsoft.EntityFrameworkCore.Relational.Tests/Update/ModificationCommandTest.cs | 16,517 | C# |
using NUnit.Framework;
using Oss.Core;
namespace Tests
{
public class StrUtilTests
{
[Test]
public void FindNextNonEmptyIndex()
{
var str = "a ( b )";
var res = StrUtil.FindNextNonEmpty(str, "(", 1);
res.ShouldEqual(2);
}
[Test]
public void NotFindNextNonEmptyIndex()
{
var str = "a c( b )";
var res = StrUtil.FindNextNonEmpty(str, "(", 1);
res.ShouldEqual(-1);
}
}
} | 20 | 60 | 0.488462 | [
"MIT"
] | omuleanu/oss | Tests/StrUtilTests.cs | 522 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MyFirstWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
}
}
}
| 21.588235 | 67 | 0.683924 | [
"MIT"
] | Daneugoncalves/GitC | WPF-1/MyFirstWPF/MainWindow.xaml.cs | 736 | C# |
using System;
using System.ComponentModel;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
namespace Ooui.Forms.Renderers
{
public class WebViewRenderer : ViewRenderer<WebView, Div>, IWebViewDelegate
{
private bool _disposed;
private Iframe _iframe;
void IWebViewDelegate.LoadHtml(string html, string baseUrl)
{
try
{
if (string.IsNullOrEmpty(html))
{
if (Element.Source is HtmlWebViewSource urlWebViewSource)
{
html = urlWebViewSource.Html;
}
}
if (_iframe != null)
{
_iframe.Source = html;
}
}
catch (Exception ex)
{
Log.Warning("WebView load string", $"WebView load string failed: {ex}");
}
}
void IWebViewDelegate.LoadUrl(string url)
{
try
{
if (string.IsNullOrEmpty(url))
{
if (Element.Source is UrlWebViewSource urlWebViewSource)
{
url = urlWebViewSource.Url;
}
}
if (_iframe != null)
{
_iframe.Source = url;
}
}
catch (Exception ex)
{
Log.Warning("WebView load url", $"WebView load url failed: {ex}");
}
}
public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
var size = new Size(100, 100);
return new SizeRequest(size, size);
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (Control == null)
{
var embed = new Div { ClassName = "embed-responsive" };
_iframe = new Iframe();
embed.AppendChild(_iframe);
SetNativeControl(embed);
}
}
Load();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == WebView.SourceProperty.PropertyName)
Load();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && !_disposed)
{
if (_iframe != null)
{
_iframe = null;
}
_disposed = true;
}
}
private void Load()
{
Element?.Source?.Load(this);
}
}
}
| 26.539823 | 99 | 0.453484 | [
"MIT"
] | Amoenus/Ooui | Ooui.Forms/Renderers/WebViewRenderer.cs | 3,001 | C# |
namespace PlayersAndMonsters.Wizards
{
public class SoulMaster : Wizard
{
public SoulMaster(string username, int level)
: base(username, level)
{
}
}
}
| 19.181818 | 54 | 0.549763 | [
"MIT"
] | q2kPetrov/SoftUni | C# OOP/02_Inheritance/03_PlayersAndMonsters/Wizards/SoulMaster.cs | 213 | C# |
namespace Regular_Expressions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public class RegularExpressions
{
public static void Main(string[] args)
{
//Character Classes
//[abc] matches any character that is either a, b or c
//[^abc] – matches any character that is not a, b or c
//[0-9] - Character range: Мatches any digit frm 0 to 9
//[a|b] - a или b.
//. - Мatches any character
//\w – Matches any word character (a-z, A-Z, 0-9, _)
//\W – Matches any non - word character(the opposite of \w)
//\s – Matches any white - space character
//\S – Matches any non - white - space character(opposite of \s)
//\d – Matches any decimal digit
//\D – Matches any non - decimal digit(opposite of \d)
//\b - задава граница на стринга - \b[a-zA-Z][a-zA-Z0-9_]{2,24}\b
//\t - tab
//\n - new line
//\+ - + - escape +
//\* - * - escape *
//\? - ? - escape ?
//Quantifiers
//* - Matches the previous element zero or more times
//+ - Matches the previous element one or more times
//? - Matches the previous element zero or one time
//Greedy repetition:
//".+"
//Text "with" some "quotations". -> "with" some "quotations" - мачва целият текст между първата и последната кавичка.
//Lazy repetition
//".+?"
//Text "with" some "quotations". -> "with", "quotations" - мачва всички думи между кавички.
//Anchors
//^ -The match must start at the beginning of the string or line
//$ -The match must occur at the end of the string or before \n
//Пример - ^\w{6,12}$ - user name validation - Започваш с дума от 6 до 12 символа и завършваш само с това. Нищо след нея няма.
//{6,12} - от 6 до 12. {6,} - минимум 6 символа. {6} - точно 6 символа.
// \d\s\d{3}s\d{3}-\d{3} - валидиране на 0 878 123-456 - {3,} - ПОНЕ 3 СИМВОЛА! - {3, 6} - от 3 до 6 символа
// (-|\/) - валидираме и "/" освен "-" като символ. С тази "\" ескейпваме.
//Grouping Constructs
//(subexpression) - captures the matched subexpression and assigns it a number
//\d{2}-(\w{3})-\d{4} => 22-Jan-2015 - запазва Jan под номер 1
//(?<name>subexpression) - Captures the matched subexpression into a named group
//(?:subexpression) – Defines a non-capturing group - дефинира група, която НЕ СЕ прихваща.
//^(?:Hi|hello),\s*(\w+)$ => Hi, Peter - мачва Peter.
//Backreference Constructs - извикване на дефинирани групи
//\number – matches the value of a numbered subexpression. Извикване вътре в реджекса, номера на дефинирана група (преизползване на група).
//\d{2}(-|\/)\d{2}\1\d{4} => мачва 22-12-2015 или 05/08/2016 - \1 извиква група 1
//\k<name> – matches the value of a named expression - можем да именоваме групите
//\d{2}(?<del>-|\/)\d{2}\k<del>\d{4} => мачва 22-12-2015 или 05/08/2016 - ?<del> - именоване на група - \k<del> извикване на именована група
//Positive and Negative Lookahead
//Negative Lookahead - a(?!b) - Match "a" if not followed by a "b".
//Positive Lookahead - a(?=b) - Match "a" if followed by a "b".
//Positive and Negative Lookbehind
//Negative Lookbehind - (?<!b)a - Match "a" if not preceded by a "b".
//Positive Lookbehind - (?<=b)a - Match "a" if preceded by a "b".
//.*? - хващa всичко до първият срещнат препинателен знак.
//\btext\b - word boundary.
//Regex in VS -> using System.Text.RegularExpressions
string text2 = "Today is 2015-05-11";
string pattern2 = @"\d{4}-\d{2}-\d{2}";
//IsMatch(string text) – determines whether the text matches the pattern
Regex regex2 = new Regex(pattern2);
bool containsValidDate = regex2.IsMatch(text2);
Console.WriteLine(containsValidDate); // True
//Checking for a Single Match
//Match(string text) – returns the first match that corresponds to the pattern
string text = "Nakov: 123";
string pattern = @"([A-Z][a-z]+): (\d+)";
Regex regex = new Regex(pattern);
Match match = regex.Match(text);
Console.WriteLine(match.Groups.Count); // 3
Console.WriteLine("Matched text: \"{0}\"", match.Groups[0]);
Console.WriteLine("Name: {0}", match.Groups[1]); // Nakov
Console.WriteLine("Number: {0}", match.Groups[2]); // 123
//0 - целият текст. 1 - първа обособена група. 2 - втора...
//Matches(string text) – returns a collection of matching strings that correspond to the pattern
string text3 = "Nakov: 123, Branson: 456";
string pattern3 = @"([A-Z][a-z]+): (\d+)";
Regex regex3 = new Regex(pattern3);
MatchCollection matches = regex3.Matches(text3);
Console.WriteLine("Found {0} matches", matches.Count);
foreach (Match match3 in matches)
{
Console.WriteLine("Name: {0}", match3.Groups[1]); //Groups[0] - вади целите групи (Nakov: 123),
//Group[1] - вади само първата група от съвпаденията (Nakov),
//Group[2] - вади само втората група от съвпаденията (123)
}
// Found 2 matches
// Name: Nakov
// Name: Branson
//Replacing With Regex
//Replace(string text, string replacement) – replaces all strings that match the pattern with the provided replacement
string text4 = "Nakov: 123, Branson: 456";
string pattern4 = @"\d{3}";
string replacement4 = "999";
Regex regex4 = new Regex(pattern4);
string result4 = regex4.Replace(text4, replacement4);
Console.WriteLine(result4);
// Nakov: 999, Branson: 999
//Да се направи валидатор на мейли от типа: test_test@som.com, te@tes.te
//\w{2,}@[A-Za-z0-9]{3,}\.[A-Za-z]{2,4}
//Splitting With Regex
//Split(string text) – splits the text by the pattern
string text5 = "1 2 3 4";
string pattern5 = @"\s+";
string[] results5 = Regex.Split(text5, pattern5);
Console.WriteLine(string.Join(", ", results5)); // 1, 2, 3, 4
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//Често използвани:
//Вмъкване на променлива в regex.
int m = int.Parse(Console.ReadLine());
Regex pattern6 = new Regex(@"^([0-9]+)([a-zA-Z]{" + m + @"})([^a-zA-Z]*)$");
//(?<=\[)(.*?)(?=\]) - прихваща всичко между два тага - в случая всичко между []
//Matching a Username - ^[a-z0-9_-]{3,16}$ - my-us3r_n4m3
//We begin by telling the parser to find the beginning of the string(^),
//followed by any lowercase letter(a - z), number(0 - 9), an underscore,
//or a hyphen. Next, { 3,16} makes sure that are at least 3 of those
//characters, but no more than 16.Finally, we want the end of the string($).
//Matching a Password - ^[a-z0-9_-]{6,18}$ - myp4ssw0rd
//Matching a password is very similar to matching a username. The only
//difference is that instead of 3 to 16 letters, numbers, underscores,
//or hyphens, we want 6 to 18 of them({ 6,18}).
//Matching a Hex Value - ^#?([a-f0-9]{6}|[a-f0-9]{3})$ - #a3c113
//We begin by telling the parser to find the beginning of the string(^).
//Next, a number sign is optional because it is followed a question mark.
//The question mark tells the parser that the preceding character —
//in this case a number sign — is optional, but to be "greedy" and capture
//it if it's there. Next, inside the first group (first group of parentheses),
//we can have two different situations. The first is any lowercase letter
//between a and f or a number six times. The vertical bar tells us that we
//can also have three lowercase letters between a and f or numbers instead.
//Finally, we want the end of the string ($).
//Matching a Slug - ^[a-z0-9-]+$ - my-title-here
//You will be using this regex if you ever have to work with mod_rewrite and
//pretty URL's. We begin by telling the parser to find the beginning of the
//string (^), followed by one or more (the plus sign) letters, numbers, or
//hyphens. Finally, we want the end of the string ($).
//Matching an Email - ^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$ - john@doe.com
//We begin by telling the parser to find the beginning of the string (^).
//Inside the first group, we match one or more lowercase letters, numbers,
//underscores, dots, or hyphens. I have escaped the dot because a non-escaped
//dot means any character. Directly after that, there must be an at sign.
//Next is the domain name which must be: one or more lowercase letters,
//numbers, underscores, dots, or hyphens. Then another (escaped) dot, with
//the extension being two to six letters or dots. I have 2 to 6 because of
//the country specific TLD's (.ny.us or .co.uk). Finally, we want the end
//of the string ($).
//Matching a URL - ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ - http://net.tutsplus.com/about
//This regex is almost like taking the ending part of the above regex, slapping it between
//"http://" and some file structure at the end. It sounds a lot simpler than it really is.
//To start off, we search for the beginning of the line with the caret.
//The first capturing group is all option. It allows the URL to begin with
//"http://", "https://", or neither of them. I have a question mark after the s to allow
//URL's that have http or https. In order to make this entire group optional,
//I just added a question mark to the end of it.
//Next is the domain name: one or more numbers, letters, dots, or hypens followed by another
//dot then two to six letters or dots. The following section is the optional files and
//directories.Inside the group, we want to match any number of forward slashes, letters,
//numbers, underscores, spaces, dots, or hyphens. Then we say that this group can be matched
//as many times as we want.Pretty much this allows multiple directories to be matched along
//with a file at the end.I have used the star instead of the question mark because the star
//says zero or more, not zero or one. If a question mark was to be used there,
//only one file / directory would be able to be matched.
//Then a trailing slash is matched, but it can be optional.Finally we end with the end of the line.
//Matching an IP Address - ^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$ - 73.60.124.136
//The first capture group really isn't a captured group because
//was placed inside which tells the parser to not capture this
//group (more on this in the last regex). We also want this
//non -captured group to be repeated three times — the {3} at
//the end of the group. This group contains another group,
//a subgroup, and a literal dot. The parser looks for a match
//in the subgroup then a dot to move on.
//The subgroup is also another non-capture group. It's just a bunch
//of character sets (things inside brackets): the string "25"
//followed by a number between 0 and 5; or the string "2" and
//a number between 0 and 4 and any number; or an optional zero
//or one followed by two numbers, with the second being optional.
//After we match three of those, it's onto the next non-capturing group.
//This one wants: the string "25" followed by a number between 0 and 5;
//or the string "2" with a number between 0 and 4 and another number at
//the end; or an optional zero or one followed by two numbers,
//with the second being optional.
//We end this confusing regex with the end of the string.
//Matching an HTML Tag - ^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$
//One of the more useful regexes on the list. It matches any HTML tag with
//the content inside. As usually, we begin with the start of the line.
//First comes the tag's name. It must be one or more letters long.
//This is the first capture group, it comes in handy when we have to grab
//the closing tag. The next thing are the tag's attributes. This is any
//character but a greater than sign(>).Since this is optional, but I want
//to match more than one character, the star is used.The plus sign makes
//up the attribute and value, and the star says as many attributes as you want.
//Next comes the third non - capture group.Inside, it will contain either a
//greater than sign, some content, and a closing tag; or some spaces,
//a forward slash, and a greater than sign.The first option looks for a greater
//than sign followed by any number of characters, and the closing tag.
//\1 is used which represents the content that was captured in the first
//capturing group.In this case it was the tag's name. Now, if that couldn't
//be matched we want to look for a self closing tag(like an img, br, or hr tag).
//This needs to have one or more spaces followed by "/>".
//The regex is ended with the end of the line.
//String pattern validation:
//(?s)^((?!manish).)*$ (string contains manish)
//\d (at list one digit)
//(.)*(\\d)(.)* (contains number)
//^\d$ (contains only number)
//^\d{11}$ (contains only 11 digit number)
//^[a-zA-Z]+$ (contains only letter)
//^[a-zA-Z0-9]+$ (contains only letter and number)
}
}
}
| 50 | 152 | 0.560391 | [
"Unlicense"
] | GoldenR1618/SoftUni-Projects | 01.Learning_C_Sharp/16. Regular Expressions/RegularExpressions.cs | 16,164 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace EF_SQLite_exercise.Migrations
{
public partial class MyFirstMigration3 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "TestField",
table: "Posts",
type: "TEXT",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "TestField",
table: "Posts");
}
}
}
| 26.291667 | 71 | 0.568938 | [
"MIT"
] | kubilayeldemir/code-exercise | EF-SQLite-exercise/EF-SQLite-exercise/Migrations/20220117203259_MyFirstMigration3.cs | 633 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
namespace HotChocolate.Data
{
/// <summary>
/// Returns the first element of the sequence that satisfies a condition or a default value if
/// no such element is found. Applies the <see cref="UseSingleOrDefaultAttribute"/> to the field
/// </summary>
public sealed class UseFirstOrDefaultAttribute
: ObjectFieldDescriptorAttribute
{
public UseFirstOrDefaultAttribute([CallerLineNumber] int order = 0)
{
Order = order;
}
public override void OnConfigure(
IDescriptorContext context,
IObjectFieldDescriptor descriptor,
MemberInfo member)
{
descriptor.UseFirstOrDefault();
}
}
}
| 29.310345 | 100 | 0.667059 | [
"MIT"
] | Ciantic/hotchocolate | src/HotChocolate/Data/src/Data/Projections/Attributes/UseFirstOrDefaultAttribute.cs | 850 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace HRC.NetCDF
{
public abstract class NcAtt
{
public string Name { get; private set; }
public NcType NcType { get; private set; }
public uint Length { get; protected set; }
public static List<NcAtt> ReadAll(BinaryReader reader)
{
var result = new List<NcAtt>();
var count = reader.ReadNetCDFUint();
for (var i = 0; i < count; i++)
result.Add(Read(reader));
return result;
}
public static NcAtt Read(BinaryReader reader)
{
var name = new NcString(reader);
var ncType = (NcType)reader.ReadNetCDFUint();
NcAtt result;
switch (ncType)
{
case NcType.Byte:
result = new NcAttByte(reader);
break;
case NcType.Char:
result = new NcAttChar(reader);
break;
case NcType.Int:
result = new NcAttInt(reader);
break;
case NcType.Short:
result = new NcAttShort(reader);
break;
case NcType.Float:
result = new NcAttFloat(reader);
break;
case NcType.Double:
throw new NotImplementedException("");
default:
throw new NotImplementedException("Unknown base type");
}
result.Name = name.Value;
result.NcType = ncType;
return result;
}
}
public abstract class NcAtt<T>: NcAtt
{
public T[] Value { get; protected set; }
public T this[uint index] { get { return Value[index]; } set { Value[index] = value; } }
protected void ReadPadding(BinaryReader reader, int elementSize)
{
if ((elementSize % 4) == 0)
return;
var dataSize = elementSize * Length;
for (var i = 0; i < 4 - (dataSize % 4); i++)
reader.ReadByte();
}
public override string ToString()
{
var sb = new StringBuilder();
foreach (var t in Value) sb.AppendFormat("{0}, ", t);
sb.Remove(sb.Length - 2, 2);
return string.Format("{0} {1} [{2}]", NcType, Name, sb);
}
}
public class NcAttByte : NcAtt<byte>
{
public NcAttByte(BinaryReader reader)
{
Value = reader.ReadBytes((int)reader.ReadNetCDFUint());
ReadPadding(reader, sizeof(byte));
}
}
public class NcAttChar : NcAtt<char>
{
public NcAttChar(BinaryReader reader)
{
Value = new NcString(reader);
}
public new NcString Value { get; set; }
public override string ToString() { return string.Format("{0} {1} [{2}]", NcType, Name, Value); }
}
public class NcAttShort : NcAtt<short>
{
public NcAttShort(BinaryReader reader)
{
var count = reader.ReadNetCDFUint();
Value = new short[count];
for (var i = 0; i < count; i++) Value[i] = reader.ReadNetCDFShort();
if ((count & 1) == 1) reader.ReadNetCDFShort();
}
}
public class NcAttInt : NcAtt<int>
{
public NcAttInt(BinaryReader reader)
{
var count = reader.ReadNetCDFUint();
Value = new int[count];
for (var i = 0; i < count; i++) Value[i] = reader.ReadNetCDFInt();
}
}
public class NcAttFloat : NcAtt<float>
{
public NcAttFloat(BinaryReader reader)
{
var count = reader.ReadNetCDFUint();
Value = new float[count];
for (var i = 0; i < count; i++) Value[i] = reader.ReadNetCDFFloat();
}
}
public class NcAttDouble : NcAtt<double>
{
public NcAttDouble(BinaryReader reader)
{
var count = reader.ReadNetCDFUint();
Value = new double[count];
for (var i = 0; i < count; i++) Value[i] = reader.ReadNetCDFDouble();
}
}
}
| 31.091549 | 106 | 0.489468 | [
"MPL-2.0"
] | AuditoryBiophysicsLab/ESME-Workbench | Libraries/HRC/NetCDF/NcAtt.cs | 4,417 | C# |
//
// EnumerableExtensions.cs
//
// Authors:
// Alan McGovern alan.mcgovern@gmail.com
//
// Copyright (C) 2019 Alan McGovern
//
// 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 System;
using System.Collections.Generic;
using System.Linq;
namespace MonoTorrent
{
public static class EnumerableExtensions
{
public static IEnumerable<T[]> Partition<T> (this IEnumerable<T> enumerable, int partitionSize)
{
var array = enumerable.ToArray ();
for (int i = 0; i < array.Length; i += partitionSize) {
var partition = new T[Math.Min (partitionSize, array.Length - i)];
Array.Copy (array, i, partition, 0, partition.Length);
yield return partition;
}
}
}
}
| 36.959184 | 103 | 0.700166 | [
"MIT"
] | OneFingerCodingWarrior/monotorrent | src/MonoTorrent.Tests/EnumerableExtensions.cs | 1,813 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Data;
using System.Globalization;
namespace Microsoft.EntityFrameworkCore.Storage;
/// <summary>
/// <para>
/// Represents the mapping between a .NET <see cref="float" /> type and a database type.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-providers">Implementation of database providers and extensions</see>
/// for more information and examples.
/// </remarks>
public class FloatTypeMapping : RelationalTypeMapping
{
/// <summary>
/// Initializes a new instance of the <see cref="FloatTypeMapping" /> class.
/// </summary>
/// <param name="storeType">The name of the database type.</param>
/// <param name="dbType">The <see cref="DbType" /> to be used.</param>
public FloatTypeMapping(
string storeType,
DbType? dbType = System.Data.DbType.Single)
: base(storeType, typeof(float), dbType)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FloatTypeMapping" /> class.
/// </summary>
/// <param name="parameters">Parameter object for <see cref="RelationalTypeMapping" />.</param>
protected FloatTypeMapping(RelationalTypeMappingParameters parameters)
: base(parameters)
{
}
/// <summary>
/// Creates a copy of this mapping.
/// </summary>
/// <param name="parameters">The parameters for this mapping.</param>
/// <returns>The newly created mapping.</returns>
protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
=> new FloatTypeMapping(parameters);
/// <summary>
/// Generates the SQL representation of a literal value.
/// </summary>
/// <param name="value">The literal value.</param>
/// <returns>
/// The generated string.
/// </returns>
protected override string GenerateNonNullSqlLiteral(object value)
=> Convert.ToSingle(value).ToString("R", CultureInfo.InvariantCulture);
}
| 36.809524 | 118 | 0.654161 | [
"MIT"
] | Applesauce314/efcore | src/EFCore.Relational/Storage/FloatTypeMapping.cs | 2,319 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace quotes
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| 23.24 | 62 | 0.576592 | [
"Apache-2.0"
] | DonSchenck/quotes | quotes/App_Start/WebApiConfig.cs | 583 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
namespace DND.Common.Reflection
{
public interface ITypeFinder
{
IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses = true);
IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses = true);
IEnumerable<Type> FindClassesOfType<T>(bool onlyConcreteClasses = true);
IEnumerable<Type> FindClassesOfType<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses = true);
}
} | 32.944444 | 132 | 0.753794 | [
"MIT"
] | davidikin45/DigitalNomadDaveAspNetCore | src/DND.Common/Reflection/ITypeFinder.cs | 595 | C# |
// Copyright(c) 2016-2017 Brian Hansen.
// 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 System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LogFileVisualizerLib;
namespace LsnConverter
{
public partial class LsnConverterForm : Form
{
private LogSequenceNumber _lsnValue;
private Dictionary<TextBox, LsnStringType> _inputTextBoxConverter;
private Dictionary<TextBox, Label> _labelMapping;
private Font _baseTextBoxFont;
private Size _baseTextBoxSize;
private Size _baseFormSize;
private Font _baseLabelFont;
private int _bottomMargin;
private int _rightMargin;
private int _spaceBetweenTextBoxes = 14;
public LsnConverterForm()
{
InitializeComponent();
_inputTextBoxConverter = new Dictionary<TextBox, LsnStringType>()
{
{ decimalTextBox, LsnStringType.Decimal },
{ hexadecimalSeparatedTextBox, LsnStringType.HexidecimalSeparated },
{ hexadecimalTextBox, LsnStringType.Hexadecimal },
{ decimalSeparatedTextBox, LsnStringType.DecimalSeparated }
};
_labelMapping = new Dictionary<TextBox, Label>()
{
{ decimalTextBox, decimalLabel },
{ hexadecimalSeparatedTextBox, hexadecimalSeparatedLabel },
{ hexadecimalTextBox, hexadecimalLabel },
{ decimalSeparatedTextBox, decimalSeparatedLabel }
};
_baseTextBoxFont = decimalTextBox.Font;
_baseTextBoxSize = decimalTextBox.Size;
_baseFormSize = this.Size;
_baseLabelFont = decimalLabel.Font;
_bottomMargin = this.Height - _inputTextBoxConverter.Keys.Max(t => t.Bottom);
_rightMargin = this.Width - _inputTextBoxConverter.Keys.Max(t => t.Right);
}
private void LsnConverterForm_Load(object sender, EventArgs e)
{
zoomComboBox.Items.Clear();
zoomComboBox.Items.Add("50%");
zoomComboBox.Items.Add("75%");
zoomComboBox.Items.Add("100%");
zoomComboBox.Items.Add("150%");
zoomComboBox.Items.Add("200%");
zoomComboBox.Items.Add("400%");
zoomComboBox.Text = "100%";
}
private void TextBox_Leave(object sender, EventArgs e)
{
Update(sender);
}
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Update(sender);
}
}
private void Update(object sender)
{
TextBox textBox = sender as TextBox;
LogSequenceNumber previousLsnValue = _lsnValue;
LoadValueAndConvert(textBox);
if (previousLsnValue != _lsnValue)
{
SetBackgroundColor(textBox);
ResetFocus(textBox);
}
textBox.SelectAll();
}
private void LoadValueAndConvert(TextBox master)
{
if (string.IsNullOrEmpty(master.Text))
{
return;
}
try
{
_lsnValue = new LogSequenceNumber(master.Text, _inputTextBoxConverter[master]);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error Parsing LSN Value", MessageBoxButtons.OK);
return;
}
foreach (TextBox textBox in _inputTextBoxConverter.Keys)
{
if (master != textBox)
{
textBox.Text = _lsnValue.ToString(_inputTextBoxConverter[textBox]);
}
}
}
private void ResetFocus(TextBox master)
{
// Did the focus move to another TextBox?
bool textBoxHasFocus = false;
foreach (TextBox textBox in _labelMapping.Keys)
{
textBoxHasFocus |= textBox.ContainsFocus;
}
if (textBoxHasFocus)
{
master.Focus();
}
}
private void SetBackgroundColor(TextBox master)
{
foreach (TextBox textBox in _labelMapping.Keys)
{
if (master == textBox)
{
textBox.BackColor = Color.LightYellow;
}
else
{
textBox.BackColor = Color.White;
textBox.Text = _lsnValue.ToString(_inputTextBoxConverter[textBox]);
}
}
}
private void ZoomComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string zoomString = zoomComboBox.Text;
if (string.IsNullOrEmpty(zoomString))
{
return;
}
if (zoomString.EndsWith("%"))
{
zoomString = zoomString.Substring(0, zoomString.Length - 1);
}
float zoom;
float.TryParse(zoomString, out zoom);
zoom /= 100;
Font textBoxFont = new Font(_baseTextBoxFont.FontFamily, _baseTextBoxFont.SizeInPoints * zoom);
Font labelFont = new Font(_baseLabelFont.FontFamily, _baseLabelFont.SizeInPoints * zoom);
foreach (TextBox textBox in _inputTextBoxConverter.Keys)
{
textBox.Font = textBoxFont;
_labelMapping[textBox].Font = labelFont;
}
// Fixup spacing
List<TextBox> boxes = _inputTextBoxConverter.Keys.ToList();
boxes.Sort((x, y) => x.Top.CompareTo(y.Top));
int maxBottom = 0;
for (int index = 1; index < boxes.Count; index++)
{
boxes[index].Top = boxes[index - 1].Top + boxes[index - 1].Height + _spaceBetweenTextBoxes;
_labelMapping[boxes[index]].Top = boxes[index].Top + 3;
int bottom = boxes[index].Bottom;
maxBottom = Math.Max(bottom, maxBottom);
}
int maxLabelWidth = _labelMapping.Values.Max(l => l.Width);
int textBoxWidth = (int)(_baseTextBoxSize.Width * zoom);
foreach (TextBox box in _labelMapping.Keys)
{
box.Left = maxLabelWidth + 40;
box.Width = textBoxWidth;
}
int maxTextBoxWidth = _labelMapping.Keys.Max(t => t.Width);
this.Height = maxBottom + _bottomMargin;
this.Width = Math.Max(maxLabelWidth + 40 + maxTextBoxWidth + _rightMargin, _baseFormSize.Width);
}
}
}
| 36.446429 | 117 | 0.564919 | [
"MIT"
] | tf3604/LogFileVisualizer | LsnConverter/LsnConverterForm.cs | 8,166 | C# |
// Generated class v2.50.0.0, don't modify
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace NHtmlUnit.Javascript.Host.Xml
{
public partial class XMLHttpRequest : NHtmlUnit.Javascript.Host.Xml.XMLHttpRequestEventTarget
{
static XMLHttpRequest()
{
ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest o) =>
new XMLHttpRequest(o));
}
public XMLHttpRequest(com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest wrappedObject) : base(wrappedObject) {}
public new com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest WObj
{
get { return (com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest)WrappedObject; }
}
public XMLHttpRequest(bool caseSensitiveProperties)
: this(new com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest(caseSensitiveProperties)) {}
public XMLHttpRequest()
: this(new com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest()) {}
public System.Int32 ReadyState
{
get
{
return WObj.getReadyState();
}
}
public System.String ResponseText
{
get
{
return WObj.getResponseText();
}
}
public System.Object ResponseXML
{
get
{
return WObj.getResponseXML();
}
}
public System.Int32 Status
{
get
{
return WObj.getStatus();
}
}
public System.String StatusText
{
get
{
return WObj.getStatusText();
}
}
public System.String AllResponseHeaders
{
get
{
return WObj.getAllResponseHeaders();
}
}
public NHtmlUnit.Javascript.Host.Xml.XMLHttpRequestUpload Upload
{
get
{
return ObjectWrapper.CreateWrapper<NHtmlUnit.Javascript.Host.Xml.XMLHttpRequestUpload>(
WObj.getUpload());
}
}
public NHtmlUnit.Javascript.Host.Xml.XMLHttpRequestEventTarget UploadIE
{
get
{
return ObjectWrapper.CreateWrapper<NHtmlUnit.Javascript.Host.Xml.XMLHttpRequestEventTarget>(
WObj.getUploadIE());
}
}
public System.Int32 Timeout
{
get
{
return WObj.getTimeout();
}
set
{
WObj.setTimeout(value);
}
}
// Generating method code for isWithCredentials
public virtual bool IsWithCredentials()
{
return WObj.isWithCredentials();
}
// Generating method code for abort
public virtual void Abort()
{
WObj.abort();
}
// Generating method code for getResponseHeader
public virtual string GetResponseHeader(string headerName)
{
return WObj.getResponseHeader(headerName);
}
// Generating method code for open
public virtual void Open(string method, object urlParam, object asyncParam, object user, object password)
{
WObj.open(method, urlParam, asyncParam, user, password);
}
// Generating method code for send
public virtual void Send(object content)
{
WObj.send(content);
}
// Generating method code for setRequestHeader
public virtual void SetRequestHeader(string name, string value)
{
WObj.setRequestHeader(name, value);
}
// Generating method code for overrideMimeType
public virtual void OverrideMimeType(string mimeType)
{
WObj.overrideMimeType(mimeType);
}
}
}
| 24.591195 | 133 | 0.599488 | [
"Apache-2.0"
] | HtmlUnit/NHtmlUnit | app/NHtmlUnit/Generated/Javascript/Host/Xml/XMLHttpRequest.cs | 3,910 | C# |
using System;
namespace ShortDev.Minecraft.Bedrock.McWebSocket.McJson
{
public struct MCPlayerInfo
{
public string activeSessionId;
public string clientId;
public string color;
public string deviceSessionId;
public string globalMultiplayerCorrelationId;
public string name;
public string randomId;
public string uuid;
public Guid GetID()
{
return Guid.Parse(uuid);
}
}
}
| 22.090909 | 55 | 0.625514 | [
"MIT"
] | ShortDevelopment/MC-Manager | MCWebSocket/McJson/MCPlayerInfo.cs | 488 | C# |
using System;
using System.Collections;
using System.Data;
using d = IrProject.Data;
namespace IrProject.Indexing
{
public class LinkIndex
{
private Hashtable inboundLinks;
private Hashtable outboundLinks;
public LinkIndex() { load(); }
public Hashtable InboundLinks { get { return inboundLinks; } }
public Hashtable OutboundLinks { get { return outboundLinks; } }
public int[] GetInboundLinks(int docid)
{
return (int[])inboundLinks[docid];
}
public int[] GetOutboundLinks(int docid)
{
return (int[])outboundLinks[docid];
}
private void load()
{
DataTable docs = new d.DocData().GetLinkCounts();
inboundLinks = new Hashtable();
outboundLinks = new Hashtable();
int id;
foreach (DataRow dr in docs.Rows)
{
id = Convert.ToInt32(dr[0]);
inboundLinks.Add(id, new int[Convert.ToInt32(dr[1])]);
outboundLinks.Add(id, new int[Convert.ToInt32(dr[2])]);
}
d.LinkData linkData = new d.LinkData();
DataTable dt = linkData.GetLinksSortByTo();
int currId = -1;
int cursor = 0;
int toid;
int fromid;
int[] currLinks = null;
foreach (DataRow dr in dt.Rows)
{
toid = Convert.ToInt32(dr[0]);
fromid = Convert.ToInt32(dr[1]);
if (currId < toid)
{
cursor = 0;
currId = toid;
currLinks = (int[])inboundLinks[toid];
}
currLinks[cursor++] = fromid;
}
dt = linkData.GetLinksSortByFrom();
currId = -1;
cursor = 0;
currLinks = null;
foreach (DataRow dr in dt.Rows)
{
fromid = Convert.ToInt32(dr[0]);
toid = Convert.ToInt32(dr[1]);
if (currId < fromid)
{
cursor = 0;
currId = fromid;
currLinks = (int[])outboundLinks[fromid];
}
currLinks[cursor++] = toid;
}
}
}
}
| 21.011628 | 66 | 0.611511 | [
"Unlicense"
] | ic4f/oldcode | 2007-ir-crawl-index-search/Indexing/LinkIndex.cs | 1,807 | C# |
using DP.Domain.Samples.Bridge;
namespace DP.Domain.Samples.Bridge
{
public class PrinterUsual : IPrinter
{
public void OrderA()
{
System.Diagnostics.Trace.WriteLine("Order A (Take your time, bro)");
}
public void OrderB()
{
System.Diagnostics.Trace.WriteLine("Order B (Take your time, bro)");
}
}
} | 22.647059 | 80 | 0.579221 | [
"MIT"
] | KarateJB/DesignPattern.Sample | CSharp/DP.Domain/Samples/Bridge/PrinterUsual.cs | 385 | C# |
using System;
using System.Windows;
using Bindables;
using Sidekick.UI.Leagues;
namespace Sidekick.Windows.Leagues
{
/// <summary>
/// Interaction logic for LeagueView.xaml
/// </summary>
[DependencyProperty]
public partial class LeagueView : BaseWindow
{
public LeagueView(ILeagueViewModel leagueViewModel, IServiceProvider serviceProvider)
: base(serviceProvider)
{
InitializeComponent();
ViewModel = leagueViewModel;
DataContext = ViewModel;
SetWindowPositionPercent(25, 0);
Show();
}
public ILeagueViewModel ViewModel { get; set; }
}
}
| 24.107143 | 93 | 0.632593 | [
"MIT"
] | cmos12345/Sidekick | src/Sidekick/Windows/Leagues/LeagueView.xaml.cs | 675 | C# |
//
// HttpResponseMessage.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.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 System.Net.Http.Headers;
namespace System.Net.Http
{
public class HttpResponseMessage : IDisposable
{
HttpResponseHeaders headers;
string reasonPhrase;
HttpStatusCode statusCode;
Version version;
bool disposed;
public HttpResponseMessage ()
: this (HttpStatusCode.OK)
{
}
public HttpResponseMessage (HttpStatusCode statusCode)
{
StatusCode = statusCode;
}
public HttpContent Content { get; set; }
public HttpResponseHeaders Headers {
get {
return headers ?? (headers = new HttpResponseHeaders ());
}
}
public bool IsSuccessStatusCode {
get {
// Successful codes are 2xx
return statusCode >= HttpStatusCode.OK && statusCode < HttpStatusCode.MultipleChoices;
}
}
public string ReasonPhrase {
get {
return reasonPhrase ?? HttpListenerResponse.GetStatusDescription ((int) statusCode);
}
set {
reasonPhrase = value;
}
}
public HttpRequestMessage RequestMessage { get; set; }
public HttpStatusCode StatusCode {
get {
return statusCode;
}
set {
if (value < 0)
throw new ArgumentOutOfRangeException ();
statusCode = value;
}
}
public Version Version {
get {
return version ?? HttpVersion.Version11;
}
set {
if (value == null)
throw new ArgumentNullException ("Version");
version = value;
}
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing && !disposed) {
disposed = true;
if (Content != null)
Content.Dispose ();
}
}
public HttpResponseMessage EnsureSuccessStatusCode ()
{
if (IsSuccessStatusCode)
return this;
throw new HttpRequestException (string.Format ("{0} ({1})", (int) statusCode, ReasonPhrase));
}
}
}
| 24.168 | 96 | 0.699106 | [
"Apache-2.0"
] | paulcbetts/mono | mcs/class/System.Net.Http/System.Net.Http/HttpResponseMessage.cs | 3,021 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StairController : MonoBehaviour
{
public enum STAIR_DIRECTION {
up,
down,
none
};
private int numSteps = 0;
protected STAIR_DIRECTION stairDirection;
//private EdgeCollider2D edgeCollider;
//private List<Vector2> verticies = new List<Vector2>();
public GameObject leftEndStep;
public GameObject rightEndStep;
public float timer;
void Awake() {
stairDirection = DetermineStairDirection();
// All this stuff is for jumping onto stairs, which we will investigate later.
//edgeCollider = GetComponent<EdgeCollider2D>();
//numSteps = CalculateNumSteps();
// if (stairDirection == STAIR_DIRECTION.Up) {
// // create the bottom of the stair step for the line y = x
// for (int x = 0; x <= ((numSteps - 1) / 2); x++) {
// verticies.Add( new Vector2(x, x));
// verticies.Add( new Vector2(x, x + 0.5f));
// verticies.Add( new Vector2(x + 0.5f, x + 0.5f));
// verticies.Add( new Vector2(x + 0.5f, x + 1f));
// if (x == ((numSteps - 1) / 2)) {
// verticies.Add( new Vector2(x + 1f, x + 1f));
// verticies.Add( new Vector2(x + 1f, x + 1.5f));
// }
// }
// // create the top half of the stair step for the line y = x
// for (int x = ((numSteps - 1) / 2); x >= 0; x--) {
// verticies.Add( new Vector2(x + 0.5f, x + 1.5f));
// verticies.Add( new Vector2(x + 0.5f, x + 1f));
// verticies.Add( new Vector2(x, x + 1f));
// verticies.Add( new Vector2(x, x + 0.5f));
// if (x == 0) {
// verticies.Add(new Vector2(0,0));
// }
// }
// } if (stairDirection == STAIR_DIRECTION.Down) {
// // same as above for y = -x
// for (int x = 0; x <= ((numSteps - 1) / 2); x++) {
// verticies.Add( new Vector2(-x, x));
// verticies.Add( new Vector2(-x, x + 0.5f));
// verticies.Add( new Vector2(-x - 0.5f, x + 0.5f));
// verticies.Add( new Vector2(-x - 0.5f, x + 1f));
// if (x == ((numSteps - 1) / 2)) {
// verticies.Add( new Vector2(-x - 1f, x + 1f));
// verticies.Add( new Vector2(-x - 1f, x + 1.5f));
// }
// }
// for (int x = ((numSteps - 1) / 2); x >= 0; x--) {
// verticies.Add( new Vector2(-x - 0.5f, x + 1.5f));
// verticies.Add( new Vector2(-x - 0.5f, x + 1f));
// verticies.Add( new Vector2(-x, x + 1f));
// verticies.Add( new Vector2(-x, x + 0.5f));
// if (x == 0) {
// verticies.Add( new Vector2(0, 0));
// }
// }
// }
// SetPoints();
}
// void SetPoints() {
// edgeCollider.points = verticies.ToArray();
// }
public STAIR_DIRECTION GetStairDirection() {
return stairDirection;
}
public int getNumSteps() {
return numSteps;
}
int CalculateNumSteps() {
return (int)(rightEndStep.transform.position.x - leftEndStep.transform.position.x) * 2;
}
STAIR_DIRECTION DetermineStairDirection() {
if (leftEndStep.transform.position.y < rightEndStep.transform.position.y)
{
return STAIR_DIRECTION.up;
} else if (leftEndStep.transform.position.y > rightEndStep.transform.position.y)
{
return STAIR_DIRECTION.down;
}
Debug.Log("Stairs in impossible state, y postion of both ends is equal. GameObject: " + this.name);
return STAIR_DIRECTION.none;
}
} | 38.262136 | 107 | 0.494291 | [
"BSD-3-Clause"
] | 2dLynxGames/Fenris-Manor | Fenris-Manor/Assets/Scripts/StairController.cs | 3,943 | C# |
using ProductScanner.Database.Entities;
using ProductScanner.Services.Interfaces.Base;
using ProductScanner.ViewModels.PhotoType;
using System;
using System.Collections.Generic;
using System.Text;
namespace ProductScanner.Services.Interfaces
{
public interface IPhotoTypeService : IServiceBase<PhotoTypeViewModel, PhotoType>
{
}
}
| 24.642857 | 84 | 0.814493 | [
"MIT"
] | konraddysput/ProductScanner | src/ProductScanner.Backend/ProductScanner.Services/Interfaces/IPhotoTypeService.cs | 347 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.Trie
{
public class Trie
{
private Dictionary<char, Trie> _children = new Dictionary<char, Trie>();
private bool _isWordCompleted = false;
private int _size = 0;
public void Insert(string s)
{
Insert(s, 0);
}
private void Insert(string s, int index)
{
_size++;
if (index == s.Length)
{
_isWordCompleted = true;
return;
}
char c = s[index];
Trie child = GetNode(c);
if (child == null)
{
child = new Trie();
InsertNode(c, child);
}
child.Insert(s, index + 1);
}
private Trie GetNode(char c)
{
if (_children.ContainsKey(c))
{
return _children[c];
}
return null;
}
private void InsertNode(char c, Trie node)
{
_children.Add(c, node);
}
public List<string> FindPrefix(string word)
{
var list = new List<string>();
if (string.IsNullOrEmpty(word))
return list;
var iterator = this;
var fetchedWord = new StringBuilder();
for (int i = 0; i < word.Length; i++)
{
var c = word[i];
if (!iterator._children.ContainsKey(c))
break;
fetchedWord.Append(c);
iterator = iterator._children[c];
}
if (iterator._isWordCompleted)
{
list.Add(fetchedWord.ToString());
}
if (fetchedWord.Length<1) return list;
var remainingWords = GetAllWordsFromTrie(iterator);
var preWord = fetchedWord.ToString();
var words = remainingWords.Select(w => $"{preWord}{w}");
list.AddRange(words);
return list;
}
private List<string> GetAllWordsFromTrie(Trie iterator)
{
var list = new List<string>();
if (iterator == null || !iterator._children.Any())
return list;
foreach (var iteratorChild in iterator._children)
{
var fetchedWord = new StringBuilder();
fetchedWord.Append(iteratorChild.Key);
if (iteratorChild.Value._isWordCompleted)
{
list.Add(fetchedWord.ToString());
}
var remaining = GetAllWordsFromTrie(iteratorChild.Value);
var preword = fetchedWord.ToString();
var res = remaining.Select(w => $"{preword}{w}");
list.AddRange(res);
}
return list;
}
public void Clear()
{
ClearNodes(this);
}
private void ClearNodes(Trie value)
{
int removedNodes = 0;
foreach (var keyValue in value._children)
{
ClearNodes(keyValue.Value);
removedNodes++;
}
_size -= removedNodes;
value._children.Clear();
}
}
}
| 27.617886 | 80 | 0.473359 | [
"MIT"
] | AshokSubedi5/Algorithms | Algorithms/Algorithms/Trie/Trie.cs | 3,399 | C# |
using Blueprint41.Neo4j.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blueprint41.Query
{
public partial class MiscResult
{
}
}
| 16.357143 | 35 | 0.759825 | [
"MIT"
] | circles-arrows/blueprint41 | Blueprint41/Query/MiscResult.cs | 231 | C# |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Connect;
namespace UnityEditor.PackageManager.UI
{
internal sealed class AssetStoreRestAPI
{
static IAssetStoreRestAPI s_Instance = null;
public static IAssetStoreRestAPI instance => s_Instance ?? AssetStoreRestAPIInternal.instance;
internal class AssetStoreRestAPIInternal : IAssetStoreRestAPI
{
private static AssetStoreRestAPIInternal s_Instance;
public static AssetStoreRestAPIInternal instance => s_Instance ?? (s_Instance = new AssetStoreRestAPIInternal());
private const string k_PurchasesUri = "/-/api/purchases";
private const string k_TaggingsUri = "/-/api/taggings";
private const string k_ProductInfoUri = "/-/api/product";
private const string k_UpdateInfoUri = "/-/api/legacy-package-update-info";
private const string k_DownloadInfoUri = "/-/api/legacy-package-download-info";
private static readonly string[] k_Categories =
{
"3D",
"Add-Ons",
"2D",
"Audio",
"Essentials",
"Templates",
"Tools",
"VFX"
};
private string m_Host;
private string host
{
get
{
if (string.IsNullOrEmpty(m_Host))
m_Host = UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudPackagesApi);
return m_Host;
}
}
private AssetStoreRestAPIInternal()
{
}
public void GetPurchases(string query, Action<Dictionary<string, object>> doneCallbackAction, Action<UIError> errorCallbackAction)
{
var httpRequest = ApplicationUtil.instance.GetASyncHTTPClient($"{host}{k_PurchasesUri}{query ?? string.Empty}");
HandleHttpRequest(httpRequest, doneCallbackAction, errorCallbackAction);
}
public void GetCategories(Action<Dictionary<string, object>> doneCallbackAction, Action<UIError> errorCallbackAction)
{
IList<string> categories = k_Categories.ToList();
var result = new Dictionary<string, object>
{
["total"] = categories.Count,
["results"] = categories
};
doneCallbackAction?.Invoke(result);
}
public void GetTaggings(Action<Dictionary<string, object>> doneCallbackAction, Action<UIError> errorCallbackAction)
{
var httpRequest = ApplicationUtil.instance.GetASyncHTTPClient($"{host}{k_TaggingsUri}");
var etag = AssetStoreCache.instance.GetLastETag(k_TaggingsUri);
httpRequest.header["If-None-Match"] = etag.Replace("\"", "\\\"");
HandleHttpRequest(httpRequest,
result =>
{
if (httpRequest.responseHeader.ContainsKey("ETag"))
etag = httpRequest.responseHeader["ETag"];
AssetStoreCache.instance.SetLastETag(k_TaggingsUri, etag);
doneCallbackAction?.Invoke(result);
},
errorCallbackAction);
}
public void GetProductDetail(long productID, Action<Dictionary<string, object>> doneCallbackAction)
{
var httpRequest = ApplicationUtil.instance.GetASyncHTTPClient($"{host}{k_ProductInfoUri}/{productID}");
var etag = AssetStoreCache.instance.GetLastETag($"{k_ProductInfoUri}/{productID}");
httpRequest.header["If-None-Match"] = etag.Replace("\"", "\\\"");
HandleHttpRequest(httpRequest,
result =>
{
if (httpRequest.responseHeader.ContainsKey("ETag"))
etag = httpRequest.responseHeader["ETag"];
AssetStoreCache.instance.SetLastETag($"{k_ProductInfoUri}/{productID}", etag);
doneCallbackAction?.Invoke(result);
},
error =>
{
var ret = new Dictionary<string, object> { ["errorMessage"] = error.message };
doneCallbackAction?.Invoke(ret);
});
}
public void GetDownloadDetail(long productID, Action<AssetStoreDownloadInfo> doneCallbackAction)
{
var httpRequest = ApplicationUtil.instance.GetASyncHTTPClient($"{host}{k_DownloadInfoUri}/{productID}");
HandleHttpRequest(httpRequest,
result =>
{
var downloadInfo = AssetStoreDownloadInfo.ParseDownloadInfo(result);
doneCallbackAction?.Invoke(downloadInfo);
},
error =>
{
var downloadInfo = new AssetStoreDownloadInfo
{
isValid = false,
errorMessage = error.message
};
doneCallbackAction?.Invoke(downloadInfo);
});
}
public void GetProductUpdateDetail(IEnumerable<AssetStoreLocalInfo> localInfos, Action<Dictionary<string, object>> doneCallbackAction)
{
if (localInfos?.Any() != true)
{
doneCallbackAction?.Invoke(new Dictionary<string, object>());
return;
}
var localInfosJsonData = Json.Serialize(localInfos.Select(info => info?.ToDictionary() ?? new Dictionary<string, string>()).ToList());
var httpRequest = ApplicationUtil.instance.PostASyncHTTPClient($"{host}{k_UpdateInfoUri}", localInfosJsonData);
HandleHttpRequest(httpRequest,
result =>
{
var ret = result["result"] as Dictionary<string, object>;
doneCallbackAction?.Invoke(ret);
},
error =>
{
var ret = new Dictionary<string, object> { ["errorMessage"] = error.message };
doneCallbackAction?.Invoke(ret);
});
}
private void HandleHttpRequest(IAsyncHTTPClient httpRequest, Action<Dictionary<string, object>> doneCallbackAction, Action<UIError> errorCallbackAction)
{
AssetStoreOAuth.instance.FetchUserInfo(
userInfo =>
{
httpRequest.header["Content-Type"] = "application/json";
httpRequest.header["Authorization"] = "Bearer " + userInfo.accessToken;
httpRequest.doneCallback = httpClient =>
{
var parsedResult = AssetStoreUtils.ParseResponseAsDictionary(httpRequest, errorMessage =>
{
errorCallbackAction?.Invoke(new UIError(UIErrorCode.AssetStoreRestApiError, errorMessage));
});
if (parsedResult != null)
doneCallbackAction?.Invoke(parsedResult);
};
httpRequest.Begin();
},
errorCallbackAction);
}
}
}
}
| 44.363128 | 164 | 0.528271 | [
"Unlicense"
] | HelloWindows/AccountBook | client/framework/UnityCsReference-master/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStoreRestAPI.cs | 7,941 | C# |
using System;
using Baseline;
namespace StoryTeller.Results
{
public class Envelope
{
public Envelope()
{
}
public Envelope(object message)
{
this.topic = ToTopic(message.GetType());
this.message = message;
}
public string topic;
public object message;
protected bool Equals(Envelope other)
{
return string.Equals(topic, other.topic) && Equals(message, other.message);
}
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((Envelope) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((topic != null ? topic.GetHashCode() : 0)*397) ^ (message != null ? message.GetHashCode() : 0);
}
}
public override string ToString()
{
return string.Format("Topic: {0}, Message: {1}", topic, message);
}
public static string ToTopic(Type messageType)
{
return messageType.Name.SplitPascalCase().Replace(' ', '-').ToLower();
}
}
} | 25.711538 | 119 | 0.529544 | [
"Apache-2.0"
] | SergeiGolos/Storyteller | src/StoryTeller/Results/Envelope.cs | 1,337 | C# |
using System;
using System.Threading.Tasks;
using AspnetRunBasics.Models;
using AspnetRunBasics.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace AspnetRunBasics
{
public class CheckOutModel : PageModel
{
private readonly IBasketService _basketService;
private readonly IOrderService _orderService;
public CheckOutModel(IBasketService basketService, IOrderService orderService)
{
_basketService = basketService ?? throw new ArgumentNullException(nameof(basketService));
_orderService = orderService ?? throw new ArgumentNullException(nameof(orderService));
}
[BindProperty]
public BasketCheckoutModel Order { get; set; }
public BasketModel Cart { get; set; } = new BasketModel();
public async Task<IActionResult> OnGetAsync()
{
string userName = "swn";
Cart = await _basketService.GetBasket(userName);
return Page();
}
public async Task<IActionResult> OnPostCheckOutAsync()
{
string userName = "swn";
Cart = await _basketService.GetBasket(userName);
if (!ModelState.IsValid)
{
return Page();
}
Order.UserName = userName;
Order.TotalPrice = Cart.TotalPrice;
await _basketService.CheckoutBasket(Order);
return RedirectToPage("Confirmation", "OrderSubmitted");
}
}
} | 30.313725 | 101 | 0.630013 | [
"MIT"
] | rprsatyendra/AspnetMicroservices | src/WebApps/AspnetRunBasics/Pages/CheckOut.cshtml.cs | 1,548 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("HelloWorldApp.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HelloWorldApp.Android")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// 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")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 36.828571 | 84 | 0.757952 | [
"BSD-3-Clause"
] | jhensley707/xamarin-app-center | HelloWorldApp/HelloWorldApp.Android/Properties/AssemblyInfo.cs | 1,292 | C# |
using commercetools.Sdk.Domain.ProductProjections;
namespace commercetools.Sdk.Domain.Messages.Products
{
[TypeMarker("ProductPriceExternalDiscountSet")]
public class ProductPriceExternalDiscountSetMessage : Message<Product>
{
public int VariantId { get; set;}
public string VariantKey { get; set;}
public string Sku { get; set;}
public string PriceId { get; set;}
public DiscountedPrice Discounted { get; set;}
public bool Staged { get; set;}
}
}
| 24.666667 | 74 | 0.681467 | [
"Apache-2.0"
] | commercetools/commercetools-dotnet-core-sdk | commercetools.Sdk/commercetools.Sdk.Domain/Messages/Products/ProductPriceExternalDiscountSetMessage.cs | 518 | C# |
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using SimpleIdServer.Common.Domains;
using SimpleIdServer.Common.Helpers;
using SimpleIdServer.OAuth.Domains;
using SimpleIdServer.OpenID;
using SimpleIdServer.OpenID.Domains;
using System;
using System.Collections.Generic;
namespace OpenId
{
public class OpenIdDefaultConfiguration
{
public static List<OAuthScope> Scopes = new List<OAuthScope>
{
SIDOpenIdConstants.StandardScopes.OpenIdScope,
SIDOpenIdConstants.StandardScopes.Phone,
SIDOpenIdConstants.StandardScopes.Profile,
SIDOpenIdConstants.StandardScopes.Role,
SIDOpenIdConstants.StandardScopes.OfflineAccessScope,
SIDOpenIdConstants.StandardScopes.Email,
SIDOpenIdConstants.StandardScopes.Address,
SIDOpenIdConstants.StandardScopes.ScimScope
};
public static List<AuthenticationContextClassReference> AcrLst => new List<AuthenticationContextClassReference>
{
new AuthenticationContextClassReference
{
DisplayName = "First level of assurance",
Name = "sid-load-01",
AuthenticationMethodReferences = new List<string>
{
"pwd"
}
},
new AuthenticationContextClassReference
{
DisplayName = "Second level of assurance",
Name = "sid-load-02",
AuthenticationMethodReferences = new List<string>
{
"pwd",
"sms"
}
}
};
public static List<OAuthUser> Users => new List<OAuthUser>
{
new OAuthUser
{
Id = "sub",
Credentials = new List<UserCredential>
{
new UserCredential
{
CredentialType = "pwd",
Value = PasswordHelper.ComputeHash("password")
}
},
CreateDateTime = DateTime.Now,
UpdateDateTime = DateTime.Now,
OAuthUserClaims = new List<UserClaim>
{
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.Subject, "sub"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.Name, "name"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.FamilyName, "familyName"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.UniqueName, "uniquename"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.GivenName, "givenName"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.MiddleName, "middleName"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.NickName, "nickName"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.BirthDate, "07-10-1989"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.PreferredUserName, "preferredUserName"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.ZoneInfo, "zoneInfo"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.Locale, "locale"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.Picture, "picture"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.WebSite, "website"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.Profile, "profile"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.Gender, "gender"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.Role, "admin"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.Email, "agentsimpleidserver@gmail.com"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.UpdatedAt, "1612355959", SimpleIdServer.Jwt.ClaimValueTypes.INTEGER),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.EmailVerified, "true", SimpleIdServer.Jwt.ClaimValueTypes.BOOLEAN),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.Address, "{ 'street_address': '1234 Hollywood Blvd.', 'locality': 'Los Angeles', 'region': 'CA', 'postal_code': '90210', 'country': 'US' }", SimpleIdServer.Jwt.ClaimValueTypes.JSONOBJECT),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.PhoneNumber, "+1 (310) 123-4567"),
new UserClaim(SimpleIdServer.Jwt.Constants.UserClaims.PhoneNumberVerified, "true", SimpleIdServer.Jwt.ClaimValueTypes.BOOLEAN)
}
}
};
public static List<OpenIdClient> GetClients()
{
return new List<OpenIdClient>
{
new OpenIdClient
{
ClientId = "scimClient",
ClientSecret = "scimClientSecret",
ApplicationKind = ApplicationKinds.Service,
TokenEndPointAuthMethod = "client_secret_post",
ApplicationType = "web",
UpdateDateTime = DateTime.UtcNow,
CreateDateTime = DateTime.UtcNow,
TokenExpirationTimeInSeconds = 60 * 30,
RefreshTokenExpirationTimeInSeconds = 60 * 30,
TokenSignedResponseAlg = "RS256",
IdTokenSignedResponseAlg = "RS256",
AllowedScopes = new List<OAuthScope>
{
SIDOpenIdConstants.StandardScopes.ScimScope
},
GrantTypes = new List<string>
{
"implicit",
},
RedirectionUrls = new List<string>
{
"http://localhost:8080",
"http://localhost:1700"
},
PreferredTokenProfile = "Bearer",
ResponseTypes = new List<string>
{
"token",
"id_token"
}
},
new OpenIdClient
{
ClientId = "umaClient",
ClientSecret = "umaClientSecret",
ApplicationKind = ApplicationKinds.Service,
TokenEndPointAuthMethod = "client_secret_post",
ApplicationType = "web",
UpdateDateTime = DateTime.UtcNow,
CreateDateTime = DateTime.UtcNow,
TokenExpirationTimeInSeconds = 60 * 30,
RefreshTokenExpirationTimeInSeconds = 60 * 30,
TokenSignedResponseAlg = "RS256",
IdTokenSignedResponseAlg = "RS256",
AllowedScopes = new List<OAuthScope>
{
SIDOpenIdConstants.StandardScopes.OpenIdScope,
SIDOpenIdConstants.StandardScopes.Profile,
SIDOpenIdConstants.StandardScopes.Email
},
GrantTypes = new List<string>
{
"implicit",
"authorization_code"
},
RedirectionUrls = new List<string>
{
"https://localhost:60001/signin-oidc"
},
PreferredTokenProfile = "Bearer",
ResponseTypes = new List<string>
{
"token",
"id_token",
"code"
}
},
new OpenIdClient
{
ClientId = "simpleIdServerWebsite",
ClientSecret = "simpleIdServerWebsiteSecret",
ApplicationKind = ApplicationKinds.SPA,
TokenEndPointAuthMethod = "pkce",
ApplicationType = "web",
UpdateDateTime = DateTime.UtcNow,
CreateDateTime = DateTime.UtcNow,
TokenExpirationTimeInSeconds = 60 * 30,
RefreshTokenExpirationTimeInSeconds = 60 * 30,
TokenSignedResponseAlg = "RS256",
IdTokenSignedResponseAlg = "RS256",
AllowedScopes = new List<OAuthScope>
{
SIDOpenIdConstants.StandardScopes.OpenIdScope,
SIDOpenIdConstants.StandardScopes.Profile,
SIDOpenIdConstants.StandardScopes.Email,
SIDOpenIdConstants.StandardScopes.Role
},
GrantTypes = new List<string>
{
"authorization_code",
"implicit"
},
RedirectionUrls = new List<string>
{
"http://localhost:4200",
"https://simpleidserver.northeurope.cloudapp.azure.com/simpleidserver/"
},
PostLogoutRedirectUris = new List<string>
{
"http://localhost:4200",
"https://simpleidserver.northeurope.cloudapp.azure.com/simpleidserver/"
},
PreferredTokenProfile = "Bearer",
ResponseTypes = new List<string>
{
"token",
"id_token",
"code"
}
},
new OpenIdClient
{
ClientId = "tradWebsite",
ClientSecret = "tradWebsiteSecret",
ApplicationKind = ApplicationKinds.Web,
TokenEndPointAuthMethod = "client_secret_post",
ApplicationType = "web",
UpdateDateTime = DateTime.UtcNow,
CreateDateTime = DateTime.UtcNow,
TokenExpirationTimeInSeconds = 60 * 30,
RefreshTokenExpirationTimeInSeconds = 60 * 30,
TokenSignedResponseAlg = "RS256",
IdTokenSignedResponseAlg = "RS256",
AllowedScopes = new List<OAuthScope>
{
SIDOpenIdConstants.StandardScopes.OpenIdScope,
SIDOpenIdConstants.StandardScopes.Profile
},
GrantTypes = new List<string>
{
"authorization_code",
"password"
},
RedirectionUrls = new List<string>
{
"https://localhost:5001/signin-oidc"
},
PreferredTokenProfile = "Bearer",
ResponseTypes = new List<string>
{
"code",
"token",
"id_token"
}
},
new OpenIdClient
{
ClientId = "native",
ClientSecret = "nativeSecret",
ApplicationKind = ApplicationKinds.Native,
TokenEndPointAuthMethod = "pkce",
ApplicationType = "web",
UpdateDateTime = DateTime.UtcNow,
CreateDateTime = DateTime.UtcNow,
TokenExpirationTimeInSeconds = 60 * 30,
RefreshTokenExpirationTimeInSeconds = 60 * 30,
TokenSignedResponseAlg = "RS256",
IdTokenSignedResponseAlg = "RS256",
AllowedScopes = new List<OAuthScope>
{
SIDOpenIdConstants.StandardScopes.OpenIdScope,
SIDOpenIdConstants.StandardScopes.Profile,
SIDOpenIdConstants.StandardScopes.Email
},
GrantTypes = new List<string>
{
"authorization_code"
},
RedirectionUrls = new List<string>
{
"com.companyname.simpleidserver.mobileapp:/oauth2redirect"
},
PreferredTokenProfile = "Bearer",
ResponseTypes = new List<string>
{
"code"
}
},
new OpenIdClient
{
ClientId = "website",
ClientSecret = "websiteSecret",
ApplicationKind = ApplicationKinds.Web,
TokenEndPointAuthMethod = "client_secret_post",
ApplicationType = "web",
UpdateDateTime = DateTime.UtcNow,
CreateDateTime = DateTime.UtcNow,
TokenExpirationTimeInSeconds = 60 * 30,
RefreshTokenExpirationTimeInSeconds = 60 * 30,
TokenSignedResponseAlg = "RS256",
IdTokenSignedResponseAlg = "RS256",
AllowedScopes = new List<OAuthScope>
{
SIDOpenIdConstants.StandardScopes.OpenIdScope,
SIDOpenIdConstants.StandardScopes.Profile,
SIDOpenIdConstants.StandardScopes.Email,
SIDOpenIdConstants.StandardScopes.Role
},
GrantTypes = new List<string>
{
"authorization_code",
},
RedirectionUrls = new List<string>
{
"https://localhost:7001/signin-oidc"
},
PreferredTokenProfile = "Bearer",
ResponseTypes = new List<string>
{
"token",
"id_token"
}
}
};
}
}
} | 46.365079 | 262 | 0.488463 | [
"Apache-2.0"
] | PetrutiuPaul/SimpleIdServer | samples/ProtectAPIFromUndesirableUsers/IdToken/src/OpenId/OpenIdDefaultConfiguration.cs | 14,605 | C# |
namespace buildeR.DAL.Entities.Common
{
public abstract class Entity
{
public int Id { get; set; }
}
} | 17.428571 | 37 | 0.614754 | [
"MIT"
] | BinaryStudioAcademy/bsa-2020-buildeR | backend/buildeR.DAL/Entities/Common/Entity.cs | 122 | C# |
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* 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.
*/
#endregion
#region Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
namespace Sanford.Multimedia
{
public abstract class DeviceException : ApplicationException
{
#region Error Codes
public const int MMSYSERR_NOERROR = 0; /* no error */
public const int MMSYSERR_ERROR = 1; /* unspecified error */
public const int MMSYSERR_BADDEVICEID = 2; /* device ID out of range */
public const int MMSYSERR_NOTENABLED = 3; /* driver failed enable */
public const int MMSYSERR_ALLOCATED = 4; /* device already allocated */
public const int MMSYSERR_INVALHANDLE = 5; /* device handle is invalid */
public const int MMSYSERR_NODRIVER = 6; /* no device driver present */
public const int MMSYSERR_NOMEM = 7; /* memory allocation error */
public const int MMSYSERR_NOTSUPPORTED = 8; /* function isn't supported */
public const int MMSYSERR_BADERRNUM = 9; /* error value out of range */
public const int MMSYSERR_INVALFLAG = 10; /* invalid flag passed */
public const int MMSYSERR_INVALPARAM = 11; /* invalid parameter passed */
public const int MMSYSERR_HANDLEBUSY = 12; /* handle being used */
/* simultaneously on another */
/* thread (eg callback) */
public const int MMSYSERR_INVALIDALIAS = 13; /* specified alias not found */
public const int MMSYSERR_BADDB = 14; /* bad registry database */
public const int MMSYSERR_KEYNOTFOUND = 15; /* registry key not found */
public const int MMSYSERR_READERROR = 16; /* registry read error */
public const int MMSYSERR_WRITEERROR = 17; /* registry write error */
public const int MMSYSERR_DELETEERROR = 18; /* registry delete error */
public const int MMSYSERR_VALNOTFOUND = 19; /* registry value not found */
public const int MMSYSERR_NODRIVERCB = 20; /* driver does not call DriverCallback */
public const int MMSYSERR_LASTERROR = 20;
#endregion
private int errorCode;
public DeviceException(int errorCode)
{
this.errorCode = errorCode;
}
public int ErrorCode
{
get
{
return errorCode;
}
}
}
}
| 41.465116 | 92 | 0.659282 | [
"MIT"
] | 3017218159/Sanford.Multimedia.Midi-master | Source/Sanford.Multimedia/DeviceException.cs | 3,566 | 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.Diagnostics;
using Internal.Text;
using Internal.TypeSystem;
namespace ILCompiler.DependencyAnalysis.ReadyToRun
{
public class GCRefMapNode : ObjectNode, ISymbolDefinitionNode
{
/// <summary>
/// Number of GC ref map records to represent with a single lookup pointer
/// </summary>
public const int GCREFMAP_LOOKUP_STRIDE = 1024;
private readonly ImportSectionNode _importSection;
private readonly List<IMethodNode> _methods;
public GCRefMapNode(ImportSectionNode importSection)
{
_importSection = importSection;
_methods = new List<IMethodNode>();
}
public override ObjectNodeSection Section => ObjectNodeSection.ReadOnlyDataSection;
public override bool IsShareable => false;
public override int ClassCode => 555444333;
public override bool StaticDependenciesAreComputed => true;
public int Offset => 0;
public void AddImport(Import import)
{
_methods.Add(import as IMethodNode);
}
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append("GCRefMap->");
sb.Append(_importSection.Name);
}
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
if (_methods.Count == 0 || relocsOnly)
{
return new ObjectData(
data: Array.Empty<byte>(),
relocs: Array.Empty<Relocation>(),
alignment: 1,
definedSymbols: new ISymbolDefinitionNode[] { this });
}
GCRefMapBuilder builder = new GCRefMapBuilder(factory.Target, relocsOnly);
builder.Builder.RequireInitialAlignment(4);
builder.Builder.AddSymbol(this);
// First, emit the initial ref map offset and reserve the offset map entries
int offsetCount = _methods.Count / GCREFMAP_LOOKUP_STRIDE;
builder.Builder.EmitInt((offsetCount + 1) * sizeof(int));
ObjectDataBuilder.Reservation[] offsets = new ObjectDataBuilder.Reservation[offsetCount];
for (int offsetIndex = 0; offsetIndex < offsetCount; offsetIndex++)
{
offsets[offsetIndex] = builder.Builder.ReserveInt();
}
// Next, generate the actual method GC ref maps and update the offset map
int nextOffsetIndex = 0;
int nextMethodIndex = GCREFMAP_LOOKUP_STRIDE - 1;
for (int methodIndex = 0; methodIndex < _methods.Count; methodIndex++)
{
if (methodIndex >= nextMethodIndex)
{
builder.Builder.EmitInt(offsets[nextOffsetIndex], builder.Builder.CountBytes);
nextOffsetIndex++;
nextMethodIndex += GCREFMAP_LOOKUP_STRIDE;
}
IMethodNode methodNode = _methods[methodIndex];
if (methodNode == null || (methodNode is MethodWithGCInfo methodWithGCInfo && methodWithGCInfo.IsEmpty))
{
// Flush an empty GC ref map block to prevent
// the indexed records from falling out of sync with methods
builder.Flush();
}
else
{
builder.GetCallRefMap(methodNode.Method);
}
}
Debug.Assert(nextOffsetIndex == offsets.Length);
return builder.Builder.ToObjectData();
}
protected override string GetName(NodeFactory factory)
{
Utf8StringBuilder sb = new Utf8StringBuilder();
AppendMangledName(factory.NameMangler, sb);
return sb.ToString();
}
}
}
| 36.910714 | 120 | 0.599903 | [
"MIT"
] | janvorli/coreclr | src/tools/crossgen2/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/GCRefMapNode.cs | 4,136 | C# |
using System;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public class Matrix4ShaderProperty : MatrixShaderProperty
{
public Matrix4ShaderProperty()
{
displayName = "Matrix4";
}
public override PropertyType propertyType
{
get { return PropertyType.Matrix4; }
}
public override INode ToConcreteNode()
{
return new Matrix4Node
{
row0 = new Vector4(value.m00, value.m01, value.m02, value.m03),
row1 = new Vector4(value.m10, value.m11, value.m12, value.m13),
row2 = new Vector4(value.m20, value.m21, value.m22, value.m23),
row3 = new Vector4(value.m30, value.m31, value.m32, value.m33)
};
}
public override IShaderProperty Copy()
{
var copied = new Matrix4ShaderProperty();
copied.displayName = displayName;
copied.value = value;
return copied;
}
}
}
| 27.225 | 79 | 0.565657 | [
"MIT"
] | 17cuA/AimRacing11 | AimRacing2019_05_31/AimRacing2019_05_31/Packages/com.unity.shadergraph/Editor/Data/Graphs/Matrix4ShaderProperty.cs | 1,089 | C# |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.MathUtils;
using System;
using System.Collections.Concurrent;
using System.Reflection.Emit;
using osu.Framework.Extensions.TypeExtensions;
using System.Reflection;
using System.Linq;
using System.Diagnostics;
namespace osu.Framework.Graphics.Transforms
{
public delegate TValue InterpolationFunc<TValue>(double time, TValue startValue, TValue endValue, double startTime, double endTime, Easing easingType);
/// <summary>
/// A transform which operates on arbitrary fields or properties of a given target.
/// </summary>
/// <typeparam name="TValue">The type of the field or property to operate upon.</typeparam>
/// <typeparam name="T">The type of the target to operate upon.</typeparam>
internal class TransformCustom<TValue, T> : Transform<TValue, T> where T : ITransformable
{
private delegate TValue ReadFunc(T transformable);
private delegate void WriteFunc(T transformable, TValue value);
private struct Accessor
{
public ReadFunc Read;
public WriteFunc Write;
}
private static readonly ConcurrentDictionary<string, Accessor> accessors = new ConcurrentDictionary<string, Accessor>();
private static readonly InterpolationFunc<TValue> interpolation_func;
static TransformCustom()
{
interpolation_func =
(InterpolationFunc<TValue>)typeof(Interpolation).GetMethod(
nameof(Interpolation.ValueAt),
typeof(InterpolationFunc<TValue>)
.GetMethod(nameof(InterpolationFunc<TValue>.Invoke))
?.GetParameters().Select(p => p.ParameterType).ToArray()
)?.CreateDelegate(typeof(InterpolationFunc<TValue>));
}
private static ReadFunc createFieldGetter(FieldInfo field)
{
string methodName = $"{typeof(T).ReadableName()}.{field.Name}.get_{Guid.NewGuid():N}";
DynamicMethod setterMethod = new DynamicMethod(methodName, typeof(TValue), new[] { typeof(T) }, true);
ILGenerator gen = setterMethod.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, field);
gen.Emit(OpCodes.Ret);
return (ReadFunc)setterMethod.CreateDelegate(typeof(ReadFunc));
}
private static WriteFunc createFieldSetter(FieldInfo field)
{
string methodName = $"{typeof(T).ReadableName()}.{field.Name}.set_{Guid.NewGuid():N}";
DynamicMethod setterMethod = new DynamicMethod(methodName, null, new[] { typeof(T), typeof(TValue) }, true);
ILGenerator gen = setterMethod.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Stfld, field);
gen.Emit(OpCodes.Ret);
return (WriteFunc)setterMethod.CreateDelegate(typeof(WriteFunc));
}
private static Accessor findAccessor(Type type, string propertyOrFieldName)
{
PropertyInfo property = type.GetProperty(propertyOrFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (property != null)
{
if (property.PropertyType != typeof(TValue))
throw new InvalidOperationException(
$"Cannot create {nameof(TransformCustom<TValue, T>)} for property {type.ReadableName()}.{propertyOrFieldName} " +
$"since its type should be {typeof(TValue).ReadableName()}, but is {property.PropertyType.ReadableName()}.");
var getter = property.GetGetMethod(true);
var setter = property.GetSetMethod(true);
if (getter == null || setter == null)
throw new InvalidOperationException(
$"Cannot create {nameof(TransformCustom<TValue, T>)} for property {type.ReadableName()}.{propertyOrFieldName} " +
"since it needs to have both a getter and a setter.");
if (getter.IsStatic || setter.IsStatic)
throw new NotSupportedException(
$"Cannot create {nameof(TransformCustom<TValue, T>)} for property {type.ReadableName()}.{propertyOrFieldName} because static fields are not supported.");
return new Accessor
{
Read = (ReadFunc)getter.CreateDelegate(typeof(ReadFunc)),
Write = (WriteFunc)setter.CreateDelegate(typeof(WriteFunc)),
};
}
FieldInfo field = type.GetField(propertyOrFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
if (field != null)
{
if (field.FieldType != typeof(TValue))
throw new InvalidOperationException(
$"Cannot create {nameof(TransformCustom<TValue, T>)} for field {type.ReadableName()}.{propertyOrFieldName} " +
$"since its type should be {typeof(TValue).ReadableName()}, but is {field.FieldType.ReadableName()}.");
if (field.IsStatic)
throw new NotSupportedException(
$"Cannot create {nameof(TransformCustom<TValue, T>)} for field {type.ReadableName()}.{propertyOrFieldName} because static fields are not supported.");
return new Accessor
{
Read = createFieldGetter(field),
Write = createFieldSetter(field),
};
}
if (type.BaseType == null)
throw new InvalidOperationException($"Cannot create {nameof(TransformCustom<TValue, T>)} for non-existent property or field {typeof(T).ReadableName()}.{propertyOrFieldName}.");
// Private members aren't visible unless we check the base type explicitly, so let's try our luck.
return findAccessor(type.BaseType, propertyOrFieldName);
}
private static Accessor getAccessor(string propertyOrFieldName) => accessors.GetOrAdd(propertyOrFieldName, _ => findAccessor(typeof(T), propertyOrFieldName));
private readonly Accessor accessor;
private readonly InterpolationFunc<TValue> interpolationFunc;
/// <summary>
/// Creates a new instance operating on a property or field of <see cref="T"/>. The property or field is
/// denoted by its name, passed as <paramref name="propertyOrFieldName"/>.
/// By default, an interpolation method "ValueAt" from <see cref="Interpolation"/> with suitable signature is
/// picked for interpolating between <see cref="Transform{TValue}.StartValue"/> and
/// <see cref="Transform{TValue}.EndValue"/> according to <see cref="Transform.StartTime"/>,
/// <see cref="Transform.EndTime"/>, and a current time.
/// Optionally, or when no suitable "ValueAt" from <see cref="Interpolation"/> exists, a custom function can be supplied
/// via <paramref name="interpolationFunc"/>.
/// </summary>
/// <param name="propertyOrFieldName">The property or field name to be operated upon.</param>
/// <param name="interpolationFunc">
/// The function to be used for interpolating between <see cref="Transform{TValue}.StartValue"/> and
/// <see cref="Transform{TValue}.EndValue"/> according to <see cref="Transform.StartTime"/>,
/// <see cref="Transform.EndTime"/>, and a current time.
/// If null, an interpolation method "ValueAt" from <see cref="Interpolation"/> with a suitable signature is picked.
/// If none exists, then this parameter must not be null.
/// </param>
public TransformCustom(string propertyOrFieldName, InterpolationFunc<TValue> interpolationFunc = null)
{
TargetMember = propertyOrFieldName;
accessor = getAccessor(propertyOrFieldName);
Trace.Assert(accessor.Read != null && accessor.Write != null, $"Failed to populate {nameof(accessor)}.");
this.interpolationFunc = interpolationFunc ?? interpolation_func;
if (this.interpolationFunc == null)
throw new InvalidOperationException(
$"Need to pass a custom {nameof(interpolationFunc)} since no default {nameof(Interpolation)}.{nameof(Interpolation.ValueAt)} exists.");
}
private TValue valueAt(double time)
{
if (time < StartTime) return StartValue;
if (time >= EndTime) return EndValue;
return interpolationFunc(time, StartValue, EndValue, StartTime, EndTime, Easing);
}
public override string TargetMember { get; }
protected override void Apply(T d, double time) => accessor.Write(d, valueAt(time));
protected override void ReadIntoStartValue(T d) => StartValue = accessor.Read(d);
}
}
| 52.728814 | 193 | 0.622951 | [
"MIT"
] | AlFasGD/osu-framework | osu.Framework/Graphics/Transforms/TransformCustom.cs | 9,157 | C# |
namespace Shorty.Web
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shorty.Data;
/// <summary>
/// Class to configure ASP.NET and EntityFramework.
/// </summary>
public class Startup
{
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">The services.</param>
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationContext>(o => o.UseSqlite(@"Data Source=data.db"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">The application.</param>
/// <param name="env">The env.</param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHttpsRedirection();
app.UseHsts();
}
this.InitializeDatabase(app);
app.UseFileServer();
app.UseMvc();
}
/// <summary>
/// Initializes the database. Creates the database if necessary and applies all missing migrations.
/// </summary>
/// <param name="app">The application.</param>
private void InitializeDatabase(IApplicationBuilder app)
{
using (IServiceScope scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
using (var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationContext>())
{
dbContext.Database.Migrate();
}
}
}
}
}
| 34.650794 | 114 | 0.584517 | [
"MIT"
] | ef4203/shorty | Shorty.Web/Startup.cs | 2,185 | C# |
// <copyright file="AssemblyInfo.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
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("SocialPlus.Server.AVERT")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SocialPlus.Server.AVERT")]
[assembly: AssemblyCopyright("Copyright (c) 2016")]
[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("21b9cfd9-0fd0-46f1-86f8-a8fad742a43d")]
// 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.5 | 84 | 0.742667 | [
"MIT"
] | Bhaskers-Blu-Org2/EmbeddedSocial-Service | code/Server/AVERT/Properties/AssemblyInfo.cs | 1,502 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using TestSupport.Common_TestSupport;
namespace TestSupport
{
/// <summary>
/// The expected range an enumerator will enumerate.
/// </summary>
[Flags]
public enum ExpectedEnumeratorRange { None = 0, Start = 1, End = 2 };
/// <summary>
/// The methods to use for verification
/// </summary>
[Flags]
public enum VerificationMethod { None = 0, Item = 1, Contains = 2, IndexOf = 4, ICollection = 8 };
/// <summary>
/// The verification level
/// </summary>
public enum VerificationLevel { None, Normal, Extensive };
/// <summary>
/// This specifies how the collection is ordered.
/// Sequential specifies that Add places items at the end of the collection and Remove will remove the first item found.
/// Reverse specifies that Add places items at the begining of the collection and Remove will remove the first item found.
/// Unspecified specifies that Add and Remove do not specify where items are added or removed.
/// </summary>
public enum CollectionOrder { Sequential, Unspecified };// TODO: Support ordeered collections
namespace Common_TestSupport
{ /// <summary>
/// Modifies the given collection
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection">The collection to modify</param>
/// <param name="expectedItems">The current items in the collection</param>
/// <returns>The items in the collection after it has been modified.</returns>
public delegate T[] ModifyUnderlyingCollection_T<T>(System.Collections.Generic.IEnumerable<T> collection, T[] expectedItems);
/// <summary>
/// Modifies the given collection
/// </summary>
/// <param name="collection">The collection to modify</param>
/// <param name="expectedItems">The current items in the collection</param>
/// <returns>The items in the collection after it has been modified.</returns>
public delegate Object[] ModifyUnderlyingCollection(IEnumerable collection, Object[] expectedItems);
/// <summary>
/// Creates a new ICollection
/// </summary>
/// <returns></returns>
public delegate ICollection CreateNewICollection();
/// <summary>
/// Generates a new unique item
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>A new unique item.</returns>
public delegate T GenerateItem<T>();
/// <summary>
/// Compares x and y
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>true if x and y are equal else false.</returns>
public delegate bool ItemEquals_T<T>(T x, T y);
/// <summary>
/// Compares x and y
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>true if x and y are equal else false.</returns>
public delegate bool ItemEquals(Object x, Object y);
/// <summary>
/// An action to perform on a Multidimentional array
/// </summary>
/// <param name="array">The array to perform the action on</param>
/// <param name="indicies">The current indicies of the array</param>
public delegate void MultiDimArrayAction(Array array, int[] indicies);
public delegate void ModifyCollection();
/// <summary>
/// Geneartes an exception
/// </summary>
public delegate void ExceptionGenerator();
/// <summary>
/// Test Scenario to run
/// </summary>
/// <returns>true if the test scenario passed else false</returns>
public delegate bool TestScenario();
public class Test
{
/// <summary>
/// The default exit code to use if the test failed
/// </summary>
public const int DEFAULT_FAIL_EXITCODE = 50;
/// <summary>
/// The default exit code to use if the test passed
/// </summary>
public const int PASS_EXITCODE = 100;
private int m_numErrors = 0;
private int m_numTestcaseFailures = 0;
private int m_numTestcases = 0;
private int m_failExitCode = DEFAULT_FAIL_EXITCODE;
private bool m_failExitCodeSet = false;
private bool m_suppressStackOutput = false;
private bool m_outputExceptionMessages = false;
private List<Scenario> m_scenarioDescriptions = new List<Scenario>();
private System.IO.TextWriter m_outputWriter = Console.Out;
private class Scenario
{
public String Description;
public bool DescriptionPrinted;
public Scenario(string description)
{
Description = description;
DescriptionPrinted = false;
}
}
public void InitScenario(string scenarioDescription)
{
m_scenarioDescriptions.Clear();
m_scenarioDescriptions.Add(new Scenario(scenarioDescription));
}
public void PushScenario(string scenarioDescription)
{
m_scenarioDescriptions.Add(new Scenario(scenarioDescription));
}
public void PushScenario(string scenarioDescription, int maxScenarioDepth)
{
while (maxScenarioDepth < m_scenarioDescriptions.Count)
{
m_scenarioDescriptions.RemoveAt(m_scenarioDescriptions.Count - 1);
}
m_scenarioDescriptions.Add(new Scenario(scenarioDescription));
}
public int ScenarioDepth
{
get
{
return m_scenarioDescriptions.Count;
}
}
public void PopScenario()
{
if (0 < m_scenarioDescriptions.Count)
{
m_scenarioDescriptions.RemoveAt(m_scenarioDescriptions.Count - 1);
}
}
public void OutputDebugInfo(string debugInfo)
{
OutputMessage(debugInfo);
}
public void OutputDebugInfo(string format, params object[] args)
{
OutputDebugInfo(String.Format(format, args));
}
private void OutputMessage(string message)
{
if (0 < m_scenarioDescriptions.Count)
{
Scenario currentScenario = m_scenarioDescriptions[m_scenarioDescriptions.Count - 1];
if (!currentScenario.DescriptionPrinted)
{
m_outputWriter.WriteLine();
m_outputWriter.WriteLine();
m_outputWriter.WriteLine("**********************************************************************");
m_outputWriter.WriteLine("** {0,-64} **", "SCENARIO:");
for (int i = 0; i < m_scenarioDescriptions.Count; ++i)
{
m_outputWriter.WriteLine(m_scenarioDescriptions[i].Description);
}
m_outputWriter.WriteLine("**********************************************************************");
currentScenario.DescriptionPrinted = true;
}
}
m_outputWriter.WriteLine(message);
}
/// <summary>
/// If the expression is false writes the message to the console and increments the error count.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="message">The message to print to the console if the expression is false.</param>
/// <returns>true if expression is true else false.</returns>
public bool Eval(bool expression, string message)
{
if (!expression)
{
OutputMessage(message);
++m_numErrors;
Xunit.Assert.True(false, message);
//if(!_suppressStackOutput) {
// System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
// _outputWriter.WriteLine(stackTrace);
//}
m_outputWriter.WriteLine();
}
return expression;
}
/// <summary>
/// If the expression is false outputs the formatted message(String.Format(format, args)
/// and increments the error count.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if expression is true else false.</returns>
public bool Eval(bool expression, String format, params object[] args)
{
if (!expression)
{
return Eval(expression, String.Format(format, args));
}
return true;
}
/// <summary>
/// Compares expected and actual if expected and actual are differnet outputs
/// and increments the error count.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="errorMsg">The message to output.
/// Uses String.Format(errorMsg, expected, actual)</param>
/// <returns>true if expected and actual are equal else false.</returns>
public bool EvalFormatted<T>(T expected, T actual, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, String.Format(errorMsg, expected, actual));
return true;
}
/// <summary>
/// Compares expected and actual if expected and actual are differnet outputs the
/// error message and increments the error count.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="errorMsg">The message to output.</param>
/// <returns>true if expected and actual are equal else false.</returns>
public bool Eval<T>(T expected, T actual, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
public bool Eval<T>(IEqualityComparer<T> comparer, T expected, T actual, String errorMsg)
{
bool retValue = comparer.Equals(expected, actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
public bool Eval<T>(IComparer<T> comparer, T expected, T actual, String errorMsg)
{
bool retValue = 0 == comparer.Compare(expected, actual);
if (!retValue)
return Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
/// <summary>
/// Compares expected and actual if expected and actual are differnet outputs the
/// error message and increments the error count.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expected">The expected value.</param>
/// <param name="actual">The actual value.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if expected and actual are equal else false.</returns>
public bool Eval<T>(T expected, T actual, String format, params object[] args)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
return Eval(retValue, String.Format(format, args) +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return true;
}
/// <summary>
/// Runs a test scenario.
/// </summary>
/// <param name="test">The test testscenario to run.</param>
/// <returns>true if the test passed else false.</returns>
public bool RunTestScenario(TestScenario test)
{
bool retValue;
if (test())
{
m_numTestcases++;
retValue = true;
}
else
{
m_numTestcaseFailures++;
retValue = false;
}
m_outputWriter.WriteLine("");
return retValue;
}
/// <summary>
/// The number of failed test cases.
/// </summary>
/// <value>The number of failed test cases.</value>
public int NumberOfFailedTestcases
{
get
{
return m_numTestcaseFailures;
}
}
/// <summary>
/// The number of test cases.
/// </summary>
/// <value>The number of test cases.</value>
public int NumberOfTestcases
{
get
{
return m_numTestcases;
}
}
/// <summary>
/// The number of errors.
/// </summary>
/// <value>The number of errors.</value>
public int NumberOfErrors
{
get
{
return m_numErrors;
}
}
/// <summary>
/// The exit code to use if the test failed.
/// </summary>
/// <value>The exit code to use if the test failed.</value>
public int FailExitCode
{
get
{
return m_failExitCode;
}
set
{
m_failExitCodeSet = true;
m_failExitCode = value;
}
}
/// <summary>
/// The exit code to use.
/// </summary>
/// <value></value>
public int ExitCode
{
get
{
if (Pass)
return PASS_EXITCODE;
return m_failExitCode;
}
}
/// <summary>
/// If the fail exit code was set.
/// </summary>
/// <value>If the fail exit code was set.</value>
public bool IsFailExitCodeSet
{
get
{
return m_failExitCodeSet;
}
}
/// <summary>
/// Returns true if all test cases passed else false.
/// </summary>
/// <value>If all test cases passed else false.</value>
public bool Pass
{
get
{
return 0 == m_numErrors && 0 == m_numTestcaseFailures;
}
}
/// <summary>
/// Determines if the stack is inlcluded with the output
/// </summary>
/// <value>False to output the stack with every failure else true to suppress the stack output</value>
public bool SuppressStackOutput
{
get
{
return m_suppressStackOutput;
}
set
{
m_suppressStackOutput = value;
}
}
public bool OutputExceptionMessages
{
get
{
return m_outputExceptionMessages;
}
set
{
m_outputExceptionMessages = value;
}
}
public System.IO.TextWriter OutputWriter
{
get
{
return m_outputWriter;
}
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
m_outputWriter = value;
}
}
/// <summary>
/// Resets all of the counters.
/// </summary>
public void Reset()
{
m_numErrors = 0;
m_numTestcaseFailures = 0;
m_numTestcases = 0;
m_failExitCodeSet = false;
m_failExitCode = DEFAULT_FAIL_EXITCODE;
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type T.
/// </summary>
/// <typeparam name="T">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <returns>true if exceptionGenerator through an exception of type T else false.</returns>
public bool VerifyException<T>(ExceptionGenerator exceptionGenerator) where T : Exception
{
return VerifyException(typeof(T), exceptionGenerator);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type T.
/// </summary>
/// <typeparam name="T">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <param name="message">The message to output if the verification fails.</param>
/// <returns>true if exceptionGenerator through an exception of type T else false.</returns>
public bool VerifyException<T>(ExceptionGenerator exceptionGenerator, string message) where T : Exception
{
return VerifyException(typeof(T), exceptionGenerator, message);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type T.
/// </summary>
/// <typeparam name="T">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if exceptionGenerator through an exception of type T else false.</returns>
public bool VerifyException<T>(ExceptionGenerator exceptionGenerator, String format, params object[] args) where T : Exception
{
return VerifyException(typeof(T), exceptionGenerator, String.Format(format, args));
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType.
/// </summary>
/// <param name="expectedExceptionType"></param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of
/// type expectedExceptionType.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType else false.</returns>
public bool VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator)
{
return VerifyException(expectedExceptionType, exceptionGenerator, String.Empty);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType.
/// </summary>
/// <param name="expectedExceptionType">The type of the exception to throw.</typeparam>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type T.</param>
/// <param name="format">A String containing zero or more format items.</param>
/// <param name="args">An Object array containing zero or more objects to format.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType else false.</returns>
public bool VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator, String format, params object[] args)
{
return VerifyException(expectedExceptionType, exceptionGenerator, String.Format(format, args));
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType.
/// </summary>
/// <param name="expectedExceptionType"></param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of
/// type expectedExceptionType.</param>
/// <param name="message">The message to output if the verification fails.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType else false.</returns>
public bool VerifyException(Type expectedExceptionType, ExceptionGenerator exceptionGenerator, string message)
{
bool retValue = true;
try
{
exceptionGenerator();
retValue &= Eval(false, (String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_05940iedz Expected exception of the type {0} to be thrown and nothing was thrown",
expectedExceptionType);
}
catch (Exception exception)
{
retValue &= Eval<Type>(expectedExceptionType, exception.GetType(),
(String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_38223oipwj Expected exception and actual exception differ. Expected {0}, got \n{1}", expectedExceptionType, exception);
if (retValue && m_outputExceptionMessages)
{
OutputDebugInfo("{0} message: {1}" + Environment.NewLine, expectedExceptionType, exception.Message);
}
}
return retValue;
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType1
/// or expectedExceptionType2.
/// </summary>
/// <param name="expectedExceptionType1">The first exception type exceptionGenerator may throw.</param>
/// <param name="expectedExceptionType2">The second exception type exceptionGenerator may throw.</param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type
/// expectedExceptionType1 or expectedExceptionType2.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType1
/// of expectedExceptionType2 else false.</returns>
public bool VerifyException(Type expectedExceptionType1, Type expectedExceptionType2, ExceptionGenerator exceptionGenerator)
{
return VerifyException(new Type[] { expectedExceptionType1, expectedExceptionType2 }, exceptionGenerator);
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of type expectedExceptionType1
/// or expectedExceptionType2 or expectedExceptionType3.
/// </summary>
/// <param name="expectedExceptionType1">The first exception type exceptionGenerator may throw.</param>
/// <param name="expectedExceptionType2">The second exception type exceptionGenerator may throw.</param>
/// <param name="expectedExceptionType3">The third exception type exceptionGenerator may throw.</param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of type
/// expectedExceptionType1 or expectedExceptionType2 or expectedExceptionType3.</param>
/// <returns>true if exceptionGenerator through an exception of type expectedExceptionType1
/// or expectedExceptionType2 or expectedExceptionType3 else false.</returns>
public bool VerifyException(Type expectedExceptionType1, Type expectedExceptionType2,
Type expectedExceptionType3, ExceptionGenerator exceptionGenerator)
{
return VerifyException(new Type[] { expectedExceptionType1, expectedExceptionType2, expectedExceptionType3 }, exceptionGenerator);
}
public bool VerifyException(Type[] expectedExceptionTypes, ExceptionGenerator exceptionGenerator)
{
return VerifyException(expectedExceptionTypes, exceptionGenerator, string.Empty);
}
public bool VerifyException(Type[] expectedExceptionTypes, ExceptionGenerator exceptionGenerator, String format, params object[] args)
{
return VerifyException(expectedExceptionTypes, exceptionGenerator, String.Format(format, args));
}
/// <summary>
/// Verifies that exceptionGenerator throws an exception of one of types in expectedExceptionTypes.
/// </summary>
/// <param name="expectedExceptionTypes">An array of the expected exception type that exceptionGenerator may throw.</param>
/// <param name="exceptionGenerator">A delegate that is expected to throw and exception of
/// one of the types in expectedExceptionTypes.</param>
/// <returns>true if exceptionGenerator through an exception of one of types in
/// expectedExceptionTypes else false.</returns>
public bool VerifyException(Type[] expectedExceptionTypes, ExceptionGenerator exceptionGenerator, string message)
{
bool retValue = true;
bool exceptionNotThrown = false;
bool exceptionTypeInvalid = true;
Type exceptionType = null;
Exception exceptionInstance = null;
try
{
exceptionGenerator();
exceptionNotThrown = true;
}
catch (Exception exception)
{
exceptionType = exception.GetType();
exceptionInstance = exception;
for (int i = 0; i < expectedExceptionTypes.Length; ++i)
{
if (null != expectedExceptionTypes[i] && exceptionType == expectedExceptionTypes[i]) //null is not a valid exception type
exceptionTypeInvalid = false;
}
}
if (exceptionNotThrown || exceptionTypeInvalid)
{
System.Text.StringBuilder exceptionTypeNames = new System.Text.StringBuilder();
for (int i = 0; i < expectedExceptionTypes.Length; ++i)
{
if (null != expectedExceptionTypes[i])
{
exceptionTypeNames.Append(expectedExceptionTypes[i].ToString());
exceptionTypeNames.Append(" ");
}
}
if (exceptionNotThrown)
{
retValue &= Eval(false, (String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_51584ajied Expected exception of one of the following types to be thrown: {0} and nothing was thrown",
exceptionTypeNames.ToString());
}
else if (exceptionTypeInvalid)
{
retValue &= Eval(false, (String.IsNullOrEmpty(message) ? String.Empty : (message + Environment.NewLine)) +
"Err_51584ajied Expected exception of one of the following types to be thrown: {0} and the following was thrown:\n {1}",
exceptionTypeNames.ToString(), exceptionInstance.ToString());
}
}
return retValue;
}
[Obsolete]
public bool VerifyException(ExceptionGenerator exceptionGenerator, Type expectedExceptionType)
{
bool retValue = true;
try
{
exceptionGenerator();
retValue &= Eval(false, "Err_05940iedz Expected exception of the type {0} to be thrown and nothing was thrown",
expectedExceptionType);
}
catch (Exception exception)
{
retValue &= Eval<Type>(expectedExceptionType, exception.GetType(), "Err_38223oipwj Expected exception and actual exception differ");
}
return retValue;
}
}
public class ArrayUtils
{
/// <summary>
/// Creates array of the parameters.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array">The paramaters to create array from.</param>
/// <returns>An array of the parameters.</returns>
public static T[] Create<T>(params T[] array)
{
return array;
}
/// <summary>
/// Creates and sub array from array
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to create the sub array from.</param>
/// <param name="length">The length of the sub array.</param>
/// <returns>A sub array from array starting at 0 with a length of length.</returns>
public static V[] SubArray<V>(V[] array, int length)
{
return SubArray(array, 0, length);
}
/// <summary>
/// Creates and sub array from array
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to create the sub array from.</param>
/// <param name="startIndex">The start index of the sub array.</param>
/// <param name="length">The length of the sub array.</param>
/// <returns></returns>
public static V[] SubArray<V>(V[] array, int startIndex, int length)
{
V[] tempArray = new V[length];
Array.Copy(array, startIndex, tempArray, 0, length);
return tempArray;
}
/// <summary>
/// Remove item from array.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to remove the item from.</param>
/// <param name="item">The item to remove from the array.</param>
/// <returns>The array with the item removed.</returns>
public static V[] RemoveItem<V>(V[] array, V item)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i].Equals(item))
{
return RemoveAt(array, i);
}
}
return array;
}
/// <summary>
/// Remove item at index from array.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to remove the item from.</param>
/// <param name="index">The index of the item to remove from the array.</param>
/// <returns></returns>
public static V[] RemoveAt<V>(V[] array, int index)
{
V[] tempArray = new V[array.Length - 1];
Array.Copy(array, 0, tempArray, 0, index);
Array.Copy(array, index + 1, tempArray, index, array.Length - index - 1);
return tempArray;
}
public static V[] RemoveRange<V>(V[] array, int startIndex, int count)
{
V[] tempArray = new V[array.Length - count];
Array.Copy(array, 0, tempArray, 0, startIndex);
Array.Copy(array, startIndex + count, tempArray, startIndex, tempArray.Length - startIndex);
return tempArray;
}
public static V[] CopyRanges<V>(V[] array, int startIndex1, int count1, int startIndex2, int count2)
{
V[] tempArray = new V[count1 + count2];
Array.Copy(array, startIndex1, tempArray, 0, count1);
Array.Copy(array, startIndex2, tempArray, count1, count2);
return tempArray;
}
/// <summary>
/// Concatenates of of the items to the end of array1.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array1">The array to concatenate.</param>
/// <param name="array2">The items to concatonate to the end of array1.</param>
/// <returns>An array with all of the items from array1 followed by all of
/// the items from array2.</returns>
public static V[] Concat<V>(V[] array1, params V[] array2)
{
if (array1.Length == 0)
return array2;
if (array2.Length == 0)
return array1;
V[] tempArray = new V[array1.Length + array2.Length];
Array.Copy(array1, 0, tempArray, 0, array1.Length);
Array.Copy(array2, 0, tempArray, array1.Length, array2.Length);
return tempArray;
}
/// <summary>
/// Concatenates of of the items to the begining of array1.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array1">The array to concatenate.</param>
/// <param name="array2">The items to concatonate to the begining of array1.</param>
/// <returns>An array with all of the items from array2 followed by all of
/// the items from array1.</returns>
public static V[] Prepend<V>(V[] array1, params V[] array2)
{
if (array1.Length == 0)
return array2;
if (array2.Length == 0)
return array1;
V[] tempArray = new V[array1.Length + array2.Length];
Array.Copy(array2, 0, tempArray, 0, array2.Length);
Array.Copy(array1, 0, tempArray, array2.Length, array1.Length);
return tempArray;
}
/// <summary>
/// Rverses array.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to revers.</param>
/// <returns>A copy of array with the items reversed.</returns>
public static V[] Reverse<V>(V[] array)
{
return Reverse(array, 0, array.Length);
}
/// <summary>
/// Rverses length items in array starting at index.
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="array">The array to reverse.</param>
/// <param name="index">The index to start reversing items at.</param>
/// <param name="length">The number of items to revers</param>
/// <returns>A copy of array with length items reversed starting at index.</returns>
public static V[] Reverse<V>(V[] array, int index, int length)
{
if (array.Length < 2)
return array;
V[] tempArray = new V[array.Length];
Array.Copy(array, 0, tempArray, 0, array.Length);
Array.Reverse(tempArray, index, length);
return tempArray;
}
/// <summary>
/// Creates an array with a length of size and fills it with the items
/// returned from generatedItem.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="size">The size of the array to create and fill.</param>
/// <param name="generateItem">Returns the items to place into the array.</param>
/// <returns>An array of length size with items returned from generateItem</returns>
public static T[] CreateAndFillArray<T>(int size, GenerateItem<T> generateItem)
{
return FillArray<T>(new T[size], generateItem);
}
/// <summary>
/// Fills array with items returned from generateItem.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array">The array to to place the items in.</param>
/// <param name="generateItem">Returns the items to place into the array.</param>
/// <returns>The array with the items in it returned from generateItem.</returns>
public static T[] FillArray<T>(T[] array, GenerateItem<T> generateItem)
{
int arrayLength = array.Length;
for (int i = 0; i < arrayLength; ++i)
array[i] = generateItem();
return array;
}
}
}
}
| 42.78617 | 152 | 0.529973 | [
"MIT"
] | bpschoch/corefx | src/System.Collections/tests/Generic/Common/TestSupport.cs | 40,219 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _06_RemoveNumbersByOddOccurence
{
class RemoveNumbersByOddOccurence
{
static void Main(string[] args)
{
var listOfNumbers = new List<int>() { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 };
var newList = listOfNumbers.Distinct().ToList();
foreach (var num in newList)
{
if (listOfNumbers.Where(n => n == num).Count() % 2 != 0)
{
listOfNumbers.RemoveAll(n => n == num);
}
}
Console.WriteLine(string.Join(", ", listOfNumbers));
}
}
}
| 26 | 84 | 0.510355 | [
"MIT"
] | alekhristov/TelerikAcademyAlpha | 02-Module2/01-DSA/03-LinearDataStructuresGitLabHW/06-RemoveNumbersByOddOccurence/06-RemoveNumbersByOddOccurence.cs | 678 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>A2A specific policy details.</summary>
public partial class A2APolicyDetails :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IA2APolicyDetails,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IA2APolicyDetailsInternal,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IValidates
{
/// <summary>
/// Backing field for Inherited model <see cref= "Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IPolicyProviderSpecificDetails"
/// />
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IPolicyProviderSpecificDetails __policyProviderSpecificDetails = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.PolicyProviderSpecificDetails();
/// <summary>Backing field for <see cref="AppConsistentFrequencyInMinute" /> property.</summary>
private int? _appConsistentFrequencyInMinute;
/// <summary>The app consistent snapshot frequency in minutes.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public int? AppConsistentFrequencyInMinute { get => this._appConsistentFrequencyInMinute; set => this._appConsistentFrequencyInMinute = value; }
/// <summary>Backing field for <see cref="CrashConsistentFrequencyInMinute" /> property.</summary>
private int? _crashConsistentFrequencyInMinute;
/// <summary>The crash consistent snapshot frequency in minutes.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public int? CrashConsistentFrequencyInMinute { get => this._crashConsistentFrequencyInMinute; set => this._crashConsistentFrequencyInMinute = value; }
/// <summary>Gets the class type. Overridden in derived classes.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inherited)]
public string InstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IPolicyProviderSpecificDetailsInternal)__policyProviderSpecificDetails).InstanceType; }
/// <summary>Internal Acessors for InstanceType</summary>
string Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IPolicyProviderSpecificDetailsInternal.InstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IPolicyProviderSpecificDetailsInternal)__policyProviderSpecificDetails).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IPolicyProviderSpecificDetailsInternal)__policyProviderSpecificDetails).InstanceType = value; }
/// <summary>Backing field for <see cref="MultiVMSyncStatus" /> property.</summary>
private string _multiVMSyncStatus;
/// <summary>A value indicating whether multi-VM sync has to be enabled.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public string MultiVMSyncStatus { get => this._multiVMSyncStatus; set => this._multiVMSyncStatus = value; }
/// <summary>Backing field for <see cref="RecoveryPointHistory" /> property.</summary>
private int? _recoveryPointHistory;
/// <summary>The duration in minutes until which the recovery points need to be stored.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public int? RecoveryPointHistory { get => this._recoveryPointHistory; set => this._recoveryPointHistory = value; }
/// <summary>Backing field for <see cref="RecoveryPointThresholdInMinute" /> property.</summary>
private int? _recoveryPointThresholdInMinute;
/// <summary>The recovery point threshold in minutes.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
public int? RecoveryPointThresholdInMinute { get => this._recoveryPointThresholdInMinute; set => this._recoveryPointThresholdInMinute = value; }
/// <summary>Creates an new <see cref="A2APolicyDetails" /> instance.</summary>
public A2APolicyDetails()
{
}
/// <summary>Validates that this object meets the validation criteria.</summary>
/// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IEventListener" /> instance that will receive validation
/// events.</param>
/// <returns>
/// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed.
/// </returns>
public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IEventListener eventListener)
{
await eventListener.AssertNotNull(nameof(__policyProviderSpecificDetails), __policyProviderSpecificDetails);
await eventListener.AssertObjectIsValid(nameof(__policyProviderSpecificDetails), __policyProviderSpecificDetails);
}
}
/// A2A specific policy details.
public partial interface IA2APolicyDetails :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IJsonSerializable,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IPolicyProviderSpecificDetails
{
/// <summary>The app consistent snapshot frequency in minutes.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The app consistent snapshot frequency in minutes.",
SerializedName = @"appConsistentFrequencyInMinutes",
PossibleTypes = new [] { typeof(int) })]
int? AppConsistentFrequencyInMinute { get; set; }
/// <summary>The crash consistent snapshot frequency in minutes.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The crash consistent snapshot frequency in minutes.",
SerializedName = @"crashConsistentFrequencyInMinutes",
PossibleTypes = new [] { typeof(int) })]
int? CrashConsistentFrequencyInMinute { get; set; }
/// <summary>A value indicating whether multi-VM sync has to be enabled.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"A value indicating whether multi-VM sync has to be enabled.",
SerializedName = @"multiVmSyncStatus",
PossibleTypes = new [] { typeof(string) })]
string MultiVMSyncStatus { get; set; }
/// <summary>The duration in minutes until which the recovery points need to be stored.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The duration in minutes until which the recovery points need to be stored.",
SerializedName = @"recoveryPointHistory",
PossibleTypes = new [] { typeof(int) })]
int? RecoveryPointHistory { get; set; }
/// <summary>The recovery point threshold in minutes.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The recovery point threshold in minutes.",
SerializedName = @"recoveryPointThresholdInMinutes",
PossibleTypes = new [] { typeof(int) })]
int? RecoveryPointThresholdInMinute { get; set; }
}
/// A2A specific policy details.
internal partial interface IA2APolicyDetailsInternal :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IPolicyProviderSpecificDetailsInternal
{
/// <summary>The app consistent snapshot frequency in minutes.</summary>
int? AppConsistentFrequencyInMinute { get; set; }
/// <summary>The crash consistent snapshot frequency in minutes.</summary>
int? CrashConsistentFrequencyInMinute { get; set; }
/// <summary>A value indicating whether multi-VM sync has to be enabled.</summary>
string MultiVMSyncStatus { get; set; }
/// <summary>The duration in minutes until which the recovery points need to be stored.</summary>
int? RecoveryPointHistory { get; set; }
/// <summary>The recovery point threshold in minutes.</summary>
int? RecoveryPointThresholdInMinute { get; set; }
}
} | 64.364286 | 455 | 0.711353 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Migrate/generated/api/Models/Api20180110/A2APolicyDetails.cs | 8,872 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
// This file was automatically generated by the UpdateVendors tool.
//------------------------------------------------------------------------------
// dnlib: See LICENSE.txt for more info
using System;
using Datadog.Trace.Vendors.dnlib.IO;
namespace Datadog.Trace.Vendors.dnlib.PE {
/// <summary>
/// Represents the IMAGE_NT_HEADERS PE section
/// </summary>
internal sealed class ImageNTHeaders : FileSection {
readonly uint signature;
readonly ImageFileHeader imageFileHeader;
readonly IImageOptionalHeader imageOptionalHeader;
/// <summary>
/// Returns the IMAGE_NT_HEADERS.Signature field
/// </summary>
public uint Signature => signature;
/// <summary>
/// Returns the IMAGE_NT_HEADERS.FileHeader field
/// </summary>
public ImageFileHeader FileHeader => imageFileHeader;
/// <summary>
/// Returns the IMAGE_NT_HEADERS.OptionalHeader field
/// </summary>
public IImageOptionalHeader OptionalHeader => imageOptionalHeader;
/// <summary>
/// Constructor
/// </summary>
/// <param name="reader">PE file reader pointing to the start of this section</param>
/// <param name="verify">Verify section</param>
/// <exception cref="BadImageFormatException">Thrown if verification fails</exception>
public ImageNTHeaders(ref DataReader reader, bool verify) {
SetStartOffset(ref reader);
signature = reader.ReadUInt32();
// Mono only checks the low 2 bytes
if (verify && (ushort)signature != 0x4550)
throw new BadImageFormatException("Invalid NT headers signature");
imageFileHeader = new ImageFileHeader(ref reader, verify);
imageOptionalHeader = CreateImageOptionalHeader(ref reader, verify);
SetEndoffset(ref reader);
}
/// <summary>
/// Creates an IImageOptionalHeader
/// </summary>
/// <param name="reader">PE file reader pointing to the start of the optional header</param>
/// <param name="verify">Verify section</param>
/// <returns>The created IImageOptionalHeader</returns>
/// <exception cref="BadImageFormatException">Thrown if verification fails</exception>
IImageOptionalHeader CreateImageOptionalHeader(ref DataReader reader, bool verify) {
ushort magic = reader.ReadUInt16();
reader.Position -= 2;
return magic switch {
0x010B => new ImageOptionalHeader32(ref reader, imageFileHeader.SizeOfOptionalHeader, verify),
0x020B => new ImageOptionalHeader64(ref reader, imageFileHeader.SizeOfOptionalHeader, verify),
_ => throw new BadImageFormatException("Invalid optional header magic"),
};
}
}
}
| 38.130435 | 98 | 0.689472 | [
"Apache-2.0"
] | theletterf/signalfx-dotnet-tracing | tracer/src/Datadog.Trace/Vendors/dnlib/PE/ImageNTHeaders.cs | 2,631 | C# |
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Screna;
namespace Captura.Models
{
// ReSharper disable once ClassNeverInstantiated.Global
public class ImgurWriter : NotifyPropertyChanged, IImageWriterItem
{
readonly DiskWriter _diskWriter;
readonly ISystemTray _systemTray;
readonly IMessageProvider _messageProvider;
readonly Settings _settings;
readonly LanguageManager _loc;
readonly IRecentList _recentList;
readonly IIconSet _icons;
public ImgurWriter(DiskWriter DiskWriter,
ISystemTray SystemTray,
IMessageProvider MessageProvider,
Settings Settings,
LanguageManager LanguageManager,
IRecentList RecentList,
IIconSet Icons)
{
_diskWriter = DiskWriter;
_systemTray = SystemTray;
_messageProvider = MessageProvider;
_settings = Settings;
_loc = LanguageManager;
_recentList = RecentList;
_icons = Icons;
LanguageManager.LanguageChanged += L => RaisePropertyChanged(nameof(Display));
}
public async Task Save(Bitmap Image, ImageFormat Format, string FileName)
{
var response = await Save(Image, Format);
switch (response)
{
case ImgurUploadResponse uploadResponse:
var link = uploadResponse.Data.Link;
var deleteHash = uploadResponse.Data.DeleteHash;
_recentList.Add(new ImgurRecentItem(link, deleteHash));
// Copy path to clipboard only when clipboard writer is off
if (_settings.CopyOutPathToClipboard && !ServiceProvider.Get<ClipboardWriter>().Active)
link.WriteToClipboard();
break;
case Exception e:
if (!_diskWriter.Active)
{
ServiceProvider.Get<IMainWindow>().IsVisible = true;
var yes = _messageProvider.ShowYesNo(
$"{_loc.ImgurFailed}\n{e.Message}\n\nDo you want to Save to Disk?", "Imgur Upload Failed");
if (yes)
await _diskWriter.Save(Image, Format, FileName);
}
break;
}
}
public async Task DeleteUploadedFile(string DeleteHash)
{
var request = WebRequest.Create($"https://api.imgur.com/3/image/{DeleteHash}");
request.Proxy = _settings.Proxy.GetWebProxy();
request.Headers.Add("Authorization", await GetAuthorizationHeader());
request.Method = "DELETE";
var stream = (await request.GetResponseAsync()).GetResponseStream();
if (stream != null)
{
var reader = new StreamReader(stream);
var text = await reader.ReadToEndAsync();
var res = JsonConvert.DeserializeObject<ImgurResponse>(text);
if (res.Success)
return;
}
throw new Exception();
}
async Task<string> GetAuthorizationHeader()
{
if (_settings.Imgur.Anonymous)
{
return $"Client-ID {ApiKeys.ImgurClientId}";
}
if (string.IsNullOrWhiteSpace(_settings.Imgur.AccessToken))
{
throw new Exception("Not logged in to Imgur");
}
if (_settings.Imgur.IsExpired())
{
if (!await RefreshToken())
{
throw new Exception("Failed to Refresh Imgur token");
}
}
return $"Bearer {_settings.Imgur.AccessToken}";
}
// Returns ImgurUploadResponse on success, Exception on failure
public async Task<object> Save(Bitmap Image, ImageFormat Format)
{
var progressItem = new ImgurNotification();
_systemTray.ShowNotification(progressItem);
using (var w = new WebClient { Proxy = _settings.Proxy.GetWebProxy() })
{
w.UploadProgressChanged += (S, E) =>
{
progressItem.Progress = E.ProgressPercentage;
};
try
{
w.Headers.Add("Authorization", await GetAuthorizationHeader());
}
catch (Exception e)
{
return e;
}
NameValueCollection values;
using (var ms = new MemoryStream())
{
Image.Save(ms, Format);
values = new NameValueCollection
{
{ "image", Convert.ToBase64String(ms.ToArray()) }
};
}
ImgurUploadResponse uploadResponse;
try
{
uploadResponse = await UploadValuesAsync<ImgurUploadResponse>(w, "https://api.imgur.com/3/upload.json", values);
if (!uploadResponse.Success)
{
throw new Exception("Response indicates Failure");
}
}
catch (Exception e)
{
progressItem.RaiseFailed();
return e;
}
var link = uploadResponse.Data.Link;
progressItem.RaiseFinished(link);
return uploadResponse;
}
}
static async Task<T> UploadValuesAsync<T>(WebClient WebClient, string Url, NameValueCollection Values)
{
// Task.Run done to prevent UI thread from freezing when upload fails.
var response = await Task.Run(async () => await WebClient.UploadValuesTaskAsync(Url, Values));
return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(response));
}
public void Authorize()
{
// response_type should be token, other types have been deprecated.
// access_token and refresh_token will be available in query string parameters attached to redirect URL entered during registration.
// eg: http://example.com#access_token=ACCESS_TOKEN&token_type=Bearer&expires_in=3600
// currently unable to retrieve them.
Process.Start($"https://api.imgur.com/oauth2/authorize?response_type=token&client_id={ApiKeys.ImgurClientId}");
}
public async Task<bool> RefreshToken()
{
var args = new NameValueCollection
{
{ "refresh_token", _settings.Imgur.RefreshToken },
{ "client_id", ApiKeys.ImgurClientId },
{ "client_secret", ApiKeys.ImgurSecret },
{ "grant_type", "refresh_token" }
};
using (var w = new WebClient { Proxy = _settings.Proxy.GetWebProxy() })
{
var token = await UploadValuesAsync<ImgurRefreshTokenResponse>(w, "https://api.imgur.com/oauth2/token.json", args);
if (string.IsNullOrEmpty(token?.AccessToken))
return false;
_settings.Imgur.AccessToken = token.AccessToken;
_settings.Imgur.RefreshToken = token.RefreshToken;
_settings.Imgur.ExpiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(token.ExpiresIn);
return true;
}
}
public string Display => "Imgur";
bool _active;
public bool Active
{
get => _active;
set
{
_active = value;
OnPropertyChanged();
}
}
public override string ToString() => Display;
}
}
| 33.651639 | 144 | 0.535867 | [
"MIT"
] | ClsTe/CapturaKorean | src/Captura.Core/Models/ImageWriterItems/ImgurWriter.cs | 8,213 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Devices.Bluetooth.Background
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class BluetoothLEAdvertisementWatcherTriggerDetails
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::System.Collections.Generic.IReadOnlyList<global::Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementReceivedEventArgs> Advertisements
{
get
{
throw new global::System.NotImplementedException("The member IReadOnlyList<BluetoothLEAdvertisementReceivedEventArgs> BluetoothLEAdvertisementWatcherTriggerDetails.Advertisements is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Devices.Bluetooth.BluetoothError Error
{
get
{
throw new global::System.NotImplementedException("The member BluetoothError BluetoothLEAdvertisementWatcherTriggerDetails.Error is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Devices.Bluetooth.BluetoothSignalStrengthFilter SignalStrengthFilter
{
get
{
throw new global::System.NotImplementedException("The member BluetoothSignalStrengthFilter BluetoothLEAdvertisementWatcherTriggerDetails.SignalStrengthFilter is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.Devices.Bluetooth.Background.BluetoothLEAdvertisementWatcherTriggerDetails.Error.get
// Forced skipping of method Windows.Devices.Bluetooth.Background.BluetoothLEAdvertisementWatcherTriggerDetails.Advertisements.get
// Forced skipping of method Windows.Devices.Bluetooth.Background.BluetoothLEAdvertisementWatcherTriggerDetails.SignalStrengthFilter.get
}
}
| 44.422222 | 212 | 0.797399 | [
"Apache-2.0"
] | AlexTrepanier/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Bluetooth.Background/BluetoothLEAdvertisementWatcherTriggerDetails.cs | 1,999 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/wingdi.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public unsafe partial struct OUTLINETEXTMETRICA
{
[NativeTypeName("UINT")]
public uint otmSize;
public TEXTMETRICA otmTextMetrics;
[NativeTypeName("BYTE")]
public byte otmFiller;
public PANOSE otmPanoseNumber;
[NativeTypeName("UINT")]
public uint otmfsSelection;
[NativeTypeName("UINT")]
public uint otmfsType;
public int otmsCharSlopeRise;
public int otmsCharSlopeRun;
public int otmItalicAngle;
[NativeTypeName("UINT")]
public uint otmEMSquare;
public int otmAscent;
public int otmDescent;
[NativeTypeName("UINT")]
public uint otmLineGap;
[NativeTypeName("UINT")]
public uint otmsCapEmHeight;
[NativeTypeName("UINT")]
public uint otmsXHeight;
public RECT otmrcFontBox;
public int otmMacAscent;
public int otmMacDescent;
[NativeTypeName("UINT")]
public uint otmMacLineGap;
[NativeTypeName("UINT")]
public uint otmusMinimumPPEM;
public POINT otmptSubscriptSize;
public POINT otmptSubscriptOffset;
public POINT otmptSuperscriptSize;
public POINT otmptSuperscriptOffset;
[NativeTypeName("UINT")]
public uint otmsStrikeoutSize;
public int otmsStrikeoutPosition;
public int otmsUnderscoreSize;
public int otmsUnderscorePosition;
[NativeTypeName("PSTR")]
public sbyte* otmpFamilyName;
[NativeTypeName("PSTR")]
public sbyte* otmpFaceName;
[NativeTypeName("PSTR")]
public sbyte* otmpStyleName;
[NativeTypeName("PSTR")]
public sbyte* otmpFullName;
}
}
| 23.066667 | 145 | 0.644509 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | sources/Interop/Windows/um/wingdi/OUTLINETEXTMETRICA.cs | 2,078 | C# |
namespace Coypu.Actions
{
public abstract class DriverAction : BrowserAction
{
protected readonly Driver Driver;
protected DriverAction(Driver driver, DriverScope scope, Options options)
: base(scope, options)
{
Driver = driver;
}
}
} | 24.230769 | 82 | 0.587302 | [
"MIT",
"Unlicense"
] | Jetski5822/coypu | src/Coypu/Actions/DriverAction.cs | 315 | 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("FacebookSharp.SQLiteProvider")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("FacebookSharp.SQLiteProvider")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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("e1ce4002-3f81-44dc-9ac7-448b75678528")]
// 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.081081 | 85 | 0.734322 | [
"BSD-3-Clause"
] | prabirshrestha/FacebookSharp | src/DotNet4/FacebookSharp.SQLiteProvider/Properties/AssemblyInfo.cs | 1,486 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/directmanipulation.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IDirectManipulationPrimaryContent" /> struct.</summary>
public static unsafe class IDirectManipulationPrimaryContentTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IDirectManipulationPrimaryContent" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IDirectManipulationPrimaryContent).GUID, Is.EqualTo(IID_IDirectManipulationPrimaryContent));
}
/// <summary>Validates that the <see cref="IDirectManipulationPrimaryContent" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IDirectManipulationPrimaryContent>(), Is.EqualTo(sizeof(IDirectManipulationPrimaryContent)));
}
/// <summary>Validates that the <see cref="IDirectManipulationPrimaryContent" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IDirectManipulationPrimaryContent).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IDirectManipulationPrimaryContent" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IDirectManipulationPrimaryContent), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IDirectManipulationPrimaryContent), Is.EqualTo(4));
}
}
}
}
| 41.307692 | 146 | 0.674581 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/directmanipulation/IDirectManipulationPrimaryContentTests.cs | 2,150 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Update.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.ValueGeneration;
#nullable enable
namespace Microsoft.EntityFrameworkCore.SqlServer.ValueGeneration.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqlServerSequenceHiLoValueGenerator<TValue> : HiLoValueGenerator<TValue>
{
private readonly IRawSqlCommandBuilder _rawSqlCommandBuilder;
private readonly ISqlServerUpdateSqlGenerator _sqlGenerator;
private readonly ISqlServerConnection _connection;
private readonly ISequence _sequence;
private readonly IDiagnosticsLogger<DbLoggerCategory.Database.Command> _commandLogger;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqlServerSequenceHiLoValueGenerator(
[NotNull] IRawSqlCommandBuilder rawSqlCommandBuilder,
[NotNull] ISqlServerUpdateSqlGenerator sqlGenerator,
[NotNull] SqlServerSequenceValueGeneratorState generatorState,
[NotNull] ISqlServerConnection connection,
[NotNull] IDiagnosticsLogger<DbLoggerCategory.Database.Command> commandLogger)
: base(generatorState)
{
_sequence = generatorState.Sequence;
_rawSqlCommandBuilder = rawSqlCommandBuilder;
_sqlGenerator = sqlGenerator;
_connection = connection;
_commandLogger = commandLogger;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override long GetNewLowValue()
=> (long)Convert.ChangeType(
_rawSqlCommandBuilder
.Build(_sqlGenerator.GenerateNextSequenceValueOperation(_sequence.Name, _sequence.Schema))
.ExecuteScalar(
new RelationalCommandParameterObject(
_connection,
parameterValues: null,
readerColumns: null,
context: null,
_commandLogger)),
typeof(long),
CultureInfo.InvariantCulture)!;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override async Task<long> GetNewLowValueAsync(CancellationToken cancellationToken = default)
=> (long)Convert.ChangeType(
await _rawSqlCommandBuilder
.Build(_sqlGenerator.GenerateNextSequenceValueOperation(_sequence.Name, _sequence.Schema))
.ExecuteScalarAsync(
new RelationalCommandParameterObject(
_connection,
parameterValues: null,
readerColumns: null,
context: null,
_commandLogger),
cancellationToken)
.ConfigureAwait(false),
typeof(long),
CultureInfo.InvariantCulture)!;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override bool GeneratesTemporaryValues
=> false;
}
}
| 54.504673 | 113 | 0.66118 | [
"Apache-2.0"
] | vitorelli/efcore | src/EFCore.SqlServer/ValueGeneration/Internal/SqlServerSequenceHiLoValueGenerator.cs | 5,832 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// NluDetectionOutput
/// </summary>
[DataContract]
public partial class NluDetectionOutput : IEquatable<NluDetectionOutput>
{
/// <summary>
/// Initializes a new instance of the <see cref="NluDetectionOutput" /> class.
/// </summary>
/// <param name="Intents">The detected intents..</param>
/// <param name="DialogActs">The detected dialog acts..</param>
public NluDetectionOutput(List<DetectedIntent> Intents = null, List<DetectedDialogAct> DialogActs = null)
{
this.Intents = Intents;
this.DialogActs = DialogActs;
}
/// <summary>
/// The detected intents.
/// </summary>
/// <value>The detected intents.</value>
[DataMember(Name="intents", EmitDefaultValue=false)]
public List<DetectedIntent> Intents { get; set; }
/// <summary>
/// The detected dialog acts.
/// </summary>
/// <value>The detected dialog acts.</value>
[DataMember(Name="dialogActs", EmitDefaultValue=false)]
public List<DetectedDialogAct> DialogActs { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class NluDetectionOutput {\n");
sb.Append(" Intents: ").Append(Intents).Append("\n");
sb.Append(" DialogActs: ").Append(DialogActs).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as NluDetectionOutput);
}
/// <summary>
/// Returns true if NluDetectionOutput instances are equal
/// </summary>
/// <param name="other">Instance of NluDetectionOutput to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(NluDetectionOutput other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Intents == other.Intents ||
this.Intents != null &&
this.Intents.SequenceEqual(other.Intents)
) &&
(
this.DialogActs == other.DialogActs ||
this.DialogActs != null &&
this.DialogActs.SequenceEqual(other.DialogActs)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Intents != null)
hash = hash * 59 + this.Intents.GetHashCode();
if (this.DialogActs != null)
hash = hash * 59 + this.DialogActs.GetHashCode();
return hash;
}
}
}
}
| 30.960526 | 113 | 0.521462 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/NluDetectionOutput.cs | 4,706 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Xml.Serialization;
namespace CodeTorch.Core
{
[Serializable]
public class GridGroupBySelectField : GridGroupByField
{
public GridAggregateFunction Aggregate { get; set; }
[TypeConverter("CodeTorch.Core.Design.DataCommandColumnTypeConverter,CodeTorch.Core.Design")]
public string FieldAlias { get; set; }
public string FormatString { get; set; }
public string HeaderText { get; set; }
public string HeaderValueSeparator { get; set; }
}
}
| 22.551724 | 101 | 0.691131 | [
"MIT"
] | EminentTechnology/CodeTorch | src/core/CodeTorch.Core/Grid/GridGroupBySelectField.cs | 656 | C# |
namespace SoftUniDi.Attributes
{
using System;
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field)]
public class NamedAttribute : Attribute
{
public NamedAttribute(string name)
{
this.Name = name;
}
public string Name { get; }
}
}
| 19.6875 | 73 | 0.615873 | [
"MIT"
] | DanielBankov/SoftUni | C# Fundamentals/C# OOP Advanced/06. Dependency Injection/02. Demo DI/DependencyInjection/SoftUniDi/Attributes/NamedAttribute.cs | 317 | C# |
//------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2020 Dassault Systèmes - CPE EMED
//
// 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 ds.enovia.common.constants;
using RestSharp;
using System.Collections.Generic;
namespace ds.enovia.service
{
public class EnoviaBaseRequest : RestRequest
{
public EnoviaBaseRequest(string _resource, string _tenant = null, string _securitycontext = null, string _csrftoken = null) : base(_resource)
{
SecurityContext = _securitycontext;
CSRFToken = _csrftoken;
Tenant = _tenant;
if (SecurityContext != null)
this.AddHeader(HttpRequestHeaders.SECURITY_CONTEXT, _securitycontext);
if (CSRFToken != null)
this.AddHeader(HttpRequestHeaders.ENO_CSRF_TOKEN, _csrftoken);
if (Tenant != null)
this.AddQueryParameter(HttpRequestParams.TENANT, _tenant);
}
public string SecurityContext { get; private set; }
public string Tenant { get; private set; }
public string CSRFToken { get; private set; }
public void AddQueryParameters(IDictionary<string, string> _queryParameters)
{
if (_queryParameters == null) return;
IEnumerator<KeyValuePair<string, string>> queryParamEnumerator = _queryParameters.GetEnumerator();
while (queryParamEnumerator.MoveNext())
{
KeyValuePair<string, string> queryParamPair = queryParamEnumerator.Current;
this.AddQueryParameter(queryParamPair.Key, queryParamPair.Value);
}
}
}
}
| 48.5 | 149 | 0.628522 | [
"MIT"
] | nogueiraantonio/3dx-ws-client-sdk | ds.enovia/service/EnoviaBaseRequest.cs | 2,913 | C# |
/*
* Prime Developer Trial
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Newtonsoft.Json.Converters;
namespace FactSet.SDK.WatchlistAPIforDigitalPortals.Client
{
/// <summary>
/// Formatter for 'date' openapi formats ss defined by full-date - RFC3339
/// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types
/// </summary>
public class OpenAPIDateConverter : IsoDateTimeConverter
{
/// <summary>
/// Initializes a new instance of the <see cref="OpenAPIDateConverter" /> class.
/// </summary>
public OpenAPIDateConverter()
{
// full-date = date-fullyear "-" date-month "-" date-mday
DateTimeFormat = "yyyy-MM-dd";
}
}
}
| 31.833333 | 109 | 0.66178 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/WatchlistAPIforDigitalPortals/v2/src/FactSet.SDK.WatchlistAPIforDigitalPortals/Client/OpenAPIDateConverter.cs | 955 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TrueCraft.Core.World
{
public interface IBiomeRepository
{
IBiomeProvider GetBiome(byte id);
IBiomeProvider GetBiome(double temperature, double rainfall, bool spawn);
void RegisterBiomeProvider(IBiomeProvider provider);
}
}
| 23.866667 | 81 | 0.740223 | [
"MIT"
] | mrj001/TrueCraft | TrueCraft.Core/World/IBiomeRepository.cs | 360 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace AspNet.Security.OAuth.Vimeo
{
public class VimeoTests : OAuthTests<VimeoAuthenticationOptions>
{
public VimeoTests(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper;
}
public override string DefaultScheme => VimeoAuthenticationDefaults.AuthenticationScheme;
protected internal override void RegisterAuthentication(AuthenticationBuilder builder)
{
builder.AddVimeo(options => ConfigureDefaults(builder, options));
}
[Theory]
[InlineData(ClaimTypes.NameIdentifier, "my-id")]
[InlineData("urn:vimeo:fullname", "John Smith")]
[InlineData("urn:vimeo:profileurl", "https://vimeo.local/JohnSmith")]
public async Task Can_Sign_In_Using_Vimeo(string claimType, string claimValue)
{
// Arrange
using var server = CreateTestServer();
// Act
var claims = await AuthenticateUserAsync(server);
// Assert
AssertClaim(claims, claimType, claimValue);
}
}
}
| 33.06383 | 98 | 0.687259 | [
"Apache-2.0"
] | AaqibAhamed/AspNet.Security.OAuth.Providers | test/AspNet.Security.OAuth.Providers.Tests/Vimeo/VimeoTests.cs | 1,556 | C# |
using System.Linq;
using ProGaudi.MsgPack.Light.Converters.Generation;
using Shouldly;
using Xunit;
namespace ProGaudi.MsgPack.Light.Tests.Generators.Discovery
{
public class Properties
{
[Fact]
public void SimpleTest()
{
var provider = new PropertyProvider();
provider.GetProperties(typeof(IC)).Select(x => x.Name).ShouldBe(new [] { "D" });
provider.GetProperties(typeof(IA)).Select(x => x.Name).ShouldBe(new [] { "D" });
provider.GetProperties(typeof(IB)).Select(x => x.Name).ShouldBe(new [] { "D" });
provider.GetProperties(typeof(A)).Select(x => x.Name).ShouldBe(new [] { "D" });
provider.GetProperties(typeof(B)).Select(x => x.Name).ShouldBe(new [] { "D" });
provider.GetProperties(typeof(C)).Select(x => x.Name).ShouldBe(new [] { "D" });
}
[Fact]
public void NewShouldBeReturned()
{
var provider = new PropertyProvider();
var properties = provider.GetProperties(typeof(ID));
properties.Select(x => x.Name).ShouldBe(new[] { "D" });
properties.Select(x => x.DeclaringType).ShouldBe(new[] {typeof(ID)});
}
[Fact]
public void Regression71()
{
var context = new MsgPackContext();
Should.NotThrow(() => context.GenerateAndRegisterMapConverter<IC, C>());
}
[Fact]
public void Regression70()
{
var context = new MsgPackContext();
Should.NotThrow(() => context.GenerateAndRegisterMapConverter<IC>());
}
public class C : B, IC
{
}
public class B : A, IB
{
}
public class A : IA
{
public string D { get; set; }
}
public interface IC : IB
{
}
public interface IB : IA
{
}
public interface IA
{
[MsgPackMapElement("T")]
string D { get; }
}
public interface ID : IA
{
new string D { get; }
}
}
}
| 26.097561 | 92 | 0.517757 | [
"MIT"
] | Szer/MsgPack.Light | tests/msgpack.light.tests/Generators/Discovery/Properties.cs | 2,142 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.PowerPointApi
{
/// <summary>
/// DispatchInterface SlideShowView
/// SupportByVersion PowerPoint, 9,10,11,12,14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744675.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface)]
public class SlideShowView : COMObject
{
#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(SlideShowView);
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 SlideShowView(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 SlideShowView(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 SlideShowView(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 SlideShowView(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 SlideShowView(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 SlideShowView(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SlideShowView() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SlideShowView(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746127.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public NetOffice.PowerPointApi.Application Application
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.PowerPointApi.Application>(this, "Application", NetOffice.PowerPointApi.Application.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744005.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16), ProxyResult]
public object Parent
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745645.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public Int32 Zoom
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "Zoom");
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744856.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public NetOffice.PowerPointApi.Slide Slide
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.PowerPointApi.Slide>(this, "Slide", NetOffice.PowerPointApi.Slide.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744941.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public NetOffice.PowerPointApi.Enums.PpSlideShowPointerType PointerType
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.PowerPointApi.Enums.PpSlideShowPointerType>(this, "PointerType");
}
set
{
Factory.ExecuteEnumPropertySet(this, "PointerType", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745272.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public NetOffice.PowerPointApi.Enums.PpSlideShowState State
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.PowerPointApi.Enums.PpSlideShowState>(this, "State");
}
set
{
Factory.ExecuteEnumPropertySet(this, "State", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff743896.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public NetOffice.OfficeApi.Enums.MsoTriState AcceleratorsEnabled
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.OfficeApi.Enums.MsoTriState>(this, "AcceleratorsEnabled");
}
set
{
Factory.ExecuteEnumPropertySet(this, "AcceleratorsEnabled", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745215.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public Single PresentationElapsedTime
{
get
{
return Factory.ExecuteSinglePropertyGet(this, "PresentationElapsedTime");
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746593.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public Single SlideElapsedTime
{
get
{
return Factory.ExecuteSinglePropertyGet(this, "SlideElapsedTime");
}
set
{
Factory.ExecuteValuePropertySet(this, "SlideElapsedTime", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744761.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public NetOffice.PowerPointApi.Slide LastSlideViewed
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.PowerPointApi.Slide>(this, "LastSlideViewed", NetOffice.PowerPointApi.Slide.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746290.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public NetOffice.PowerPointApi.Enums.PpSlideShowAdvanceMode AdvanceMode
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.PowerPointApi.Enums.PpSlideShowAdvanceMode>(this, "AdvanceMode");
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744312.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public NetOffice.PowerPointApi.ColorFormat PointerColor
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.PowerPointApi.ColorFormat>(this, "PointerColor", NetOffice.PowerPointApi.ColorFormat.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745856.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public NetOffice.OfficeApi.Enums.MsoTriState IsNamedShow
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.OfficeApi.Enums.MsoTriState>(this, "IsNamedShow");
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745076.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public string SlideShowName
{
get
{
return Factory.ExecuteStringPropertyGet(this, "SlideShowName");
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744575.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public Int32 CurrentShowPosition
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "CurrentShowPosition");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff743996.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public NetOffice.OfficeApi.Enums.MsoTriState MediaControlsVisible
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.OfficeApi.Enums.MsoTriState>(this, "MediaControlsVisible");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744165.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Single MediaControlsLeft
{
get
{
return Factory.ExecuteSinglePropertyGet(this, "MediaControlsLeft");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746549.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Single MediaControlsTop
{
get
{
return Factory.ExecuteSinglePropertyGet(this, "MediaControlsTop");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff743865.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Single MediaControlsWidth
{
get
{
return Factory.ExecuteSinglePropertyGet(this, "MediaControlsWidth");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744879.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Single MediaControlsHeight
{
get
{
return Factory.ExecuteSinglePropertyGet(this, "MediaControlsHeight");
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746368.aspx </remarks>
/// <param name="beginX">Single beginX</param>
/// <param name="beginY">Single beginY</param>
/// <param name="endX">Single endX</param>
/// <param name="endY">Single endY</param>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void DrawLine(Single beginX, Single beginY, Single endX, Single endY)
{
Factory.ExecuteMethod(this, "DrawLine", beginX, beginY, endX, endY);
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746340.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void EraseDrawing()
{
Factory.ExecuteMethod(this, "EraseDrawing");
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745022.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void First()
{
Factory.ExecuteMethod(this, "First");
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744036.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void Last()
{
Factory.ExecuteMethod(this, "Last");
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746314.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void Next()
{
Factory.ExecuteMethod(this, "Next");
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745842.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void Previous()
{
Factory.ExecuteMethod(this, "Previous");
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746743.aspx </remarks>
/// <param name="index">Int32 index</param>
/// <param name="resetSlide">optional NetOffice.OfficeApi.Enums.MsoTriState ResetSlide = -1</param>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void GotoSlide(Int32 index, object resetSlide)
{
Factory.ExecuteMethod(this, "GotoSlide", index, resetSlide);
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746743.aspx </remarks>
/// <param name="index">Int32 index</param>
[CustomMethod]
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void GotoSlide(Int32 index)
{
Factory.ExecuteMethod(this, "GotoSlide", index);
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745384.aspx </remarks>
/// <param name="slideShowName">string slideShowName</param>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void GotoNamedShow(string slideShowName)
{
Factory.ExecuteMethod(this, "GotoNamedShow", slideShowName);
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744143.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void EndNamedShow()
{
Factory.ExecuteMethod(this, "EndNamedShow");
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745898.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void ResetSlideTime()
{
Factory.ExecuteMethod(this, "ResetSlideTime");
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745742.aspx </remarks>
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void Exit()
{
Factory.ExecuteMethod(this, "Exit");
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="pTracker">NetOffice.PowerPointApi.MouseTracker pTracker</param>
/// <param name="presenter">NetOffice.OfficeApi.Enums.MsoTriState presenter</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersion("PowerPoint", 9,10,11,12,14,15,16)]
public void InstallTracker(NetOffice.PowerPointApi.MouseTracker pTracker, NetOffice.OfficeApi.Enums.MsoTriState presenter)
{
Factory.ExecuteMethod(this, "InstallTracker", pTracker, presenter);
}
/// <summary>
/// SupportByVersion PowerPoint 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745994.aspx </remarks>
/// <param name="index">Int32 index</param>
[SupportByVersion("PowerPoint", 12,14,15,16)]
public void GotoClick(Int32 index)
{
Factory.ExecuteMethod(this, "GotoClick", index);
}
/// <summary>
/// SupportByVersion PowerPoint 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745129.aspx </remarks>
[SupportByVersion("PowerPoint", 12,14,15,16)]
public Int32 GetClickIndex()
{
return Factory.ExecuteInt32MethodGet(this, "GetClickIndex");
}
/// <summary>
/// SupportByVersion PowerPoint 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744635.aspx </remarks>
[SupportByVersion("PowerPoint", 12,14,15,16)]
public Int32 GetClickCount()
{
return Factory.ExecuteInt32MethodGet(this, "GetClickCount");
}
/// <summary>
/// SupportByVersion PowerPoint 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745143.aspx </remarks>
[SupportByVersion("PowerPoint", 12,14,15,16)]
public bool FirstAnimationIsAutomatic()
{
return Factory.ExecuteBoolMethodGet(this, "FirstAnimationIsAutomatic");
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746401.aspx </remarks>
/// <param name="shapeId">object shapeId</param>
[SupportByVersion("PowerPoint", 14,15,16)]
public NetOffice.PowerPointApi.Player Player(object shapeId)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.PowerPointApi.Player>(this, "Player", NetOffice.PowerPointApi.Player.LateBindingApiWrapperType, shapeId);
}
#endregion
#pragma warning restore
}
}
| 33.05082 | 174 | 0.685085 | [
"MIT"
] | DominikPalo/NetOffice | Source/PowerPoint/DispatchInterfaces/SlideShowView.cs | 20,163 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Xml;
using Microsoft.Build.Construction;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Tests for the ProjectTaskElement class
/// </summary>
public class ProjectTaskElement_Tests
{
/// <summary>
/// Read task with no parameters
/// </summary>
[Fact]
public void ReadNoParameters()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1/>
</Target>
</Project>
";
ProjectTaskElement task = GetTaskFromContent(content);
var parameters = Helpers.MakeDictionary(task.Parameters);
Assert.Equal("t1", task.Name);
Assert.Equal(0, parameters.Count);
Assert.Equal(0, Helpers.Count(task.Outputs));
Assert.Equal(String.Empty, task.ContinueOnError);
}
/// <summary>
/// Read task with continue on error
/// </summary>
[Fact]
public void ReadContinueOnError()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1 ContinueOnError='coe'/>
</Target>
</Project>
";
ProjectTaskElement task = GetTaskFromContent(content);
Assert.Equal("coe", task.ContinueOnError);
}
/// <summary>
/// Read task with condition
/// </summary>
[Fact]
public void ReadCondition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1 Condition='c'/>
</Target>
</Project>
";
ProjectTaskElement task = GetTaskFromContent(content);
Assert.Equal("c", task.Condition);
}
/// <summary>
/// Read task with invalid child
/// </summary>
[Fact]
public void ReadInvalidChild()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<X/>
</t1>
</Target>
</Project>
";
GetTaskFromContent(content);
}
);
}
/// <summary>
/// Read task with empty parameter.
/// Although MSBuild does not set these on tasks, they
/// are visible in the XML objects for editing purposes.
/// </summary>
[Fact]
public void ReadEmptyParameter()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1 p1='' />
</Target>
</Project>
";
ProjectTaskElement task = GetTaskFromContent(content);
var parameters = Helpers.MakeDictionary(task.Parameters);
Assert.Equal(1, parameters.Count);
}
/// <summary>
/// Read task with parameters
/// </summary>
[Fact]
public void ReadParameters()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1 p1='v1' p2='v2' />
</Target>
</Project>
";
ProjectTaskElement task = GetTaskFromContent(content);
var parameters = Helpers.MakeDictionary(task.Parameters);
Assert.Equal(2, parameters.Count);
Assert.Equal("v1", parameters["p1"]);
Assert.Equal("v2", parameters["p2"]);
Assert.Equal("v1", task.GetParameter("p1"));
Assert.Equal(String.Empty, task.GetParameter("xxxx"));
}
/// <summary>
/// Change a parameter value on the task
/// </summary>
[Fact]
public void SetParameterValue()
{
ProjectTaskElement task = GetBasicTask();
Helpers.ClearDirtyFlag(task.ContainingProject);
task.SetParameter("p1", "v1b");
var parameters = Helpers.MakeDictionary(task.Parameters);
Assert.Equal("v1b", parameters["p1"]);
Assert.Equal(true, task.ContainingProject.HasUnsavedChanges);
}
/// <summary>
/// Set a parameter to null
/// </summary>
[Fact]
public void SetInvalidNullParameterValue()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectTaskElement task = GetBasicTask();
task.SetParameter("p1", null);
}
);
}
/// <summary>
/// Set a parameter with the reserved name 'continueonerror'
/// </summary>
[Fact]
public void SetInvalidParameterNameContinueOnError()
{
Assert.Throws<ArgumentException>(() =>
{
ProjectTaskElement task = GetBasicTask();
task.SetParameter("ContinueOnError", "v");
}
);
}
/// <summary>
/// Set a parameter with the reserved name 'condition'
/// </summary>
[Fact]
public void SetInvalidParameterNameCondition()
{
Assert.Throws<ArgumentException>(() =>
{
ProjectTaskElement task = GetBasicTask();
task.SetParameter("Condition", "c");
}
);
}
/// <summary>
/// Set a parameter using a null name
/// </summary>
[Fact]
public void SetInvalidNullParameterName()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectTaskElement task = GetBasicTask();
task.SetParameter(null, "v1");
}
);
}
/// <summary>
/// Add a parameter to the task
/// </summary>
[Fact]
public void SetNotExistingParameter()
{
ProjectTaskElement task = GetBasicTask();
Helpers.ClearDirtyFlag(task.ContainingProject);
task.SetParameter("p2", "v2");
var parameters = Helpers.MakeDictionary(task.Parameters);
Assert.Equal("v2", parameters["p2"]);
Assert.Equal(true, task.ContainingProject.HasUnsavedChanges);
}
/// <summary>
/// Remove a parameter from the task
/// </summary>
[Fact]
public void RemoveExistingParameter()
{
ProjectTaskElement task = GetBasicTask();
Helpers.ClearDirtyFlag(task.ContainingProject);
task.RemoveParameter("p1");
var parameters = Helpers.MakeDictionary(task.Parameters);
Assert.Equal(0, parameters.Count);
Assert.Equal(true, task.ContainingProject.HasUnsavedChanges);
}
/// <summary>
/// Remove a parameter that is not on the task
/// </summary>
/// <remarks>
/// This should not throw.
/// </remarks>
[Fact]
public void RemoveNonExistingParameter()
{
ProjectTaskElement task = GetBasicTask();
task.RemoveParameter("XX");
var parameters = Helpers.MakeDictionary(task.Parameters);
Assert.Equal(1, parameters.Count);
}
/// <summary>
/// Set continue on error
/// </summary>
[Fact]
public void SetContinueOnError()
{
ProjectRootElement project = ProjectRootElement.Create();
ProjectTaskElement task = project.AddTarget("t").AddTask("tt");
Helpers.ClearDirtyFlag(task.ContainingProject);
task.ContinueOnError = "true";
Assert.Equal("true", task.ContinueOnError);
Assert.Equal(true, project.HasUnsavedChanges);
}
/// <summary>
/// Set condition
/// </summary>
[Fact]
public void SetCondition()
{
ProjectRootElement project = ProjectRootElement.Create();
ProjectTaskElement task = project.AddTarget("t").AddTask("tt");
Helpers.ClearDirtyFlag(task.ContainingProject);
task.Condition = "c";
Assert.Equal("c", task.Condition);
Assert.Equal(true, project.HasUnsavedChanges);
}
/// <summary>
/// Helper to return the first ProjectTaskElement from the parsed project content provided
/// </summary>
private static ProjectTaskElement GetTaskFromContent(string content)
{
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
return (ProjectTaskElement)Helpers.GetFirst(target.Children);
}
/// <summary>
/// Get a basic ProjectTaskElement with one parameter p1
/// </summary>
private static ProjectTaskElement GetBasicTask()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1 p1='v1' />
</Target>
</Project>
";
ProjectTaskElement task = GetTaskFromContent(content);
return task;
}
}
}
| 31.993921 | 112 | 0.510925 | [
"MIT"
] | AaronRobinsonMSFT/msbuild | src/Build.OM.UnitTests/Construction/ProjectTaskElement_Tests.cs | 10,526 | C# |
namespace Aspose.Slides.Web.API.Clients.Enums
{
/// <summary>
/// Slides conversion formats.
/// </summary>
public enum SlidesConversionFormats
{
/// <summary>
/// ODP format
/// </summary>
odp,
/// <summary>
/// OTP format
/// </summary>
otp,
/// <summary>
/// PPTX format
/// </summary>
pptx,
/// <summary>
/// PPTM format
/// </summary>
pptm,
/// <summary>
/// POTX format
/// </summary>
potx,
/// <summary>
/// PPT format
/// </summary>
ppt,
/// <summary>
/// PPS format
/// </summary>
pps,
/// <summary>
/// PPSM format
/// </summary>
ppsm,
/// <summary>
/// POT format
/// </summary>
pot,
/// <summary>
/// POTM format
/// </summary>
potm,
/// <summary>
/// PDF format
/// </summary>
pdf,
/// <summary>
/// XPS format
/// </summary>
xps,
/// <summary>
/// PPSX format
/// </summary>
ppsx,
/// <summary>
/// TIFF format
/// </summary>
tiff,
/// <summary>
/// HTML format
/// </summary>
html,
/// <summary>
/// SWF format
/// </summary>
swf,
// above native supported
/// <summary>
/// TXT format
/// </summary>
txt,
/// <summary>
/// DOC format
/// </summary>
doc,
/// <summary>
/// DOCX format
/// </summary>
docx,
/// <summary>
/// BMP format
/// </summary>
bmp,
/// <summary>
/// JPEG format
/// </summary>
jpeg,
/// <summary>
/// PNG format
/// </summary>
png,
/// <summary>
/// EMF format
/// </summary>
emf,
/// <summary>
/// WMF format
/// </summary>
wmf,
/// <summary>
/// GIF format
/// </summary>
gif,
/// <summary>
/// EXIF format
/// </summary>
exif,
/// <summary>
/// ICO format
/// </summary>
ico,
/// <summary>
/// SVG format
/// </summary>
svg
}
}
| 12.112583 | 45 | 0.48059 | [
"MIT"
] | aspose-slides/Aspose.Slides-for-.NET | Demos/Aspose.Slides.Web.API.Clients/Enums/SlidesConversionFormats.cs | 1,829 | C# |
/* Copyright 2010-2014 MongoDB Inc.
*
* 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 MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Internal;
namespace MongoDB.Driver.Operations
{
internal class CommandOperation<TCommandResult> : ReadOperationBase where TCommandResult : CommandResult
{
private readonly IMongoCommand _command;
private readonly QueryFlags _flags;
private readonly BsonDocument _options;
private readonly ReadPreference _readPreference;
private readonly IBsonSerializationOptions _serializationOptions;
private readonly IBsonSerializer _serializer;
public CommandOperation(
string databaseName,
BsonBinaryReaderSettings readerSettings,
BsonBinaryWriterSettings writerSettings,
IMongoCommand command,
QueryFlags flags,
BsonDocument options,
ReadPreference readPreference,
IBsonSerializationOptions serializationOptions,
IBsonSerializer serializer)
: base(databaseName, "$cmd", readerSettings, writerSettings)
{
_command = command;
_flags = flags;
_options = options;
_readPreference = readPreference;
_serializationOptions = serializationOptions;
_serializer = serializer;
}
public TCommandResult Execute(MongoConnection connection)
{
var maxWireDocumentSize = connection.ServerInstance.MaxWireDocumentSize;
var forShardRouter = connection.ServerInstance.InstanceType == MongoServerInstanceType.ShardRouter;
var wrappedQuery = WrapQuery(_command, _options, _readPreference, forShardRouter);
var queryMessage = new MongoQueryMessage(WriterSettings, CollectionFullName, _flags, maxWireDocumentSize, 0, -1, wrappedQuery, null);
connection.SendMessage(queryMessage);
var reply = connection.ReceiveMessage<TCommandResult>(ReaderSettings, _serializer, _serializationOptions);
if (reply.NumberReturned == 0)
{
var commandDocument = _command.ToBsonDocument();
var commandName = (commandDocument.ElementCount == 0) ? "(no name)" : commandDocument.GetElement(0).Name;
var message = string.Format("Command '{0}' failed. No response returned.", commandName);
throw new MongoCommandException(message);
}
var commandResult = reply.Documents[0];
commandResult.ServerInstance = connection.ServerInstance;
commandResult.Command = _command;
if (!commandResult.Ok)
{
throw ExceptionMapper.Map(commandResult.Response) ?? new MongoCommandException(commandResult);
}
return commandResult;
}
}
}
| 41.658537 | 145 | 0.681206 | [
"Apache-2.0"
] | EvilMindz/mongo-csharp-driver | MongoDB.Driver/Operations/CommandOperation.cs | 3,418 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Emit;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Emit
{
public class EmitBaselineTests
{
[Fact]
public void CreateInitialBaseline()
{
var provider = new LocalVariableNameProvider(_ => ImmutableArray.Create<string>());
var peModule = ModuleMetadata.CreateFromImage(TestResources.MetadataTests.Basic.Members);
var peReader = peModule.Module.PEReaderOpt;
var mdBytes = peReader.GetMetadata().GetContent();
var mdBytesHandle = PinnedImmutableArray.Create(mdBytes);
var mdModule = ModuleMetadata.CreateFromMetadata(mdBytesHandle.Pointer, mdBytes.Length);
Assert.Throws<ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(null, provider));
Assert.Throws<ArgumentNullException>(() => EmitBaseline.CreateInitialBaseline(peModule, null));
Assert.Throws<ArgumentException>(() => EmitBaseline.CreateInitialBaseline(mdModule, provider));
}
}
}
| 43.833333 | 184 | 0.71635 | [
"Apache-2.0"
] | semihokur/pattern-matching-csharp | Src/Compilers/Core/CodeAnalysisTest/Emit/EmitBaselineTests.cs | 1,317 | C# |
namespace ComputerPartsCatalog.Services.Data.Ratings
{
using System.Linq;
using System.Threading.Tasks;
using ComputerPartsCatalog.Data.Common.Repositories;
using ComputerPartsCatalog.Data.Models;
using Microsoft.EntityFrameworkCore;
public class RatingsService : IRatingsService
{
private readonly IRepository<Rating> ratingsRepository;
public RatingsService(IRepository<Rating> ratingsRepository)
{
this.ratingsRepository = ratingsRepository;
}
public async Task<double> GetAverageRatingAsync(int productId)
{
return await this.ratingsRepository.All()
.Where(x => x.ProductId == productId)
.AverageAsync(x => x.Value);
}
public async Task SetRatingAsync(int productId, string userId, byte value)
{
var rating = await this.ratingsRepository.All()
.FirstOrDefaultAsync(x => x.ProductId == productId && x.UserId == userId);
if (rating == null)
{
rating = new Rating
{
ProductId = productId,
UserId = userId,
};
await this.ratingsRepository.AddAsync(rating);
}
rating.Value = value;
await this.ratingsRepository.SaveChangesAsync();
}
}
}
| 29.893617 | 90 | 0.586477 | [
"MIT"
] | StanislavTsanev/ComputerPartsCatalog | Services/ComputerPartsCatalog.Services.Data/Ratings/RatingsService.cs | 1,407 | C# |
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
namespace Spine {
/// <summary>>An attachment with vertices that are transformed by one or more bones and can be deformed by a slot's
/// <see cref="Slot.Deform"/>.</summary>
public abstract class VertexAttachment : Attachment {
static int nextID = 0;
static readonly Object nextIdLock = new Object();
internal readonly int id;
internal int[] bones;
internal float[] vertices;
internal int worldVerticesLength;
internal VertexAttachment deformAttachment;
/// <summary>Gets a unique ID for this attachment.</summary>
public int Id { get { return id; } }
public int[] Bones { get { return bones; } set { bones = value; } }
public float[] Vertices { get { return vertices; } set { vertices = value; } }
public int WorldVerticesLength { get { return worldVerticesLength; } set { worldVerticesLength = value; } }
///<summary>Deform keys for the deform attachment are also applied to this attachment.
/// May be null if no deform keys should be applied.</summary>
public VertexAttachment DeformAttachment { get { return deformAttachment; } set { deformAttachment = value; } }
public VertexAttachment (string name)
: base(name) {
deformAttachment = this;
lock (VertexAttachment.nextIdLock) {
id = (VertexAttachment.nextID++ & 65535) << 11;
}
}
public void ComputeWorldVertices (Slot slot, float[] worldVertices) {
ComputeWorldVertices(slot, 0, worldVerticesLength, worldVertices, 0);
}
/// <summary>
/// Transforms the attachment's local <see cref="Vertices"/> to world coordinates. If the slot's <see cref="Slot.Deform"/> is
/// not empty, it is used to deform the vertices.
/// <para />
/// See <a href="http://esotericsoftware.com/spine-runtime-skeletons#World-transforms">World transforms</a> in the Spine
/// Runtimes Guide.
/// </summary>
/// <param name="start">The index of the first <see cref="Vertices"/> value to transform. Each vertex has 2 values, x and y.</param>
/// <param name="count">The number of world vertex values to output. Must be less than or equal to <see cref="WorldVerticesLength"/> - start.</param>
/// <param name="worldVertices">The output world vertices. Must have a length greater than or equal to <paramref name="offset"/> + <paramref name="count"/>.</param>
/// <param name="offset">The <paramref name="worldVertices"/> index to begin writing values.</param>
/// <param name="stride">The number of <paramref name="worldVertices"/> entries between the value pairs written.</param>
public void ComputeWorldVertices (Slot slot, int start, int count, float[] worldVertices, int offset, int stride = 2) {
count = offset + (count >> 1) * stride;
Skeleton skeleton = slot.bone.skeleton;
var deformArray = slot.deform;
float[] vertices = this.vertices;
int[] bones = this.bones;
if (bones == null) {
if (deformArray.Count > 0) vertices = deformArray.Items;
Bone bone = slot.bone;
float x = bone.worldX, y = bone.worldY;
float a = bone.a, b = bone.b, c = bone.c, d = bone.d;
for (int vv = start, w = offset; w < count; vv += 2, w += stride) {
float vx = vertices[vv], vy = vertices[vv + 1];
worldVertices[w] = vx * a + vy * b + x;
worldVertices[w + 1] = vx * c + vy * d + y;
}
return;
}
int v = 0, skip = 0;
for (int i = 0; i < start; i += 2) {
int n = bones[v];
v += n + 1;
skip += n;
}
var skeletonBones = skeleton.bones.Items;
if (deformArray.Count == 0) {
for (int w = offset, b = skip * 3; w < count; w += stride) {
float wx = 0, wy = 0;
int n = bones[v++];
n += v;
for (; v < n; v++, b += 3) {
Bone bone = skeletonBones[bones[v]];
float vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2];
wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight;
wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight;
}
worldVertices[w] = wx;
worldVertices[w + 1] = wy;
}
} else {
float[] deform = deformArray.Items;
for (int w = offset, b = skip * 3, f = skip << 1; w < count; w += stride) {
float wx = 0, wy = 0;
int n = bones[v++];
n += v;
for (; v < n; v++, b += 3, f += 2) {
Bone bone = skeletonBones[bones[v]];
float vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2];
wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight;
wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight;
}
worldVertices[w] = wx;
worldVertices[w + 1] = wy;
}
}
}
///<summary>Does not copy id (generated) or name (set on construction).</summary>
internal void CopyTo (VertexAttachment attachment) {
if (bones != null) {
attachment.bones = new int[bones.Length];
Array.Copy(bones, 0, attachment.bones, 0, bones.Length);
}
else
attachment.bones = null;
if (vertices != null) {
attachment.vertices = new float[vertices.Length];
Array.Copy(vertices, 0, attachment.vertices, 0, vertices.Length);
}
else
attachment.vertices = null;
attachment.worldVerticesLength = worldVerticesLength;
attachment.deformAttachment = deformAttachment;
}
}
}
| 44.904459 | 167 | 0.634894 | [
"Apache-2.0"
] | NGTO-WONG/KishiStory | Assets/Spine/Runtime/spine-csharp/Attachments/VertexAttachment.cs | 7,050 | C# |
using Org.BouncyCastle.Crypto.Digests;
using System;
using System.Collections.Generic;
using System.Text;
namespace Hashgraph.Implementation
{
/// <summary>
/// Internal Helper class for ABI encoding
/// of parameter arguments sent to smart
/// contract methods.
/// </summary>
internal static class Abi
{
internal static ReadOnlyMemory<byte> EncodeFunctionWithArguments(string functionName, object[] functionArgs)
{
var selector = GetFunctionSelector(functionName, functionArgs);
var arguments = EncodeArguments(functionArgs);
var result = new byte[selector.Length + arguments.Length];
selector.CopyTo(result.AsMemory());
arguments.CopyTo(result.AsMemory(selector.Length));
return result;
}
internal static ReadOnlyMemory<byte> EncodeArguments(object[] args)
{
if (args is null || args.Length == 0)
{
return ReadOnlyMemory<byte>.Empty;
}
var headerSize = 0;
var totalSize = 0;
var argsCount = args.Length;
var parts = new (bool isDynamic, ReadOnlyMemory<byte> bytes)[argsCount];
for (int i = 0; i < args.Length; i++)
{
var (isDynamic, bytes) = parts[i] = EncodePart(args[i]);
if (isDynamic)
{
headerSize += 32;
totalSize += 32 + bytes.Length;
}
else
{
headerSize += bytes.Length;
totalSize += bytes.Length;
}
}
var result = new byte[totalSize];
var headerPtr = 0;
var dataPtr = headerSize;
for (int i = 0; i < argsCount; i++)
{
var (isDynamic, bytes) = parts[i];
if (isDynamic)
{
WriteInt256(result.AsSpan(headerPtr), dataPtr);
bytes.CopyTo(result.AsMemory(dataPtr));
headerPtr += 32;
dataPtr += bytes.Length;
}
else
{
bytes.CopyTo(result.AsMemory(headerPtr));
headerPtr += bytes.Length;
}
}
return result;
}
internal static object[] DecodeArguments(ReadOnlyMemory<byte> data, params Type[] types)
{
if (types is null || types.Length == 0)
{
return new object[0];
}
var results = new object[types.Length];
var headerPtr = 0;
for (int i = 0; i < types.Length; i++)
{
var typeMapping = GetMapping(types[i]);
if (typeMapping.IsDynamic)
{
var positionPtr = (int)ReadUint256(data.Slice(headerPtr));
results[i] = typeMapping.Decode(data.Slice(positionPtr));
headerPtr += typeMapping.HeaderSize;
}
else
{
results[i] = typeMapping.Decode(data.Slice(headerPtr));
headerPtr += typeMapping.HeaderSize;
}
}
return results;
}
private static (bool isDynamic, ReadOnlyMemory<byte> bytes) EncodePart(object value)
{
var mapping = GetMapping(value);
return (mapping.IsDynamic, mapping.Encode(value));
}
private static ReadOnlyMemory<byte> GetFunctionSelector(string functionName, object[] functionArgs)
{
var buffer = new StringBuilder(100);
buffer.Append(functionName);
buffer.Append('(');
if (functionArgs != null && functionArgs.Length > 0)
{
buffer.Append(GetMapping(functionArgs[0]).AbiCode);
for (int i = 1; i < functionArgs.Length; i++)
{
buffer.Append(',');
buffer.Append(GetMapping(functionArgs[i]).AbiCode);
}
}
buffer.Append(')');
var bytes = Encoding.ASCII.GetBytes(buffer.ToString());
var digest = new KeccakDigest(256);
digest.BlockUpdate(bytes, 0, bytes.Length);
var hash = new byte[digest.GetByteLength()];
digest.DoFinal(hash, 0);
return hash.AsMemory(0, 4);
}
private static ReadOnlyMemory<byte> EncodeStringPart(object value)
{
#nullable disable
return EncodeByteArrayPart(Encoding.UTF8.GetBytes(Convert.ToString(value)));
#nullable enable
}
private static object DecodeStringPart(ReadOnlyMemory<byte> arg)
{
return Encoding.UTF8.GetString((byte[])DecodeByteArrayPart(arg));
}
private static ReadOnlyMemory<byte> EncodeByteArrayPart(object value)
{
var bytes = (byte[])value;
var words = (bytes.Length / 32) + (bytes.Length % 32 > 0 ? 2 : 1);
var result = new byte[32 * words];
WriteInt256(result.AsSpan(0, 32), bytes.Length);
bytes.CopyTo(result.AsSpan(32));
return result;
}
private static object DecodeByteArrayPart(ReadOnlyMemory<byte> arg)
{
var size = (int)ReadInt256(arg.Slice(0, 32));
return arg.Slice(32, size).ToArray();
}
private static ReadOnlyMemory<byte> EncodeReadOnlyMemoryPart(object value)
{
var bytes = (ReadOnlyMemory<byte>)value;
var words = (bytes.Length / 32) + (bytes.Length % 32 > 0 ? 2 : 1);
var result = new byte[32 * words];
WriteInt256(result.AsSpan(0, 32), bytes.Length);
bytes.CopyTo(result.AsMemory(32));
return result;
}
private static object DecodeReadOnlyMemoryPart(ReadOnlyMemory<byte> arg)
{
var size = (int)ReadInt256(arg.Slice(0, 32));
return arg.Slice(32, size);
}
private static ReadOnlyMemory<byte> EncodeInt32Part(object value)
{
var bytes = new byte[32];
WriteInt256(bytes.AsSpan(), Convert.ToInt32(value));
return bytes;
}
private static object DecodeInt32Part(ReadOnlyMemory<byte> arg)
{
return (int)ReadInt256(arg.Slice(0, 32));
}
private static ReadOnlyMemory<byte> EncodeInt64Part(object value)
{
var bytes = new byte[32];
WriteInt256(bytes.AsSpan(), Convert.ToInt64(value));
return bytes;
}
private static object DecodeInt64Part(ReadOnlyMemory<byte> arg)
{
return ReadInt256(arg.Slice(0, 32));
}
private static ReadOnlyMemory<byte> EncodeUInt32Part(object value)
{
var bytes = new byte[32];
WriteUint256(bytes.AsSpan(), Convert.ToUInt32(value));
return bytes;
}
private static object DecodeUInt32Part(ReadOnlyMemory<byte> arg)
{
return (uint)ReadUint256(arg.Slice(0, 32));
}
private static ReadOnlyMemory<byte> EncodeUInt64Part(object value)
{
var bytes = new byte[32];
WriteUint256(bytes.AsSpan(), Convert.ToUInt64(value));
return bytes;
}
private static object DecodeUInt64Part(ReadOnlyMemory<byte> arg)
{
return ReadUint256(arg.Slice(0, 32));
}
private static ReadOnlyMemory<byte> EncodeBoolPart(object value)
{
var bytes = new byte[32];
WriteInt256(bytes.AsSpan(), Convert.ToBoolean(value) ? 1 : 0);
return bytes;
}
private static object DecodeBoolPart(ReadOnlyMemory<byte> arg)
{
return ReadInt256(arg.Slice(0, 32)) > 0;
}
// Note this is internal to provide support to the
// "Contract" type of Endorsement.
internal static ReadOnlyMemory<byte> EncodeAddressPart(object value)
{
// For 20 bytes total (aka uint160)
// byte 0 to 3 are shard
// byte 4 to 11 are realm
// byte 12 to 19 are account number
// Note: packed in 32 bytes, right aligned
if (value is Address address)
{
var bytes = new byte[32];
var shard = BitConverter.GetBytes(address.ShardNum);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(shard);
}
shard[^4..^0].CopyTo(bytes, 12);
var realm = BitConverter.GetBytes(address.RealmNum);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(realm);
}
realm.CopyTo(bytes, 16);
var num = BitConverter.GetBytes(address.AccountNum);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(num);
}
num.CopyTo(bytes, 24);
return bytes;
}
throw new ArgumentException("Argument was not an address.", nameof(value));
}
// Note this is internal to provide support to the
// "Contract" type of Endorsement.
internal static object DecodeAddressPart(ReadOnlyMemory<byte> arg)
{
// See EncodeAddressPart for packing notes
var shardAsBytes = arg.Slice(12, 4).ToArray();
if (BitConverter.IsLittleEndian)
{
Array.Reverse(shardAsBytes);
}
var shard = BitConverter.ToInt32(shardAsBytes);
var realmAsBytes = arg.Slice(16, 8).ToArray();
if (BitConverter.IsLittleEndian)
{
Array.Reverse(realmAsBytes);
}
var realm = BitConverter.ToInt64(realmAsBytes);
var numAsBytes = arg.Slice(24, 8).ToArray();
if (BitConverter.IsLittleEndian)
{
Array.Reverse(numAsBytes);
}
var num = BitConverter.ToInt64(numAsBytes);
return new Address(shard, realm, num);
}
private static void WriteInt256(Span<byte> buffer, long value)
{
var valueAsBytes = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(valueAsBytes);
}
valueAsBytes.CopyTo(buffer.Slice(24));
}
private static long ReadInt256(ReadOnlyMemory<byte> buffer)
{
var valueAsBytes = buffer.Slice(24, 8).ToArray();
if (BitConverter.IsLittleEndian)
{
Array.Reverse(valueAsBytes);
}
return BitConverter.ToInt64(valueAsBytes);
}
private static void WriteUint256(Span<byte> buffer, ulong value)
{
var valueAsBytes = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(valueAsBytes);
}
valueAsBytes.CopyTo(buffer.Slice(24));
}
private static ulong ReadUint256(ReadOnlyMemory<byte> buffer)
{
var valueAsBytes = buffer.Slice(24, 8).ToArray();
if (BitConverter.IsLittleEndian)
{
Array.Reverse(valueAsBytes);
}
return BitConverter.ToUInt64(valueAsBytes);
}
private static TypeMapping GetMapping(object value)
{
if (value is null)
{
return _typeMap[typeof(int)];
}
return GetMapping(value.GetType());
}
private static TypeMapping GetMapping(Type type)
{
#nullable disable
if (_typeMap.TryGetValue(type, out TypeMapping mapping))
{
return mapping;
}
throw new InvalidOperationException($"Encoding of type {type.Name} is not currently supported.");
#nullable enable
}
private static readonly Dictionary<Type, TypeMapping> _typeMap;
static Abi()
{
_typeMap = new Dictionary<Type, TypeMapping>();
_typeMap.Add(typeof(bool), new TypeMapping("bool", false, 32, EncodeBoolPart, DecodeBoolPart));
_typeMap.Add(typeof(int), new TypeMapping("int32", false, 32, EncodeInt32Part, DecodeInt32Part));
_typeMap.Add(typeof(long), new TypeMapping("int64", false, 32, EncodeInt64Part, DecodeInt64Part));
_typeMap.Add(typeof(uint), new TypeMapping("uint32", false, 32, EncodeUInt32Part, DecodeUInt32Part));
_typeMap.Add(typeof(ulong), new TypeMapping("uint64", false, 32, EncodeUInt64Part, DecodeUInt64Part));
_typeMap.Add(typeof(string), new TypeMapping("string", true, 32, EncodeStringPart, DecodeStringPart));
_typeMap.Add(typeof(byte[]), new TypeMapping("bytes", true, 32, EncodeByteArrayPart, DecodeByteArrayPart));
_typeMap.Add(typeof(ReadOnlyMemory<byte>), new TypeMapping("bytes", true, 32, EncodeReadOnlyMemoryPart, DecodeReadOnlyMemoryPart));
_typeMap.Add(typeof(Address), new TypeMapping("address", false, 32, EncodeAddressPart, DecodeAddressPart));
}
internal class TypeMapping
{
internal readonly string AbiCode;
internal readonly bool IsDynamic;
internal readonly int HeaderSize;
internal readonly Func<object, ReadOnlyMemory<byte>> Encode;
internal readonly Func<ReadOnlyMemory<byte>, object> Decode;
public TypeMapping(string abiCode, bool isDynamic, int headerSize, Func<object, ReadOnlyMemory<byte>> encode, Func<ReadOnlyMemory<byte>, object> decode)
{
AbiCode = abiCode;
IsDynamic = isDynamic;
HeaderSize = headerSize;
Encode = encode;
Decode = decode;
}
}
}
}
| 40.820728 | 165 | 0.532423 | [
"Apache-2.0"
] | ZhingShan/Hashgraph | src/Hashgraph/Implementation/Abi.cs | 14,575 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace CalculatorCode.Models
{
public class CombinationsCalculator : Calculator
{
[Display(Name = "Number of Objects (n)")]
public int NumberOfObjects { get; set; }
[Display(Name = "Sample Size (r)")]
public int SampleSize { get; set; }
new public long Result { get; set; }
public long CalculateResult()
{
return Combinations(NumberOfObjects, SampleSize);
}
public static long Combinations(int noOfObjects, int noChosen)
{
return Permutations(noOfObjects, noChosen) / Factorial(noChosen);
}
private static long Permutations(int noOjObjects, int noChosen)
{
return FactorialDivision(noOjObjects, noOjObjects - noChosen);
}
private static long Factorial(int i)
{
if (i <= 1)
return 1;
return i * Factorial(i - 1);
}
private static long FactorialDivision(int topFactorial, int divisorFactorial)
{
long result = 1;
for (int i = topFactorial; i > divisorFactorial; i--)
{
result = result * i;
}
return result;
}
}
} | 26.431373 | 85 | 0.571217 | [
"MIT"
] | brandiweekes/5210_CalculatorCode | TimeCalculator/Models/CombinationsCalculator.cs | 1,348 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\IMethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface ISensitivityLabelEvaluateRequestBuilder.
/// </summary>
public partial interface ISensitivityLabelEvaluateRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
ISensitivityLabelEvaluateRequest Request(IEnumerable<Option> options = null);
}
}
| 37.551724 | 153 | 0.589532 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/ISensitivityLabelEvaluateRequestBuilder.cs | 1,089 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Neo.Network.P2P.Payloads;
namespace Neo.Models.Transactions
{
public class TransactionPreviewModel
{
public UInt256 TxId { get; set; }
public uint BlockHeight { get; set; }
public DateTime BlockTime => Timestamp.FromTimestampMS().ToLocalTime();
public ulong Timestamp { get; set; }
public List<TransferModel> Transfers { get; set; }
}
}
| 27 | 79 | 0.695906 | [
"MIT"
] | MingxiaYan/Neo3-GUI | neo3-gui/neo3-gui/Models/Transactions/TransactionPreviewModel.cs | 515 | C# |
namespace DotNetInterceptTester.My_System.Xml.XmlNodeReader
{
public class MoveToAttribute_System_Xml_XmlNodeReader_System_Int32
{
public static bool _MoveToAttribute_System_Xml_XmlNodeReader_System_Int32( )
{
//Parameters
System.Int32 attributeIndex = null;
//Exception
Exception exception_Real = null;
Exception exception_Intercepted = null;
InterceptionMaintenance.disableInterception( );
try
{
returnValue_Real = System.Xml.XmlNodeReader.MoveToAttribute(attributeIndex);
}
catch( Exception e )
{
exception_Real = e;
}
InterceptionMaintenance.enableInterception( );
try
{
returnValue_Intercepted = System.Xml.XmlNodeReader.MoveToAttribute(attributeIndex);
}
catch( Exception e )
{
exception_Intercepted = e;
}
}
}
}
| 19.409091 | 90 | 0.696721 | [
"MIT"
] | SecurityInnovation/Holodeck | Test/Automation/DotNetInterceptTester/DotNetInterceptTester/System.Xml.XmlNodeReader.MoveToAttribute(Int32).cs | 854 | C# |
using Trill.Shared.Abstractions.Kernel;
namespace Trill.Modules.Users.Core.Domain.Exceptions
{
internal class InvalidCredentialsException : DomainException
{
public string Name { get; }
public InvalidCredentialsException(string name) : base("Invalid credentials.")
{
Name = name;
}
}
} | 25.428571 | 87 | 0.63764 | [
"MIT"
] | devmentors/Trill-modular-monolith | src/Modules/Users/src/Trill.Modules.Users.Core/Domain/Exceptions/InvalidCredentialsException.cs | 356 | C# |
// <copyright file="ChannelHandlerIntegration.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
#if NETFRAMEWORK
using System;
using System.ComponentModel;
using Datadog.Trace.ClrProfiler.CallTarget;
using Datadog.Trace.ClrProfiler.Integrations;
using Datadog.Trace.Configuration;
namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Wcf
{
/// <summary>
/// System.ServiceModel.Dispatcher.ChannelHandler calltarget instrumentation
/// </summary>
[InstrumentMethod(
AssemblyName = "System.ServiceModel",
TypeName = "System.ServiceModel.Dispatcher.ChannelHandler",
MethodName = "HandleRequest",
ReturnTypeName = ClrNames.Bool,
ParameterTypeNames = new[] { "System.ServiceModel.Channels.RequestContext", "System.ServiceModel.OperationContext" },
MinimumVersion = "4.0.0",
MaximumVersion = "4.*.*",
IntegrationName = IntegrationName)]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ChannelHandlerIntegration
{
private const string IntegrationName = nameof(IntegrationIds.Wcf);
/// <summary>
/// OnMethodBegin callback
/// </summary>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <typeparam name="TRequestContext">Type of the request context</typeparam>
/// <typeparam name="TOperationContext">Type of the operation context</typeparam>
/// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
/// <param name="request">RequestContext instance</param>
/// <param name="currentOperationContext">OperationContext instance</param>
/// <returns>Calltarget state value</returns>
public static CallTargetState OnMethodBegin<TTarget, TRequestContext, TOperationContext>(TTarget instance, TRequestContext request, TOperationContext currentOperationContext)
{
return new CallTargetState(WcfIntegration.CreateScope(request));
}
/// <summary>
/// OnMethodEnd callback
/// </summary>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <typeparam name="TReturn">Type of the response</typeparam>
/// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
/// <param name="returnValue">Return value</param>
/// <param name="exception">Exception instance in case the original code threw an exception.</param>
/// <param name="state">Calltarget state value</param>
/// <returns>A response value, in an async scenario will be T of Task of T</returns>
public static CallTargetReturn<TReturn> OnMethodEnd<TTarget, TReturn>(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state)
{
state.Scope.DisposeWithException(exception);
return new CallTargetReturn<TReturn>(returnValue);
}
}
}
#endif
| 48.318182 | 182 | 0.695202 | [
"Apache-2.0"
] | ganeshkumarsv/dd-trace-dotnet | src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Wcf/ChannelHandlerIntegration.cs | 3,189 | C# |
/*
* Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty
*/
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using RootMotion.FinalIK;
using UnityEngine;
// Image 65: Assembly-CSharp-firstpass.dll - Assembly: Assembly-CSharp-firstpass, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - Types 8269-8551
namespace RootMotion.Demos
{
public class InteractionC2CDemo : MonoBehaviour // TypeDefIndex: 8325
{
// Fields
public InteractionSystem character1; // 0x18
public InteractionSystem character2; // 0x20
public InteractionObject handShake; // 0x28
// Constructors
public InteractionC2CDemo(); // 0x0000000180265240-0x0000000180265250
// Methods
private void OnGUI(); // 0x00000001807FA820-0x00000001807FA8D0
private void LateUpdate(); // 0x00000001807FA650-0x00000001807FA820
}
}
| 29.5 | 153 | 0.769492 | [
"MIT"
] | TotalJTM/PrimitierModdingFramework | Dumps/PrimitierDumpV1.0.1/RootMotion/Demos/InteractionC2CDemo.cs | 887 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
namespace Microsoft.PowerFx.Core.IR.Nodes
{
internal abstract class IntermediateNode
{
public IRContext IRContext { get; }
public IntermediateNode(IRContext irContext)
{
IRContext = irContext;
}
public abstract TResult Accept<TResult, TContext>(IRNodeVisitor<TResult, TContext> visitor, TContext context);
}
}
| 25.166667 | 118 | 0.675497 | [
"MIT"
] | Grant-Archibald-MS/Power-Fx | src/libraries/Microsoft.PowerFx.Core/IR/Nodes/IntermediateNode.cs | 455 | C# |
using System;
using Anvil.API.Events;
using NWN.Core;
namespace Anvil.API.Events
{
/// <summary>
/// Events for <see cref="NwCreature"/>.
/// </summary>
public static partial class CreatureEvents
{
/// <summary>
/// Triggered at the end of the <see cref="NwCreature"/> combat round.
/// </summary>
[GameEvent(EventScriptType.CreatureOnEndCombatRound)]
public sealed class OnCombatRoundEnd : IEvent
{
/// <summary>
/// Gets the <see cref="NwCreature"/> whose combat round is ending.
/// </summary>
public NwCreature Creature { get; } = NWScript.OBJECT_SELF.ToNwObject<NwCreature>()!;
NwObject IEvent.Context => Creature;
}
}
}
namespace Anvil.API
{
public sealed partial class NwCreature
{
/// <inheritdoc cref="CreatureEvents.OnCombatRoundEnd"/>
public event Action<CreatureEvents.OnCombatRoundEnd> OnCombatRoundEnd
{
add => EventService.Subscribe<CreatureEvents.OnCombatRoundEnd, GameEventFactory, GameEventFactory.RegistrationData>(this, new GameEventFactory.RegistrationData(this), value);
remove => EventService.Unsubscribe<CreatureEvents.OnCombatRoundEnd, GameEventFactory>(this, value);
}
}
}
| 30.15 | 180 | 0.699005 | [
"MIT"
] | milliorn/Anvil | NWN.Anvil/src/main/API/Events/Game/CreatureEvents/CreatureEvents.OnCombatRoundEnd.cs | 1,206 | C# |
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using BootstrapBlazor.Components;
using BootstrapBlazor.Shared.Common;
namespace BootstrapBlazor.Shared.Samples;
/// <summary>
///
/// </summary>
public sealed partial class AutoCompletes
{
private readonly List<string> _items = new();
private IEnumerable<string> Items => _items;
private Foo Model { get; set; } = new Foo() { Name = "" };
private static List<string> StaticItems => new() { "1", "12", "123", "1234", "12345", "123456", "abc", "abcdef", "ABC", "aBcDeFg", "ABCDEFG" };
private Task OnValueChanged(string val)
{
_items.Clear();
_items.Add($"{val}@163.com");
_items.Add($"{val}@126.com");
_items.Add($"{val}@sina.com");
_items.Add($"{val}@hotmail.com");
return Task.CompletedTask;
}
/// <summary>
/// 获得属性方法
/// </summary>
/// <returns></returns>
private IEnumerable<AttributeItem> GetAttributes() => new AttributeItem[]
{
// TODO: 移动到数据库中
new AttributeItem() {
Name = "ShowLabel",
Description = Localizer["Att1"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "true"
},
new AttributeItem() {
Name = "ChildContent",
Description = Localizer["Att2"],
Type = "RenderFragment",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "Items",
Description = Localizer["Att3"],
Type = "IEnumerable<string>",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "NoDataTip",
Description = Localizer["Att4"],
Type = "string",
ValueList = " — ",
DefaultValue = Localizer["Att4DefaultValue"]!
},
new AttributeItem() {
Name = "DisplayCount",
Description = Localizer["Att5"],
Type = "int?",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "ValueChanged",
Description = Localizer["Att6"],
Type = "Action<string>",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem() {
Name = "IsLikeMatch",
Description = Localizer["Att7"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "false"
},
new AttributeItem()
{
Name = "IgnoreCase",
Description = Localizer["Att8"],
Type = "bool",
ValueList = "true|false",
DefaultValue = "true"
},
new AttributeItem()
{
Name = "CustomFilter",
Description = Localizer["Att9"],
Type = "Func<Task<IEnumerable<string>>>",
ValueList = " — ",
DefaultValue = " — "
},
new AttributeItem()
{
Name = "Debounce",
Description = Localizer["Att10"],
Type = "int",
ValueList = " — ",
DefaultValue = "0"
},
new AttributeItem()
{
Name = nameof(AutoComplete.SkipEnter),
Description = Localizer[nameof(AutoComplete.SkipEnter)],
Type = "bool",
ValueList = "true/false",
DefaultValue = "false"
},
new AttributeItem()
{
Name = nameof(AutoComplete.SkipEsc),
Description = Localizer[nameof(AutoComplete.SkipEsc)],
Type = "bool",
ValueList = "true/false",
DefaultValue = "false"
}
};
}
| 30.480916 | 147 | 0.49737 | [
"Apache-2.0"
] | Ashhhhhh520/BootstrapBlazor | src/BootstrapBlazor.Shared/Samples/AutoCompletes.razor.cs | 4,045 | C# |
namespace ValkyrDoc.DocumentationEntry
{
public class DocumentationEntryFactory
{
private readonly IGuidService _guidService;
public DocumentationEntryFactory(IGuidService guidService)
{
_guidService = guidService;
}
public IDocumentationEntry CreateTextDocumentationEntry(string text)
{
return new TextDocumentationEntry(_guidService.CreateNewGuid(), text);
}
public IDocumentationEntry CreateUrlDocumentationEntry(string description, string url)
{
return new UrlDocumentationEntry(_guidService.CreateNewGuid(), description, url);
}
}
}
| 26.347826 | 90 | 0.755776 | [
"MIT"
] | Leginiel/ValkyrDoc | ValkyrDoc/DocumentationEntry/DocumentationEntryFactory.cs | 608 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UniGLTF;
using UnityEditor;
using UnityEngine;
namespace VRM
{
[CustomEditor(typeof(BlendShapeAvatar))]
public class BlendShapeAvatarEditor : PreviewEditor
{
static String[] Presets = ((BlendShapePreset[])Enum.GetValues(typeof(BlendShapePreset)))
.Select(x => x.ToString()).ToArray();
BlendShapeAvatar m_target;
void AddBlendShapeClip()
{
var dir = Path.GetDirectoryName(AssetDatabase.GetAssetPath(m_target));
var path = EditorUtility.SaveFilePanel(
"Create BlendShapeClip",
dir,
string.Format("BlendShapeClip#{0}.asset", m_target.Clips.Count),
"asset");
if (string.IsNullOrEmpty(path))
{
return;
}
path = path.ToUnityRelativePath();
//Debug.LogFormat("{0}", path);
var clip = ScriptableObject.CreateInstance<BlendShapeClip>();
clip.BlendShapeName = Path.GetFileNameWithoutExtension(path);
clip.Prefab = AssetDatabase.LoadAssetAtPath<GameObject>(AssetDatabase.GetAssetPath(m_target));
AssetDatabase.CreateAsset(clip, path);
AssetDatabase.ImportAsset(path);
m_target.Clips.Add(clip);
EditorUtility.SetDirty(m_target);
AssetDatabase.SaveAssets();
}
BlendShapeClip m_currentClip;
BlendShapeClip CurrentClip
{
get { return m_currentClip; }
set
{
if (m_currentClip == value) return;
m_currentClip = value;
//ClearBlendShape();
if (m_currentClip != null)
{
Bake(m_currentClip.Values, m_currentClip.MaterialValues, 1.0f);
}
}
}
void OnPrefabChanged()
{
if (m_currentClip != null)
{
Bake(m_currentClip.Values, m_currentClip.MaterialValues, 1.0f);
}
}
protected override void OnEnable()
{
PrefabChanged += OnPrefabChanged;
base.OnEnable();
m_target = (BlendShapeAvatar)target;
// remove missing values
foreach(var x in m_target.Clips.Select((x, i) => new { i, x }).Where(x => x.x == null).Reverse())
{
m_target.Clips.RemoveAt(x.i);
}
if(m_target.Clips.Count > 0)
{
CurrentClip = m_target.Clips[0];
}
}
protected override void OnDisable()
{
base.OnDisable();
PrefabChanged -= OnPrefabChanged;
}
List<bool> m_meshFolds = new List<bool>();
int m_preset;
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
// buttons
if (m_target.Clips != null)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField("Select BlendShapeClip", EditorStyles.boldLabel);
var array = m_target.Clips
.Select(x => x != null
? BlendShapeKey.CreateFrom(x).ToString()
: "null"
).ToArray();
var preset = GUILayout.SelectionGrid(m_preset, array, 4);
if (preset != m_preset)
{
CurrentClip = m_target.Clips[preset];
m_preset = preset;
}
}
// Add
if (GUILayout.Button("Add BlendShapeClip"))
{
AddBlendShapeClip();
}
if (CurrentClip != null)
{
// clip
EditorGUILayout.Space();
EditorGUILayout.LabelField("CurrentClip", EditorStyles.boldLabel);
/*var loadClip = (BlendShapeClip)*/
GUI.enabled = false;
EditorGUILayout.ObjectField("Current clip",
CurrentClip, typeof(BlendShapeClip), false);
GUI.enabled = true;
CurrentClip.Preset = (BlendShapePreset)EditorGUILayout.Popup("Preset", (int)CurrentClip.Preset, Presets);
GUI.enabled = false;
CurrentClip.BlendShapeName = EditorGUILayout.TextField("BlendShapeName", CurrentClip.BlendShapeName);
GUI.enabled = true;
var key = BlendShapeKey.CreateFrom(CurrentClip);
if (m_target.Clips.Where(x => key.Match(x)).Count() > 1)
{
EditorGUILayout.HelpBox("duplicate clip", MessageType.Error);
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("BlendShapeValues", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Clear"))
{
ClearBlendShape();
}
if (CurrentClip != null && GUILayout.Button("Apply"))
{
string maxWeightString;
CurrentClip.Values = GetBindings(out maxWeightString);
EditorUtility.SetDirty(CurrentClip);
}
EditorGUILayout.EndHorizontal();
// sliders
bool changed = false;
int foldIndex = 0;
if (PreviewSceneManager != null)
{
foreach (var item in PreviewSceneManager.EnumRenderItems.Where(x => x.SkinnedMeshRenderer != null))
{
var mesh = item.SkinnedMeshRenderer.sharedMesh;
if (mesh != null && mesh.blendShapeCount > 0)
{
//var relativePath = UniGLTF.UnityExtensions.RelativePathFrom(renderer.transform, m_target.transform);
//EditorGUILayout.LabelField(m_target.name + "/" + item.Path);
if (foldIndex >= m_meshFolds.Count)
{
m_meshFolds.Add(false);
}
m_meshFolds[foldIndex] = EditorGUILayout.Foldout(m_meshFolds[foldIndex], item.SkinnedMeshRenderer.name);
if (m_meshFolds[foldIndex])
{
//EditorGUI.indentLevel += 1;
for (int i = 0; i < mesh.blendShapeCount; ++i)
{
var src = item.SkinnedMeshRenderer.GetBlendShapeWeight(i);
var dst = EditorGUILayout.Slider(mesh.GetBlendShapeName(i), src, 0, 100.0f);
if (dst != src)
{
item.SkinnedMeshRenderer.SetBlendShapeWeight(i, dst);
changed = true;
}
}
//EditorGUI.indentLevel -= 1;
}
++foldIndex;
}
}
if (changed)
{
PreviewSceneManager.Bake();
}
}
}
}
BlendShapeBinding[] GetBindings(out string _maxWeightName)
{
var maxWeight = 0.0f;
var maxWeightName = "";
// weightのついたblendShapeを集める
var values = PreviewSceneManager.EnumRenderItems
.Where(x => x.SkinnedMeshRenderer!=null)
.SelectMany(x =>
{
var mesh = x.SkinnedMeshRenderer.sharedMesh;
var relativePath = x.Path;
var list = new List<BlendShapeBinding>();
if (mesh != null)
{
for (int i = 0; i < mesh.blendShapeCount; ++i)
{
var weight = x.SkinnedMeshRenderer.GetBlendShapeWeight(i);
if (weight == 0)
{
continue;
}
var name = mesh.GetBlendShapeName(i);
if (weight > maxWeight)
{
maxWeightName = name;
maxWeight = weight;
}
list.Add(new BlendShapeBinding
{
Index = i,
RelativePath = relativePath,
Weight = weight
});
}
}
return list;
}).ToArray()
;
_maxWeightName = maxWeightName;
return values;
}
private void ClearBlendShape()
{
foreach (var item in PreviewSceneManager.EnumRenderItems.Where(x => x.SkinnedMeshRenderer!=null))
{
var renderer = item.SkinnedMeshRenderer;
var mesh = renderer.sharedMesh;
if (mesh != null)
{
for (int i = 0; i < mesh.blendShapeCount; ++i)
{
renderer.SetBlendShapeWeight(i, 0);
}
}
}
}
}
}
| 35.966912 | 132 | 0.452826 | [
"MIT"
] | sotanmochi/VRMLipSyncSample | Assets/VRM/Scripts/BlendShape/Editor/BlendShapeAvatarEditor.cs | 9,801 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NeoSmart.Unicode;
using System.Linq;
namespace UnicodeTests
{
[TestClass]
public class SequenceTests
{
private string _swimmerString = "🏊";
private UnicodeSequence _swimmer = new UnicodeSequence("U+1F3CA");
private string _femaleSwimmerString = "🏊♀️";
private UnicodeSequence _femaleSwimmer = new UnicodeSequence("U+1F3CA U+200D U+2640 U+FE0F");
[TestMethod]
public void TestSequenceEquality()
{
Assert.AreEqual(_swimmer.AsString, _swimmerString);
Assert.IsTrue(_swimmer.Codepoints.SequenceEqual(_swimmerString.Codepoints()));
Assert.AreEqual(_femaleSwimmer.AsString, _femaleSwimmerString);
Assert.IsFalse(_swimmer.Equals((UnicodeSequence)null));
Assert.IsFalse(_swimmer.Equals((string)null));
Assert.IsTrue(_swimmer.Equals(_swimmer));
Assert.IsFalse(Equals(_swimmer, null));
Assert.IsTrue(Equals(_swimmer, _swimmer));
Assert.IsFalse(_swimmer.Equals(null, _femaleSwimmer));
Assert.IsFalse(_swimmer.Equals(_femaleSwimmer, null));
Assert.IsTrue(_swimmer.Equals(_femaleSwimmer, _femaleSwimmer));
}
[TestMethod]
public void TestSequenceMembership()
{
Assert.IsTrue(_femaleSwimmer.Contains(_swimmer.Codepoints.First()));
}
[TestMethod]
public void TestSequenceCompareTo()
{
Assert.IsTrue(_swimmer.CompareTo(_femaleSwimmer) != 0);
Assert.IsTrue(_swimmer.CompareTo(_swimmer) == 0);
}
[TestMethod]
public void TestSequenceSame()
{
Assert.IsFalse(_swimmer == null);
Assert.IsFalse(null == _swimmer);
Assert.IsFalse(_swimmer == _femaleSwimmer);
#pragma warning disable CS1718 // Comparison made to same variable
Assert.IsTrue(_swimmer == _swimmer);
#pragma warning restore CS1718 // Comparison made to same variable
}
[TestMethod]
public void TestSequenceNotSame()
{
Assert.IsTrue(_swimmer != null);
Assert.IsTrue(null != _swimmer);
Assert.IsTrue(_swimmer != _femaleSwimmer);
#pragma warning disable CS1718 // Comparison made to same variable
Assert.IsFalse(_swimmer != _swimmer);
#pragma warning restore CS1718 // Comparison made to same variable
}
}
}
| 36.485714 | 102 | 0.624119 | [
"MIT"
] | UWPX/unicode.net | tests/SequenceTests.cs | 2,499 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;
using Aspectize.Core;
using System.Security.Permissions;
namespace Clipboard
{
public interface ILoadDataService
{
DateTime LoadClipboardDate(Guid clipboardId);
[Command(BrowserCacheDuration = "30 Days")]
DataSet LoadClipboard(Guid clipboardId, DateTime dateModified);
DataSet LoadClipboards();
DataSet CreateClipboard(string libelle);
DataSet EnterClipboard(string code);
}
[Service(Name = "LoadDataService")]
public class LoadDataService : ILoadDataService //, IInitializable, ISingleton
{
DateTime ILoadDataService.LoadClipboardDate(Guid clipboardId)
{
IDataManager dm = EntityManager.FromDataBaseService(ServiceName.DataService);
var cb = dm.GetEntity<Clipboard>(clipboardId);
return cb.DateModified;
}
DataSet ILoadDataService.LoadClipboard(Guid clipboardId, DateTime dateModified)
{
IDataManager dm = EntityManager.FromDataBaseService(ServiceName.DataService);
dm.LoadEntity<Clipboard>(clipboardId);
return dm.Data;
}
DataSet ILoadDataService.LoadClipboards()
{
IDataManager dm = EntityManager.FromDataBaseService(ServiceName.DataService);
dm.LoadEntities<Clipboard>();
return dm.Data;
}
DataSet ILoadDataService.CreateClipboard(string libelle)
{
IDataManager dm = EntityManager.FromDataBaseService(ServiceName.DataService);
IEntityManager em = dm as IEntityManager;
var newClipboard = em.CreateInstance<Clipboard>();
newClipboard.Libelle = libelle;
newClipboard.AccessCode = Utilities.GenerateUniqueCode(dm);
//AspectizeUser aspectizeUser = ExecutingContext.CurrentUser;
//var animateur = dm.GetEntity<User>(new Guid(aspectizeUser.UserId.ToString()));
//em.AssociateInstance<Anime>(animateur, newMP);
dm.SaveTransactional();
return em.Data;
}
DataSet ILoadDataService.EnterClipboard(string code)
{
code = code.Replace(" ", "");
IDataManager dm = EntityManager.FromDataBaseService(ServiceName.DataService);
IEntityManager em = dm as IEntityManager;
dm.LoadEntities<Clipboard>(new QueryCriteria(Clipboard.Fields.AccessCode, ComparisonOperator.Equal, code.Trim()));
var clipboard = em.GetAllInstances<Clipboard>().SingleOrDefault(item => item.AccessCode == code.Trim());
if (clipboard == null) throw new SmartException(1000, "Invalid code, try again.");
return dm.Data;
}
}
}
| 29.8 | 126 | 0.655245 | [
"MIT"
] | Aspectize/Samples | Clipboard/Services/LoadDataService.cs | 2,831 | 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.
// </auto-generated>
namespace Microsoft.Azure.Management.Monitor.Fluent
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
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>
/// DiagnosticSettingsCategoryOperations operations.
/// </summary>
internal partial class DiagnosticSettingsCategoryOperations : IServiceOperations<MonitorManagementClient>, IDiagnosticSettingsCategoryOperations
{
/// <summary>
/// Initializes a new instance of the DiagnosticSettingsCategoryOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DiagnosticSettingsCategoryOperations(MonitorManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the MonitorManagementClient
/// </summary>
public MonitorManagementClient Client { get; private set; }
/// <summary>
/// Gets the diagnostic settings category for the specified resource.
/// </summary>
/// <param name='resourceUri'>
/// The identifier of the resource.
/// </param>
/// <param name='name'>
/// The name of the diagnostic setting.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<DiagnosticSettingsCategoryResourceInner>> GetWithHttpMessagesAsync(string resourceUri, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceUri == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
string apiVersion = "2017-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettingsCategories/{name}").ToString();
_url = _url.Replace("{resourceUri}", resourceUri);
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
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);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DiagnosticSettingsCategoryResourceInner>();
_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<DiagnosticSettingsCategoryResourceInner>(_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>
/// Lists the diagnostic settings categories for the specified resource.
/// </summary>
/// <param name='resourceUri'>
/// The identifier of the resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<DiagnosticSettingsCategoryResourceCollectionInner>> ListWithHttpMessagesAsync(string resourceUri, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceUri == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri");
}
string apiVersion = "2017-05-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("apiVersion", apiVersion);
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("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettingsCategories").ToString();
_url = _url.Replace("{resourceUri}", resourceUri);
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
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);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DiagnosticSettingsCategoryResourceCollectionInner>();
_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<DiagnosticSettingsCategoryResourceCollectionInner>(_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.313107 | 269 | 0.566358 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/Monitor/Generated/DiagnosticSettingsCategoryOperations.cs | 18,257 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace AnimalShelterAPI.Migrations
{
public partial class SeedData : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
table: "Animals",
columns: new[] { "AnimalId", "Age", "Description", "Gender", "Name", "Species" },
values: new object[,]
{
{ 1, 13, "sweet old granny", "Female", "Doggy", "Dog" },
{ 2, 8, "people pleaser", "Male", "Dax", "Dog" },
{ 3, 4, "big teddy bear", "Male", "Bruce", "Dog" },
{ 4, 6, "explorer", "Female", "Kiki", "Cat" },
{ 5, 7, "hates crowds", "Female", "Pepper", "Cat" },
{ 6, 6, "super friendly", "Female", "Ramona", "Cat" }
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Animals",
keyColumn: "AnimalId",
keyValue: 1);
migrationBuilder.DeleteData(
table: "Animals",
keyColumn: "AnimalId",
keyValue: 2);
migrationBuilder.DeleteData(
table: "Animals",
keyColumn: "AnimalId",
keyValue: 3);
migrationBuilder.DeleteData(
table: "Animals",
keyColumn: "AnimalId",
keyValue: 4);
migrationBuilder.DeleteData(
table: "Animals",
keyColumn: "AnimalId",
keyValue: 5);
migrationBuilder.DeleteData(
table: "Animals",
keyColumn: "AnimalId",
keyValue: 6);
}
}
}
| 29.368421 | 91 | 0.522103 | [
"Unlicense"
] | popoyuyu/AnimalShelterAPI.Solution | AnimalShelterAPI/Migrations/20220121225618_SeedData.cs | 1,676 | C# |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Xml.Linq;
using PCAxis.Chart;
using PCAxis.Web.Controls;
using System.Web.Routing;
using PCAxis.Api;
using PCAxis.Search;
using PXWeb.BackgroundWorker;
using System.Collections.Generic;
using log4net;
using PX.Web.Interfaces.Cache;
using System.Runtime.Caching;
using System.Web.Http;
using PXWeb.API;
using Ninject;
using Ninject.Web.Common;
namespace PXWeb
{
public class RouteInstance
{
public static IRouteExtender RouteExtender { get; set; }
public static IPxUrlProvider PxUrlProvider { get; set; }
}
public interface ICacheService
{
T Get<T>(string cacheKey) where T : class;
void Set(string cacheKey, object obj);
void ClearCache();
}
public class InMemoryCache : ICacheService, IPxCache
{
static log4net.ILog _logger = log4net.LogManager.GetLogger(typeof(InMemoryCache));
private bool _isEnabled = true;
private int _cacheExpirationInMinutes;
private HashSet<string> _cacheKeys = new HashSet<string>();
private bool inCacheCleanProcess = false;
private Object lockObject = new Object();
public bool DefaultEnabled
{
get
{
return true;
}
}
public InMemoryCache(int cacheExpirationInMinutes)
{
_cacheExpirationInMinutes = cacheExpirationInMinutes;
}
public T Get<T>(string cacheKey) where T : class
{
if (_coherenceChecker != null)
{
if (!_coherenceChecker())
{
//Clear the cache if it is not coherent
Clear();
return null;
}
}
lock (lockObject)
{
if (!_isEnabled) return null;
return MemoryCache.Default.Get(cacheKey) as T;
}
}
public void Set(string cacheKey, object obj)
{
lock (lockObject)
{
if (!_isEnabled) return;
if (inCacheCleanProcess) return;
if (!_cacheKeys.Contains(cacheKey))
{
_cacheKeys.Add(cacheKey);
}
MemoryCache.Default.Set(cacheKey, obj, DateTime.Now.AddMinutes(_cacheExpirationInMinutes));
}
}
public void ClearCache()
{
lock (lockObject)
{
if (inCacheCleanProcess) return;
inCacheCleanProcess = true;
try
{
foreach (string cacheKey in _cacheKeys)
{
MemoryCache.Default.Remove(cacheKey);
}
_cacheKeys.Clear();
}
finally
{
inCacheCleanProcess = false;
_logger.Info("Cache cleared");
}
}
}
public bool IsEnabled()
{
return _isEnabled;
}
public void Clear()
{
ClearCache();
}
public void Disable()
{
_isEnabled = false;
}
public void Enable()
{
_isEnabled = true;
}
private Func<bool> _coherenceChecker;
public void SetCoherenceChecker(Func<bool> coherenceChecker)
{
_coherenceChecker = coherenceChecker;
}
}
public class Global : System.Web.HttpApplication
{
static log4net.ILog _logger = log4net.LogManager.GetLogger("Global");
private ICacheService _metaCacheService = null;
private IPxCache _metaPxCache = null;
private IPxCacheController _cacheController = null;
public static void InitializeChartSettings(PCAxis.Chart.ChartSettings settings)
{
settings.AxisFontSize = Settings.Current.Features.Charts.Font.AxisSize;
//settings.ChartType
settings.Colors = Settings.Current.Features.Charts.Colors.ToList();
settings.CurrentCulture = PCAxis.Web.Core.Management.LocalizationManager.CurrentCulture;
settings.FontName = Settings.Current.Features.Charts.Font.Name;
settings.Guidelines = ChartSettings.GuidelinesType.None;
if (Settings.Current.Features.Charts.Guidelines.Horizontal) settings.Guidelines = ChartSettings.GuidelinesType.Horizontal;
if (Settings.Current.Features.Charts.Guidelines.Vertical) settings.Guidelines |= ChartSettings.GuidelinesType.Vertical;
settings.GuidelinesColor = Settings.Current.Features.Charts.Guidelines.Color;
settings.Height = Settings.Current.Features.Charts.Height;
settings.LabelOrientation = Settings.Current.Features.Charts.LabelOrientation;
settings.LegendFontSize = Settings.Current.Features.Charts.Legend.FontSize;
settings.LegendHeight = Settings.Current.Features.Charts.Legend.Height;
settings.LineThickness = Settings.Current.Features.Charts.LineThickness;
settings.Logotype = Settings.Current.Features.Charts.Logotype;
settings.ShowLegend = Settings.Current.Features.Charts.Legend.Visible;
settings.TimeSortOrder = Settings.Current.Features.Charts.TimeSortOrder;
//settings.Title = PCAxis.Web.Core.Management.PaxiomManager.PaxiomModel.Meta.Title;
settings.TitleFontSize = Settings.Current.Features.Charts.Font.TitleSize;
settings.Width = Settings.Current.Features.Charts.Width;
settings.ShowSource = Settings.Current.Features.Charts.ShowSource;
settings.ShowLogo = Settings.Current.Features.Charts.ShowLogo;
settings.BackgroundColorGraphs = Settings.Current.Features.Charts.BackgroundColorGraphs;
settings.LineThicknessPhrame = Settings.Current.Features.Charts.LineThicknessPhrame;
settings.LogotypePath = Settings.Current.General.Paths.ImagesPath;
settings.LineColorPhrame = Settings.Current.Features.Charts.LineColorPhrame;
}
protected void Application_Start(object sender, EventArgs e)
{
_logger.Info(" === Application start ===");
//Trigger reading of settings file
Settings s = PXWeb.Settings.Current;
//Trigger reading of databases
DatabaseInfo dbi = PXWeb.Settings.Current.General.Databases.GetDatabase("");
PCAxis.Web.Controls.ChartManager.SettingsInitializer = InitializeChartSettings;
//Set if strict check of groupings shall be performed or not
PCAxis.Paxiom.GroupRegistry.GetRegistry().Strict = PXWeb.Settings.Current.General.Global.StrictAggregationCheck;
//Load aggregations
PCAxis.Paxiom.GroupRegistry.GetRegistry().LoadGroupingsAsync();
if (s.Features.General.ApiEnabled)
{
RouteManager.AddApiRoute();
}
if (ConfigurationManager.AppSettings["CacheServiceExpirationInMinutes"] != null)
{
int cacheServiceExpirationInMinutes = int.Parse(ConfigurationManager.AppSettings["CacheServiceExpirationInMinutes"]);
if (cacheServiceExpirationInMinutes > 0)
{
var cacheService = new InMemoryCache(cacheServiceExpirationInMinutes);
_metaCacheService = cacheService;
_metaPxCache = cacheService;
}
PXWeb.Management.PxContext.CacheService = _metaCacheService;
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["RouteExtender"]))
{
RouteInstance.RouteExtender = Activator.CreateInstance(Type.GetType(ConfigurationManager.AppSettings["RouteExtender"])) as IRouteExtender;
RouteInstance.RouteExtender.MetaCacheService = _metaCacheService;
RouteInstance.RouteExtender.Db = PCAxis.Sql.DbConfig.SqlDbConfigsStatic.DefaultDatabase;
RouteInstance.RouteExtender.AddSavedQueryRoute(RouteTable.Routes);
RouteInstance.RouteExtender.RegisterCustomRoutes(RouteTable.Routes);
RouteInstance.RouteExtender.HomeSitePage = ConfigurationManager.AppSettings["HomeSitePage"] ?? "";
RouteInstance.RouteExtender.DefaultRedirectPage = ConfigurationManager.AppSettings["DefaultRedirectPage"] ?? "";
RouteInstance.PxUrlProvider = RouteInstance.RouteExtender.PxUrlProvider;
PCAxis.Web.Core.Management.LinkManager.CreateLinkMethod = new PCAxis.Web.Core.Management.LinkManager.LinkMethod(RouteInstance.RouteExtender.CreateLink);
}
else
{
RouteManager.AddDefaultGotoRoute();
RouteManager.AddSavedQueryRoute();
RegisterRoutes(RouteTable.Routes);
RouteInstance.PxUrlProvider = new PxUrlProvider();
if (PXWeb.Settings.Current.Features.General.UserFriendlyUrlsEnabled)
{
PCAxis.Web.Core.Management.LinkManager.CreateLinkMethod = new PCAxis.Web.Core.Management.LinkManager.LinkMethod(PXWeb.UserFriendlyLinkManager.CreateLink);
}
}
//Initialize Index search
SearchManager.Current.Initialize(PXWeb.Settings.Current.General.Paths.PxDatabasesPath,
new PCAxis.Search.GetMenuDelegate(PXWeb.Management.PxContext.GetMenuAndItem),
PXWeb.Settings.Current.Features.Search.CacheTime,
PXWeb.Settings.Current.Features.Search.DefaultOperator);
PCAxis.Query.SavedQueryManager.StorageType = PXWeb.Settings.Current.Features.SavedQuery.StorageType;
PCAxis.Query.SavedQueryManager.Reset();
InitializeCacheController();
if (PXWeb.Settings.Current.Features.General.BackgroundWorkerEnabled)
{
//Start PX-Web background worker
PxWebBackgroundWorker.Work(PXWeb.Settings.Current.Features.BackgroundWorker.SleepTime);
}
}
protected void Session_Start(object sender, EventArgs e)
{
// InitializeChartSettings();
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
MDC.Set("addr", Request.UserHostAddress);
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
string errCode = "";
Exception ex = Server.GetLastError();
if (ex is System.Threading.ThreadAbortException)
{
return;
}
else if (ex is HttpException)
{
errCode = ((HttpException)ex).GetHttpCode().ToString();
}
_logger.Error(ex);
//Check if the error is caused by illegal characters in parameter
if (ex is PCAxis.Web.Core.Exceptions.InvalidQuerystringParameterException || ex.InnerException is PCAxis.Web.Core.Exceptions.InvalidQuerystringParameterException)
{
Server.Transfer("~/ErrorGeneral.aspx");
}
else if (!string.IsNullOrEmpty(errCode))
{
Server.Transfer("~/ErrorGeneral.aspx?errcode=" + errCode);
}
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
//Stop background worker
PxWebBackgroundWorker.Run = false;
ApplicationShutdownReason shutdownReason = System.Web.Hosting.HostingEnvironment.ShutdownReason;
_logger.InfoFormat("ShutdownReason: {0}", shutdownReason);
_logger.Info(" === Application end ===");
}
void RegisterRoutes(RouteCollection routes)
{
// string routePrefix = ConfigurationManager.AppSettings["routePrefix"];
// if (routePrefix == null)
// throw new Exception("No route prefix set up in app config");
// routes.Add(new Route
// (
// routePrefix + "{language}/{*path}"
// , new SSDRouteHandler()
// ));
RouteTable.Routes.MapPageRoute("DefaultRoute",
PxUrl.PX_START + "/",
"~/Default.aspx");
RouteTable.Routes.MapPageRoute("LangRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/",
"~/Default.aspx");
RouteTable.Routes.MapPageRoute("DbRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/",
"~/Menu.aspx");
RouteTable.Routes.MapPageRoute("DbSearchRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
PxUrl.VIEW_SEARCH + "/",
"~/Search.aspx");
RouteTable.Routes.MapPageRoute("DbPathRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
"{" + PxUrl.PATH_KEY + "}/",
"~/Menu.aspx");
RouteTable.Routes.MapPageRoute("SelectionRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
"{" + PxUrl.PATH_KEY + "}/" +
"{" + PxUrl.TABLE_KEY + "}/",
"~/Selection.aspx");
//RouteTable.Routes.MapPageRoute("GotoRoute",
// PxUrl.PX_GOTO + "/" +
// "{" + PxUrl.LANGUAGE_KEY + "}/" +
// "{" + PxUrl.DB_KEY + "}/" +
// "{" + PxUrl.TABLE_KEY + "}/",
// "~/Goto.ashx");
RouteTable.Routes.MapPageRoute("SelectionInformationRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
"{" + PxUrl.PATH_KEY + "}/" +
"{" + PxUrl.TABLE_KEY + "}/" +
PxUrl.VIEW_INFORMATION_IDENTIFIER + "/",
"~/InformationSelection.aspx");
RouteTable.Routes.MapPageRoute("SelectionTipsRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
"{" + PxUrl.PATH_KEY + "}/" +
"{" + PxUrl.TABLE_KEY + "}/" +
PxUrl.VIEW_TIPS_IDENTIFIER + "/",
"~/MarkingTips.aspx");
RouteTable.Routes.MapPageRoute("SelectionFootnotesRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
"{" + PxUrl.PATH_KEY + "}/" +
"{" + PxUrl.TABLE_KEY + "}/" +
PxUrl.VIEW_FOOTNOTES_IDENTIFIER + "/",
"~/FootnotesSelection.aspx");
RouteTable.Routes.MapPageRoute("TablePresentationRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
"{" + PxUrl.PATH_KEY + "}/" +
"{" + PxUrl.TABLE_KEY + "}/" +
PxUrl.VIEW_TABLE_IDENTIFIER + "/" +
"{" + PxUrl.LAYOUT_KEY + "}/",
"~/Table.aspx");
RouteTable.Routes.MapPageRoute("ChartPresentationRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
"{" + PxUrl.PATH_KEY + "}/" +
"{" + PxUrl.TABLE_KEY + "}/" +
PxUrl.VIEW_CHART_IDENTIFIER + "/" +
"{" + PxUrl.LAYOUT_KEY + "}/",
"~/Chart.aspx");
RouteTable.Routes.MapPageRoute("InformationPresentationRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
"{" + PxUrl.PATH_KEY + "}/" +
"{" + PxUrl.TABLE_KEY + "}/" +
PxUrl.VIEW_INFORMATION_IDENTIFIER + "/" +
"{" + PxUrl.LAYOUT_KEY + "}/",
"~/InformationPresentation.aspx");
RouteTable.Routes.MapPageRoute("SortedTablePresentationRoute",
PxUrl.PX_START + "/" +
"{" + PxUrl.LANGUAGE_KEY + "}/" +
"{" + PxUrl.DB_KEY + "}/" +
"{" + PxUrl.PATH_KEY + "}/" +
"{" + PxUrl.TABLE_KEY + "}/" +
PxUrl.VIEW_SORTEDTABLE_IDENTIFIER + "/" +
"{" + PxUrl.LAYOUT_KEY + "}/",
"~/DataSort.aspx");
RouteTable.Routes.MapHttpRoute(name: "CacheApi", routeTemplate: "api/admin/v1/{controller}");
RouteTable.Routes.MapHttpRoute(name: "MenuApi", routeTemplate: "api/admin/v1/{controller}/{database}");
}
/// <summary>
/// Initialize the cache controller that handles all of the PX caches
/// </summary>
private void InitializeCacheController()
{
//IPxCacheController controller;
string strCacheController = ConfigurationManager.AppSettings["pxCacheController"]; // Do we have a customized cache controller?
if (string.IsNullOrEmpty(strCacheController))
{
_cacheController = new PXWeb.Management.CacheController(); // Use the default cache controller
}
else
{
try
{
var typeString = strCacheController;
var parts = typeString.Split(',');
var typeName = parts[0].Trim();
var assemblyName = parts[1].Trim();
_cacheController = (IPxCacheController)Activator.CreateInstance(assemblyName, typeName).Unwrap(); // Use the customized cache controller
}
catch (Exception)
{
_cacheController = new PXWeb.Management.CacheController();
}
}
List<IPxCache> lstCache = new List<IPxCache>();
// Add all PX caches to the list
lstCache.Add(PXWeb.Management.SavedQueryPaxiomCache.Current);
lstCache.Add(PCAxis.Api.ApiCache.Current);
if (_metaPxCache != null)
{
lstCache.Add(_metaPxCache);
}
_cacheController.Initialize(lstCache);
PXWeb.Management.PxContext.CacheController = _cacheController;
}
}
}
| 44.520576 | 174 | 0.497158 | [
"Apache-2.0"
] | runejo/PxWeb | PXWeb/Global.asax.cs | 21,639 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace SMVC.Models
{
public class RegisterCreateVM
{
[DisplayName("First Name")]
[Required]
public string CustomerFirstName { get; set; }
[DisplayName("Last Name")]
[Required]
public string CustomerLastName { get; set; }
[DisplayName("Email")]
[Required]
[EmailAddress]
public string Email { get; set; }
[DisplayName("Phone Number")]
[Required]
[Phone]
public string CustomerPhoneNumber { get; set; }
}
}
| 22.83871 | 55 | 0.629944 | [
"MIT"
] | 210215-USF-NET/Ulices_Esqueda-P1 | StoreApp/SMVC/Models/RegisterCreateVM.cs | 710 | C# |
using EnvDTE80;
using log4net;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TCatSysManagerLib;
namespace TcUnit.TcUnit_Runner
{
/// <summary>
/// This class is used to instantiate the Visual Studio Development Tools Environment (DTE)
/// which is used to programatically access all the functions in VS.
/// </summary>
class VisualStudioInstance
{
[DllImport("ole32.dll")]
private static extern int CreateBindCtx(uint reserved, out IBindCtx ppbc);
[DllImport("ole32.dll")]
public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
private string @filePath = null;
private string vsVersion = null;
private string tcVersion = null;
private string forceToThisTwinCatVersion = null;
private EnvDTE80.DTE2 dte = null;
private Type type = null;
private EnvDTE.Solution visualStudioSolution = null;
EnvDTE.Project pro = null;
ILog log = LogManager.GetLogger("TcUnit-Runner");
private bool loaded = false;
public VisualStudioInstance(string @visualStudioSolutionFilePath, string twinCatVersion, string forceToThisTwinCatVersion)
{
this.filePath = visualStudioSolutionFilePath;
string visualStudioVersion = VisualStudioTools.FindVisualStudioVersion(@filePath);
this.vsVersion = visualStudioVersion;
this.tcVersion = twinCatVersion;
this.forceToThisTwinCatVersion = forceToThisTwinCatVersion;
}
public VisualStudioInstance(int vsVersionMajor, int vsVersionMinor)
{
string visualStudioVersion = vsVersionMajor.ToString() + "." + vsVersionMinor.ToString();
this.vsVersion = visualStudioVersion;
}
/// <summary>
/// Loads the development tools environment. It does this by:
/// 1. First checking whether there is an existing VS-DTE process for this solution already created, and in that case attach to it.
/// If an existing process doesn't exist, go to step 2.
/// 2. Create a new instance of the VS DTE
/// TODO: Implement the AttachToExistingDte() function
/// </summary>
public void Load(bool isTcVersionPinned)
{
// First try attach to an existing process
//log.Info("Checking if there is an existing Visual Studio process to attach to ...");
//string progId = VisualStudioDteAvailable(vsVersion);
//dte = AttachToExistingDte(progId);
//AttachToExistingDte();
//log.Info("DTE: " + dte.ToString());
if (dte == null)
{
// log.Info("... none existing Visual Studio process found. Creating new instance of visual studio DTE.");
// If existing process doesn't exist, load a new DTE process
LoadDevelopmentToolsEnvironment(vsVersion, isTcVersionPinned);
}
else
{
log.Info("... existing Visual Studio process found! Re-using.");
}
}
/// <summary>
/// Loads the solution-file defined when creating this object
/// </summary>
public void LoadSolution()
{
if (!String.IsNullOrEmpty(@filePath))
{
LoadSolution(@filePath);
LoadProject();
loaded = true;
}
}
/// <summary>
/// Closes the DTE and makes sure the VS process is completely shutdown
/// </summary>
public void Close()
{
if (loaded) {
log.Info("Closing the Visual Studio Development Tools Environment (DTE)...");
Thread.Sleep(20000); // Avoid 'Application is busy'-problem (RPC_E_CALL_REJECTED 0x80010001 or RPC_E_SERVERCALL_RETRYLATER 0x8001010A)
dte.Quit();
}
loaded = false;
}
private void LoadDevelopmentToolsEnvironment(string visualStudioVersion, bool isTwinCatVersionPinned)
{
/* Make sure the DTE loads with the same version of Visual Studio as the
* TwinCAT project was created in
*/
// Load the DTE
string VisualStudioProgId = VisualStudioDteAvailable(visualStudioVersion);
bool isVersionAvailable = false;
bool isForceVersionAvailable = false;
dte.UserControl = false; // have devenv.exe automatically close when launched using automation
dte.SuppressUI = true;
// Make sure all types of errors in the error list are collected
dte.ToolWindows.ErrorList.ShowErrors = true;
dte.ToolWindows.ErrorList.ShowMessages = true;
dte.ToolWindows.ErrorList.ShowWarnings = true;
// First set the SilentMode and then try to open the Remote Manager
var tcAutomationSettings = dte.GetObject("TcAutomationSettings");
tcAutomationSettings.SilentMode = true; // Only available from TC3.1.4020.0 and above
// Load the correct version of TwinCAT using the remote manager in the automation interface
ITcRemoteManager remoteManager = dte.GetObject("TcRemoteManager");
var allTwinCatVersions = new List<Version>();
Version latestTwinCatVersion = null;
// Check if version is installed
foreach (var possibleVersion in remoteManager.Versions)
{
// Add installed TwinCAT version to versions list
allTwinCatVersions.Add(new Version(possibleVersion));
if (possibleVersion == this.tcVersion)
{
isVersionAvailable = true;
}
// Check if forced version is installed
if (possibleVersion == this.forceToThisTwinCatVersion && this.forceToThisTwinCatVersion != null)
{
isForceVersionAvailable = true;
log.Info("The forced TwinCAT version is available");
}
}
// Find latest installed TwinCAT version
latestTwinCatVersion = allTwinCatVersions.Max();
// If the version is pinned, check if the pinned version is available
if (isTwinCatVersionPinned && (String.IsNullOrEmpty(this.forceToThisTwinCatVersion)))
{
if (isVersionAvailable)
{
log.Info("The pinned TwinCAT version is available");
} else {
log.Error("The pinned TwinCAT version is not available");
throw new Exception("The pinned TwinCAT version is not available");
}
}
/* The basic procedure/priority for selection of which TwinCAT version should be used is as this:
* - If TwinCAT project version is forced (by -w argument to TcUnit-Runner), go with this version, otherwise...
* - If TwinCAT project is pinned, go with this version, otherwise...
* - Go with latest installed version of TwinCAT
*/
if (isTwinCatVersionPinned && isVersionAvailable && (String.IsNullOrEmpty(this.forceToThisTwinCatVersion)))
{
remoteManager.Version = this.tcVersion;
}
else if (isForceVersionAvailable)
{
log.Info("TwinCAT version is forced to " + this.forceToThisTwinCatVersion);
remoteManager.Version = this.forceToThisTwinCatVersion;
}
else if (!isForceVersionAvailable && (!String.IsNullOrEmpty(this.forceToThisTwinCatVersion)))
{
log.Error("The forced TwinCAT version " + this.forceToThisTwinCatVersion + " is not available");
throw new Exception("The forced TwinCAT version is not available");
}
else if (latestTwinCatVersion != null)
{
remoteManager.Version = latestTwinCatVersion.ToString();
}
else
{
log.Error("It´s not possible to run TwinCAT in this configuration (TwinCAT-ForcedVersion / pinned TwinCAT Version / installed TwinCAT Version ");
throw new Exception("Wrong configuration for this TwinCAT version");
}
// Log the Version which will be loaded
log.Info("Using the TwinCAT remote manager to load TwinCAT version '" + remoteManager.Version + "'...");
}
/// <summary>
/// Returns any version of Visual Studio that is available on the machine, first trying with the provided version as parameter.
/// If a version is found, it loads the DTE.
/// If it fails try to use any DTE starting from the latest DTE to the oldest DTE (12.0 - VS 2013)
/// If no DTE is found, return null
/// If the version is greater than 15.0 (2017) or later, try to use the TcXaeShell first.
/// If that fails use VisulStudio as DTE.
/// </summary>
/// <param name="visualStudioVersion"></param>
/// <returns>The full visual studio prog id (for example "VisualStudio.DTE.15.0") or null if not found</returns>
private string VisualStudioDteAvailable(string visualStudioVersion)
{
/* Try to load the DTE with the same version of Visual Studio as the
* TwinCAT project was created in
*/
string VisualStudioProgId;
Version vsVersion15 = new Version("15.0"); // Beckhoff started with TcXaeShell from version 15.0 (VS2017)
Version vsVersion = new Version(visualStudioVersion);
// Check if the TcXaeShell is installed for everything equal or above version 15.0 (VS2017)
if (vsVersion >= vsVersion15)
{
VisualStudioProgId = "TcXaeShell.DTE." + visualStudioVersion;
}
else
{
VisualStudioProgId = "VisualStudio.DTE." + visualStudioVersion;
}
if (TryLoadDte(VisualStudioProgId))
{
return VisualStudioProgId;
} else
{
List<string> VisualStudioProgIds = new List<string>();
VisualStudioProgIds.Add("VisualStudio.DTE.16.0"); // VS2019
VisualStudioProgIds.Add("TcXaeShell.DTE.15.0"); // TcXaeShell (VS2017)
VisualStudioProgIds.Add("VisualStudio.DTE.15.0"); // VS2017
VisualStudioProgIds.Add("VisualStudio.DTE.14.0"); // VS2015
VisualStudioProgIds.Add("VisualStudio.DTE.12.0"); // VS2013
foreach (string visualStudioProgIdent in VisualStudioProgIds)
{
if (TryLoadDte(visualStudioProgIdent))
{
return visualStudioProgIdent;
}
}
}
// None found, return null
return null;
}
/// <summary>
/// Tries to load the selected version of VisualStudioProgramIdentity
/// </summary>
/// <param name="visualStudioProgIdentity"></param>
/// <returns>True if successful. False if failed loading DTE</returns>
private bool TryLoadDte(string visualStudioProgIdentity)
{
log.Info("Trying to load the Visual Studio Development Tools Environment (DTE) version '" + visualStudioProgIdentity + "' ...");
type = System.Type.GetTypeFromProgID(visualStudioProgIdentity);
try
{
dte = (EnvDTE80.DTE2)System.Activator.CreateInstance(type);
log.Info("...SUCCESSFUL!");
return true;
} catch
{
log.Info("...FAILED!");
return false;
}
}
/// <summary>
/// Searches for DTE instances in the ROT snapshot and returns a Hashtable with all found instances.
/// This Hashtable may then be used by the method attachToExistingDte() to select single DTE instances.
/// </summary>
//private Hashtable GetIDEInstances(bool openSolutionsOnly, string progId)
private Hashtable GetIDEInstances(bool openSolutionsOnly)
{
Hashtable runningIDEInstances = new Hashtable();
Hashtable runningObjects = GetRunningObjectTable();
IDictionaryEnumerator rotEnumerator = runningObjects.GetEnumerator();
while (rotEnumerator.MoveNext())
{
string candidateName = (string)rotEnumerator.Key;
//if (!candidateName.StartsWith("!" + progId))
// continue;
EnvDTE.DTE ide = rotEnumerator.Value as EnvDTE.DTE;
if (ide == null)
continue;
if (openSolutionsOnly)
{
try
{
string solutionFile = ide.Solution.FullName;
if (solutionFile != String.Empty)
runningIDEInstances[candidateName] = ide;
}
catch { }
}
else
runningIDEInstances[candidateName] = ide;
}
return runningIDEInstances;
}
/// <summary>
/// Queries the Running Object Table (ROT) for a snapshot of all running processes in the table. Returns all found processes in a Hashtable, which are then used by
/// getIdeInstances() for further filtering for DTE instances.
/// </summary>
private Hashtable GetRunningObjectTable()
{
Hashtable result = new Hashtable();
IntPtr numFetched = IntPtr.Zero;
IRunningObjectTable runningObjectTable;
IEnumMoniker monikerEnumerator;
IMoniker[] monikers = new IMoniker[1];
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
{
IBindCtx ctx;
CreateBindCtx(0, out ctx);
string runningObjectName;
monikers[0].GetDisplayName(ctx, null, out runningObjectName);
object runningObjectVal;
runningObjectTable.GetObject(monikers[0], out runningObjectVal);
result[runningObjectName] = runningObjectVal;
}
return result;
}
// TODO: Implement the AttachToExistingDte() function
/// <summary>
/// Uses the GetIdeInstances() method to select a DTE instance based on its solution path and, when found,
/// attaches a new DTE object to this instance.
/// </summary>
//private EnvDTE.DTE AttachToExistingDte(string progId)
private EnvDTE.DTE AttachToExistingDte()
{
EnvDTE.DTE dteReturn = null;
//Hashtable dteInstances = GetIDEInstances(false, progId);
Hashtable dteInstances = GetIDEInstances(false);
IDictionaryEnumerator hashtableEnumerator = dteInstances.GetEnumerator();
while (hashtableEnumerator.MoveNext())
{
EnvDTE.DTE dteTemp = hashtableEnumerator.Value as EnvDTE.DTE;
if (dteTemp.Solution.FullName == filePath)
{
log.Info("Found solution in list of all open DTE objects.");
dteReturn = dteTemp;
break;
}
}
return dteReturn;
}
private void LoadSolution(string filePath)
{
visualStudioSolution = dte.Solution;
visualStudioSolution.Open(@filePath);
}
private void LoadProject()
{
pro = visualStudioSolution.Projects.Item(1);
}
/// <returns>Returns null if no version was found</returns>
public string GetVisualStudioVersion()
{
return this.vsVersion;
}
public EnvDTE.Project GetProject()
{
return this.pro;
}
public EnvDTE80.DTE2 GetDevelopmentToolsEnvironment()
{
return dte;
}
public void CleanSolution()
{
visualStudioSolution.SolutionBuild.Clean(true);
}
public void BuildSolution()
{
visualStudioSolution.SolutionBuild.Build(false);
SpinWait.SpinUntil(() => visualStudioSolution.SolutionBuild.BuildState == EnvDTE.vsBuildState.vsBuildStateDone);
}
public ErrorItems GetErrorItems()
{
return dte.ToolWindows.ErrorList.ErrorItems;
}
}
} | 41.485577 | 171 | 0.586105 | [
"MIT"
] | Hopperpop/TcUnit-Runner | TcUnit-Runner/VisualStudioInstance.cs | 17,261 | C# |
using DevExpress.XtraSplashScreen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsForm
{
public static class Global
{
public static string SEVER_URL = "http://localhost:51989";
public static string CREATE_UPDATE_INFO_URL = "cap-nhat-thong-tin/tao-moi";
public static string UPLOAD_IMAGE_URL = "api/Media";
public static void ShowWaitForm(Form form)
{
SplashScreenManager.ShowForm(form, typeof(WaitForm1), true, true, false, ParentFormState.Locked);
//The Wait Form is opened in a separate thread. To change its Description, use the SetWaitFormDescription method.
for (int i = 1; i <= 100; i++)
{
SplashScreenManager.Default.SetWaitFormDescription(i.ToString() + "%");
Random random = new Random();
int sleepRandom = random.Next(20, 50);
Thread.Sleep(sleepRandom);
}
//Close Wait Form
SplashScreenManager.CloseForm();
}
}
public static class StringExtensions
{
private static Random random = new Random();
private const int MaxDescriptionSEO = 150;
private const int MaxDescriptionNormal = 300;
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public static string RandomNumber(int length)
{
const string chars = "0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public static string MakeUrlFriendly(this string value)
{
value = value.ToLowerInvariant().Replace(" ", "-");
value = value.ToLowerInvariant().Replace(".", "");
value = Regex.Replace(value, @"[^0-9a-z-]", string.Empty);
return value;
}
//Chuyen chuoi sang danh sach chuoi
public static List<string> ConvertStringToListString(string value)
{
while (value.IndexOf(" ") >= 0) //tim trong chuoi vi tri co 2 khoang trong tro len
{
value = value.Replace(" ", " "); //sau do thay the bang 1 khoang trong
}
List<string> list = new List<string>(10000);
//Ham cat chuoi
while (value.IndexOf(" ") >= 0 && value.IndexOf(",") >= 0)
{
int begin = 0;
int end = 0;
if (value.IndexOf(" ") == 0 || value.IndexOf(",") == 0)
begin = 1;
if (value.IndexOf(", ") == 0)
begin = 2;
if (value.IndexOf(",", begin) != -1)
{
end = value.IndexOf(",", begin);
}
else
{
end = value.Length;
}
string temp = "";
if (begin == 0)
{
temp = value.Substring(begin, end);
}
else if (begin == 1)
{
temp = value.Substring(begin, end - 1);
}
else
{
temp = value.Substring(begin, end - 2);
}
value = value.Remove(0, end);
list.Add(temp);
}
return list;
}
//Chuyen sang tieng viet khong dau
public static string ConvertToUnSign3(string s)
{
Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
string temp = s.Normalize(NormalizationForm.FormD);
temp = temp.ToLower();
return regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D').Replace(" ", "-");
}
}
}
| 35.033333 | 125 | 0.516413 | [
"Apache-2.0"
] | nguyendev/DATN | Code/WindowsForm/Global.cs | 4,206 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.