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 |
|---|---|---|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Text;
namespace System.Runtime.InteropServices
{
public static partial class Marshal
{
public static string? PtrToStringAuto(IntPtr ptr, int len)
{
return PtrToStringUTF8(ptr, len);
}
public static string? PtrToStringAuto(IntPtr ptr)
{
return PtrToStringUTF8(ptr);
}
public static IntPtr StringToHGlobalAuto(string? s)
{
return StringToHGlobalUTF8(s);
}
public static IntPtr StringToCoTaskMemAuto(string? s)
{
return StringToCoTaskMemUTF8(s);
}
private static int GetSystemMaxDBCSCharSize() => 3;
private static bool IsNullOrWin32Atom(IntPtr ptr) => ptr == IntPtr.Zero;
internal static unsafe int StringToAnsiString(string s, byte* buffer, int bufferLength, bool bestFit = false, bool throwOnUnmappableChar = false)
{
Debug.Assert(bufferLength >= (s.Length + 1) * SystemMaxDBCSCharSize, "Insufficient buffer length passed to StringToAnsiString");
int convertedBytes;
fixed (char* pChar = s)
{
convertedBytes = Encoding.UTF8.GetBytes(pChar, s.Length, buffer, bufferLength);
}
buffer[convertedBytes] = 0;
return convertedBytes;
}
// Returns number of bytes required to convert given string to Ansi string. The return value includes null terminator.
internal static unsafe int GetAnsiStringByteCount(ReadOnlySpan<char> chars)
{
int byteLength = Encoding.UTF8.GetByteCount(chars);
return checked(byteLength + 1);
}
// Converts given string to Ansi string. The destination buffer must be large enough to hold the converted value, including null terminator.
internal static unsafe void GetAnsiStringBytes(ReadOnlySpan<char> chars, Span<byte> bytes)
{
int actualByteLength = Encoding.UTF8.GetBytes(chars, bytes);
bytes[actualByteLength] = 0;
}
public static unsafe IntPtr AllocHGlobal(IntPtr cb)
{
return (nint)NativeMemory.Alloc((nuint)(nint)cb);
}
public static unsafe void FreeHGlobal(IntPtr hglobal)
{
NativeMemory.Free((void*)(nint)hglobal);
}
public static unsafe IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
{
return (nint)NativeMemory.Realloc((void*)(nint)pv, (nuint)(nint)cb);
}
public static IntPtr AllocCoTaskMem(int cb) => AllocHGlobal((nint)(uint)cb);
public static void FreeCoTaskMem(IntPtr ptr) => FreeHGlobal(ptr);
public static unsafe IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
{
nuint cbNative = (nuint)(uint)cb;
void* pvNative = (void*)(nint)pv;
if ((cbNative == 0) && (pvNative != null))
{
Interop.Sys.Free(pvNative);
return IntPtr.Zero;
}
return (nint)NativeMemory.Realloc((void*)(nint)pv, cbNative);
}
internal static unsafe IntPtr AllocBSTR(int length)
{
// SysAllocString on Windows aligns the memory block size up
const nuint WIN32_ALLOC_ALIGN = 15;
ulong cbNative = 2 * (ulong)(uint)length + (uint)sizeof(IntPtr) + (uint)sizeof(char) + WIN32_ALLOC_ALIGN;
if (cbNative > uint.MaxValue)
{
throw new OutOfMemoryException();
}
void* p = Interop.Sys.Malloc((nuint)cbNative & ~WIN32_ALLOC_ALIGN);
if (p == null)
{
throw new OutOfMemoryException();
}
void* s = (byte*)p + sizeof(nuint);
*(((uint*)s) - 1) = (uint)(length * sizeof(char));
((char*)s)[length] = '\0';
return (nint)s;
}
internal static unsafe IntPtr AllocBSTRByteLen(uint length)
{
// SysAllocString on Windows aligns the memory block size up
const nuint WIN32_ALLOC_ALIGN = 15;
ulong cbNative = (ulong)(uint)length + (uint)sizeof(IntPtr) + (uint)sizeof(char) + WIN32_ALLOC_ALIGN;
if (cbNative > uint.MaxValue)
{
throw new OutOfMemoryException();
}
void* p = Interop.Sys.Malloc((nuint)cbNative & ~WIN32_ALLOC_ALIGN);
if (p == null)
{
throw new OutOfMemoryException();
}
void* s = (byte*)p + sizeof(nuint);
*(((uint*)s) - 1) = (uint)length;
// NULL-terminate with both a narrow and wide zero.
*(byte*)((byte*)s + length) = (byte)'\0';
*(short*)((byte*)s + ((length + 1) & ~1)) = 0;
return (nint)s;
}
public static unsafe void FreeBSTR(IntPtr ptr)
{
void* ptrNative = (void*)(nint)ptr;
if (ptrNative != null)
{
Interop.Sys.Free((byte*)ptr - sizeof(nuint));
}
}
internal static Type? GetTypeFromProgID(string progID, string? server, bool throwOnError)
{
if (progID == null)
throw new ArgumentNullException(nameof(progID));
if (throwOnError)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
return null;
}
/// <summary>
/// Get the last system error on the current thread
/// </summary>
/// <returns>The last system error</returns>
/// <remarks>
/// The error is that for the current operating system (e.g. errno on Unix, GetLastError on Windows)
/// </remarks>
public static int GetLastSystemError()
{
return Interop.Sys.GetErrNo();
}
/// <summary>
/// Set the last system error on the current thread
/// </summary>
/// <param name="error">Error to set</param>
/// <remarks>
/// The error is that for the current operating system (e.g. errno on Unix, SetLastError on Windows)
/// </remarks>
public static void SetLastSystemError(int error)
{
Interop.Sys.SetErrNo(error);
}
}
}
| 32.623116 | 153 | 0.5687 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Unix.cs | 6,492 | C# |
//#define USE_SharpZipLib
/* * * * *
* This is an extension of the SimpleJSON framework to provide methods to
* serialize a JSON object tree into a compact binary format. Optionally the
* binary stream can be compressed with the SharpZipLib when using the define
* "USE_SharpZipLib"
*
* Those methods where originally part of the framework but since it's rarely
* used I've extracted this part into this seperate module file.
*
* You can use the define "SimpleJSON_ExcludeBinary" to selectively disable
* this extension without the need to remove the file from the project.
*
*
* The MIT License (MIT)
*
* Copyright (c) 2012-2017 Markus Göbel (Bunny83)
*
* 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;
namespace SimpleJSON
{
#if !SimpleJSON_ExcludeBinary
public abstract partial class JSONNode
{
public abstract void SerializeBinary(System.IO.BinaryWriter aWriter);
public void SaveToBinaryStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
SerializeBinary(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToBinaryStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public void SaveToBinaryFile(string aFileName)
{
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using (var F = System.IO.File.OpenWrite(aFileName))
{
SaveToBinaryStream(F);
}
}
public string SaveToBinaryBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToBinaryStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JSONNode DeserializeBinary(System.IO.BinaryReader aReader)
{
JSONNodeType type = (JSONNodeType)aReader.ReadByte();
switch (type)
{
case JSONNodeType.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for (int i = 0; i < count; i++)
tmp.Add(DeserializeBinary(aReader));
return tmp;
}
case JSONNodeType.Object:
{
int count = aReader.ReadInt32();
JSONObject tmp = new JSONObject();
for (int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = DeserializeBinary(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONNodeType.String:
{
return new JSONString(aReader.ReadString());
}
case JSONNodeType.Number:
{
return new JSONNumber(aReader.ReadDouble());
}
case JSONNodeType.Boolean:
{
return new JSONBool(aReader.ReadBoolean());
}
case JSONNodeType.NullValue:
{
return JSONNull.CreateOrGet();
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromBinaryStream(System.IO.Stream aData)
{
using (var R = new System.IO.BinaryReader(aData))
{
return DeserializeBinary(R);
}
}
public static JSONNode LoadFromBinaryFile(string aFileName)
{
using (var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromBinaryStream(F);
}
}
public static JSONNode LoadFromBinaryBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromBinaryStream(stream);
}
}
public partial class JSONArray : JSONNode
{
public override void SerializeBinary(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONNodeType.Array);
aWriter.Write(m_List.Count);
for (int i = 0; i < m_List.Count; i++)
{
m_List[i].SerializeBinary(aWriter);
}
}
}
public partial class JSONObject : JSONNode
{
public override void SerializeBinary(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONNodeType.Object);
aWriter.Write(m_Dict.Count);
foreach (string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].SerializeBinary(aWriter);
}
}
}
public partial class JSONString : JSONNode
{
public override void SerializeBinary(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONNodeType.String);
aWriter.Write(m_Data);
}
}
public partial class JSONNumber : JSONNode
{
public override void SerializeBinary(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONNodeType.Number);
aWriter.Write(m_Data);
}
}
public partial class JSONBool : JSONNode
{
public override void SerializeBinary(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONNodeType.Boolean);
aWriter.Write(m_Data);
}
}
public partial class JSONNull : JSONNode
{
public override void SerializeBinary(System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONNodeType.NullValue);
}
}
internal partial class JSONLazyCreator : JSONNode
{
public override void SerializeBinary(System.IO.BinaryWriter aWriter)
{
}
}
#endif
} | 34.151515 | 150 | 0.602977 | [
"MIT"
] | QuantumCalzone/UnityGitPackageUpdater | Packages/UnityGitPackageUpdater/Editor/SimpleJSON/SimpleJSONBinary.cs | 10,144 | 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("Case.ExportSharedParameters")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Case.ExportSharedParameters")]
[assembly: AssemblyCopyright("")]
[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("97a31c0d-c96c-4a41-b30e-f8d8b056e1bd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.108108 | 84 | 0.748936 | [
"MIT"
] | johnpierson/case-apps | 2018/Case.ExportSharedParameters/Case.ExportSharedParameters/Properties/AssemblyInfo.cs | 1,412 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-09-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the RevokeDBSecurityGroupIngress operation.
/// Revokes ingress from a DBSecurityGroup for previously authorized IP ranges or EC2
/// or VPC Security Groups. Required parameters for this API are one of CIDRIP, EC2SecurityGroupId
/// for VPC, or (EC2SecurityGroupOwnerId and either EC2SecurityGroupName or EC2SecurityGroupId).
/// </summary>
public partial class RevokeDBSecurityGroupIngressRequest : AmazonRDSRequest
{
private string _cIDRIP;
private string _dBSecurityGroupName;
private string _eC2SecurityGroupId;
private string _eC2SecurityGroupName;
private string _eC2SecurityGroupOwnerId;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public RevokeDBSecurityGroupIngressRequest() { }
/// <summary>
/// Instantiates RevokeDBSecurityGroupIngressRequest with the parameterized properties
/// </summary>
/// <param name="dbSecurityGroupName"> The name of the DB security group to revoke ingress from. </param>
public RevokeDBSecurityGroupIngressRequest(string dbSecurityGroupName)
{
_dBSecurityGroupName = dbSecurityGroupName;
}
/// <summary>
/// Gets and sets the property CIDRIP.
/// <para>
/// The IP range to revoke access from. Must be a valid CIDR range. If <code>CIDRIP</code>
/// is specified, <code>EC2SecurityGroupName</code>, <code>EC2SecurityGroupId</code> and
/// <code>EC2SecurityGroupOwnerId</code> cannot be provided.
/// </para>
/// </summary>
public string CIDRIP
{
get { return this._cIDRIP; }
set { this._cIDRIP = value; }
}
// Check to see if CIDRIP property is set
internal bool IsSetCIDRIP()
{
return this._cIDRIP != null;
}
/// <summary>
/// Gets and sets the property DBSecurityGroupName.
/// <para>
/// The name of the DB security group to revoke ingress from.
/// </para>
/// </summary>
public string DBSecurityGroupName
{
get { return this._dBSecurityGroupName; }
set { this._dBSecurityGroupName = value; }
}
// Check to see if DBSecurityGroupName property is set
internal bool IsSetDBSecurityGroupName()
{
return this._dBSecurityGroupName != null;
}
/// <summary>
/// Gets and sets the property EC2SecurityGroupId.
/// <para>
/// The id of the EC2 security group to revoke access from. For VPC DB security groups,
/// <code>EC2SecurityGroupId</code> must be provided. Otherwise, EC2SecurityGroupOwnerId
/// and either <code>EC2SecurityGroupName</code> or <code>EC2SecurityGroupId</code> must
/// be provided.
/// </para>
/// </summary>
public string EC2SecurityGroupId
{
get { return this._eC2SecurityGroupId; }
set { this._eC2SecurityGroupId = value; }
}
// Check to see if EC2SecurityGroupId property is set
internal bool IsSetEC2SecurityGroupId()
{
return this._eC2SecurityGroupId != null;
}
/// <summary>
/// Gets and sets the property EC2SecurityGroupName.
/// <para>
/// The name of the EC2 security group to revoke access from. For VPC DB security groups,
/// <code>EC2SecurityGroupId</code> must be provided. Otherwise, EC2SecurityGroupOwnerId
/// and either <code>EC2SecurityGroupName</code> or <code>EC2SecurityGroupId</code> must
/// be provided.
/// </para>
/// </summary>
public string EC2SecurityGroupName
{
get { return this._eC2SecurityGroupName; }
set { this._eC2SecurityGroupName = value; }
}
// Check to see if EC2SecurityGroupName property is set
internal bool IsSetEC2SecurityGroupName()
{
return this._eC2SecurityGroupName != null;
}
/// <summary>
/// Gets and sets the property EC2SecurityGroupOwnerId.
/// <para>
/// The AWS Account Number of the owner of the EC2 security group specified in the <code>EC2SecurityGroupName</code>
/// parameter. The AWS Access Key ID is not an acceptable value. For VPC DB security groups,
/// <code>EC2SecurityGroupId</code> must be provided. Otherwise, EC2SecurityGroupOwnerId
/// and either <code>EC2SecurityGroupName</code> or <code>EC2SecurityGroupId</code> must
/// be provided.
/// </para>
/// </summary>
public string EC2SecurityGroupOwnerId
{
get { return this._eC2SecurityGroupOwnerId; }
set { this._eC2SecurityGroupOwnerId = value; }
}
// Check to see if EC2SecurityGroupOwnerId property is set
internal bool IsSetEC2SecurityGroupOwnerId()
{
return this._eC2SecurityGroupOwnerId != null;
}
}
} | 38.055901 | 125 | 0.635874 | [
"Apache-2.0"
] | ermshiperete/aws-sdk-net | AWSSDK_DotNet35/Amazon.RDS/Model/RevokeDBSecurityGroupIngressRequest.cs | 6,127 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Security;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Configuration;
using Microsoft.Practices.Unity;
using DD4T.Mvc.Controllers;
using DD4T.ContentModel;
using DD4T.ContentModel.Exceptions;
using DD4T.Mvc;
using DD4T.Mvc.Html;
using DD4T.Examples.Unity;
using DD4T.Utils;
using DD4T.ContentModel.Factories;
using Trivident.DD4T.Examples.PublicationResolvers;
namespace DD4T.Examples.Controllers
{
public class PageController : TridionControllerBase
{
private IPageFactory _pageFactory = null;
public override ContentModel.Factories.IPageFactory PageFactory
{
get
{
if (_pageFactory == null)
{
_pageFactory = base.PageFactory;
_pageFactory.PublicationResolver = new HostNamePublicationResolver();
}
return _pageFactory;
}
}
#region private members
//private Regex reDefaultPage = new Regex(@".*/[^/\.]*$");
private Regex reDefaultPage = new Regex(@".*/[^/\.]*(/?)$");
private string defaultPageFileName = null;
#endregion
#region constructor(s)
public PageController()
: base()
{
componentPresentationRenderer = UnityHelper.Container.Resolve<IComponentPresentationRenderer>();
}
#endregion
#region public properties
public string DefaultPageFileName
{
get
{
if (defaultPageFileName == null)
{
defaultPageFileName = ConfigurationManager.AppSettings["DD4T.DefaultPage"];
}
return defaultPageFileName;
}
}
#endregion
#region MVC
/// <summary>
/// Create IPage from XML in the broker and forward to the view
/// </summary>
/// <param name="pageId"></param>
/// <returns></returns>
#if (!DEBUG)
[OutputCache(CacheProfile = "ControllerCache")]
#endif
[HandleError]
[AcceptVerbs(HttpVerbs.Get)]
public override System.Web.Mvc.ActionResult Page(string pageId)
{
if (string.IsNullOrEmpty(pageId))
{
pageId = DefaultPageFileName;
}
else
{
if (reDefaultPage.IsMatch("/" + pageId))
{
if (pageId.EndsWith("/"))
{
pageId += DefaultPageFileName;
}
else
{
pageId += "/" + DefaultPageFileName;
}
}
}
try
{
return base.Page(pageId);
}
catch (SecurityException se)
{
throw new HttpException(403, se.Message);
}
}
/// <summary>
/// Create IPage from XML and forward to the view
/// </summary>
/// <remarks>Todo: include this in framework, URL rewriting for images, JS, CSS, etc</remarks>
/// <returns></returns>
[HandleError]
[AcceptVerbs(HttpVerbs.Post)]
public System.Web.Mvc.ActionResult PreviewPage()
{
try
{
using (StreamReader reader = new StreamReader(this.Request.InputStream))
{
string pageXml = reader.ReadToEnd();
IPage model = this.PageFactory.GetIPageObject(pageXml);
if (model == null)
{
throw new ModelNotCreatedException("--unknown--");
}
ViewBag.Title = model.Title;
ViewBag.Renderer = ComponentPresentationRenderer;
return GetView(model);
}
}
catch (SecurityException se)
{
throw new HttpException(403, se.Message);
}
}
/// <summary>
/// Execute search, add results to viewbag and execute standard action result
/// </summary>
/// <param name="pageId"></param>
/// <returns></returns>
[HandleError]
[AcceptVerbs(HttpVerbs.Post)]
public System.Web.Mvc.ActionResult Search(string pageId)
{
using (StreamReader reader = new StreamReader(this.Request.InputStream))
{
NameValueCollection queryString = HttpUtility.ParseQueryString(reader.ReadToEnd());
string query = queryString.Get("query");
List<string> searchResults = new List<string>();
// ToDo: implement actual search
if (query.ToLower().Equals("test"))
{
searchResults.Add("first example result");
searchResults.Add("second example result");
searchResults.Add("third example result");
}
// add result to viewbag
ViewBag.SearchResults = searchResults;
ViewBag.SearchQuery = query;
ViewBag.ShowSearchResults = true;
return Page("Search/" + pageId);
}
}
[AcceptVerbs(HttpVerbs.Get)]
public System.Web.Mvc.ActionResult Xml(string pageId)
{
LoggerService.Information(">>PageController.Xml (url={0})", pageId);
pageId = ParseUrl(pageId);
if (!pageId.StartsWith("/"))
pageId = "/" + pageId;
return GetPlainContent(pageId, "text/xml", Encoding.UTF8);
}
#endregion
#region private
public System.Web.Mvc.ContentResult GetPlainContent(string url, string contentType, System.Text.Encoding encoding)
{
try
{
string raw = PageFactory.FindPageContent(url);
return new ContentResult
{
ContentType = contentType,
Content = raw,
ContentEncoding = encoding
};
}
catch (PageNotFoundException)
{
throw new HttpException(404, "Page cannot be found");
}
catch (SecurityException se)
{
throw new HttpException(403, se.Message);
}
}
private string ParseUrl(string pageId)
{
if (string.IsNullOrEmpty(pageId))
{
pageId = DefaultPageFileName;
}
else
{
if (reDefaultPage.IsMatch("/" + pageId))
{
if (pageId.EndsWith("/"))
{
pageId += DefaultPageFileName;
}
else
{
pageId += "/" + DefaultPageFileName;
}
}
}
return pageId;
}
#endregion
}
}
| 31.42562 | 123 | 0.483761 | [
"Apache-2.0"
] | code-monkee/dynamic-delivery-4-tridion | dotnet/DD4T.Examples/Controllers/PageController.cs | 7,607 | C# |
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MathBarld;
namespace MathBarldTest
{
/// <summary>
/// Summary description for PalindromeTests
/// </summary>
[TestClass]
public class PalindromeTests
{
public PalindromeTests()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void PalindromeWords()
{
Assert.IsTrue("maandnaam".IsPalindrome());
Assert.IsFalse("Hello".IsPalindrome());
}
[TestMethod]
public void PalinDromeWithSentence()
{
Assert.IsTrue("er is daar nog onraad sire".IsPalindrome(true));
}
}
}
| 27.181818 | 85 | 0.559006 | [
"MIT"
] | barld/MathBarld | MathBarldTest/PalindromeTests.cs | 2,095 | C# |
using System.Collections.Generic;
using Elastic.Apm.Api;
using Elastic.Apm.Helpers;
using Newtonsoft.Json;
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable ClassNeverInstantiated.Global
namespace Elastic.Apm.Tests.MockApmServer
{
internal class SpanContextDto : IDto
{
public Database Db { get; set; }
public Http Http { get; set; }
[JsonProperty("tags")]
public Dictionary<string, string> Labels { get; set; }
public override string ToString() => new ToStringBuilder(nameof(SpanContextDto))
{
{ nameof(Db), Db }, { nameof(Http), Http }, { nameof(Labels), Labels }
}.ToString();
public void AssertValid()
{
Db?.AssertValid();
Http?.AssertValid();
Labels?.LabelsAssertValid();
}
}
}
| 22.8 | 82 | 0.719298 | [
"Apache-2.0"
] | Mpdreamz/apm-agent-dotnet | test/Elastic.Apm.Tests.MockApmServer/SpanContextDto.cs | 798 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LinQ.Katas.DataRepository
{
using System;
using System.Collections.Generic;
public partial class CurrencyRate
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public CurrencyRate()
{
this.SalesOrderHeaders = new HashSet<SalesOrderHeader>();
}
public int CurrencyRateID { get; set; }
public System.DateTime CurrencyRateDate { get; set; }
public string FromCurrencyCode { get; set; }
public string ToCurrencyCode { get; set; }
public decimal AverageRate { get; set; }
public decimal EndOfDayRate { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual Currency Currency { get; set; }
public virtual Currency Currency1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; }
}
}
| 41.216216 | 128 | 0.60918 | [
"MIT"
] | cybk/LinQ.Katas | LinQ.Katas/LinQ.Katas.DataRepository/CurrencyRate.cs | 1,525 | C# |
/*
[The "BSD licence"]
Copyright (c) 2005-2007 Kunle Odutola
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code MUST RETAIN the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form MUST REPRODUCE the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior WRITTEN permission.
4. Unless explicitly state otherwise, any contribution intentionally
submitted for inclusion in this work to the copyright owner or licensor
shall be under the terms and conditions of this license, without any
additional terms or conditions.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Antlr.Runtime.Tree
{
using System;
using IToken = Antlr.Runtime.IToken;
using CommonToken = Antlr.Runtime.CommonToken;
public class TreePatternParser
{
protected TreePatternLexer tokenizer;
protected int ttype;
protected TreeWizard wizard;
protected ITreeAdaptor adaptor;
public TreePatternParser(TreePatternLexer tokenizer, TreeWizard wizard, ITreeAdaptor adaptor)
{
this.tokenizer = tokenizer;
this.wizard = wizard;
this.adaptor = adaptor;
ttype = tokenizer.NextToken(); // kickstart
}
public object Pattern()
{
if (ttype == TreePatternLexer.BEGIN)
{
return ParseTree();
}
else if (ttype == TreePatternLexer.ID)
{
object node = ParseNode();
if (ttype == TreePatternLexer.EOF)
{
return node;
}
return null; // extra junk on end
}
return null;
}
public object ParseTree()
{
if (ttype != TreePatternLexer.BEGIN)
{
Console.Out.WriteLine("no BEGIN");
return null;
}
ttype = tokenizer.NextToken();
object root = ParseNode();
if (root == null)
{
return null;
}
while (ttype == TreePatternLexer.BEGIN ||
ttype == TreePatternLexer.ID ||
ttype == TreePatternLexer.PERCENT ||
ttype == TreePatternLexer.DOT)
{
if (ttype == TreePatternLexer.BEGIN)
{
object subtree = ParseTree();
adaptor.AddChild(root, subtree);
}
else
{
object child = ParseNode();
if (child == null)
{
return null;
}
adaptor.AddChild(root, child);
}
}
if (ttype != TreePatternLexer.END)
{
Console.Out.WriteLine("no END");
return null;
}
ttype = tokenizer.NextToken();
return root;
}
public object ParseNode()
{
// "%label:" prefix
string label = null;
if (ttype == TreePatternLexer.PERCENT)
{
ttype = tokenizer.NextToken();
if (ttype != TreePatternLexer.ID)
{
return null;
}
label = tokenizer.sval.ToString();
ttype = tokenizer.NextToken();
if (ttype != TreePatternLexer.COLON)
{
return null;
}
ttype = tokenizer.NextToken(); // move to ID following colon
}
// Wildcard?
if (ttype == TreePatternLexer.DOT)
{
ttype = tokenizer.NextToken();
IToken wildcardPayload = new CommonToken(0, ".");
TreeWizard.TreePattern node = new TreeWizard.WildcardTreePattern(wildcardPayload);
if (label != null)
{
node.label = label;
}
return node;
}
// "ID" or "ID[arg]"
if (ttype != TreePatternLexer.ID)
{
return null;
}
string tokenName = tokenizer.sval.ToString();
ttype = tokenizer.NextToken();
if (tokenName.Equals("nil"))
{
return adaptor.GetNilNode();
}
string text = tokenName;
// check for arg
string arg = null;
if (ttype == TreePatternLexer.ARG)
{
arg = tokenizer.sval.ToString();
text = arg;
ttype = tokenizer.NextToken();
}
// create node
int treeNodeType = wizard.GetTokenType(tokenName);
if (treeNodeType == Token.INVALID_TOKEN_TYPE)
{
return null;
}
object nodeObj;
nodeObj = adaptor.Create(treeNodeType, text);
if ((label != null) && (nodeObj.GetType() == typeof(TreeWizard.TreePattern)))
{
((TreeWizard.TreePattern)nodeObj).label = label;
}
if ((arg != null) && (nodeObj.GetType() == typeof(TreeWizard.TreePattern)))
{
((TreeWizard.TreePattern)nodeObj).hasTextArg = true;
}
return nodeObj;
}
}
} | 27.137566 | 95 | 0.682394 | [
"Apache-2.0"
] | 19Leonidas99/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | java/java2py/antlr-3.1.3/runtime/CSharp/Sources/Antlr3.Runtime/Antlr.Runtime.Tree/TreePatternParser.cs | 5,129 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.F5BigIP
{
[F5BigIPResourceType("f5bigip:index/eventServiceDiscovery:EventServiceDiscovery")]
public partial class EventServiceDiscovery : Pulumi.CustomResource
{
/// <summary>
/// Map of node which will be added to pool which will be having node name(id),node address(ip) and node port(port)
/// </summary>
[Output("nodes")]
public Output<ImmutableArray<Outputs.EventServiceDiscoveryNode>> Nodes { get; private set; } = null!;
/// <summary>
/// servicediscovery endpoint ( Below example shows how to create endpoing using AS3 )
/// </summary>
[Output("taskid")]
public Output<string> Taskid { get; private set; } = null!;
/// <summary>
/// Create a EventServiceDiscovery resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public EventServiceDiscovery(string name, EventServiceDiscoveryArgs args, CustomResourceOptions? options = null)
: base("f5bigip:index/eventServiceDiscovery:EventServiceDiscovery", name, args ?? new EventServiceDiscoveryArgs(), MakeResourceOptions(options, ""))
{
}
private EventServiceDiscovery(string name, Input<string> id, EventServiceDiscoveryState? state = null, CustomResourceOptions? options = null)
: base("f5bigip:index/eventServiceDiscovery:EventServiceDiscovery", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing EventServiceDiscovery resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static EventServiceDiscovery Get(string name, Input<string> id, EventServiceDiscoveryState? state = null, CustomResourceOptions? options = null)
{
return new EventServiceDiscovery(name, id, state, options);
}
}
public sealed class EventServiceDiscoveryArgs : Pulumi.ResourceArgs
{
[Input("nodes")]
private InputList<Inputs.EventServiceDiscoveryNodeArgs>? _nodes;
/// <summary>
/// Map of node which will be added to pool which will be having node name(id),node address(ip) and node port(port)
/// </summary>
public InputList<Inputs.EventServiceDiscoveryNodeArgs> Nodes
{
get => _nodes ?? (_nodes = new InputList<Inputs.EventServiceDiscoveryNodeArgs>());
set => _nodes = value;
}
/// <summary>
/// servicediscovery endpoint ( Below example shows how to create endpoing using AS3 )
/// </summary>
[Input("taskid", required: true)]
public Input<string> Taskid { get; set; } = null!;
public EventServiceDiscoveryArgs()
{
}
}
public sealed class EventServiceDiscoveryState : Pulumi.ResourceArgs
{
[Input("nodes")]
private InputList<Inputs.EventServiceDiscoveryNodeGetArgs>? _nodes;
/// <summary>
/// Map of node which will be added to pool which will be having node name(id),node address(ip) and node port(port)
/// </summary>
public InputList<Inputs.EventServiceDiscoveryNodeGetArgs> Nodes
{
get => _nodes ?? (_nodes = new InputList<Inputs.EventServiceDiscoveryNodeGetArgs>());
set => _nodes = value;
}
/// <summary>
/// servicediscovery endpoint ( Below example shows how to create endpoing using AS3 )
/// </summary>
[Input("taskid")]
public Input<string>? Taskid { get; set; }
public EventServiceDiscoveryState()
{
}
}
}
| 42.628099 | 160 | 0.640946 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-f5bigip | sdk/dotnet/EventServiceDiscovery.cs | 5,158 | C# |
using System;
using Master40.DB.Nominal;
using Master40.DB.Interfaces;
namespace Master40.DB.ReportingModel
{
public class StockExchange : ResultBaseEntity, IStockExchange
{
public int StockId { get; set; }
public Guid TrackingGuid { get; set; }
public int SimulationConfigurationId { get; set; }
public SimulationType SimulationType { get; set; }
public int SimulationNumber { get; set; }
public string Stock { get; set; }
public int RequiredOnTime { get; set; }
public State State { get; set; }
public decimal Quantity { get; set; }
public int Time { get; set; }
public ExchangeType ExchangeType { get; set; }
}
}
| 31.608696 | 65 | 0.635488 | [
"Apache-2.0"
] | MaxWeickert/ng-erp-4.0 | Master40.DB/ReportingModel/StockExchange.cs | 729 | 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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Metadata.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 Key : ConventionAnnotatable, IMutableKey, IConventionKey
{
private ConfigurationSource _configurationSource;
// Warning: Never access these fields directly as access needs to be thread-safe
private Func<bool, IIdentityMap> _identityMapFactory;
private object _principalKeyValueFactory;
/// <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 Key([NotNull] IReadOnlyList<Property> properties, ConfigurationSource configurationSource)
{
Check.NotEmpty(properties, nameof(properties));
Check.HasNoNulls(properties, nameof(properties));
Properties = properties;
_configurationSource = configurationSource;
Builder = new InternalKeyBuilder(this, DeclaringEntityType.Model.Builder);
}
/// <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 virtual IReadOnlyList<Property> Properties { [DebuggerStepThrough] get; }
/// <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 virtual EntityType DeclaringEntityType
{
[DebuggerStepThrough] get => Properties[0].DeclaringEntityType;
}
/// <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 virtual InternalKeyBuilder Builder
{
[DebuggerStepThrough] get;
[DebuggerStepThrough]
[param: CanBeNull]
set;
}
/// <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>
[DebuggerStepThrough]
public virtual ConfigurationSource GetConfigurationSource() => _configurationSource;
/// <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 virtual void UpdateConfigurationSource(ConfigurationSource configurationSource)
{
_configurationSource = configurationSource.Max(_configurationSource);
foreach (var property in Properties)
{
property.UpdateConfigurationSource(configurationSource);
}
}
/// <summary>
/// Runs the conventions when an annotation was set or removed.
/// </summary>
/// <param name="name"> The key of the set annotation. </param>
/// <param name="annotation"> The annotation set. </param>
/// <param name="oldAnnotation"> The old annotation. </param>
/// <returns> The annotation that was set. </returns>
protected override IConventionAnnotation OnAnnotationSet(
string name, IConventionAnnotation annotation, IConventionAnnotation oldAnnotation)
=> Builder.ModelBuilder.Metadata.ConventionDispatcher.OnKeyAnnotationChanged(Builder, name, annotation, oldAnnotation);
/// <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 virtual IEnumerable<ForeignKey> GetReferencingForeignKeys()
=> ReferencingForeignKeys ?? Enumerable.Empty<ForeignKey>();
/// <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 virtual Func<bool, IIdentityMap> IdentityMapFactory
=> NonCapturingLazyInitializer.EnsureInitialized(
ref _identityMapFactory, this, k => new IdentityMapFactoryFactory().Create(k));
/// <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 virtual IPrincipalKeyValueFactory<TKey> GetPrincipalKeyValueFactory<TKey>()
=> (IPrincipalKeyValueFactory<TKey>)NonCapturingLazyInitializer.EnsureInitialized(
ref _principalKeyValueFactory, this, k => new KeyValueFactoryFactory().Create<TKey>(k));
/// <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>
// Note this is ISet because there is no suitable readonly interface in the profiles we are using
public virtual ISet<ForeignKey> ReferencingForeignKeys { get; [param: CanBeNull] set; }
/// <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 string ToString() => this.ToDebugString();
/// <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 virtual DebugView<Key> DebugView
=> new DebugView<Key>(this, m => m.ToDebugString(false));
/// <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>
IReadOnlyList<IProperty> IKey.Properties
{
[DebuggerStepThrough] get => Properties;
}
/// <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>
IEntityType IKey.DeclaringEntityType
{
[DebuggerStepThrough] get => DeclaringEntityType;
}
/// <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>
IReadOnlyList<IMutableProperty> IMutableKey.Properties
{
[DebuggerStepThrough] get => Properties;
}
/// <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>
IMutableEntityType IMutableKey.DeclaringEntityType
{
[DebuggerStepThrough] get => DeclaringEntityType;
}
/// <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>
IConventionKeyBuilder IConventionKey.Builder
{
[DebuggerStepThrough] get => Builder;
}
/// <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>
IReadOnlyList<IConventionProperty> IConventionKey.Properties
{
[DebuggerStepThrough] get => Properties;
}
/// <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>
IConventionEntityType IConventionKey.DeclaringEntityType
{
[DebuggerStepThrough] get => DeclaringEntityType;
}
}
}
| 59.638554 | 131 | 0.675488 | [
"Apache-2.0"
] | StanleyGoldman/EntityFrameworkCore | src/EFCore/Metadata/Internal/Key.cs | 14,850 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.Altcoins.Nist5
{
public class Nist5
{
private IHash[] _hashers;
public Nist5()
{
var blake512 = HashFactory.Crypto.SHA3.CreateBlake512();
var groestl512 = HashFactory.Crypto.SHA3.CreateGroestl512();
var skein512 = HashFactory.Crypto.SHA3.CreateSkein512_Custom();
var jh512 = HashFactory.Crypto.SHA3.CreateJH512();
var keccak512 = HashFactory.Crypto.SHA3.CreateKeccak512();
_hashers = new IHash[]
{
blake512, groestl512, skein512, jh512, keccak512
};
}
public byte[] ComputeBytes(byte[] input)
{
byte[] hashResult = input;
for (int i = 0; i < _hashers.Length; i++)
{
hashResult = _hashers[i].ComputeBytes(hashResult).GetBytes();
}
return hashResult.Take(32).ToArray();
}
}
}
| 22.425 | 66 | 0.687848 | [
"MIT"
] | NicoDFS/NBitcoin | NBitcoin.Altcoins/Nist5/nist5.cs | 899 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace WikiCore.TagHelpers
{
/// <summary>
/// <see cref="ITagHelper"/> implementation targeting <menulink> elements that assist with rendering contextually aware menu links.
/// If the current route is matched the given <menulink> will be active. This was added to demonstrate how a TagHelper might be used
/// with Semantic UI to implement a simple menu.
/// </summary>
[HtmlTargetElement("menulink", Attributes = "controller-name, action-name, menu-text, link-name, icon-name")]
public class MenuLinkTagHelper : TagHelper
{
public string ControllerName { get; set; }
public string ActionName { get; set; }
public string MenuText { get; set; }
public string LinkName { get; set; }
public string IconName { get; set; }
[ViewContext]
public ViewContext ViewContext { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var urlHelper = new UrlHelper(ViewContext);
string menuUrl = urlHelper.Action(ActionName, ControllerName);
output.TagName = "a";
output.Attributes.Add("href", $"{menuUrl}");
output.Attributes.Add("class", "item blue");
output.Content.SetHtmlContent($"<i class='{IconName} icon'></i> {MenuText}");
var routeData = ViewContext.RouteData.Values;
var currentController = routeData["controller"] + "/" + routeData["action"];
if (String.Equals(LinkName, currentController, StringComparison.OrdinalIgnoreCase))
{
output.Attributes.SetAttribute("class", "active item blue");
}
}
}
}
| 38.314815 | 142 | 0.675689 | [
"MIT"
] | philphilphil/WikiCore | src/Helpers/MenuLinkTagHelper.cs | 2,069 | 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#nullable enable
namespace Microsoft.Extensions.Hosting
{
internal sealed class HostFactoryResolver
{
private const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
public const string BuildWebHost = nameof(BuildWebHost);
public const string CreateWebHostBuilder = nameof(CreateWebHostBuilder);
public const string CreateHostBuilder = nameof(CreateHostBuilder);
// The amount of time we wait for the diagnostic source events to fire
private static readonly TimeSpan s_defaultWaitTimeout = Debugger.IsAttached ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(5);
public static Func<string[], TWebHost>? ResolveWebHostFactory<TWebHost>(Assembly assembly)
{
return ResolveFactory<TWebHost>(assembly, BuildWebHost);
}
public static Func<string[], TWebHostBuilder>? ResolveWebHostBuilderFactory<TWebHostBuilder>(Assembly assembly)
{
return ResolveFactory<TWebHostBuilder>(assembly, CreateWebHostBuilder);
}
public static Func<string[], THostBuilder>? ResolveHostBuilderFactory<THostBuilder>(Assembly assembly)
{
return ResolveFactory<THostBuilder>(assembly, CreateHostBuilder);
}
// This helpers encapsulates all of the complex logic required to:
// 1. Execute the entry point of the specified assembly in a different thread.
// 2. Wait for the diagnostic source events to fire
// 3. Give the caller a chance to execute logic to mutate the IHostBuilder
// 4. Resolve the instance of the applications's IHost
// 5. Allow the caller to determine if the entry point has completed
public static Func<string[], object>? ResolveHostFactory(Assembly assembly,
TimeSpan? waitTimeout = null,
bool stopApplication = true,
Action<object>? configureHostBuilder = null,
Action<Exception?>? entrypointCompleted = null)
{
if (assembly.EntryPoint is null)
{
return null;
}
try
{
// Attempt to load hosting and check the version to make sure the events
// even have a chance of firing (they were added in .NET >= 6)
var hostingAssembly = Assembly.Load("Microsoft.Extensions.Hosting");
if (hostingAssembly.GetName().Version is Version version && version.Major < 6)
{
return null;
}
// We're using a version >= 6 so the events can fire. If they don't fire
// then it's because the application isn't using the hosting APIs
}
catch
{
// There was an error loading the extensions assembly, return null.
return null;
}
return args => new HostingListener(args, assembly.EntryPoint, waitTimeout ?? s_defaultWaitTimeout, stopApplication, configureHostBuilder, entrypointCompleted).CreateHost();
}
private static Func<string[], T>? ResolveFactory<T>(Assembly assembly, string name)
{
var programType = assembly?.EntryPoint?.DeclaringType;
if (programType == null)
{
return null;
}
var factory = programType.GetMethod(name, DeclaredOnlyLookup);
if (!IsFactory<T>(factory))
{
return null;
}
return args => (T)factory!.Invoke(null, new object[] { args })!;
}
// TReturn Factory(string[] args);
private static bool IsFactory<TReturn>(MethodInfo? factory)
{
return factory != null
&& typeof(TReturn).IsAssignableFrom(factory.ReturnType)
&& factory.GetParameters().Length == 1
&& typeof(string[]).Equals(factory.GetParameters()[0].ParameterType);
}
// Used by EF tooling without any Hosting references. Looses some return type safety checks.
public static Func<string[], IServiceProvider?>? ResolveServiceProviderFactory(Assembly assembly, TimeSpan? waitTimeout = null)
{
// Prefer the older patterns by default for back compat.
var webHostFactory = ResolveWebHostFactory<object>(assembly);
if (webHostFactory != null)
{
return args =>
{
var webHost = webHostFactory(args);
return GetServiceProvider(webHost);
};
}
var webHostBuilderFactory = ResolveWebHostBuilderFactory<object>(assembly);
if (webHostBuilderFactory != null)
{
return args =>
{
var webHostBuilder = webHostBuilderFactory(args);
var webHost = Build(webHostBuilder);
return GetServiceProvider(webHost);
};
}
var hostBuilderFactory = ResolveHostBuilderFactory<object>(assembly);
if (hostBuilderFactory != null)
{
return args =>
{
var hostBuilder = hostBuilderFactory(args);
var host = Build(hostBuilder);
return GetServiceProvider(host);
};
}
var hostFactory = ResolveHostFactory(assembly, waitTimeout: waitTimeout);
if (hostFactory != null)
{
return args =>
{
var host = hostFactory(args);
return GetServiceProvider(host);
};
}
return null;
}
private static object? Build(object builder)
{
var buildMethod = builder.GetType().GetMethod("Build");
return buildMethod?.Invoke(builder, Array.Empty<object>());
}
private static IServiceProvider? GetServiceProvider(object? host)
{
if (host == null)
{
return null;
}
var hostType = host.GetType();
var servicesProperty = hostType.GetProperty("Services", DeclaredOnlyLookup);
return (IServiceProvider?)servicesProperty?.GetValue(host);
}
private sealed class HostingListener : IObserver<DiagnosticListener>, IObserver<KeyValuePair<string, object?>>
{
private readonly string[] _args;
private readonly MethodInfo _entryPoint;
private readonly TimeSpan _waitTimeout;
private readonly bool _stopApplication;
private readonly TaskCompletionSource<object> _hostTcs = new();
private IDisposable? _disposable;
private readonly Action<object>? _configure;
private readonly Action<Exception?>? _entrypointCompleted;
private static readonly AsyncLocal<HostingListener> _currentListener = new();
public HostingListener(string[] args, MethodInfo entryPoint, TimeSpan waitTimeout, bool stopApplication, Action<object>? configure, Action<Exception?>? entrypointCompleted)
{
_args = args;
_entryPoint = entryPoint;
_waitTimeout = waitTimeout;
_stopApplication = stopApplication;
_configure = configure;
_entrypointCompleted = entrypointCompleted;
}
public object CreateHost()
{
using var subscription = DiagnosticListener.AllListeners.Subscribe(this);
// Kick off the entry point on a new thread so we don't block the current one
// in case we need to timeout the execution
var thread = new Thread(() =>
{
Exception? exception = null;
try
{
// Set the async local to the instance of the HostingListener so we can filter events that
// aren't scoped to this execution of the entry point.
_currentListener.Value = this;
var parameters = _entryPoint.GetParameters();
if (parameters.Length == 0)
{
_entryPoint.Invoke(null, Array.Empty<object>());
}
else
{
_entryPoint.Invoke(null, new object[] { _args });
}
// Try to set an exception if the entry point returns gracefully, this will force
// build to throw
_hostTcs.TrySetException(new InvalidOperationException("Unable to build IHost"));
}
catch (TargetInvocationException tie) when (tie.InnerException is StopTheHostException)
{
// The host was stopped by our own logic
}
catch (TargetInvocationException tie)
{
exception = tie.InnerException ?? tie;
// Another exception happened, propagate that to the caller
_hostTcs.TrySetException(exception);
}
catch (Exception ex)
{
exception = ex;
// Another exception happened, propagate that to the caller
_hostTcs.TrySetException(ex);
}
finally
{
// Signal that the entry point is completed
_entrypointCompleted?.Invoke(exception);
}
})
{
// Make sure this doesn't hang the process
IsBackground = true
};
// Start the thread
thread.Start();
try
{
// Wait before throwing an exception
if (!_hostTcs.Task.Wait(_waitTimeout))
{
throw new InvalidOperationException("Unable to build IHost");
}
}
catch (AggregateException) when (_hostTcs.Task.IsCompleted)
{
// Lets this propagate out of the call to GetAwaiter().GetResult()
}
Debug.Assert(_hostTcs.Task.IsCompleted);
return _hostTcs.Task.GetAwaiter().GetResult();
}
public void OnCompleted()
{
_disposable?.Dispose();
}
public void OnError(Exception error)
{
}
public void OnNext(DiagnosticListener value)
{
if (_currentListener.Value != this)
{
// Ignore events that aren't for this listener
return;
}
if (value.Name == "Microsoft.Extensions.Hosting")
{
_disposable = value.Subscribe(this);
}
}
public void OnNext(KeyValuePair<string, object?> value)
{
if (_currentListener.Value != this)
{
// Ignore events that aren't for this listener
return;
}
if (value.Key == "HostBuilding")
{
_configure?.Invoke(value.Value!);
}
if (value.Key == "HostBuilt")
{
_hostTcs.TrySetResult(value.Value!);
if (_stopApplication)
{
// Stop the host from running further
throw new StopTheHostException();
}
}
}
private sealed class StopTheHostException : Exception
{
}
}
}
}
| 38.987915 | 184 | 0.521968 | [
"MIT"
] | 3DCloud/runtime | src/libraries/Microsoft.Extensions.HostFactoryResolver/src/HostFactoryResolver.cs | 12,905 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.SceneManagement;
// TODO consider re-wire...
using RPG.CameraUI;
using RPG.Core;
using RPG.Weapons;
namespace RPG.Characters
{
public class Player : MonoBehaviour, IDamageable
{
[SerializeField] float maxHealthPoints = 100f;
[SerializeField] float baseDamage = 10f;
[SerializeField] Weapon weaponInUse = null;
[SerializeField] AnimatorOverrideController animatorOverrideController = null;
[SerializeField] AudioClip[] damageSounds;
[SerializeField] AudioClip[] deathSounds;
[Range(.1f, 1.0f)] [SerializeField] float criticalHitChance = 0.1f;
[SerializeField] float criticalHitMultiplier = 1.25f;
[SerializeField] ParticleSystem criticalHitParticle = null;
// Temporarily serialized for dubbing
[SerializeField] AbilityConfig[] abilities;
const string DEATH_TRIGGER = "Death";
const string ATTACK_TRIGGER = "Attack";
Enemy enemy = null;
AudioSource audioSource = null;
Animator animator = null;
float currentHealthPoints = 0;
CameraRaycaster cameraRaycaster = null;
float lastHitTime = 0;
public float healthAsPercentage { get { return currentHealthPoints / maxHealthPoints; } }
void Start()
{
audioSource = GetComponent<AudioSource>();
RegisterForMouseClick();
SetCurrentMaxHealth();
PutWeaponInHand();
SetupRuntimeAnimator();
AttachInitialAbilities();
}
private void AttachInitialAbilities()
{
for (int abilityIndex = 0; abilityIndex < abilities.Length; abilityIndex++)
{
abilities[abilityIndex].AttachComponentTo(gameObject);
}
}
void Update()
{
if (healthAsPercentage > Mathf.Epsilon)
{
ScanForAbilityKeyDown();
}
}
private void ScanForAbilityKeyDown()
{
for (int keyIndex = 1; keyIndex < abilities.Length; keyIndex++)
{
if (Input.GetKeyDown(keyIndex.ToString()))
{
AttemptSpecialAbility(keyIndex);
}
}
}
public void TakeDamage(float damage)
{
currentHealthPoints = Mathf.Clamp(currentHealthPoints - damage, 0f, maxHealthPoints);
audioSource.clip = damageSounds[UnityEngine.Random.Range(0, damageSounds.Length)];
audioSource.Play();
if (currentHealthPoints <= 0)
{
StartCoroutine(KillPlayer());
}
}
public void Heal(float points)
{
currentHealthPoints = Mathf.Clamp(currentHealthPoints + points, 0f, maxHealthPoints);
}
IEnumerator KillPlayer()
{
animator.SetTrigger(DEATH_TRIGGER);
audioSource.clip = deathSounds[UnityEngine.Random.Range(0, deathSounds.Length)];
audioSource.Play();
yield return new WaitForSecondsRealtime(audioSource.clip.length);
SceneManager.LoadScene(0);
}
private void SetCurrentMaxHealth()
{
currentHealthPoints = maxHealthPoints;
}
private void SetupRuntimeAnimator()
{
animator = GetComponent<Animator>();
animator.runtimeAnimatorController = animatorOverrideController;
animatorOverrideController["DEFAULT ATTACK"] = weaponInUse.GetAttackAnimClip(); // remove const
}
private void PutWeaponInHand()
{
var weaponPrefab = weaponInUse.GetWeaponPrefab();
GameObject dominantHand = RequestDominantHand();
var weapon = Instantiate(weaponPrefab, dominantHand.transform);
weapon.transform.localPosition = weaponInUse.gripTransform.localPosition;
weapon.transform.localRotation = weaponInUse.gripTransform.localRotation;
}
private GameObject RequestDominantHand()
{
var dominantHands = GetComponentsInChildren<DominantHand>();
int numberOfDominantHands = dominantHands.Length;
Assert.IsFalse(numberOfDominantHands <= 0, "No DominantHand found on Player, please add one");
Assert.IsFalse(numberOfDominantHands > 1, "Multiple DominantHand scripts on Player, please remove one");
return dominantHands[0].gameObject;
}
private void RegisterForMouseClick()
{
cameraRaycaster = FindObjectOfType<CameraUI.CameraRaycaster>();
cameraRaycaster.onMouseOverEnemy += OnMouseOverEnemy;
}
void OnMouseOverEnemy(Enemy enemyToSet)
{
this.enemy = enemyToSet;
if (Input.GetMouseButton(0) && IsTargetInRange(enemy.gameObject))
{
AttackTarget();
}
else if (Input.GetMouseButtonDown(1))
{
AttemptSpecialAbility(0);
}
}
private void AttemptSpecialAbility(int abilityIndex)
{
var energyComponent = GetComponent<Energy>();
var energyCost = abilities[abilityIndex].GetEnergyCost();
if (energyComponent.IsEnergyAvailable(energyCost))
{
energyComponent.ConsumeEnergy(energyCost);
var abilityParams = new AbilityUseParams(enemy, baseDamage);
abilities[abilityIndex].Use(abilityParams);
}
}
private void AttackTarget()
{
if (Time.time - lastHitTime > weaponInUse.GetMinTimeBetweenHits())
{
animator.SetTrigger(ATTACK_TRIGGER);
print(weaponInUse.GetAdditionalDamage());
enemy.TakeDamage(CalculateDamage());
lastHitTime = Time.time;
}
}
private float CalculateDamage()
{
bool isCriticalHit = UnityEngine.Random.Range(0f, 1f) <= criticalHitChance;
float damageBeforeCritical = baseDamage + weaponInUse.GetAdditionalDamage();
if (isCriticalHit)
{
criticalHitParticle.Play();
return damageBeforeCritical * criticalHitMultiplier;
}
else
{
return damageBeforeCritical;
}
}
private bool IsTargetInRange(GameObject target)
{
float distanceToTarget = (target.transform.position - transform.position).magnitude;
return distanceToTarget <= weaponInUse.GetMaxAttackRange();
}
}
} | 33.706468 | 116 | 0.604576 | [
"MIT"
] | UnityRPG/Modifiers-And-Abilities | Assets/_Characters/Player/Player.cs | 6,783 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("IpcServerChannel_")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IpcServerChannel_")]
[assembly: AssemblyCopyright("Copyright (C) 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントには
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("b05cc5b0-274f-47b7-9378-3a6dfbbc4b2c")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 29.529412 | 56 | 0.75 | [
"MIT"
] | bg1bgst333/Sample | dotnet/IpcServerChannel/IpcServerChannel/src/IpcServerChannel_/IpcServerChannel_/Properties/AssemblyInfo.cs | 1,428 | C# |
#pragma checksum "C:\Users\brady\Documents\GitHub\EngineTest\EngineTest\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "8DBCD47B3EDBFCD470F8692647483B01"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EngineTest
{
partial class App : global::Windows.UI.Xaml.Application
{
}
}
| 34.166667 | 158 | 0.528455 | [
"MIT"
] | bradylangdale/EngineTest | EngineTest/obj/x86/Debug/App.g.cs | 617 | C# |
// ***********************************************************************
// Assembly : OpenAC.Net.NFSe
// Author : Diego Martins
// Created : 08-29-2021
//
// Last Modified By : Rafael Dias
// Last Modified On : 07-11-2018
// ***********************************************************************
// <copyright file="NFeCidadesServiceClient.cs" company="OpenAC .Net">
// The MIT License (MIT)
// Copyright (c) 2014 - 2021 Projeto OpenAC .Net
//
// 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.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Text;
using System.Xml.Linq;
using OpenAC.Net.Core.Extensions;
namespace OpenAC.Net.NFSe.Providers
{
internal sealed class AmericanaServiceClient : NFSeSOAP11ServiceClient, IServiceClient
{
#region Constructors
public AmericanaServiceClient(ProviderAmericana provider, TipoUrl tipoUrl) : base(provider, tipoUrl, provider.Certificado)
{
}
#endregion Constructors
#region Methods
public string Enviar(string cabec, string msg)
{
var message = new StringBuilder();
message.Append("<nfe:RecepcionarLoteRpsRequest>");
message.Append("<nfe:inputXML>");
message.AppendCData(msg);
message.Append("</nfe:inputXML>");
message.Append("</nfe:RecepcionarLoteRpsRequest>");
return Execute("http://www.nfe.com.br/RecepcionarLoteRps", message.ToString(), "RecepcionarLoteRpsResponse");
}
public string EnviarSincrono(string cabec, string msg)
{
throw new NotImplementedException();
}
public string ConsultarSituacao(string cabec, string msg)
{
var message = new StringBuilder();
message.Append("<nfe:ConsultarSituacaoLoteRpsRequest>");
message.Append("<nfe:inputXML>");
message.AppendCData(msg);
message.Append("</nfe:inputXML>");
message.Append("</nfe:ConsultarSituacaoLoteRpsRequest>");
return Execute("http://www.nfe.com.br/ConsultarSituacaoLoteRps", message.ToString(), "ConsultarSituacaoLoteRpsResponse");
}
public string ConsultarLoteRps(string cabec, string msg)
{
var message = new StringBuilder();
message.Append("<nfe:ConsultarLoteRpsRequest>");
message.Append("<nfe:inputXML>");
message.AppendCData(msg);
message.Append("</nfe:inputXML>");
message.Append("</nfe:ConsultarLoteRpsRequest>");
return Execute("http://www.nfe.com.br/ConsultarLoteRps", message.ToString(), "ConsultarLoteRpsResponse");
}
public string ConsultarSequencialRps(string cabec, string msg)
{
throw new NotImplementedException();
}
public string ConsultarNFSeRps(string cabec, string msg)
{
var message = new StringBuilder();
message.Append("<nfe:ConsultarNfsePorRpsRequest>");
message.Append("<nfe:inputXML>");
message.AppendCData(msg);
message.Append("</nfe:inputXML>");
message.Append("</nfe:ConsultarNfsePorRpsRequest>");
return Execute("http://www.nfe.com.br/ConsultarNfsePorRps", message.ToString(), "ConsultarNfsePorRpsResponse");
}
public string ConsultarNFSe(string cabec, string msg)
{
var message = new StringBuilder();
message.Append("<nfe:ConsultarNfseRequest>");
message.Append("<nfe:inputXML>");
message.AppendCData(msg);
message.Append("</nfe:inputXML>");
message.Append("</nfe:ConsultarNfseRequest>");
return Execute("http://www.nfe.com.br/ConsultarNfse", message.ToString(), "ConsultarNfseResponse");
}
public string CancelarNFSe(string cabec, string msg)
{
var message = new StringBuilder();
message.Append("<nfe:CancelarNfseRequest>");
message.Append("<nfe:inputXML>");
message.AppendCData(msg);
message.Append("</nfe:inputXML>");
message.Append("</nfe:CancelarNfseRequest>");
return Execute("http://www.nfe.com.br/CancelarNfse", message.ToString(), "CancelarNfseResponse");
}
public string CancelarNFSeLote(string cabec, string msg)
{
throw new NotImplementedException();
}
public string SubstituirNFSe(string cabec, string msg)
{
throw new NotImplementedException();
}
private string Execute(string soapAction, string message, string responseTag)
{
return Execute(soapAction, message, "", responseTag, "xmlns:nfe=\"http://www.nfe.com.br/\"", "xmlns=\"http://www.nfe.com.br/WSNacional/XSD/1/nfse_municipal_v01.xsd\"");
}
protected override string TratarRetorno(XDocument xmlDocument, string[] responseTag)
{
return xmlDocument.ElementAnyNs(responseTag[0]).ElementAnyNs("outputXML").Value;
}
#endregion Methods
}
} | 40.425806 | 180 | 0.619534 | [
"MIT"
] | DiegoNetoMartins/OpenAC.Net.NFSe | src/OpenAC.Net.NFSe/Providers/Americana/AmericanaServiceClient.cs | 6,268 | C# |
using System;
using System.IO;
namespace FluffySpoon.Kibana.Sample
{
class Program
{
static void Main(string[] args)
{
var kibanaUrl = File.ReadAllText("KibanaUrl.txt");
var parser = new KibanaParser();
var elasticsearchQuery = parser.ConvertUrlToElasticsearchQueryString(kibanaUrl, "order_date");
Console.WriteLine(elasticsearchQuery);
File.WriteAllText("ElasticsearchQuery.txt", elasticsearchQuery);
Console.ReadLine();
}
}
}
| 24.590909 | 106 | 0.630314 | [
"MIT"
] | JTOne123/FluffySpoon.Kibana | src/FluffySpoon.Kibana.Sample/Program.cs | 543 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http.Headers;
namespace Contacts.API.Areas.HelpPage
{
/// <summary>
/// This is used to identify the place where the sample should be applied.
/// </summary>
public class HelpPageSampleKey
{
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type.
/// </summary>
/// <param name="mediaType">The media type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
ActionName = String.Empty;
ControllerName = String.Empty;
MediaType = mediaType;
ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The CLR type.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)
: this(mediaType)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
ParameterType = type;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
: this(sampleDirection, controllerName, actionName, parameterNames)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
MediaType = mediaType;
}
/// <summary>
/// Gets the name of the controller.
/// </summary>
/// <value>
/// The name of the controller.
/// </value>
public string ControllerName { get; private set; }
/// <summary>
/// Gets the name of the action.
/// </summary>
/// <value>
/// The name of the action.
/// </value>
public string ActionName { get; private set; }
/// <summary>
/// Gets the media type.
/// </summary>
/// <value>
/// The media type.
/// </value>
public MediaTypeHeaderValue MediaType { get; private set; }
/// <summary>
/// Gets the parameter names.
/// </summary>
public HashSet<string> ParameterNames { get; private set; }
public Type ParameterType { get; private set; }
/// <summary>
/// Gets the <see cref="SampleDirection"/>.
/// </summary>
public SampleDirection? SampleDirection { get; private set; }
public override bool Equals(object obj)
{
HelpPageSampleKey otherKey = obj as HelpPageSampleKey;
if (otherKey == null)
{
return false;
}
return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) &&
ParameterType == otherKey.ParameterType &&
SampleDirection == otherKey.SampleDirection &&
ParameterNames.SetEquals(otherKey.ParameterNames);
}
public override int GetHashCode()
{
int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();
if (MediaType != null)
{
hashCode ^= MediaType.GetHashCode();
}
if (SampleDirection != null)
{
hashCode ^= SampleDirection.GetHashCode();
}
if (ParameterType != null)
{
hashCode ^= ParameterType.GetHashCode();
}
foreach (string parameterName in ParameterNames)
{
hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
}
}
| 37.433526 | 175 | 0.569642 | [
"MIT"
] | CamiKaze/Contacts | Contacts.API/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs | 6,476 | C# |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace ILG.Codex.Codex2007
{
/// <summary>
/// Summary description for frmInsertTable.
/// </summary>
public class frmInsertTable : System.Windows.Forms.Form
{
internal System.Windows.Forms.NumericUpDown updownColumns;
internal System.Windows.Forms.NumericUpDown updownRows;
internal System.Windows.Forms.Label Label2;
internal System.Windows.Forms.Label Label1;
internal System.Windows.Forms.Button cmdCancel;
internal System.Windows.Forms.Button cmdOK;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public frmInsertTable()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.updownColumns = new System.Windows.Forms.NumericUpDown();
this.updownRows = new System.Windows.Forms.NumericUpDown();
this.Label2 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdOK = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.updownColumns)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.updownRows)).BeginInit();
this.SuspendLayout();
//
// updownColumns
//
this.updownColumns.Location = new System.Drawing.Point(64, 40);
this.updownColumns.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.updownColumns.Name = "updownColumns";
this.updownColumns.Size = new System.Drawing.Size(64, 20);
this.updownColumns.TabIndex = 13;
this.updownColumns.Value = new decimal(new int[] {
5,
0,
0,
0});
//
// updownRows
//
this.updownRows.Location = new System.Drawing.Point(64, 16);
this.updownRows.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.updownRows.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.updownRows.Name = "updownRows";
this.updownRows.Size = new System.Drawing.Size(64, 20);
this.updownRows.TabIndex = 12;
this.updownRows.Value = new decimal(new int[] {
2,
0,
0,
0});
//
// Label2
//
this.Label2.Location = new System.Drawing.Point(8, 40);
this.Label2.Name = "Label2";
this.Label2.Size = new System.Drawing.Size(56, 16);
this.Label2.TabIndex = 17;
this.Label2.Text = "Columns";
//
// Label1
//
this.Label1.Location = new System.Drawing.Point(8, 16);
this.Label1.Name = "Label1";
this.Label1.Size = new System.Drawing.Size(56, 16);
this.Label1.TabIndex = 16;
this.Label1.Text = "Rows";
//
// cmdCancel
//
this.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cmdCancel.Location = new System.Drawing.Point(184, 40);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.Size = new System.Drawing.Size(80, 24);
this.cmdCancel.TabIndex = 15;
this.cmdCancel.Text = "Cancel";
this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
//
// cmdOK
//
this.cmdOK.Location = new System.Drawing.Point(184, 8);
this.cmdOK.Name = "cmdOK";
this.cmdOK.Size = new System.Drawing.Size(80, 24);
this.cmdOK.TabIndex = 14;
this.cmdOK.Text = "OK";
this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
//
// frmInsertTable
//
this.AcceptButton = this.cmdOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.cmdCancel;
this.ClientSize = new System.Drawing.Size(272, 71);
this.Controls.Add(this.updownColumns);
this.Controls.Add(this.updownRows);
this.Controls.Add(this.Label2);
this.Controls.Add(this.Label1);
this.Controls.Add(this.cmdCancel);
this.Controls.Add(this.cmdOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "frmInsertTable";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Insert Table";
((System.ComponentModel.ISupportInitialize)(this.updownColumns)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.updownRows)).EndInit();
this.ResumeLayout(false);
}
#endregion
public TXTextControl.TextControl tx;
private void cmdOK_Click(object sender, System.EventArgs e)
{
tx.Tables.Add((int)updownRows.Value, (int)updownColumns.Value);
Close();
}
private void cmdCancel_Click(object sender, System.EventArgs e)
{
Close();
}
}
}
| 34.00565 | 89 | 0.579 | [
"Unlicense"
] | IrakliLomidze/CodexDS12 | CodexDS/CodexProgram/frmInsertTable.cs | 6,019 | C# |
using Snapsearch.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;
namespace Snapsearch.ViewModels
{
public class NewItemViewModel : BaseViewModel
{
private string text;
private string description;
public NewItemViewModel()
{
SaveCommand = new Command(OnSave, ValidateSave);
CancelCommand = new Command(OnCancel);
this.PropertyChanged +=
(_, __) => SaveCommand.ChangeCanExecute();
}
private bool ValidateSave()
{
return !String.IsNullOrWhiteSpace(text)
&& !String.IsNullOrWhiteSpace(description);
}
public string Text
{
get => text;
set => SetProperty(ref text, value);
}
public string Description
{
get => description;
set => SetProperty(ref description, value);
}
public Command SaveCommand { get; }
public Command CancelCommand { get; }
private async void OnCancel()
{
// This will pop the current page off the navigation stack
await Shell.Current.GoToAsync("..");
}
private async void OnSave()
{
Item newItem = new Item()
{
Id = Guid.NewGuid().ToString(),
Path = Text,
Description = Description
};
await DataStore.AddItemAsync(newItem);
// This will pop the current page off the navigation stack
await Shell.Current.GoToAsync("..");
}
}
}
| 25.575758 | 70 | 0.548578 | [
"MIT"
] | sinantutan/SnapsearchUI | Snapsearch/Snapsearch/Snapsearch/ViewModels/NewItemViewModel.cs | 1,690 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Shop.Core.BaseObjects;
using Shop.Core.Interfaces;
namespace Shop.Core.Entites
{
public class ProductConfiguration : LifetimeBase, IReferenceable<ProductConfiguration>
{
[Key]
public int ProductConfigurationId { get; set; }
[Required]
[StringLength(25)]
public string ProductConfigurationReference { get; set; }
public Product BaseProduct { get; set; }
public List<ProductComponent> Components { get; set; }
public ProductConfiguration CreateReference(IReferenceGenerator referenceGenerator)
{
ProductConfigurationReference = referenceGenerator.CreateReference(Constants.Constants.ReferenceLength);
return this;
}
}
} | 31.653846 | 116 | 0.705954 | [
"MIT"
] | jontansey/.Net-Core-Ecommerce-Base | src/Shop.Core/Entites/ProductConfiguration.cs | 825 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Infrastructure.Data;
namespace Infrastructure.Migrations
{
[DbContext(typeof(Data.AppContext))]
[Migration("20210403105328_initial")]
partial class initial
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.0");
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.DietPlanAggregate.DietPlan", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("DietPlans");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.DietPlanAggregate.DietPlanPeriod", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("DietPlanId")
.HasColumnType("int");
b.Property<DateTime>("EndDate")
.HasColumnType("datetime2");
b.Property<DateTime>("StartDate")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("DietPlanId");
b.ToTable("DietPlanPeriods");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.FoodProduct", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<float>("Calories")
.HasColumnType("real");
b.Property<float>("Carbohydrates")
.HasColumnType("real");
b.Property<float>("Fats")
.HasColumnType("real");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<float>("Protein")
.HasColumnType("real");
b.Property<int?>("UnitOfMeasureId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("UnitOfMeasureId");
b.ToTable("FoodProducts");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.FoodStock", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<float>("Amount")
.HasColumnType("real");
b.Property<DateTime?>("BestUseByDate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateOfPurchase")
.HasColumnType("datetime2");
b.Property<int?>("FoodProductId")
.HasColumnType("int");
b.Property<float?>("LowerAmount")
.HasColumnType("real");
b.Property<float?>("UpperAmount")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("FoodProductId");
b.ToTable("FoodStocks");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.MealAggregate.Meal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("DietPlanId")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("DietPlanId");
b.ToTable("Meals");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.MealAggregate.MealItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<float>("Amount")
.HasColumnType("real");
b.Property<int?>("FoodProductId")
.HasColumnType("int");
b.Property<int?>("MealId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("FoodProductId");
b.HasIndex("MealId");
b.ToTable("MealItems");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.NotificationRule", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int?>("FoodProductId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("FoodProductId");
b.ToTable("NotificationRules");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.UnitOfMeasure", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Measure")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("UnitOfMeasures");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.UserAggregate.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.UserAggregate.UserContactInfo", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Contact")
.HasColumnType("nvarchar(max)");
b.Property<int?>("NotificationRuleId")
.HasColumnType("int");
b.Property<int?>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("NotificationRuleId");
b.HasIndex("UserId");
b.ToTable("UserContactInfos");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.DietPlanAggregate.DietPlanPeriod", b =>
{
b.HasOne("Microsoft.Inventura.ApplicationCore.Entities.DietPlanAggregate.DietPlan", "DietPlan")
.WithMany()
.HasForeignKey("DietPlanId");
b.Navigation("DietPlan");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.FoodProduct", b =>
{
b.HasOne("Microsoft.Inventura.ApplicationCore.Entities.UnitOfMeasure", "UnitOfMeasure")
.WithMany()
.HasForeignKey("UnitOfMeasureId");
b.Navigation("UnitOfMeasure");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.FoodStock", b =>
{
b.HasOne("Microsoft.Inventura.ApplicationCore.Entities.FoodProduct", "FoodProduct")
.WithMany()
.HasForeignKey("FoodProductId");
b.Navigation("FoodProduct");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.MealAggregate.Meal", b =>
{
b.HasOne("Microsoft.Inventura.ApplicationCore.Entities.DietPlanAggregate.DietPlan", null)
.WithMany("Meals")
.HasForeignKey("DietPlanId");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.MealAggregate.MealItem", b =>
{
b.HasOne("Microsoft.Inventura.ApplicationCore.Entities.FoodProduct", "FoodProduct")
.WithMany()
.HasForeignKey("FoodProductId");
b.HasOne("Microsoft.Inventura.ApplicationCore.Entities.MealAggregate.Meal", null)
.WithMany("Items")
.HasForeignKey("MealId");
b.Navigation("FoodProduct");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.NotificationRule", b =>
{
b.HasOne("Microsoft.Inventura.ApplicationCore.Entities.FoodProduct", "FoodProduct")
.WithMany()
.HasForeignKey("FoodProductId");
b.Navigation("FoodProduct");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.UserAggregate.UserContactInfo", b =>
{
b.HasOne("Microsoft.Inventura.ApplicationCore.Entities.NotificationRule", null)
.WithMany("UserContactInfos")
.HasForeignKey("NotificationRuleId");
b.HasOne("Microsoft.Inventura.ApplicationCore.Entities.UserAggregate.User", null)
.WithMany("UserContactInfos")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.DietPlanAggregate.DietPlan", b =>
{
b.Navigation("Meals");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.MealAggregate.Meal", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.NotificationRule", b =>
{
b.Navigation("UserContactInfos");
});
modelBuilder.Entity("Microsoft.Inventura.ApplicationCore.Entities.UserAggregate.User", b =>
{
b.Navigation("UserContactInfos");
});
#pragma warning restore 612, 618
}
}
}
| 36.035714 | 117 | 0.474232 | [
"MIT"
] | StefanBalaban/CoreApp | src/Infrastructure/Migrations/20210403105328_initial.Designer.cs | 12,110 | C# |
namespace Cogs.Threading;
/// <summary>
/// Provides a set of static methods for quickly leveraging the Microsoft Dataflow library
/// </summary>
public static class DataflowExtensions
{
static readonly ExecutionDataflowBlockOptions cpuBoundBlock = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
static readonly DataflowLinkOptions propagateLink = new DataflowLinkOptions { PropagateCompletion = true };
static readonly ExecutionDataflowBlockOptions singleThreadBlock = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 1 };
/// <summary>
/// Performs a specified action for each element of a sequence in parallel utilizing all hardware threads
/// </summary>
/// <typeparam name="TSource">The type of the elements in the sequence</typeparam>
/// <param name="source">The sequence</param>
/// <param name="action">The action</param>
public static Task DataflowForAllAsync<TSource>(this IEnumerable<TSource> source, Action<TSource> action) => DataflowForAllAsync(source, action, cpuBoundBlock);
/// <summary>
/// Performs a specified asynchronous action for each element of a sequence in parallel utilizing all hardware threads
/// </summary>
/// <typeparam name="TSource">The type of the elements in the sequence</typeparam>
/// <param name="source">The sequence</param>
/// <param name="asyncAction">The asynchronous action</param>
public static Task DataflowForAllAsync<TSource>(this IEnumerable<TSource> source, Func<TSource, Task> asyncAction) => DataflowForAllAsync(source, asyncAction, cpuBoundBlock);
/// <summary>
/// Performs a specified action for each element of a sequence in parallel
/// </summary>
/// <typeparam name="TSource">The type of the elements in the sequence</typeparam>
/// <param name="source">The sequence</param>
/// <param name="action">The action</param>
/// <param name="options">Manual Dataflow options</param>
public static Task DataflowForAllAsync<TSource>(this IEnumerable<TSource> source, Action<TSource> action, ExecutionDataflowBlockOptions options)
{
if (source is null)
throw new ArgumentNullException(nameof(source));
var block = new ActionBlock<TSource>(action, options);
foreach (var element in source)
block.Post(element);
block.Complete();
return block.Completion;
}
/// <summary>
/// Performs a specified asynchronous action for each element of a sequence in parallel
/// </summary>
/// <typeparam name="TSource">The type of the elements in the sequence</typeparam>
/// <param name="source">The sequence</param>
/// <param name="asyncAction">The asynchronous action</param>
/// <param name="options">Manual Dataflow options</param>
public static Task DataflowForAllAsync<TSource>(this IEnumerable<TSource> source, Func<TSource, Task> asyncAction, ExecutionDataflowBlockOptions options)
{
if (source is null)
throw new ArgumentNullException(nameof(source));
var block = new ActionBlock<TSource>(asyncAction, options);
foreach (var element in source)
block.Post(element);
block.Complete();
return block.Completion;
}
/// <summary>
/// Performs a specified transform on each element of a sequence in parallel utilizing all hardware threads
/// </summary>
/// <typeparam name="TSource">The type of the elements in the sequence</typeparam>
/// <typeparam name="TResult">The type rendered by the transform</typeparam>
/// <param name="source">The sequence</param>
/// <param name="selector">The transform</param>
/// <returns>The results of the transform on each element in no particular order</returns>
public static Task<IEnumerable<TResult>> DataflowSelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) => DataflowSelectAsync(source, selector, cpuBoundBlock);
/// <summary>
/// Performs a specified asynchronous transform on each element of a sequence in parallel utilizing all hardware threads
/// </summary>
/// <typeparam name="TSource">The type of the elements in the sequence</typeparam>
/// <typeparam name="TResult">The type rendered by the asynchronous transform</typeparam>
/// <param name="source">The sequence</param>
/// <param name="asyncSelector">The asynchronous transform</param>
/// <returns>The results of the asynchronous transform on each element in no particular order</returns>
public static Task<IEnumerable<TResult>> DataflowSelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> asyncSelector) => DataflowSelectAsync(source, asyncSelector, cpuBoundBlock);
/// <summary>
/// Performs a specified transform on each element of a sequence in parallel
/// </summary>
/// <typeparam name="TSource">The type of the elements in the sequence</typeparam>
/// <typeparam name="TResult">The type rendered by the transform</typeparam>
/// <param name="source">The sequence</param>
/// <param name="selector">The transform</param>
/// <param name="options">Manual Dataflow options</param>
/// <returns>The results of the transform on each element in no particular order</returns>
public static async Task<IEnumerable<TResult>> DataflowSelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, ExecutionDataflowBlockOptions options)
{
if (source is null)
throw new ArgumentNullException(nameof(source));
var results = new BlockingCollection<TResult>();
var transformBlock = new TransformBlock<TSource, TResult>(selector, options);
var actionBlock = new ActionBlock<TResult>(result => results.Add(result), singleThreadBlock);
transformBlock.LinkTo(actionBlock, propagateLink);
foreach (var element in source)
transformBlock.Post(element);
transformBlock.Complete();
await actionBlock.Completion.ConfigureAwait(false);
return results;
}
/// <summary>
/// Performs a specified asynchronous transform on each element of a sequence in parallel
/// </summary>
/// <typeparam name="TSource">The type of the elements in the sequence</typeparam>
/// <typeparam name="TResult">The type rendered by the asynchronous transform</typeparam>
/// <param name="source">The sequence</param>
/// <param name="asyncSelector">The asynchronous transform</param>
/// <param name="options">Manual Dataflow options</param>
/// <returns>The results of the asynchronous transform on each element in no particular order</returns>
public static async Task<IEnumerable<TResult>> DataflowSelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> asyncSelector, ExecutionDataflowBlockOptions options)
{
if (source is null)
throw new ArgumentNullException(nameof(source));
var results = new BlockingCollection<TResult>();
var transformBlock = new TransformBlock<TSource, TResult>(asyncSelector, options);
var actionBlock = new ActionBlock<TResult>(result => results.Add(result), singleThreadBlock);
transformBlock.LinkTo(actionBlock, propagateLink);
foreach (var element in source)
transformBlock.Post(element);
transformBlock.Complete();
await actionBlock.Completion.ConfigureAwait(false);
return results;
}
}
| 57.477273 | 222 | 0.712271 | [
"Apache-2.0"
] | Epiforge/Cogs | Cogs.Threading/DataflowExtensions.cs | 7,587 | C# |
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Factory.Models;
using System.Collections.Generic;
using System.Linq;
namespace Factory.Controllers
{
public class MachinesController : Controller
{
private readonly FactoryContext _db;
public MachinesController(FactoryContext db)
{
_db = db;
}
public ActionResult Index()
{
List<Machine> allMachines = _db.Machines
.OrderBy(machine => machine.Manufacturer)
.ThenBy(machine => machine.ProductModel)
.ToList();
return View(allMachines);
}
public ActionResult Create()
{
ViewBag.EngineerId = new SelectList(_db.Engineers, "EngineerId", "ProductModel");
return View();
}
[HttpPost]
public ActionResult Create(Machine machine, int[] engineerIds)
{
foreach (int engineerId in engineerIds)
{
bool entryExists = _db.EngineerMachine
.Any(entry => entry.MachineId == machine.MachineId && entry.EngineerId == engineerId);
if (!entryExists)
{
_db.EngineerMachine.Add(new EngineerMachine() { MachineId = machine.MachineId, EngineerId = engineerId });
}
}
_db.Machines.Add(machine);
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Details(int id)
{
Machine selectedMachine = _db.Machines
.Include(machine => machine.EngineerMachineJoinEntities)
.ThenInclude(join => join.Engineer)
.FirstOrDefault(machine => machine.MachineId == id);
return View(selectedMachine);
}
public ActionResult Edit(int id)
{
Machine selectedMachine = _db.Machines
.Include(machine => machine.EngineerMachineJoinEntities)
.ThenInclude(join => join.Engineer)
.FirstOrDefault(machine => machine.MachineId == id);
ViewBag.CourseId = new SelectList(_db.Engineers, "EngineerId", "Name");
return View(selectedMachine);
}
[HttpPost]
public ActionResult Edit(Machine machine, int[] engineerIds)
{
foreach (int engineerId in engineerIds)
{
EngineerMachine joinEntry = _db.EngineerMachine
.Where(entry => entry.EngineerId == engineerId && entry.MachineId == machine.MachineId)
.Single();
_db.EngineerMachine.Remove(joinEntry);
}
_db.Entry(machine).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Details", new { id = machine.MachineId });
}
public ActionResult Delete(int id)
{
Machine selectedMachine = _db.Machines.FirstOrDefault(machine => machine.MachineId == id);
return View(selectedMachine);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Machine selectedMachine = _db.Machines.FirstOrDefault(machine => machine.MachineId == id);
_db.Machines.Remove(selectedMachine);
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult AddRepairEngineer(int id)
{
Machine selectedMachine = _db.Machines
.Include(machine => machine.EngineerMachineJoinEntities)
.ThenInclude(join => join.Engineer)
.FirstOrDefault(machine => machine.MachineId == id);
List<Engineer> allEngineers = _db.Engineers
.OrderBy(engineer => engineer.LastName)
.ThenBy(engineer => engineer.FirstName)
.ToList();
ViewBag.EngineerList = allEngineers;
return View(selectedMachine);
}
[HttpPost]
public ActionResult AddRepairEngineer(Machine machine, int[] engineerIds)
{
foreach (int engineerId in engineerIds)
{
bool entryExists = _db.EngineerMachine
.Any(entry => entry.EngineerId == engineerId && entry.MachineId == machine.MachineId);
if (!entryExists)
{
_db.EngineerMachine.Add(new EngineerMachine() { MachineId = machine.MachineId, EngineerId = engineerId });
}
}
_db.SaveChanges();
return RedirectToAction("Details", new { id = machine.MachineId });
}
}
}
| 31.240602 | 116 | 0.65728 | [
"MIT"
] | vnessa-su/Factory.Solution | Factory/Controllers/MachinesController.cs | 4,155 | C# |
// YieldReturnNode.cs
// Script#/Core/Compiler
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Diagnostics;
namespace ScriptSharp.CodeModel {
// NOTE: Not supported in conversion
internal sealed class YieldReturnNode : StatementNode {
private ParseNode _value;
public YieldReturnNode(Token token, ParseNode value)
: base(ParseNodeType.YieldReturn, token) {
_value = GetParentedNode(value);
}
}
}
| 24.272727 | 90 | 0.689139 | [
"Apache-2.0"
] | AmanArnold/dsharp | src/Core/Compiler/CodeModel/Statements/YieldReturnNode.cs | 534 | C# |
namespace Bakery.Models.BakedFoods
{
public class Bread : BakedFood
{
private const int INITIAL_BREAD_PORTION = 200;
public Bread(string name, decimal price)
: base(name, INITIAL_BREAD_PORTION, price)
{
}
}
} | 22.166667 | 54 | 0.609023 | [
"MIT"
] | georgidelchev/CSharp-Advanced-Tasks | 02 - [CSharp OOP]/[CSharp OOP - Exams]/08 - [C# OOP Exam - 12 December 2020]/01 - [Structure & Business Logic]/Models/BakedFoods/Bread.cs | 268 | C# |
using Data.Commands;
using Data.Log;
using Data.Notifications;
using LunarAPIClient.LogEntryRepository;
using LunarAPIClient.NotificationClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LunarAPIClient.CommandProcessors
{
public class CommandProcessor
{
private readonly ILogEntryRepository _logEntryRepository;
private readonly INotificationClient _notificationClient;
private readonly ILogEntryAttachmentContentTypeRepository _logEntryAttachmentContentTypeRepository;
public CommandProcessor(
ILogEntryRepository logEntryRepository,
INotificationClient notificationClient,
ILogEntryAttachmentContentTypeRepository logEntryAttachmentContentTypeRepository)
{
_logEntryRepository = logEntryRepository;
_notificationClient = notificationClient;
_logEntryAttachmentContentTypeRepository = logEntryAttachmentContentTypeRepository;
}
public async Task ProcessCommand(Command cmd, CancellationToken cancellationToken)
{
ICommandProcessor processor;
if (cmd is AppendLogEntryCommand)
{
processor = new AppendLogEntryCommandProcessor(_logEntryAttachmentContentTypeRepository, _logEntryRepository);
}
else if (cmd is UpdateLogEntryCommand)
{
processor = new UpdateLogEntryCommandProcessor(_logEntryRepository);
}
else if (cmd is FinalizeUserLogEntriesCommand)
{
processor = new FinalizeUserLogEntriesCommandProcessor(_logEntryRepository);
}
else
{
throw new Exception("Unknown command type");
}
await processor.ProcessCommand(cmd, cancellationToken);
if (processor is ILogEntryProducer logEntryProducer)
{
await _logEntryRepository.CreateOrUpdate(logEntryProducer.LogEntries, cancellationToken);
}
if (processor is INotificationProducer notificationProducer)
{
await _notificationClient.SendNotifications(notificationProducer.Notifications, cancellationToken);
}
}
}
}
| 36.415385 | 126 | 0.686523 | [
"MIT"
] | adityakm24/lunar-cmd-local | APIClient/CommandProcessors/CommandProcessor.cs | 2,369 | C# |
//
// System.Configuration.ConfigurationValidatorAttribute.cs
//
// Authors:
// Lluis Sanchez Gual (lluis@novell.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.
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
using System;
namespace System.Configuration
{
[AttributeUsage (AttributeTargets.Property)]
public class ConfigurationValidatorAttribute : Attribute
{
Type validatorType;
ConfigurationValidatorBase instance;
protected ConfigurationValidatorAttribute ()
{
}
public ConfigurationValidatorAttribute (Type validator)
{
validatorType = validator;
}
public virtual ConfigurationValidatorBase ValidatorInstance {
get {
if (instance == null)
instance = (ConfigurationValidatorBase) Activator.CreateInstance (validatorType);
return instance;
}
}
public Type ValidatorType {
get { return validatorType; }
}
}
}
| 31.080645 | 86 | 0.750908 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Configuration/System.Configuration/ConfigurationValidatorAttribute.cs | 1,927 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the es-2015-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Elasticsearch.Model
{
/// <summary>
/// Container for the parameters to the ListPackagesForDomain operation.
/// Lists all packages associated with the Amazon ES domain.
/// </summary>
public partial class ListPackagesForDomainRequest : AmazonElasticsearchRequest
{
private string _domainName;
private int? _maxResults;
private string _nextToken;
/// <summary>
/// Gets and sets the property DomainName.
/// <para>
/// The name of the domain for which you want to list associated packages.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=3, Max=28)]
public string DomainName
{
get { return this._domainName; }
set { this._domainName = value; }
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this._domainName != null;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// Limits results to a maximum number of packages.
/// </para>
/// </summary>
[AWSProperty(Max=100)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// Used for pagination. Only necessary if a previous API call includes a non-null NextToken
/// value. If provided, returns results for the next page.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 30.656566 | 100 | 0.611203 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Elasticsearch/Generated/Model/ListPackagesForDomainRequest.cs | 3,035 | C# |
using System;
namespace socket_client_programming
{
class Program
{
static void Main()
{
var socket = new SocketClient();
socket.Start();
}
}
} | 14.714286 | 44 | 0.514563 | [
"Unlicense"
] | Tuoof/TCPServerClient | socket client programming/Program.cs | 208 | C# |
namespace SETUNA.Main.Style
{
// Token: 0x0200004A RID: 74
public class CCaptureStyle : CPreStyle
{
// Token: 0x060002C0 RID: 704 RVA: 0x0000F549 File Offset: 0x0000D749
public CCaptureStyle()
{
_styleid = -9;
_stylename = "Start";
}
// Token: 0x060002C1 RID: 705 RVA: 0x0000F564 File Offset: 0x0000D764
public override void Apply(ref ScrapBase scrap)
{
var bindForm = scrap.Manager.BindForm;
bindForm.StartCapture();
}
}
}
| 26.380952 | 77 | 0.575812 | [
"MIT"
] | nv-h/SETUNA2 | SETUNA/Main/Style/CCaptureStyle.cs | 556 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Protocols.TestTools.StackSdk.CommonStack
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
/// <summary>
/// The http server side.
/// </summary>
public class HttpServerTransport : IDisposable
{
#region field
/// <summary>
/// The const variable SEND_DATA_SIZE specifies size of the data sent every time.
/// </summary>
private const int SENDDATASIZE = 2048;
/// <summary>
/// The simultaneous connection max number.
/// </summary>
private const int CONNECTIONMAXNUMBER = 500;
/// <summary>
/// Http request event handle.
/// </summary>
private EventHandler<HttpRequestEventArg> httpRequestEventHandle;
/// <summary>
/// The http listener.
/// </summary>
private HttpListener httpListener;
/// <summary>
/// The http request manager thread.
/// </summary>
private Thread httpRequestManagerThread;
/// <summary>
/// The http server's state.
/// </summary>
private long runState = (long)State.Stopped;
/// <summary>
/// Track whether Dispose has been called.
/// </summary>
private bool disposed;
/// <summary>
/// The logger.
/// </summary>
private ILogPrinter logger;
#endregion
#region constructor/destructor
/// <summary>
/// Initializes a new instance of the HttpServerTransport class.
/// </summary>
/// <param name="transferProtocol">The transport type will be used</param>
/// <param name="listenPort">The listen port.</param>
/// <param name="resource">The resource.</param>
public HttpServerTransport(
TransferProtocol transferProtocol,
int listenPort,
string resource)
{
this.httpListener = new HttpListener();
this.httpListener.Prefixes.Add(
this.GetListenPrefix(transferProtocol, listenPort, resource));
}
/// <summary>
/// Initializes a new instance of the HttpServerTransport class.
/// </summary>
/// <param name="transferProtocol">The transport type will be used</param>
/// <param name="listenPort">The listen port.</param>
/// <param name="ipaddressType">The IP address type.</param>
/// <param name="resource">The resource.</param>
public HttpServerTransport(
TransferProtocol transferProtocol,
int listenPort,
IPAddressType ipaddressType,
string resource)
{
this.httpListener = new HttpListener();
this.httpListener.Prefixes.Add(
this.GetListenPrefix(transferProtocol, listenPort, resource));
}
/// <summary>
/// Initializes a new instance of the HttpServerTransport class.
/// </summary>
/// <param name="transferProtocol">The transport type will be used</param>
/// <param name="listenPort">The listen port.</param>
/// <param name="ipaddressType">The IP address type.</param>
/// <param name="resource">The resource.</param>
/// <param name="logger">The logger.</param>
public HttpServerTransport(
TransferProtocol transferProtocol,
int listenPort,
IPAddressType ipaddressType,
string resource,
ILogPrinter logger)
{
if (logger == null)
{
throw new ArgumentNullException("logger", "The input parameter \"logger\" is null.");
}
this.logger = logger;
this.httpListener = new HttpListener();
string prefix = this.GetListenPrefix(transferProtocol, listenPort, resource);
this.httpListener.Prefixes.Add(prefix);
this.logger.AddDebug(string.Format(
"Initialize the http server transport and add prefix: {0} to http listener.",
prefix));
}
/// <summary>
/// Finalizes an instance of the HttpServerTransport class
/// This destructor will run only if the Dispose method
/// does not get called.
/// It gives your base class the opportunity to finalize.
/// Do not provide destructors in types derived from this class.
/// </summary>
~HttpServerTransport()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
#endregion
#region property
/// <summary>
/// Gets the http server's state.
/// </summary>
public State RunState
{
get
{
return (State)Interlocked.Read(ref this.runState);
}
}
/// <summary>
/// Gets or sets the http request event handle.
/// </summary>
public EventHandler<HttpRequestEventArg> HttpRequestEventHandle
{
get { return this.httpRequestEventHandle; }
set { this.httpRequestEventHandle = value; }
}
#endregion
#region public method
/// <summary>
/// Start http server to listen and receive the http request.
/// </summary>
/// <exception cref="ThreadStateException">Represents Exception about the Thread State</exception>
/// <exception cref="TimeoutException">Unable to start the request handling process in 10 seconds</exception>
public void StartHttpServer()
{
if (this.httpRequestManagerThread == null || this.httpRequestManagerThread.ThreadState == ThreadState.Running)
{
this.httpRequestManagerThread = new Thread(new ThreadStart(this.HttpRequestManagerStart));
}
else if (this.httpRequestManagerThread.ThreadState == ThreadState.Running)
{
throw new ThreadStateException("The http request manager thread is already running!");
}
if (this.httpRequestManagerThread.ThreadState != ThreadState.Unstarted)
{
throw new ThreadStateException("The http request manager thread is not initialized.");
}
this.httpRequestManagerThread.Start();
// Wait for 10 seconds.
long waitMilliseconds = 10000;
DateTime startTime = DateTime.Now;
while (this.RunState != State.Started)
{
Thread.Sleep(100);
if ((DateTime.Now - startTime).TotalMilliseconds > waitMilliseconds)
{
throw new TimeoutException(
string.Format(
"Unable to start the request handling process within {0}",
(DateTime.Now - startTime).TotalSeconds));
}
}
if (this.logger != null)
{
this.logger.AddDebug("Http server process is started successfully.");
}
}
/// <summary>
/// Send the response message.
/// </summary>
/// <param name="header">Http header.</param>
/// <param name="payLoadData">The payload data.</param>
/// <param name="httpListenerContext">The payload data.</param>
public void Send(
Dictionary<string, string> header,
byte[] payLoadData,
HttpListenerContext httpListenerContext)
{
if (httpListenerContext == null)
{
throw new ArgumentNullException("httpListenerContext");
}
if (this.RunState == State.Stopped)
{
throw new InvalidOperationException("The http server process is stopped.");
}
while (this.RunState == State.Stopping)
{
Thread.Sleep(100);
}
HttpListenerResponse response = httpListenerContext.Response;
// Add the response header.
if (header != null)
{
foreach (string key in header.Keys)
{
response.AddHeader(key, header[key]);
}
}
if (payLoadData != null)
{
byte[][] data = new byte[][] { payLoadData };
for (int i = 0; i < data.Length; i++)
{
// Set length of Write method,
// This is used to separate large message to small blocks, default 10KB per block
int len = SENDDATASIZE;
for (int index = 0; index < data[i].Length; index += len)
{
// Send same size data every time, except the last one
if (data[i].Length - index < len)
{
len = data[i].Length - index;
}
response.OutputStream.Write(data[i], index, len);
}
}
}
response.OutputStream.Close();
response.Close();
if (this.logger != null)
{
this.logger.AddDebug("The response message is sent successfully.");
}
}
/// <summary>
/// Send the response message.
/// </summary>
/// <param name="statusCode">Status code.</param>
/// <param name="header">Http header.</param>
/// <param name="payLoadData">The payload data.</param>
/// <param name="httpListenerContext">The http listener context.</param>
/// <param name="needNextRequest">Whether need next request before sending response.</param>
public void Send(
int statusCode,
Dictionary<string, string> header,
byte[] payLoadData,
HttpListenerContext httpListenerContext,
bool needNextRequest)
{
if (httpListenerContext == null)
{
throw new ArgumentNullException("httpListenerContext");
}
if (this.RunState == State.Stopped)
{
throw new InvalidOperationException("The http server process is stopped.");
}
while (this.RunState == State.Stopping)
{
Thread.Sleep(100);
}
HttpListenerResponse response = httpListenerContext.Response;
response.StatusCode = statusCode;
// Add the response header.
if (header != null)
{
foreach (string key in header.Keys)
{
response.AddHeader(key, header[key]);
}
}
if (payLoadData != null)
{
byte[][] data = new byte[][] { payLoadData };
for (int i = 0; i < data.Length; i++)
{
// Set length of Write method,
// This is used to separate large message to small blocks, default 10KB per block
int len = SENDDATASIZE;
for (int index = 0; index < data[i].Length; index += len)
{
// Send same size data every time, except the last one
if (data[i].Length - index < len)
{
len = data[i].Length - index;
}
response.OutputStream.Write(data[i], index, len);
}
}
}
if (needNextRequest == false)
{
response.OutputStream.Close();
response.Close();
if (this.logger != null)
{
this.logger.AddDebug("The response message is sent successfully.");
}
}
}
/// <summary>
/// Stop http server to listen and receive the http request.
/// </summary>
public void StopHttpServer()
{
Interlocked.Exchange(ref this.runState, (long)State.Stopping);
if (this.httpListener.IsListening)
{
this.httpListener.Stop();
}
if (!this.httpListener.IsListening && this.logger != null)
{
this.logger.AddDebug("Http server process is stopped listening successfully.");
}
// Wait for 10 seconds.
long waitMilliseconds = 10000;
DateTime startTime = DateTime.Now;
while (this.RunState != State.Stopped)
{
Thread.Sleep(100);
if ((DateTime.Now - startTime).TotalMilliseconds > waitMilliseconds)
{
throw new TimeoutException("Unable to stop the http server process.");
}
}
this.httpRequestManagerThread = null;
if (this.logger != null)
{
this.logger.AddDebug("Http server process is stopped successfully.");
}
}
/// <summary>
/// Implement IDisposable.
/// Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </summary>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
#endregion
#region private method
/// <summary>
/// The thread start method for http request manager thread.
/// </summary>
private void HttpRequestManagerStart()
{
Interlocked.Exchange(ref this.runState, (long)State.Starting);
try
{
if (!this.httpListener.IsListening)
{
this.httpListener.Start();
}
if (this.httpListener.IsListening)
{
Interlocked.Exchange(ref this.runState, (long)State.Started);
if (this.logger != null)
{
this.logger.AddDebug("Http server process is listening now.");
}
}
try
{
while (this.RunState == State.Started)
{
HttpListenerContext context = this.httpListener.GetContext();
this.RaiseIncomingRequest(context);
}
}
catch (HttpListenerException e)
{
if (this.logger != null)
{
this.logger.AddWarning(
string.Format("Unexpected exception error code: {0}; detail information: {1}.", e.ErrorCode, e.Message));
}
}
}
finally
{
Interlocked.Exchange(ref this.runState, (long)State.Stopped);
}
}
/// <summary>
/// The event handle for the received http request.
/// </summary>
/// <param name="context">The http listener context.</param>
private void RaiseIncomingRequest(HttpListenerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (this.logger != null)
{
this.logger.AddDebug(string.Format(
"Http request is received, the remote endpoint's ip address is {0}, the port is {1}",
context.Request.RemoteEndPoint.Address,
context.Request.RemoteEndPoint.Port));
}
HttpRequestEventArg newHttpReqeust = new HttpRequestEventArg(context);
try
{
if (this.httpRequestEventHandle != null)
{
this.httpRequestEventHandle.BeginInvoke(this, newHttpReqeust, null, null);
}
}
catch (InvalidOperationException e)
{
if (this.logger != null)
{
this.logger.AddWarning(
string.Format("Unexpected exception detailed information: {0}.", e.Message));
}
}
}
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed
/// </summary>
/// <param name="disposing">Specify which scenario is used.</param>
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
if (this.logger != null)
{
this.logger = null;
}
if (this.RunState != State.Stopped)
{
this.StopHttpServer();
}
if (this.httpRequestManagerThread != null)
{
this.httpRequestManagerThread.Abort();
this.httpRequestManagerThread = null;
}
if (this.httpListener != null)
{
this.httpListener.Close();
this.httpListener = null;
}
}
}
// Note disposing has been done.
this.disposed = true;
}
/// <summary>
/// Get the listen prefix.
/// </summary>
/// <param name="transferProtocol">The transport type will be used</param>
/// <param name="ipaddressType">The ip address type.</param>
/// <param name="hostedCacheModeListenPort">The hosted cache mode listen port.</param>
/// <param name="resource">The customer resource data.</param>
/// <returns>The listen prefix string.</returns>
private string GetListenPrefix(
TransferProtocol transferProtocol,
int hostedCacheModeListenPort,
string resource)
{
string transportTypeStr;
string listenPrefix = null;
if (resource == null)
{
resource = string.Empty;
}
else if (!resource.EndsWith("/") && resource != string.Empty)
{
resource = resource + "/";
}
if (transferProtocol == TransferProtocol.HTTPS)
{
transportTypeStr = "https";
}
else if (transferProtocol == TransferProtocol.HTTP)
{
transportTypeStr = "http";
}
else
{
throw new ArgumentException("The supported transport type in pchc is http or https for this version.", "transportType");
}
listenPrefix =
transportTypeStr + "://+:"
+ hostedCacheModeListenPort + "/" + resource;
return listenPrefix;
}
#endregion
}
}
| 34.271523 | 136 | 0.508406 | [
"MIT"
] | 0neb1n/WindowsProtocolTestSuites | TestSuites/BranchCache/src/COMMON/CommonStack/Transport/HttpServerTransport.cs | 20,700 | C# |
/*
MIT License
Copyright (c) 2016-2017 Florian Cäsar, Michael Plainer
For full license see LICENSE in the root directory of this project.
*/
using System;
namespace Sigma.Core.Training.Initialisers
{
/// <summary>
/// A custom initialiser adapter for simple initialiser assignment with lambdas.
/// </summary>
public class CustomInitialiser : BaseInitialiser
{
private readonly Func<long[], long[], Random, object> _valueFunc;
/// <summary>
/// Create a custom initialiser with a given per value function.
/// </summary>
/// <param name="valueFunc">The value function with the inputs indices, shape and a randomiser and the output value at the given index.</param>
public CustomInitialiser(Func<long[], long[], Random, object> valueFunc)
{
if (valueFunc == null) throw new ArgumentNullException(nameof(valueFunc));
_valueFunc = valueFunc;
}
public override object GetValue(long[] indices, long[] shape, Random random)
{
return _valueFunc(indices, shape, random);
}
}
}
| 27.486486 | 145 | 0.719764 | [
"MIT"
] | GreekDictionary/Sigma | Sigma.Core/Training/Initialisers/CustomInitialiser.cs | 1,020 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
/* Todo list
* organize functions
* find way to make answer checking more optimal?
*/
public class UIManager : MonoBehaviour
{
public GameObject slot;
[Header("Title Scene Properties", order = 0)]
[Space(2f)]
[Header("Intro Scene Properties", order = 1)]
public TMP_Text introText;
public GameObject introImage;
public GameObject backButton;
public GameObject nextButton;
[Header("Tutorial Scene Properties", order = 2)]
[Space(2f)]
public TMP_Text tutorialIntroTitleText;
public TMP_Text tutorialIntroText;
public TMP_Text tutText;
public GameObject beginTutorialButton;
public GameObject tutBackButton;
public GameObject tutNextButton;
public GameObject imageBits;
public GameObject imageLogicGateEx;
public GameObject imageTruthTables;
public GameObject imageLogicGates;
public GameObject andGateT;
public GameObject orGateT;
public GameObject emptySlotT;
public GameObject gatePiecesT;
public GameObject goButtonT;
public GameObject incorrectOverlay;
public GameObject overlay;
public GameObject tutTextBox;
public GameObject tutTextBoxNextButton;
public GameObject tutTextBoxBackButton;
[Header("Level01 Scene Properties", order = 3)]
public TMP_Text levelIntroText;
public TMP_Text taskText;
public TMP_Text inputText1;
public TMP_Text inputText2;
public TMP_Text outputText;
public TMP_Text explanationText;
public GameObject startButton;
public GameObject goButton;
public GameObject hintButton;
public GameObject andGate;
public GameObject orGate;
public GameObject notGate;
public GameObject emptySlot;
public GameObject gatePieces;
public GameObject hintScreen;
public GameObject winScreen;
public GameObject loseScreen;
public GameObject output0;
public GameObject output1;
int introSequenceCount;
int tutorialSequenceCount;
int levelSequenceCount;
int tutTextCount;
Vector3 andGateDefaultPos;
Vector3 orGateDefaultPos;
Scene currentScene;
private void Start()
{
}
private void Awake()
{
currentScene = SceneManager.GetActiveScene();
switch(currentScene.name)
{
case "00TitleScene":
break;
case "01IntroScene":
InitializeIntro();
break;
case "02TutorialScene":
InitializeTutorial();
break;
case "03Level01Scene":
InitializeLevel();
break;
}
}
public void SetScene(string sceneName)
{
SceneManager.LoadScene(sceneName);
}
public void IntroSequenceBack()
{
introSequenceCount--;
SetIntroSequence();
}
public void IntroSequenceNext()
{
introSequenceCount++;
SetIntroSequence();
}
public void TutorialSequenceBack()
{
tutorialSequenceCount--;
SetTutorialSequence();
}
public void TutorialSequenceNext()
{
tutorialSequenceCount++;
SetTutorialSequence();
}
public void TutorialTextBack()
{
tutTextCount--;
TutTextCycle();
}
public void TutorialTextNext()
{
tutTextCount++;
TutTextCycle();
}
void SetIntroSequence()
{
switch (introSequenceCount)
{
case 0:
InitializeIntro();
break;
case 1:
introImage.SetActive(false);
backButton.SetActive(true);
introText.horizontalAlignment = HorizontalAlignmentOptions.Left;
introText.text = "OVERVIEW\n\n" +
"Title: Logic Gate Game\n" +
"Platform: WebGL build\n" +
"Subject: Science\n" +
"Sub Subject: Computer Science\n" +
"Main Focus: Logic Gates\n" +
"Learning Level: 6-8th grade"
;
break;
case 2:
introText.fontSize = 24;
introText.text = "PROPOSED EDTECH SOLUTION\n\n" +
"Computer science continues to grow in popularity and importance as the years go by and more and more students seem to be showing interest in the field. However, younger students may find it hard to get into the field, as it might seem intimidating or daunting to some at first. Computer science might not even have a place in their school’s curriculum, making it harder for them to access or be introduced to the topic. In order to aid them, I propose an easy-to-use and easy-to-understand game that helps them learn about logic gates, which can look more complicated than it actually is. The game can be in a minigame format where they need to assemble a certain “logic machine” with a specific output given certain pieces (like AND gates, OR gates, and input such as 0 and 1) and drag/place them together or pick the correct pieces, somewhat like a puzzle game where they figure out how logic gates work. It can be an introduction to logic gates, simplified for them to understand at a young age but educational enough for them to retain what they learn and use it when the concepts get more complex. This hopefully serves as just one building block in their computer science journey."
;
break;
case 3:
introText.fontSize = 17;
introText.text = "COMPETING SOFTWARE REVIEW\n\n" +
"Khan Academy - A nonprofit, educational website with lessons on various topics for students of all ages. This specific lesson on logic gates has articles to read and quiz problems to test what the user has learned. A user doesn’t need to create an account to access and use the content, but needs one in order to save and track their progress or get personalized help if so desired.\n\n" +
"Minecraft (Education Edition) - A widely popular sandbox video game’s educational version of the game. Free demo/trial available for teachers and their students, but might need to pay or be eligible for accessing the full edition. Minecraft has its own programming system in game via redstone. Students can build redstone circuits and play around with the assortment of redstone items. Very interactive and engaging as students have the freedom to build their contraptions and environments and interact with them. They can learn about logic gates and various other topics through redstone in conjunction with guided lesson plans.\n\n" +
"Nandgame - A web browser game that serves as an exercise aimed at older students (high school/college) or older people looking to learn about logic gates and building computers. Based off of a course called “From NAND to Tetris - Building a Modern Computer From First Principles”. Nandgame itself has users slowly progress through its levels, each one having them make a certain component (like an inverter or AND gate) using previous components. Aptly named, as the first component the user is given to build with is a NAND gate. It becomes more complex as it transitions from making logic gates to building a CPU."
;
break;
case 4:
introText.fontSize = 24;
introText.text = "COMPETING SOFTWARE SUGGESTED IMPROVEMENTS\n\n" +
"Learnability - Less clunky/overwhelming/hard-to-follow instructions. Built-in guide, clearer instructions, and additional guidance. Maybe addition of better tips or hints.\n\n" +
"Engagement - Visuals that are interesting and easy to look at. Interactive and visually appealing scenes and assets could keep students engaged and excited for a topic that could be difficult to grasp or be interested in. Reward/win screen that boldly presents itself to congratulate the student clearly and reinforces engagement.\n\n" +
"Clarification/Reinforcement of concepts - More explanation needed for certain levels or concepts. Repeat or have similar iterations of certain problems in order to reinforce what they learn. Expand on types of questions to explore more of the concept. "
;
break;
case 5:
introText.text = "STAKEHOLDERS\n\n" +
"Teachers\n" +
"Parents\n" +
"Students\n\n" +
"USERS\n\n" +
"Middle school students (6-8th graders)"
;
break;
case 6:
introText.text = "PERSONA\n\n" +
"Name: Fiona\n" +
"Age: 13\n" +
"Gender: Female\n" +
"Location: Suburbia USA\n" +
"Personal Notes:\n" +
" Enjoys computer games\n" +
" Is tech-savvy\n" +
"Student Notes:\n" +
" Struggles with conceptual computer science topics and basics\n" +
" Struggles with written tests and quizzes\n" +
" Likes computer lab classes\n" +
" Needs to work with visuals/hands-on examples since abstract concepts are hard to grasp"
;
break;
case 7:
introText.text = "PERSONA JUSTIFICATION\n\n" +
"Having worked with K-6 students before and having been a middle school student with a brief look into the world of computer science, I created this persona based on familiarity and my past experiences. Fiona represents the potential users of this game: middle schoolers with an interest in or even little knowledge with computer science but limited access to relevant learning resources. I chose this persona because CS is a subject that is very quickly becoming more and more popular yet it is difficult to get into, especially at younger ages. Also computer science classes are not as common in lower grades when they could be at the same level as foreign language classes, or rather they can be not part of the core curriculum but an optional extension of it if students are interested."
;
break;
case 8:
introText.fontSize = 24;
introText.text = "PROBLEM SCENARIO\n\n" +
"Fiona thinks she’s pretty interested in computers and coding, but her school doesn’t really offer much in terms of computer science classes. They have a computer lab where some classes take place. Although they had a brief introduction to programming through Scratch, they didn’t really learn much in terms of computer science topics/coding, just how to use the internet and tools like Google Docs. She doesn’t know where to start and doesn’t seem to have much resources available to her at school that can introduce her to computer science-related topics.\n\n" +
"Fiona enjoys watching Youtube videos and playing Minecraft after school, and stumbles across some videos about using redstone in Minecraft. She thinks the things people build with redstone are really cool but is overwhelmed and doesn’t know where to start learning about this fairly complicated system. Frustrated, she just continues watching instead of doing, and doesn’t try to further her knowledge or satiate her curiosity."
;
break;
case 9:
introText.fontSize = 22;
nextButton.SetActive(true);
introText.text = "ACTIVITY SCENARIO\n\n" +
"One day, Fiona’s parents, knowing her love for games, introduce her to one she might be interested in - one where she can easily start learning about logic gates while being able to stay engaged in the topic. They think it can help her get a headstart in CS before she moves on to more complex topics in the future. At first, Fiona is a bit hesitant because it isn’t exactly like the games she likes at the moment, but she decides to try it anyway.\n\n" +
"Fiona finds herself able to pick up on the basics of logic gates, thanks to this game being interactive enough for her to feel like she can understand the information without feeling like she’s taking a test. She likes being able to interact with the different pieces and is able to see the result of her actions right away, which feels rewarding to her. She realizes logic gates and things like redstone don’t have to be so complicated after all, and with her newfound knowledge she is able to apply it to simple redstone projects in her Minecraft world. Fiona decides she wants to continue her education in computer science in the future, but for now will have fun with her games and whatever she can find on the internet."
;
break;
case 10:
introText.fontSize = 24;
nextButton.SetActive(false);
introText.text = "PROBLEM STATEMENT\n\n" +
"Fiona is interested in computer science but feels a bit deterred by the abstract concepts and logic surrounding it, somewhat intimidated due to a lack of a proper introduction to any computer science-related topic. She finds herself not knowing some basics and doesn’t have an easy way to learn some building blocks before she gets into more complicated topics. She needs something that’s easy to understand/use and engaging that can show her a simplified version of what could be a complicated topic while teaching her an important building block in CS. After being introduced to just a small part of computers, Fiona wants to learn more. She is inspired and feels comfortable in pursuing a computer science education in the future."
;
break;
}
}
public void SetTutorialSequence()
{
incorrectOverlay.SetActive(false);
switch(tutorialSequenceCount)
{
case 0:
InitializeTutorial();
break;
case 1:
tutorialIntroText.fontSize = 22;
tutorialIntroTitleText.text = "First, let's go over the concept of \"bits\"!";
tutorialIntroText.text = "\n\n\n\n\n\nA bit is the smallest unit of storage on the computer. \"Bit\" is short for binary digit.\n" +
"Bits have a value of either 0 or 1. It can only have one of these two states.\n" +
"It's like how something can be either on or off, open or closed, true or false - bits are either 0 or 1.\n" +
"Used together, bits can be used to store or communicate information, or various other things.";
beginTutorialButton.SetActive(false);
tutNextButton.SetActive(true);
tutBackButton.SetActive(false);
imageBits.SetActive(true);
imageLogicGateEx.SetActive(false);
break;
case 2:
tutorialIntroText.fontSize = 22;
tutorialIntroTitleText.text = "Next, let's look at logic gates.";
tutorialIntroText.text = "\n\n\n\nLogic gates help electronic devices do their tasks, which can be complex. In a way, they help computers \"think\" by using logic and making it easier to do what they need to.\n" +
"\nA logic gate takes in some bits as an input. It will then output one bit based on these inputs.\n" +
"You can picture it as a machine that takes in bits, looks at them, and spits out one bit for you to have.";
tutBackButton.SetActive(true);
imageBits.SetActive(false);
imageLogicGateEx.SetActive(true);
imageLogicGates.SetActive(false);
break;
case 3:
tutorialIntroTitleText.text = "Here are some examples of logic gates!";
tutorialIntroText.text = "\n\n\n\nAND gates output 1 if and only if both inputs are 1. Otherwise, it will output a 0." +
"\nOR gates output 1 when at least one input is 1. Otherwise, it will output a 0." +
"\nNOT gates will output the opposite of their input. They INVERSE their input. So, if the input is 1, it will output 0, and vice versa.";
imageLogicGateEx.SetActive(false);
imageTruthTables.SetActive(false);
imageLogicGates.SetActive(true);
break;
case 4:
tutorialIntroText.fontSize = 22;
tutorialIntroTitleText.text = "Truth tables can help you understand and predict the output of certain logic gate matchups.";
tutorialIntroText.text = "\n\nDepending on the input, logic gates will give a certain output. Truth tables show you the different combinations of inputs and the output based on the logic gate. Here are some examples using the logic gates we already talked about!";
imageTruthTables.SetActive(true);
imageLogicGates.SetActive(false);
break;
case 5:
tutorialIntroText.fontSize = 32;
tutorialIntroTitleText.text = "Let's put it all together!";
tutorialIntroText.text = "\n\n\nIn this game, we will be making \"logic machines\"! These logic machines will help you learn how to use bits and logic gates together. Click the \"next\" button to continue!";
imageTruthTables.SetActive(false);
tutBackButton.SetActive(true);
break;
case 6:
//show how to use the game
gatePiecesT.SetActive(true);
andGateT.SetActive(true);
orGateT.SetActive(true);
emptySlotT.SetActive(true);
goButtonT.SetActive(true);
tutTextBox.SetActive(true);
tutBackButton.SetActive(false);
tutNextButton.SetActive(false);
incorrectOverlay.SetActive(false);
tutTextBoxNextButton.SetActive(true);
tutTextBoxBackButton.SetActive(false);
overlay.SetActive(true);
tutorialIntroTitleText.text = "";
tutorialIntroText.text = "";
tutText.text = "This is what the game looks like! Below is a \"logic machine\" you need to help put together. The input and output bits are already there for you at the right and left respectively. The logic gates AND and OR are at the bottom.";
break;
case 7:
gatePiecesT.SetActive(false);
andGateT.SetActive(false);
orGateT.SetActive(false);
emptySlotT.SetActive(false);
goButtonT.SetActive(false);
tutTextBox.SetActive(false);
tutNextButton.SetActive(true);
tutorialIntroTitleText.text = "That's correct!";
tutorialIntroText.text = "\n\n\n\nEither logic gate would have been correct.\n" +
"For the AND gate, both input bits were NOT 1, so it would output a 0 in this case.\n" +
"For the OR gate, there needs to be at least one input bit that is 1, but both were 0 in this case, so it would output 0 as well.\n" +
"Click the next button to continue.";
break;
case 8:
//congrats u finished tutorial
tutNextButton.SetActive(false);
tutorialIntroTitleText.text = "Congratulations! You finished the tutorial!";
tutorialIntroText.text = "\n\n\nYou're ready to play the game. Press the home button to go back to the menu and play Level 01. Feel free to come back to this tutorial at any time if you need help!";
break;
}
}
void InitializeIntro()
{
introText.fontSize = 24;
introText.horizontalAlignment = HorizontalAlignmentOptions.Center;
introText.text = "Welcome to Logic Gate Game!\n\n" +
"Learn about logic gates by putting together \"logic machines\" of your own!" +
"(Remember, there can be more than one correct answer!)";
introImage.SetActive(true);
backButton.SetActive(false);
}
void InitializeTutorial()
{
tutorialIntroText.fontSize = 32;
tutorialIntroTitleText.text = "Welcome to the tutorial!";
tutorialIntroText.text = "Before playing the game, let's go over some basic concepts and how to play!";
beginTutorialButton.SetActive(true);
tutNextButton.SetActive(false);
tutBackButton.SetActive(false);
imageBits.SetActive(false);
imageLogicGateEx.SetActive(false);
imageTruthTables.SetActive(false);
imageLogicGates.SetActive(false);
gatePiecesT.SetActive(false);
andGateT.SetActive(false);
orGateT.SetActive(false);
emptySlotT.SetActive(false);
goButtonT.SetActive(false);
incorrectOverlay.SetActive(false);
overlay.SetActive(false);
}
void InitializeLevel()
{
goButton.SetActive(false);
hintButton.SetActive(false);
andGate.SetActive(false);
orGate.SetActive(false);
notGate.SetActive(false);
emptySlot.SetActive(false);
gatePieces.SetActive(false);
output0.SetActive(false);
output1.SetActive(false);
andGateDefaultPos = andGate.GetComponent<RectTransform>().position;
orGateDefaultPos = orGate.GetComponent<RectTransform>().position;
}
//set up first exercise
public void BeginLevel()
{
goButton.SetActive(true);
hintButton.SetActive(true);
startButton.SetActive(false);
levelIntroText.text = "";
SetLevelExercise();
}
// used to check if tutorial was completed correctly
public void CheckTutorial()
{
string currGate = slot.GetComponent<Slot>().currentGate;
if(currGate.Equals("GateOr") || currGate.Equals("GateAnd"))
{
tutorialSequenceCount++;
SetTutorialSequence();
} else
{
tutTextCount = 0;
incorrectOverlay.SetActive(true);
}
}
public void TutTextCycle()
{
switch(tutTextCount)
{
case 0:
tutText.text = "This is what the game looks like! Below is a \"logic machine\" you need to help put together. The input and output bits are already there for you at the right and left respectively. The logic gates AND and OR are at the bottom.";
tutTextBoxNextButton.SetActive(true);
tutTextBoxBackButton.SetActive(false);
break;
case 1:
tutText.text = "This machine is incomplete. Our input is two bits that are both 0, and our output is also 0. Use your previous knowledge to finish this logic machine! (There can be more than one right answer!)";
tutTextBoxNextButton.SetActive(true);
tutTextBoxBackButton.SetActive(true);
break;
case 2:
tutText.text = "To complete this logic machine, use your Left Mouse Button to click, hold, and drag one of the logic gates to the empty slot with a question mark in the middle. To remove it, click and drag again and move it outside of the slot.";
tutTextBoxNextButton.SetActive(true);
tutTextBoxBackButton.SetActive(true);
break;
case 3:
tutText.text = "Good luck! When you're ready, click the GO! button to check your work.";
tutTextBoxNextButton.SetActive(false);
tutTextBoxBackButton.SetActive(true);
overlay.SetActive(false);
break;
}
}
/* checks if current exercise is done correctly
* if not, restart exercise
* if so, show congratulations screen and set up next exercise
*/
public void CheckWork()
{
string currGate = slot.GetComponent<Slot>().currentGate;
switch(levelSequenceCount)
{
case 0:
//right answer
if (currGate.Equals("GateOr"))
{
Debug.Log("Correct!");
levelSequenceCount++;
explanationText.text = "OR is the correct gate since using AND requires both inputs to be 1 in order to output 1.\n" +
"With the OR gate, you only need one input to be 1 to output 1.";
winScreen.SetActive(true);
}
//else if wrong answer
else
{
Debug.Log("Incorrect");
loseScreen.SetActive(true);
}
break;
case 1:
if (currGate.Equals("GateAnd") || currGate.Equals("GateOr"))
{
Debug.Log("Correct!");
levelSequenceCount++;
explanationText.text = "Either the AND or OR gate can work here, since both inputs are 1.\n" +
"An AND gate will give 1 only when both inputs are 1. As long as either input is 1, OR works too.";
winScreen.SetActive(true);
}
//else if wrong answer
else
{
Debug.Log("Incorrect");
loseScreen.SetActive(true);
}
break;
case 2:
if (currGate.Equals("GateAnd"))
{
Debug.Log("Correct!");
levelSequenceCount++;
explanationText.text = "AND is the correct gate since using OR would output a 1 (because if at least one input is 1 and our gate is OR, our output will be 1).\n" +
"Here we wanted our output to be 0, and since both inputs aren't 1, we will get a 0 from using an AND gate.";
winScreen.SetActive(true);
}
//else if wrong answer
else
{
Debug.Log("Incorrect");
loseScreen.SetActive(true);
}
break;
case 3:
break;
}
}
//display hint to player
public void ShowHint()
{
hintScreen.SetActive(true);
}
//return to game, exit hint
public void ExitHint()
{
hintScreen.SetActive(false);
}
public void SetLevelExercise()
{
winScreen.SetActive(false);
loseScreen.SetActive(false);
andGate.transform.position = andGateDefaultPos;
orGate.transform.position = orGateDefaultPos;
switch (levelSequenceCount)
{
case 0:
//first exercise - inputs 0,1 / output 1 / answer: OR gate
taskText.text = "Using the input and output provided below, please place the correct logic gate in the empty ? space to complete the circuit so it produces the desired output.";
inputText1.text = "0";
inputText2.text = "1";
//outputText.text = "1";
output0.SetActive(false);
output1.SetActive(true);
andGate.SetActive(true);
orGate.SetActive(true);
gatePieces.SetActive(true);
emptySlot.SetActive(true);
break;
case 1:
//second exercise - inputs 1,1 / output 1 / answer: AND gate or OR gate
inputText1.text = "1";
inputText2.text = "1";
//outputText.text = "1";
output0.SetActive(false);
output1.SetActive(true);
andGate.SetActive(true);
orGate.SetActive(true);
break;
case 2:
//third exercise - inputs 1,0 / output 0 / answer: AND gate
taskText.text = "Using the input and output provided below, please place the correct logic gate in the empty ? space to complete the circuit so it produces the desired output. (Pay attention to the output this time!)";
inputText1.text = "1";
inputText2.text = "0";
//outputText.text = "0";
output0.SetActive(true);
output1.SetActive(false);
break;
case 3:
//end
levelIntroText.text = "Thanks for playing!";
taskText.text = "";
inputText1.text = "";
inputText2.text = "";
outputText.text = "";
goButton.SetActive(false);
hintButton.SetActive(false);
andGate.SetActive(false);
orGate.SetActive(false);
notGate.SetActive(false);
emptySlot.SetActive(false);
gatePieces.SetActive(false);
output0.SetActive(false);
output1.SetActive(false);
break;
}
}
}
| 52.372792 | 1,208 | 0.612421 | [
"MIT"
] | audobii/IT265 | Assets/Scripts/UIManager.cs | 29,685 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace ES2.Amplitude.Unity.Simulation
{
/// <remarks/>
[XmlInclude(typeof(QuestExecutionTreeDecorator_EmpireEventOfEventOnColonizedPlanet))]
[XmlInclude(typeof(QuestExecutionTreeDecorator_ColonizedPlanet))]
[GeneratedCode("xsd", "2.0.50727.3038")]
[Serializable]
[DebuggerStepThrough]
[DesignerCategory("code")]
public class QuestExecutionTreeDecoratorOfEventOnColonizedPlanet : QuestExecutionTreeNode
{
private QuestExecutionTreeCondition[] itemsField;
private QuestInitiatorFilter initiatorField;
private int progressionIncrementField;
private bool stopAtFirstFailedConditionField;
public QuestExecutionTreeDecoratorOfEventOnColonizedPlanet()
{
this.initiatorField = QuestInitiatorFilter.AllEmpires;
this.progressionIncrementField = 0;
this.stopAtFirstFailedConditionField = false;
}
/// <remarks/>
[XmlElement("Condition_AreEqual", typeof(QuestExecutionTreeCondition_AreVariablesEqual), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_BattleEndedWithShips", typeof(QuestExecutionTreeCondition_BattleEndedWithShips), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_BattleEnded_FleetDestroyed", typeof(QuestExecutionTreeCondition_BattleEnded_FleetDestroyed), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_CheckDiplomaticAbility", typeof(QuestExecutionTreeCondition_CheckDiplomaticAbility), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_CheckDiplomaticRelation", typeof(QuestExecutionTreeCondition_CheckDiplomaticRelation), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_CheckInterpreter", typeof(QuestExecutionTreeCondition_CheckInterpreter), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_CheckPath", typeof(QuestExecutionTreeCondition_CheckPath), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_CheckSenateComposition", typeof(QuestExecutionTreeCondition_CheckSenateComposition), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_CountSimulationObjectsWithTag", typeof(QuestExecutionTreeCondition_CountSimulationObjectsWithTag), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_DiplomaticContracts", typeof(QuestExecutionTreeCondition_DiplomaticContracts), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_ExplorationProgress", typeof(QuestExecutionTreeCondition_ExplorationProgress), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_FleetHasHero", typeof(QuestExecutionTreeCondition_FleetHasHero), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_FleetShipStats", typeof(QuestExecutionTreeCondition_FleetShipStats), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_FleetShipStatsOnNode", typeof(QuestExecutionTreeCondition_FleetShipStatsOnNode), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_GovernmentType", typeof(QuestExecutionTreeCondition_GovernmentType), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasDeposits", typeof(QuestExecutionTreeCondition_HasDeposits), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasFidsi", typeof(QuestExecutionTreeCondition_HasFidsi), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasFleets", typeof(QuestExecutionTreeCondition_HasFleets), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasGarrisonComposition", typeof(QuestExecutionTreeCondition_HasGarrisonComposition), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasHappiness", typeof(QuestExecutionTreeCondition_HasHappiness), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasHeroes", typeof(QuestExecutionTreeCondition_HasHeroes), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasLaws", typeof(QuestExecutionTreeCondition_HasLaws), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasManpower", typeof(QuestExecutionTreeCondition_HasManpower), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasPlanets", typeof(QuestExecutionTreeCondition_HasPlanets), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasPoliticsScore", typeof(QuestExecutionTreeCondition_HasPoliticsScore), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasPopulationAmount", typeof(QuestExecutionTreeCondition_HasPopulationAmount), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasPopulationDiversity", typeof(QuestExecutionTreeCondition_HasPopulationDiversity), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasPopulationSlots", typeof(QuestExecutionTreeCondition_HasPopulationSlots), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasResource", typeof(QuestExecutionTreeCondition_HasResource), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasSpecialNodes", typeof(QuestExecutionTreeCondition_HasSpecialNodes), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasSystemDefense", typeof(QuestExecutionTreeCondition_HasSystemDefense), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasSystems", typeof(QuestExecutionTreeCondition_HasSystems), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasTradeIncome", typeof(QuestExecutionTreeCondition_HasTradeIncome), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_HasTradeRoutes", typeof(QuestExecutionTreeCondition_HasTradeRoutes), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_IsFleetDockedOnNode", typeof(QuestExecutionTreeCondition_IsFleetDockedOnNode), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_IsProgressionComplete", typeof(QuestExecutionTreeCondition_IsProgressionComplete), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_IsSystemOwnedBy", typeof(QuestExecutionTreeCondition_IsSystemOwnedBy), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_IsVariableNotEmpty", typeof(QuestExecutionTreeCondition_IsVariableNotEmpty), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_ManpowerDistribution", typeof(QuestExecutionTreeCondition_ManpowerDistribution), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_MinorFactionRelationship", typeof(QuestExecutionTreeCondition_MinorFactionRelationship), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_Pressure", typeof(QuestExecutionTreeCondition_Pressure), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_ShipHasResource", typeof(QuestExecutionTreeCondition_ShipHasResourceCost), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_ShipStats", typeof(QuestExecutionTreeCondition_ShipStats), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_SystemsHaveFidsi", typeof(QuestExecutionTreeCondition_SystemsHaveFidsi), Form = XmlSchemaForm.Unqualified)]
[XmlElement("Condition_TimerEnded", typeof(QuestExecutionTreeCondition_TimerEnded), Form = XmlSchemaForm.Unqualified)]
public QuestExecutionTreeCondition[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
this.RaisePropertyChanged("Items");
}
}
/// <remarks/>
[XmlAttribute]
[DefaultValue(QuestInitiatorFilter.AllEmpires)]
public QuestInitiatorFilter Initiator
{
get
{
return this.initiatorField;
}
set
{
this.initiatorField = value;
this.RaisePropertyChanged("Initiator");
}
}
/// <remarks/>
[XmlAttribute]
[DefaultValue(0)]
public int ProgressionIncrement
{
get
{
return this.progressionIncrementField;
}
set
{
this.progressionIncrementField = value;
this.RaisePropertyChanged("ProgressionIncrement");
}
}
/// <remarks/>
[XmlAttribute]
[DefaultValue(false)]
public bool StopAtFirstFailedCondition
{
get
{
return this.stopAtFirstFailedConditionField;
}
set
{
this.stopAtFirstFailedConditionField = value;
this.RaisePropertyChanged("StopAtFirstFailedCondition");
}
}
}
} | 55.590278 | 158 | 0.825484 | [
"MIT"
] | Scrivener07/Endless-Studio | Source/Studio.ES2/Amplitude/Unity/Simulation/quest/QuestExecutionTreeDecoratorOfEventOnColonizedPlanet.cs | 8,005 | C# |
//
// HttpContentHeaders.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.Collections.Generic;
namespace System.Net.Http.Headers
{
public sealed class HttpContentHeaders : HttpHeaders
{
readonly HttpContent content;
internal HttpContentHeaders (HttpContent content)
: base (HttpHeaderKind.Content)
{
this.content = content;
}
public ICollection<string> Allow {
get {
return GetValues<string> ("Allow");
}
}
public ICollection<string> ContentEncoding {
get {
return GetValues<string> ("Content-Encoding");
}
}
public ICollection<string> ContentLanguage {
get {
return GetValues<string> ("Content-Language");
}
}
public long? ContentLength {
get {
long? v = GetValue<long?> ("Content-Length");
if (v != null)
return v;
long l;
if (content.TryComputeLength (out l))
return l;
return null;
}
set {
AddOrRemove ("Content-Length", value);
}
}
public Uri ContentLocation {
get {
return GetValue<Uri> ("Content-Location");
}
set {
AddOrRemove ("Content-Location", value);
}
}
public byte[] ContentMD5 {
get {
return GetValue<byte[]> ("Content-MD5");
}
set {
AddOrRemove ("Content-MD5", value);
}
}
public ContentRangeHeaderValue ContentRange {
get {
return GetValue<ContentRangeHeaderValue> ("Content-Range");
}
set {
AddOrRemove ("Content-Range", value);
}
}
public MediaTypeHeaderValue ContentType {
get {
return GetValue<MediaTypeHeaderValue> ("Content-Type");
}
set {
AddOrRemove ("Content-Type", value);
}
}
public DateTimeOffset? Expires {
get {
return GetValue<DateTimeOffset?> ("Expires");
}
set {
AddOrRemove ("Expires", value);
}
}
public DateTimeOffset? LastModified {
get {
return GetValue<DateTimeOffset?> ("Last-Modified");
}
set {
AddOrRemove ("Last-Modified", value);
}
}
}
}
| 23.451128 | 73 | 0.67714 | [
"Apache-2.0"
] | pcc/mono | mcs/class/System.Net.Http/System.Net.Http.Headers/HttpContentHeaders.cs | 3,119 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.Acm
{
/// <summary>
/// This resource represents a successful validation of an ACM certificate in concert
/// with other resources.
///
/// Most commonly, this resource is used together with `aws.route53.Record` and
/// `aws.acm.Certificate` to request a DNS validated certificate,
/// deploy the required validation records and wait for validation to complete.
///
/// > **WARNING:** This resource implements a part of the validation workflow. It does not represent a real-world entity in AWS, therefore changing or deleting this resource on its own has no immediate effect.
///
///
///
///
/// > This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/acm_certificate_validation.html.markdown.
/// </summary>
public partial class CertificateValidation : Pulumi.CustomResource
{
/// <summary>
/// The ARN of the certificate that is being validated.
/// </summary>
[Output("certificateArn")]
public Output<string> CertificateArn { get; private set; } = null!;
/// <summary>
/// List of FQDNs that implement the validation. Only valid for DNS validation method ACM certificates. If this is set, the resource can implement additional sanity checks and has an explicit dependency on the resource that is implementing the validation
/// </summary>
[Output("validationRecordFqdns")]
public Output<ImmutableArray<string>> ValidationRecordFqdns { get; private set; } = null!;
/// <summary>
/// Create a CertificateValidation resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public CertificateValidation(string name, CertificateValidationArgs args, CustomResourceOptions? options = null)
: base("aws:acm/certificateValidation:CertificateValidation", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, ""))
{
}
private CertificateValidation(string name, Input<string> id, CertificateValidationState? state = null, CustomResourceOptions? options = null)
: base("aws:acm/certificateValidation:CertificateValidation", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing CertificateValidation resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static CertificateValidation Get(string name, Input<string> id, CertificateValidationState? state = null, CustomResourceOptions? options = null)
{
return new CertificateValidation(name, id, state, options);
}
}
public sealed class CertificateValidationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The ARN of the certificate that is being validated.
/// </summary>
[Input("certificateArn", required: true)]
public Input<string> CertificateArn { get; set; } = null!;
[Input("validationRecordFqdns")]
private InputList<string>? _validationRecordFqdns;
/// <summary>
/// List of FQDNs that implement the validation. Only valid for DNS validation method ACM certificates. If this is set, the resource can implement additional sanity checks and has an explicit dependency on the resource that is implementing the validation
/// </summary>
public InputList<string> ValidationRecordFqdns
{
get => _validationRecordFqdns ?? (_validationRecordFqdns = new InputList<string>());
set => _validationRecordFqdns = value;
}
public CertificateValidationArgs()
{
}
}
public sealed class CertificateValidationState : Pulumi.ResourceArgs
{
/// <summary>
/// The ARN of the certificate that is being validated.
/// </summary>
[Input("certificateArn")]
public Input<string>? CertificateArn { get; set; }
[Input("validationRecordFqdns")]
private InputList<string>? _validationRecordFqdns;
/// <summary>
/// List of FQDNs that implement the validation. Only valid for DNS validation method ACM certificates. If this is set, the resource can implement additional sanity checks and has an explicit dependency on the resource that is implementing the validation
/// </summary>
public InputList<string> ValidationRecordFqdns
{
get => _validationRecordFqdns ?? (_validationRecordFqdns = new InputList<string>());
set => _validationRecordFqdns = value;
}
public CertificateValidationState()
{
}
}
}
| 46.407407 | 262 | 0.661293 | [
"ECL-2.0",
"Apache-2.0"
] | Dominik-K/pulumi-aws | sdk/dotnet/Acm/CertificateValidation.cs | 6,265 | 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("workshop_dotnet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("workshop_dotnet")]
[assembly: AssemblyCopyright("Copyright © 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("6be449e8-1d3e-496f-beff-4a955928769c")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.861111 | 84 | 0.749817 | [
"MIT"
] | couchbaselabs/aspnet-nosql-workshop | 03/dotnet/workshop-dotnet/workshop-dotnet/Properties/AssemblyInfo.cs | 1,366 | C# |
namespace Springboard365.Xrm.Plugins.Core.IntegrationTest
{
using System;
using Microsoft.Xrm.Sdk;
using NUnit.Framework;
using Springboard365.UnitTest.Core;
[TestFixture]
public class CloneContractSpecification : SpecificationBase
{
private CloneContractSpecificationFixture testFixture;
protected override void Context()
{
testFixture = new CloneContractSpecificationFixture();
testFixture.PerformTestSetup();
}
protected override void BecauseOf()
{
testFixture.CrmWriter.Execute(testFixture.RequestId, testFixture.CloneContractRequest);
testFixture.Result = Retry.Do(() => testFixture.EntitySerializer.Deserialize(testFixture.RequestId, testFixture.MessageName));
}
[Test]
public void ShouldReturnInputParametersContainingTwoParameters()
{
Assert.IsTrue(testFixture.Result.InputParameters.Count == 2);
}
[Test]
public void ShouldReturnInputParametersContainingContractId()
{
Assert.IsTrue(testFixture.Result.InputParameters.OneOf<Guid>("ContractId"));
}
[Test]
public void ShouldReturnInputParametersContainingIncludeCanceledLines()
{
Assert.IsTrue(testFixture.Result.InputParameters.OneOf<bool>("IncludeCanceledLines"));
}
[Test]
public void ShouldReturnNoPreEntityImages()
{
Assert.IsTrue(testFixture.Result.PreEntityImages.NoParameters());
}
[Test]
public void ShouldReturnPostEntityImagesContainingOneParameter()
{
Assert.IsTrue(testFixture.Result.PostEntityImages.One());
}
[Test]
public void ShouldReturnPostEntityImagesContainingAsynchronousStepPrimaryName()
{
Assert.IsTrue(testFixture.Result.PostEntityImages.OneOf<Entity>("AsynchronousStepPrimaryName"));
}
}
} | 31.983871 | 138 | 0.66465 | [
"Apache-2.0"
] | Davesmall28/DSmall.DynamicsCrm.Plugins.Core | Springboard365.Xrm.Plugins.Core.IntegrationTest/PluginTest/CloneContract/CloneContractSpecification.cs | 1,983 | C# |
namespace OccultMerchant.Models
{
public class TodoItem
{
public long Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
} | 21.777778 | 44 | 0.581633 | [
"MIT"
] | MrFizban/OccultMerchantProject | OccultMerchant/OccultMerchant/Models/TodoItem.cs | 196 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using NetOffice;
namespace NetOffice.WordApi
{
#pragma warning disable
#region SinkPoint Interface
[SupportByVersionAttribute("Word", 11,12,14,15)]
[ComImport, Guid("00020A01-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch), TypeLibType((short)0x1010)]
public interface ApplicationEvents4
{
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)]
void Startup();
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2)]
void Quit();
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(3)]
void DocumentChange();
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(4)]
void DocumentOpen([In, MarshalAs(UnmanagedType.IDispatch)] object doc);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(6)]
void DocumentBeforeClose([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object cancel);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(7)]
void DocumentBeforePrint([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object cancel);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(8)]
void DocumentBeforeSave([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object saveAsUI, [In] [Out] ref object cancel);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(9)]
void NewDocument([In, MarshalAs(UnmanagedType.IDispatch)] object doc);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(10)]
void WindowActivate([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In, MarshalAs(UnmanagedType.IDispatch)] object wn);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(11)]
void WindowDeactivate([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In, MarshalAs(UnmanagedType.IDispatch)] object wn);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(12)]
void WindowSelectionChange([In, MarshalAs(UnmanagedType.IDispatch)] object sel);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(13)]
void WindowBeforeRightClick([In, MarshalAs(UnmanagedType.IDispatch)] object sel, [In] [Out] ref object cancel);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(14)]
void WindowBeforeDoubleClick([In, MarshalAs(UnmanagedType.IDispatch)] object sel, [In] [Out] ref object cancel);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(15)]
void EPostagePropertyDialog([In, MarshalAs(UnmanagedType.IDispatch)] object doc);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(16)]
void EPostageInsert([In, MarshalAs(UnmanagedType.IDispatch)] object doc);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(17)]
void MailMergeAfterMerge([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In, MarshalAs(UnmanagedType.IDispatch)] object docResult);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(18)]
void MailMergeAfterRecordMerge([In, MarshalAs(UnmanagedType.IDispatch)] object doc);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(19)]
void MailMergeBeforeMerge([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] object startRecord, [In] object endRecord, [In] [Out] ref object cancel);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(20)]
void MailMergeBeforeRecordMerge([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object cancel);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(21)]
void MailMergeDataSourceLoad([In, MarshalAs(UnmanagedType.IDispatch)] object doc);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(22)]
void MailMergeDataSourceValidate([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object handled);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(23)]
void MailMergeWizardSendToCustom([In, MarshalAs(UnmanagedType.IDispatch)] object doc);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(24)]
void MailMergeWizardStateChange([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object fromState, [In] [Out] ref object toState, [In] [Out] ref object handled);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(25)]
void WindowSize([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In, MarshalAs(UnmanagedType.IDispatch)] object wn);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(26)]
void XMLSelectionChange([In, MarshalAs(UnmanagedType.IDispatch)] object sel, [In, MarshalAs(UnmanagedType.IDispatch)] object oldXMLNode, [In, MarshalAs(UnmanagedType.IDispatch)] object newXMLNode, [In] [Out] ref object reason);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(27)]
void XMLValidationError([In, MarshalAs(UnmanagedType.IDispatch)] object xMLNode);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(28)]
void DocumentSync([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] object syncEventType);
[SupportByVersionAttribute("Word", 11,12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(29)]
void EPostageInsertEx([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] object cpDeliveryAddrStart, [In] object cpDeliveryAddrEnd, [In] object cpReturnAddrStart, [In] object cpReturnAddrEnd, [In] object xaWidth, [In] object yaHeight, [In] object bstrPrinterName, [In] object bstrPaperFeed, [In] object fPrint, [In] [Out] ref object fCancel);
[SupportByVersionAttribute("Word", 12,14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(30)]
void MailMergeDataSourceValidate2([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object handled);
[SupportByVersionAttribute("Word", 14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(31)]
void ProtectedViewWindowOpen([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow);
[SupportByVersionAttribute("Word", 14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(32)]
void ProtectedViewWindowBeforeEdit([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow, [In] [Out] ref object cancel);
[SupportByVersionAttribute("Word", 14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(33)]
void ProtectedViewWindowBeforeClose([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow, [In] object closeReason, [In] [Out] ref object cancel);
[SupportByVersionAttribute("Word", 14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(34)]
void ProtectedViewWindowSize([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow);
[SupportByVersionAttribute("Word", 14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(35)]
void ProtectedViewWindowActivate([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow);
[SupportByVersionAttribute("Word", 14,15)]
[PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(36)]
void ProtectedViewWindowDeactivate([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow);
}
#endregion
#region SinkHelper
[ComVisible(true), ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FHidden)]
public class ApplicationEvents4_SinkHelper : SinkHelper, ApplicationEvents4
{
#region Static
public static readonly string Id = "00020A01-0000-0000-C000-000000000046";
#endregion
#region Fields
private IEventBinding _eventBinding;
private COMObject _eventClass;
#endregion
#region Construction
public ApplicationEvents4_SinkHelper(COMObject eventClass, IConnectionPoint connectPoint): base(eventClass)
{
_eventClass = eventClass;
_eventBinding = (IEventBinding)eventClass;
SetupEventBinding(connectPoint);
}
#endregion
#region Properties
internal Core Factory
{
get
{
if (null != _eventClass)
return _eventClass.Factory;
else
return Core.Default;
}
}
#endregion
#region ApplicationEvents4 Members
public void Startup()
{
Delegate[] recipients = _eventBinding.GetEventRecipients("Startup");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray();
return;
}
object[] paramsArray = new object[0];
_eventBinding.RaiseCustomEvent("Startup", ref paramsArray);
}
public void Quit()
{
Delegate[] recipients = _eventBinding.GetEventRecipients("Quit");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray();
return;
}
object[] paramsArray = new object[0];
_eventBinding.RaiseCustomEvent("Quit", ref paramsArray);
}
public void DocumentChange()
{
Delegate[] recipients = _eventBinding.GetEventRecipients("DocumentChange");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray();
return;
}
object[] paramsArray = new object[0];
_eventBinding.RaiseCustomEvent("DocumentChange", ref paramsArray);
}
public void DocumentOpen([In, MarshalAs(UnmanagedType.IDispatch)] object doc)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("DocumentOpen");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[1];
paramsArray[0] = newDoc;
_eventBinding.RaiseCustomEvent("DocumentOpen", ref paramsArray);
}
public void DocumentBeforeClose([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object cancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("DocumentBeforeClose");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, cancel);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray.SetValue(cancel, 1);
_eventBinding.RaiseCustomEvent("DocumentBeforeClose", ref paramsArray);
cancel = (bool)paramsArray[1];
}
public void DocumentBeforePrint([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object cancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("DocumentBeforePrint");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, cancel);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray.SetValue(cancel, 1);
_eventBinding.RaiseCustomEvent("DocumentBeforePrint", ref paramsArray);
cancel = (bool)paramsArray[1];
}
public void DocumentBeforeSave([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object saveAsUI, [In] [Out] ref object cancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("DocumentBeforeSave");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, saveAsUI, cancel);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[3];
paramsArray[0] = newDoc;
paramsArray.SetValue(saveAsUI, 1);
paramsArray.SetValue(cancel, 2);
_eventBinding.RaiseCustomEvent("DocumentBeforeSave", ref paramsArray);
saveAsUI = (bool)paramsArray[1];
cancel = (bool)paramsArray[2];
}
public void NewDocument([In, MarshalAs(UnmanagedType.IDispatch)] object doc)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("NewDocument");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[1];
paramsArray[0] = newDoc;
_eventBinding.RaiseCustomEvent("NewDocument", ref paramsArray);
}
public void WindowActivate([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In, MarshalAs(UnmanagedType.IDispatch)] object wn)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("WindowActivate");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, wn);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
NetOffice.WordApi.Window newWn = Factory.CreateObjectFromComProxy(_eventClass, wn) as NetOffice.WordApi.Window;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray[1] = newWn;
_eventBinding.RaiseCustomEvent("WindowActivate", ref paramsArray);
}
public void WindowDeactivate([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In, MarshalAs(UnmanagedType.IDispatch)] object wn)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("WindowDeactivate");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, wn);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
NetOffice.WordApi.Window newWn = Factory.CreateObjectFromComProxy(_eventClass, wn) as NetOffice.WordApi.Window;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray[1] = newWn;
_eventBinding.RaiseCustomEvent("WindowDeactivate", ref paramsArray);
}
public void WindowSelectionChange([In, MarshalAs(UnmanagedType.IDispatch)] object sel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("WindowSelectionChange");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(sel);
return;
}
NetOffice.WordApi.Selection newSel = Factory.CreateObjectFromComProxy(_eventClass, sel) as NetOffice.WordApi.Selection;
object[] paramsArray = new object[1];
paramsArray[0] = newSel;
_eventBinding.RaiseCustomEvent("WindowSelectionChange", ref paramsArray);
}
public void WindowBeforeRightClick([In, MarshalAs(UnmanagedType.IDispatch)] object sel, [In] [Out] ref object cancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("WindowBeforeRightClick");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(sel, cancel);
return;
}
NetOffice.WordApi.Selection newSel = Factory.CreateObjectFromComProxy(_eventClass, sel) as NetOffice.WordApi.Selection;
object[] paramsArray = new object[2];
paramsArray[0] = newSel;
paramsArray.SetValue(cancel, 1);
_eventBinding.RaiseCustomEvent("WindowBeforeRightClick", ref paramsArray);
cancel = (bool)paramsArray[1];
}
public void WindowBeforeDoubleClick([In, MarshalAs(UnmanagedType.IDispatch)] object sel, [In] [Out] ref object cancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("WindowBeforeDoubleClick");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(sel, cancel);
return;
}
NetOffice.WordApi.Selection newSel = Factory.CreateObjectFromComProxy(_eventClass, sel) as NetOffice.WordApi.Selection;
object[] paramsArray = new object[2];
paramsArray[0] = newSel;
paramsArray.SetValue(cancel, 1);
_eventBinding.RaiseCustomEvent("WindowBeforeDoubleClick", ref paramsArray);
cancel = (bool)paramsArray[1];
}
public void EPostagePropertyDialog([In, MarshalAs(UnmanagedType.IDispatch)] object doc)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("EPostagePropertyDialog");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[1];
paramsArray[0] = newDoc;
_eventBinding.RaiseCustomEvent("EPostagePropertyDialog", ref paramsArray);
}
public void EPostageInsert([In, MarshalAs(UnmanagedType.IDispatch)] object doc)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("EPostageInsert");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[1];
paramsArray[0] = newDoc;
_eventBinding.RaiseCustomEvent("EPostageInsert", ref paramsArray);
}
public void MailMergeAfterMerge([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In, MarshalAs(UnmanagedType.IDispatch)] object docResult)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("MailMergeAfterMerge");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, docResult);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
NetOffice.WordApi.Document newDocResult = Factory.CreateObjectFromComProxy(_eventClass, docResult) as NetOffice.WordApi.Document;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray[1] = newDocResult;
_eventBinding.RaiseCustomEvent("MailMergeAfterMerge", ref paramsArray);
}
public void MailMergeAfterRecordMerge([In, MarshalAs(UnmanagedType.IDispatch)] object doc)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("MailMergeAfterRecordMerge");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[1];
paramsArray[0] = newDoc;
_eventBinding.RaiseCustomEvent("MailMergeAfterRecordMerge", ref paramsArray);
}
public void MailMergeBeforeMerge([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] object startRecord, [In] object endRecord, [In] [Out] ref object cancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("MailMergeBeforeMerge");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, startRecord, endRecord, cancel);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
Int32 newStartRecord = Convert.ToInt32(startRecord);
Int32 newEndRecord = Convert.ToInt32(endRecord);
object[] paramsArray = new object[4];
paramsArray[0] = newDoc;
paramsArray[1] = newStartRecord;
paramsArray[2] = newEndRecord;
paramsArray.SetValue(cancel, 3);
_eventBinding.RaiseCustomEvent("MailMergeBeforeMerge", ref paramsArray);
cancel = (bool)paramsArray[3];
}
public void MailMergeBeforeRecordMerge([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object cancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("MailMergeBeforeRecordMerge");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, cancel);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray.SetValue(cancel, 1);
_eventBinding.RaiseCustomEvent("MailMergeBeforeRecordMerge", ref paramsArray);
cancel = (bool)paramsArray[1];
}
public void MailMergeDataSourceLoad([In, MarshalAs(UnmanagedType.IDispatch)] object doc)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("MailMergeDataSourceLoad");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[1];
paramsArray[0] = newDoc;
_eventBinding.RaiseCustomEvent("MailMergeDataSourceLoad", ref paramsArray);
}
public void MailMergeDataSourceValidate([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object handled)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("MailMergeDataSourceValidate");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, handled);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray.SetValue(handled, 1);
_eventBinding.RaiseCustomEvent("MailMergeDataSourceValidate", ref paramsArray);
handled = (bool)paramsArray[1];
}
public void MailMergeWizardSendToCustom([In, MarshalAs(UnmanagedType.IDispatch)] object doc)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("MailMergeWizardSendToCustom");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[1];
paramsArray[0] = newDoc;
_eventBinding.RaiseCustomEvent("MailMergeWizardSendToCustom", ref paramsArray);
}
public void MailMergeWizardStateChange([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object fromState, [In] [Out] ref object toState, [In] [Out] ref object handled)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("MailMergeWizardStateChange");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, fromState, toState, handled);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[4];
paramsArray[0] = newDoc;
paramsArray.SetValue(fromState, 1);
paramsArray.SetValue(toState, 2);
paramsArray.SetValue(handled, 3);
_eventBinding.RaiseCustomEvent("MailMergeWizardStateChange", ref paramsArray);
fromState = (Int32)paramsArray[1];
toState = (Int32)paramsArray[2];
handled = (bool)paramsArray[3];
}
public void WindowSize([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In, MarshalAs(UnmanagedType.IDispatch)] object wn)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("WindowSize");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, wn);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
NetOffice.WordApi.Window newWn = Factory.CreateObjectFromComProxy(_eventClass, wn) as NetOffice.WordApi.Window;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray[1] = newWn;
_eventBinding.RaiseCustomEvent("WindowSize", ref paramsArray);
}
public void XMLSelectionChange([In, MarshalAs(UnmanagedType.IDispatch)] object sel, [In, MarshalAs(UnmanagedType.IDispatch)] object oldXMLNode, [In, MarshalAs(UnmanagedType.IDispatch)] object newXMLNode, [In] [Out] ref object reason)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("XMLSelectionChange");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(sel, oldXMLNode, newXMLNode, reason);
return;
}
NetOffice.WordApi.Selection newSel = Factory.CreateObjectFromComProxy(_eventClass, sel) as NetOffice.WordApi.Selection;
NetOffice.WordApi.XMLNode newOldXMLNode = Factory.CreateObjectFromComProxy(_eventClass, oldXMLNode) as NetOffice.WordApi.XMLNode;
NetOffice.WordApi.XMLNode newNewXMLNode = Factory.CreateObjectFromComProxy(_eventClass, newXMLNode) as NetOffice.WordApi.XMLNode;
object[] paramsArray = new object[4];
paramsArray[0] = newSel;
paramsArray[1] = newOldXMLNode;
paramsArray[2] = newNewXMLNode;
paramsArray.SetValue(reason, 3);
_eventBinding.RaiseCustomEvent("XMLSelectionChange", ref paramsArray);
reason = (Int32)paramsArray[3];
}
public void XMLValidationError([In, MarshalAs(UnmanagedType.IDispatch)] object xMLNode)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("XMLValidationError");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(xMLNode);
return;
}
NetOffice.WordApi.XMLNode newXMLNode = Factory.CreateObjectFromComProxy(_eventClass, xMLNode) as NetOffice.WordApi.XMLNode;
object[] paramsArray = new object[1];
paramsArray[0] = newXMLNode;
_eventBinding.RaiseCustomEvent("XMLValidationError", ref paramsArray);
}
public void DocumentSync([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] object syncEventType)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("DocumentSync");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, syncEventType);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
NetOffice.OfficeApi.Enums.MsoSyncEventType newSyncEventType = (NetOffice.OfficeApi.Enums.MsoSyncEventType)syncEventType;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray[1] = newSyncEventType;
_eventBinding.RaiseCustomEvent("DocumentSync", ref paramsArray);
}
public void EPostageInsertEx([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] object cpDeliveryAddrStart, [In] object cpDeliveryAddrEnd, [In] object cpReturnAddrStart, [In] object cpReturnAddrEnd, [In] object xaWidth, [In] object yaHeight, [In] object bstrPrinterName, [In] object bstrPaperFeed, [In] object fPrint, [In] [Out] ref object fCancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("EPostageInsertEx");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, cpDeliveryAddrStart, cpDeliveryAddrEnd, cpReturnAddrStart, cpReturnAddrEnd, xaWidth, yaHeight, bstrPrinterName, bstrPaperFeed, fPrint, fCancel);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
Int32 newcpDeliveryAddrStart = Convert.ToInt32(cpDeliveryAddrStart);
Int32 newcpDeliveryAddrEnd = Convert.ToInt32(cpDeliveryAddrEnd);
Int32 newcpReturnAddrStart = Convert.ToInt32(cpReturnAddrStart);
Int32 newcpReturnAddrEnd = Convert.ToInt32(cpReturnAddrEnd);
Int32 newxaWidth = Convert.ToInt32(xaWidth);
Int32 newyaHeight = Convert.ToInt32(yaHeight);
string newbstrPrinterName = Convert.ToString(bstrPrinterName);
string newbstrPaperFeed = Convert.ToString(bstrPaperFeed);
bool newfPrint = Convert.ToBoolean(fPrint);
object[] paramsArray = new object[11];
paramsArray[0] = newDoc;
paramsArray[1] = newcpDeliveryAddrStart;
paramsArray[2] = newcpDeliveryAddrEnd;
paramsArray[3] = newcpReturnAddrStart;
paramsArray[4] = newcpReturnAddrEnd;
paramsArray[5] = newxaWidth;
paramsArray[6] = newyaHeight;
paramsArray[7] = newbstrPrinterName;
paramsArray[8] = newbstrPaperFeed;
paramsArray[9] = newfPrint;
paramsArray.SetValue(fCancel, 10);
_eventBinding.RaiseCustomEvent("EPostageInsertEx", ref paramsArray);
fCancel = (bool)paramsArray[10];
}
public void MailMergeDataSourceValidate2([In, MarshalAs(UnmanagedType.IDispatch)] object doc, [In] [Out] ref object handled)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("MailMergeDataSourceValidate2");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(doc, handled);
return;
}
NetOffice.WordApi.Document newDoc = Factory.CreateObjectFromComProxy(_eventClass, doc) as NetOffice.WordApi.Document;
object[] paramsArray = new object[2];
paramsArray[0] = newDoc;
paramsArray.SetValue(handled, 1);
_eventBinding.RaiseCustomEvent("MailMergeDataSourceValidate2", ref paramsArray);
handled = (bool)paramsArray[1];
}
public void ProtectedViewWindowOpen([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("ProtectedViewWindowOpen");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(pvWindow);
return;
}
NetOffice.WordApi.ProtectedViewWindow newPvWindow = Factory.CreateObjectFromComProxy(_eventClass, pvWindow) as NetOffice.WordApi.ProtectedViewWindow;
object[] paramsArray = new object[1];
paramsArray[0] = newPvWindow;
_eventBinding.RaiseCustomEvent("ProtectedViewWindowOpen", ref paramsArray);
}
public void ProtectedViewWindowBeforeEdit([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow, [In] [Out] ref object cancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("ProtectedViewWindowBeforeEdit");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(pvWindow, cancel);
return;
}
NetOffice.WordApi.ProtectedViewWindow newPvWindow = Factory.CreateObjectFromComProxy(_eventClass, pvWindow) as NetOffice.WordApi.ProtectedViewWindow;
object[] paramsArray = new object[2];
paramsArray[0] = newPvWindow;
paramsArray.SetValue(cancel, 1);
_eventBinding.RaiseCustomEvent("ProtectedViewWindowBeforeEdit", ref paramsArray);
cancel = (bool)paramsArray[1];
}
public void ProtectedViewWindowBeforeClose([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow, [In] object closeReason, [In] [Out] ref object cancel)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("ProtectedViewWindowBeforeClose");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(pvWindow, closeReason, cancel);
return;
}
NetOffice.WordApi.ProtectedViewWindow newPvWindow = Factory.CreateObjectFromComProxy(_eventClass, pvWindow) as NetOffice.WordApi.ProtectedViewWindow;
Int32 newCloseReason = Convert.ToInt32(closeReason);
object[] paramsArray = new object[3];
paramsArray[0] = newPvWindow;
paramsArray[1] = newCloseReason;
paramsArray.SetValue(cancel, 2);
_eventBinding.RaiseCustomEvent("ProtectedViewWindowBeforeClose", ref paramsArray);
cancel = (bool)paramsArray[2];
}
public void ProtectedViewWindowSize([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("ProtectedViewWindowSize");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(pvWindow);
return;
}
NetOffice.WordApi.ProtectedViewWindow newPvWindow = Factory.CreateObjectFromComProxy(_eventClass, pvWindow) as NetOffice.WordApi.ProtectedViewWindow;
object[] paramsArray = new object[1];
paramsArray[0] = newPvWindow;
_eventBinding.RaiseCustomEvent("ProtectedViewWindowSize", ref paramsArray);
}
public void ProtectedViewWindowActivate([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("ProtectedViewWindowActivate");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(pvWindow);
return;
}
NetOffice.WordApi.ProtectedViewWindow newPvWindow = Factory.CreateObjectFromComProxy(_eventClass, pvWindow) as NetOffice.WordApi.ProtectedViewWindow;
object[] paramsArray = new object[1];
paramsArray[0] = newPvWindow;
_eventBinding.RaiseCustomEvent("ProtectedViewWindowActivate", ref paramsArray);
}
public void ProtectedViewWindowDeactivate([In, MarshalAs(UnmanagedType.IDispatch)] object pvWindow)
{
Delegate[] recipients = _eventBinding.GetEventRecipients("ProtectedViewWindowDeactivate");
if( (true == _eventClass.IsCurrentlyDisposing) || (recipients.Length == 0) )
{
Invoker.ReleaseParamsArray(pvWindow);
return;
}
NetOffice.WordApi.ProtectedViewWindow newPvWindow = Factory.CreateObjectFromComProxy(_eventClass, pvWindow) as NetOffice.WordApi.ProtectedViewWindow;
object[] paramsArray = new object[1];
paramsArray[0] = newPvWindow;
_eventBinding.RaiseCustomEvent("ProtectedViewWindowDeactivate", ref paramsArray);
}
#endregion
}
#endregion
#pragma warning restore
} | 45.760098 | 358 | 0.739769 | [
"MIT"
] | NetOffice/NetOffice | Source/Word/EventInterfaces/ApplicationEvents4.cs | 37,386 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iottwinmaker-2021-11-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoTTwinMaker.Model
{
/// <summary>
/// An error returned by the <code>BatchPutProperty</code> action.
/// </summary>
public partial class BatchPutPropertyError
{
private PropertyValueEntry _entry;
private string _errorCode;
private string _errorMessage;
/// <summary>
/// Gets and sets the property Entry.
/// <para>
/// An object that contains information about errors returned by the <code>BatchPutProperty</code>
/// action.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public PropertyValueEntry Entry
{
get { return this._entry; }
set { this._entry = value; }
}
// Check to see if Entry property is set
internal bool IsSetEntry()
{
return this._entry != null;
}
/// <summary>
/// Gets and sets the property ErrorCode.
/// <para>
/// The error code.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=256)]
public string ErrorCode
{
get { return this._errorCode; }
set { this._errorCode = value; }
}
// Check to see if ErrorCode property is set
internal bool IsSetErrorCode()
{
return this._errorCode != null;
}
/// <summary>
/// Gets and sets the property ErrorMessage.
/// <para>
/// The error message.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=256)]
public string ErrorMessage
{
get { return this._errorMessage; }
set { this._errorMessage = value; }
}
// Check to see if ErrorMessage property is set
internal bool IsSetErrorMessage()
{
return this._errorMessage != null;
}
}
} | 28.737374 | 110 | 0.594376 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/IoTTwinMaker/Generated/Model/BatchPutPropertyError.cs | 2,845 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Network;
using RandoMainDLL.Memory;
namespace RandoMainDLL {
public static class Multiplayer {
public static BlockingCollection<Packet> Queue = new BlockingCollection<Packet>();
public static string Id { get; private set; }
public static string Name { get; private set; }
private static HashSet<string> currentPlayers = new HashSet<string>();
private static MultiverseInfoMessage lastMultiverseInfo = null;
public static void SetCurrentUser(UserInfo user) {
Id = user.Id;
Name = user.Name;
if (lastMultiverseInfo != null)
UpdateMultivere(lastMultiverseInfo);
}
public static void UpdateMultivere(MultiverseInfoMessage multiverse) {
lastMultiverseInfo = multiverse;
var universe = multiverse.Universes.First(u => u.Worlds.Any(w => w.Members.Any(m => m.Id == Id)));
var players = new Dictionary<string, UserInfo>();
foreach (var world in universe.Worlds)
foreach (var member in world.Members)
if (member.Id != Id)
players.Add(member.Id, member);
var toAdd = players.Keys.Except(currentPlayers);
var toRemove = currentPlayers.Except(players.Keys);
foreach (var player in toRemove)
InterOp.Multiplayer.remove_player(player);
foreach (var player in toAdd)
InterOp.Multiplayer.add_player(player, players[player].Name);
currentPlayers = players.Keys.ToHashSet();
foreach (var player in players)
InterOp.Multiplayer.set_player_online(player.Key, player.Value.HasConnectedMultiverseId);
}
public static void UpdatePlayerPosition(string id, float x, float y) {
if (currentPlayers.Any(p => p == id)) {
InterOp.Multiplayer.update_player_position(id, x, y);
}
else {
Randomizer.Log($"Got player position from unknown player {id}: {x}, {y}");
}
}
public static void Update() {
var playerPosition = InterOp.get_position();
UDPSocketClient.SendPlayerPosition(playerPosition.X, playerPosition.Y);
while (Queue.TryTake(out var packet)) {
switch (packet.Id) {
case 8:
var multiverse = MultiverseInfoMessage.Parser.ParseFrom(packet.Packet_);
UpdateMultivere(multiverse);
break;
case 11:
var position = UpdatePlayerPositionMessage.Parser.ParseFrom(packet.Packet_);
UpdatePlayerPosition(position.PlayerId, position.X, position.Y);
break;
case 12:
var authenticated = AuthenticatedMessage.Parser.ParseFrom(packet.Packet_);
SetCurrentUser(authenticated.User);
break;
default:
break;
}
}
}
}
}
| 33.813953 | 104 | 0.66575 | [
"MIT"
] | LoadCake/OriWotwRandomizerClient | projects/RandoMainDLL/Multiplayer.cs | 2,910 | 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/winioctl.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="STORAGE_OFFLOAD_TOKEN" /> struct.</summary>
[SupportedOSPlatform("windows8.0")]
public static unsafe partial class STORAGE_OFFLOAD_TOKENTests
{
/// <summary>Validates that the <see cref="STORAGE_OFFLOAD_TOKEN" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<STORAGE_OFFLOAD_TOKEN>(), Is.EqualTo(sizeof(STORAGE_OFFLOAD_TOKEN)));
}
/// <summary>Validates that the <see cref="STORAGE_OFFLOAD_TOKEN" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(STORAGE_OFFLOAD_TOKEN).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="STORAGE_OFFLOAD_TOKEN" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(STORAGE_OFFLOAD_TOKEN), Is.EqualTo(512));
}
}
| 38.432432 | 145 | 0.731364 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/Windows/um/winioctl/STORAGE_OFFLOAD_TOKENTests.cs | 1,424 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Rasmus Mikkelsen
// Copyright (c) 2015-2017 eBay Software Foundation
// https://github.com/eventflow/EventFlow
//
// 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.Threading;
using System.Threading.Tasks;
using EventFlow.Aggregates;
using EventFlow.Sagas;
namespace EventFlow.TestHelpers.Aggregates.Sagas
{
public class ThingySagaLocator : ISagaLocator
{
public Task<ISagaId> LocateSagaAsync(IDomainEvent domainEvent, CancellationToken cancellationToken)
{
var aggregateId = domainEvent.GetIdentity();
return Task.FromResult<ISagaId>(new ThingySagaId($"saga-{aggregateId.Value}"));
}
}
} | 44.641026 | 107 | 0.750144 | [
"MIT"
] | Jaben/EventFlow | Source/EventFlow.TestHelpers/Aggregates/Sagas/ThingySagaLocator.cs | 1,743 | C# |
using System;
using Autofac;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Order;
using DryIoc;
using Grace.DependencyInjection;
using LightInject;
using Microsoft.Extensions.DependencyInjection;
using SimpleInjector;
using SimpleInjector.Lifestyles;
using Container = DryIoc.Container;
using IContainer = Autofac.IContainer;
namespace PerformanceTests
{
public class OpenScopeAndResolveScopedWithSingletonTransientScopedDeps
{
public static DryIoc.IContainer PrepareDryIoc()
{
var container = new Container();
container.Register<Parameter1>(Reuse.Transient);
container.Register<Parameter2>(Reuse.Singleton);
container.Register<Parameter3>(Reuse.Scoped);
container.Register<ScopedBlah>(Reuse.Scoped);
return container;
}
public static object Measure(DryIoc.IContainer container)
{
using (var scope = container.OpenScope())
return scope.Resolve<ScopedBlah>();
}
public static IServiceProvider PrepareMsDi()
{
var services = new ServiceCollection();
services.AddTransient<Parameter1>();
services.AddSingleton<Parameter2>();
services.AddScoped<Parameter3>();
services.AddScoped<ScopedBlah>();
return services.BuildServiceProvider();
}
public static object Measure(IServiceProvider serviceProvider)
{
using (var scope = serviceProvider.CreateScope())
return scope.ServiceProvider.GetRequiredService<ScopedBlah>();
}
public static IContainer PrepareAutofac()
{
var builder = new ContainerBuilder();
builder.RegisterType<Parameter1>().AsSelf().InstancePerDependency();
builder.RegisterType<Parameter2>().AsSelf().SingleInstance();
builder.RegisterType<Parameter3>().AsSelf().InstancePerLifetimeScope();
builder.RegisterType<ScopedBlah>().AsSelf().InstancePerLifetimeScope();
return builder.Build();
}
public static object Measure(IContainer container)
{
using (var scope = container.BeginLifetimeScope())
return scope.Resolve<ScopedBlah>();
}
public static DependencyInjectionContainer PrepareGrace()
{
var container = new DependencyInjectionContainer();
container.Configure(c =>
{
c.Export<Parameter1>();
c.Export<Parameter2>().Lifestyle.Singleton();
c.Export<Parameter3>().Lifestyle.SingletonPerScope();
c.Export<ScopedBlah>().Lifestyle.SingletonPerScope();
});
return container;
}
public static object Measure(DependencyInjectionContainer container)
{
using (var scope = container.BeginLifetimeScope())
return scope.Locate<ScopedBlah>();
}
public static LightInject.ServiceContainer PrepareLightInject()
{
var c = new LightInject.ServiceContainer();
c.Register<Parameter1>();
c.Register<Parameter2>(new PerContainerLifetime());
c.Register<Parameter3>(new PerScopeLifetime());
c.Register<ScopedBlah>(new PerScopeLifetime());
return c;
}
public static object Measure(LightInject.ServiceContainer container)
{
using (var scope = container.BeginScope())
return scope.GetInstance<ScopedBlah>();
}
//public static Lamar.Container PrepareLamar()
//{
// return new Lamar.Container(c =>
// {
// c.AddTransient<Parameter1>();
// c.AddSingleton<Parameter2>();
// c.AddScoped<Parameter3>();
// c.AddScoped<ScopedBlah>();
// });
//}
//public static object Measure(Lamar.Container container)
//{
// using (var scope = container.CreateScope())
// return scope.ServiceProvider.GetRequiredService<ScopedBlah>();
//}
public static SimpleInjector.Container PrepareSimpleInjector()
{
var c = new SimpleInjector.Container();
c.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
c.Register<Parameter1>(Lifestyle.Singleton);
c.Register<Parameter2>(Lifestyle.Singleton);
c.Register<Parameter3>(Lifestyle.Scoped);
c.Register<ScopedBlah>(Lifestyle.Scoped);
return c;
}
public static object Measure(SimpleInjector.Container container)
{
using (AsyncScopedLifestyle.BeginScope(container))
return container.GetInstance<ScopedBlah>();
}
public class Parameter1 { }
public class Parameter2 { }
public class Parameter3 { }
public class ScopedBlah
{
public Parameter1 Parameter1 { get; }
public Parameter2 Parameter2 { get; }
public Parameter3 Parameter3 { get; }
public ScopedBlah(
Parameter1 parameter1,
Parameter2 parameter2,
Parameter3 parameter3)
{
Parameter1 = parameter1;
Parameter2 = parameter2;
Parameter3 = parameter3;
}
}
public class R
{
public Single1 Single1 { get; }
public Single2 Single2 { get; }
public Scoped1 Scoped1 { get; }
public Scoped2 Scoped2 { get; }
public Trans1 Trans1 { get; }
public Trans2 Trans2 { get; }
public ScopedFac1 ScopedFac1 { get; }
public ScopedFac2 ScopedFac2 { get; }
public SingleObj1 SingleObj1 { get; }
public SingleObj2 SingleObj2 { get; }
public R(
Single1 single1,
Single2 single2,
Scoped1 scoped1,
Scoped2 scoped2,
Trans1 trans1,
Trans2 trans2,
ScopedFac1 scopedFac1,
ScopedFac2 scopedFac2,
SingleObj1 singleObj1,
SingleObj2 singleObj2
)
{
Single1 = single1;
Single2 = single2;
Scoped1 = scoped1;
Scoped2 = scoped2;
Trans1 = trans1;
Trans2 = trans2;
ScopedFac1 = scopedFac1;
ScopedFac2 = scopedFac2;
SingleObj1 = singleObj1;
SingleObj2 = singleObj2;
}
}
public class Single1
{
}
public class Single2
{
}
public class Scoped1
{
}
public class Scoped2
{
}
public class SingleObj1
{
}
public class SingleObj2
{
}
public class ScopedFac1
{
}
public class ScopedFac2
{
}
public class Trans1
{
}
public class Trans2
{
}
/*
## 28.11.2018
BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17134.407 (1803/April2018Update/Redstone4)
Intel Core i7-8750H CPU 2.20GHz (Coffee Lake), 1 CPU, 12 logical and 6 physical cores
Frequency=2156248 Hz, Resolution=463.7685 ns, Timer=TSC
.NET Core SDK=2.1.500
[Host] : .NET Core 2.1.6 (CoreCLR 4.6.27019.06, CoreFX 4.6.27019.05), 64bit RyuJIT
DefaultJob : .NET Core 2.1.6 (CoreCLR 4.6.27019.06, CoreFX 4.6.27019.05), 64bit RyuJIT
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
----------------------------------- |-----------:|----------:|-----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkAutofac | 1,970.3 ns | 11.519 ns | 10.7747 ns | 7.17 | 0.06 | 0.6676 | - | - | 3152 B |
BmarkDryIoc | 207.0 ns | 1.062 ns | 0.9931 ns | 0.75 | 0.01 | 0.0966 | - | - | 456 B |
BmarkMicrosoftSDependencyInjection | 274.9 ns | 2.064 ns | 1.9308 ns | 1.00 | 0.00 | 0.0758 | - | - | 360 B |
BmarkGrace | 264.8 ns | 1.653 ns | 1.5462 ns | 0.96 | 0.01 | 0.1216 | - | - | 576 B |
BmarkLightInject | 998.6 ns | 4.589 ns | 4.0676 ns | 3.64 | 0.02 | 0.2422 | - | - | 1144 B |
# 25.01.2019
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
----------------------------------- |-----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkDryIoc | 172.6 ns | 1.664 ns | 1.556 ns | 0.61 | 0.01 | 0.0896 | - | - | 424 B |
BmarkGrace | 301.3 ns | 4.890 ns | 4.574 ns | 1.06 | 0.02 | 0.1216 | - | - | 576 B |
BmarkMicrosoftSDependencyInjection | 285.0 ns | 1.564 ns | 1.463 ns | 1.00 | 0.00 | 0.0758 | - | - | 360 B |
BmarkLightInject | 1,079.8 ns | 14.331 ns | 13.406 ns | 3.79 | 0.05 | 0.2422 | - | - | 1144 B |
BmarkAutofac | 2,017.9 ns | 9.589 ns | 8.501 ns | 7.08 | 0.05 | 0.6676 | - | - | 3152 B |
# 06.08.2019
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated |
----------------------------------- |-----------:|----------:|----------:|------:|--------:|-------:|------:|------:|----------:|
BmarkDryIoc | 247.9 ns | 1.768 ns | 1.654 ns | 0.79 | 0.01 | 0.1135 | - | - | 536 B |
BmarkGrace | 234.3 ns | 1.369 ns | 1.280 ns | 0.75 | 0.00 | 0.0575 | - | - | 272 B |
BmarkMicrosoftSDependencyInjection | 313.2 ns | 1.092 ns | 1.022 ns | 1.00 | 0.00 | 0.0811 | - | - | 384 B |
BmarkLightInject | 1,025.1 ns | 19.367 ns | 23.055 ns | 3.26 | 0.08 | 0.2403 | - | - | 1136 B |
BmarkAutofac | 2,640.2 ns | 30.274 ns | 25.280 ns | 8.43 | 0.08 | 0.8965 | - | - | 4232 B |
*/
[MemoryDiagnoser]
public class FirstTimeOpenScopeResolve
{
private readonly IContainer _autofac = PrepareAutofac();
private readonly DryIoc.IContainer _dryioc = PrepareDryIoc();
private readonly IServiceProvider _msDi = PrepareMsDi();
private readonly DependencyInjectionContainer _grace = PrepareGrace();
private readonly ServiceContainer _lightInject = PrepareLightInject();
//private readonly Lamar.Container _lamar = PrepareLamar();
private readonly SimpleInjector.Container _simpleInjector = PrepareSimpleInjector();
[Benchmark]
public object BmarkAutofac() => Measure(_autofac);
[Benchmark]
public object BmarkDryIoc() => Measure(_dryioc);
[Benchmark(Baseline = true)]
public object BmarkMicrosoftSDependencyInjection() => Measure(_msDi);
[Benchmark]
public object BmarkGrace() => Measure(_grace);
[Benchmark]
public object BmarkLightInject() => Measure(_lightInject);
//[Benchmark]
//public object BmarkLamar() => Measure(_lamar);
//[Benchmark]
public object BmarkSimpleInjector() => Measure(_simpleInjector);
}
/*
## 28.11.2018: Starting point - no scoped dependency interpretation for DryIoc yet
BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17134.407 (1803/April2018Update/Redstone4)
Intel Core i7-8750H CPU 2.20GHz (Coffee Lake), 1 CPU, 12 logical and 6 physical cores
Frequency=2156248 Hz, Resolution=463.7685 ns, Timer=TSC
.NET Core SDK=2.1.500
[Host] : .NET Core 2.1.6 (CoreCLR 4.6.27019.06, CoreFX 4.6.27019.05), 64bit RyuJIT
DefaultJob : .NET Core 2.1.6 (CoreCLR 4.6.27019.06, CoreFX 4.6.27019.05), 64bit RyuJIT
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
----------------------------------- |-----------:|----------:|----------:|-------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkAutofac | 35.672 us | 0.3983 us | 0.3326 us | 7.32 | 0.08 | 6.4697 | - | - | 29.83 KB |
BmarkDryIoc | 529.302 us | 2.3636 us | 2.0953 us | 108.60 | 0.69 | 1.9531 | 0.9766 | - | 12.61 KB |
BmarkMicrosoftSDependencyInjection | 4.873 us | 0.0267 us | 0.0250 us | 1.00 | 0.00 | 1.0529 | - | - | 4.87 KB |
BmarkGrace | 783.044 us | 3.8283 us | 3.5810 us | 160.68 | 1.18 | 8.7891 | 3.9063 | - | 42.44 KB |
BmarkLightInject | 666.277 us | 6.2531 us | 5.8492 us | 136.72 | 1.38 | 8.7891 | 3.9063 | - | 43.12 KB |
## 30.11.2018: First DryIoc version with interpreted scoped dependency
Method | Mean | Error | StdDev | Median | P95 | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |-----------:|-----------:|------------:|-----------:|-------------:|-------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.797 us | 0.1125 us | 0.2904 us | 4.724 us | 5.754 us | 1.00 | 0.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 5.547 us | 0.0401 us | 0.0313 us | 5.535 us | 5.594 us | 1.17 | 0.01 | 1.6251 | - | - | 7.49 KB |
BmarkAutofac | 36.195 us | 0.1435 us | 0.1198 us | 36.232 us | 36.332 us | 7.64 | 0.03 | 6.4697 | - | - | 29.83 KB |
BmarkGrace | 776.478 us | 5.3626 us | 4.4780 us | 774.993 us | 783.422 us | 163.89 | 1.13 | 8.7891 | 3.9063 | - | 42.44 KB |
BmarkLightInject | 799.472 us | 79.1998 us | 231.0294 us | 658.761 us | 1,299.696 us | 169.62 | 51.94 | 8.7891 | 3.9063 | - | 43.12 KB |
## 09.12.2018: Shaved some bites from registration phase
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.689 us | 0.0256 us | 0.0239 us | 1.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 5.519 us | 0.0571 us | 0.0534 us | 1.18 | 1.5488 | - | - | 7.17 KB |
NO DIFFERENCE FROM Asp.NET / Core 2.2
## 11.12.2018: Shaved almost a 1kb by optimizing Request allocations
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.876 us | 0.0346 us | 0.0307 us | 1.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 5.524 us | 0.0505 us | 0.0447 us | 1.13 | 1.3733 | - | - | 6.33 KB |
## 13.12.2018: Never know where you can win until you measure!
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkDryIoc | 4.920 us | 0.0229 us | 0.0191 us | 0.99 | 0.06 | 1.1444 | - | - | 5.3 KB |
BmarkMicrosoftDependencyInjection | 4.982 us | 0.3916 us | 0.3472 us | 1.00 | 0.00 | 1.0529 | - | - | 4.87 KB |
## 16.12.2018: Removing more closure - now in `Scope.GetOrAdd` method family
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.728 us | 0.0065 us | 0.0058 us | 1.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 4.928 us | 0.0246 us | 0.0230 us | 1.04 | 1.0834 | - | - | 5 KB |
## 16.12.2018: Removing internal Data class from ImHashMap
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.742 us | 0.0101 us | 0.0095 us | 1.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 4.786 us | 0.0340 us | 0.0318 us | 1.01 | 1.0605 | - | - | 4.91 KB |
## 25.12.2018: Split conflicts from ImHashMap - Win in memory over MS.DI
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |-----------:|----------:|----------:|-------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.697 us | 0.0162 us | 0.0151 us | 1.00 | 0.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 4.901 us | 0.0264 us | 0.0234 us | 1.04 | 0.01 | 1.0452 | - | - | 4.84 KB |
BmarkAutofac | 35.076 us | 0.4491 us | 0.3981 us | 7.47 | 0.08 | 6.4697 | - | - | 29.83 KB |
BmarkLightInject | 649.004 us | 5.4030 us | 5.0539 us | 138.18 | 1.04 | 8.7891 | 3.9063 | - | 43.12 KB |
BmarkGrace | 768.939 us | 3.1469 us | 2.9437 us | 163.71 | 0.66 | 8.7891 | 3.9063 | - | 42.44 KB |
## 25.12.2018: Split Branch from Node from ImHashMap
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.640 us | 0.0168 us | 0.0140 us | 1.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 4.872 us | 0.0303 us | 0.0283 us | 1.05 | 1.0300 | - | - | 4.76 KB |
## 01.01.2018: Optimized Lookup speed in ImMap
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.599 us | 0.0165 us | 0.0147 us | 1.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 4.773 us | 0.0284 us | 0.0252 us | 1.04 | 1.0300 | - | - | 4.76 KB |
## 11.01.2019: Optimized ImHashMap without virtual methods
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkDryIoc | 4.679 us | 0.0465 us | 0.0435 us | 0.99 | 1.0300 | - | - | 4.76 KB |
BmarkMicrosoftDependencyInjection | 4.736 us | 0.0236 us | 0.0221 us | 1.00 | 1.0529 | - | - | 4.87 KB |
## 25.01.2019: _data is back
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.677 us | 0.0275 us | 0.0257 us | 1.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 4.863 us | 0.0370 us | 0.0328 us | 1.04 | 1.0834 | - | - | 5 KB |
## 28.01.2019: After improvements in ImMap
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkDryIoc | 4.703 us | 0.0225 us | 0.0188 us | 0.99 | 1.0681 | - | - | 4.95 KB |
BmarkMicrosoftDependencyInjection | 4.750 us | 0.0082 us | 0.0076 us | 1.00 | 1.0529 | - | - | 4.87 KB |
## Final cut
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 4.671 us | 0.0223 us | 0.0208 us | 1.00 | 1.0529 | - | - | 4.87 KB |
BmarkDryIoc | 5.147 us | 0.0237 us | 0.0198 us | 1.10 | 1.0986 | - | - | 5.08 KB |
*/
[MemoryDiagnoser, Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class CreateContainerAndRegister_FirstTimeOpenScopeResolve
{
//[Benchmark]
public object BmarkAutofac() => Measure(PrepareAutofac());
[Benchmark]
public object BmarkDryIoc() => Measure(PrepareDryIoc());
[Benchmark(Baseline = true)]
public object BmarkMicrosoftDependencyInjection() => Measure(PrepareMsDi());
//[Benchmark]
public object BmarkGrace() => Measure(PrepareGrace());
//[Benchmark]
public object BmarkLightInject() => Measure(PrepareLightInject());
//[Benchmark]
//public object BmarkLamar() => Measure(PrepareLamar());
//[Benchmark]
public object BmarkSimpleInjector() => Measure(PrepareSimpleInjector());
}
/*
## Initial:
Method | Mean | Error | StdDev | Median | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |----------:|----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 1.071 us | 0.0224 us | 0.0306 us | 1.065 us | 1.00 | 0.00 | 0.5436 | - | - | 2.51 KB |
BmarkDryIoc | 1.228 us | 0.0260 us | 0.0587 us | 1.209 us | 1.16 | 0.08 | 0.4864 | - | - | 2.25 KB |
BmarkGrace | 8.158 us | 0.9760 us | 2.8776 us | 8.028 us | 8.30 | 2.68 | 1.4801 | - | - | 6.84 KB |
BmarkLightInject | 8.511 us | 1.0015 us | 2.9529 us | 7.533 us | 6.18 | 1.49 | 3.8376 | 0.0076 | - | 17.7 KB |
BmarkAutofac | 32.694 us | 3.3321 us | 9.7725 us | 30.384 us | 33.91 | 10.09 | 4.5471 | 0.0305 | - | 20.96 KB |
## After converting lambdas to local functions in Register:
Method | Mean | Error | StdDev | Median | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|---------:|------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 1.078 us | 0.0039 us | 0.0030 us | 1.078 us | 1.00 | 0.00 | 0.5436 | - | - | 2.51 KB |
BmarkDryIoc | 1.373 us | 0.0670 us | 0.1812 us | 1.284 us | 1.22 | 0.20 | 0.4807 | - | - | 2.22 KB |
## After removing lambdas altogether in Register:
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 1.054 us | 0.0069 us | 0.0061 us | 1.00 | 0.5436 | - | - | 2.51 KB |
BmarkDryIoc | 1.190 us | 0.0082 us | 0.0077 us | 1.13 | 0.4253 | - | - | 1.97 KB |
## After stripping conflicts from ImHashMap:
Method | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |---------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 1.070 us | 0.0052 us | 0.0048 us | 1.00 | 0.5436 | - | - | 2.51 KB |
BmarkDryIoc | 1.188 us | 0.0086 us | 0.0080 us | 1.11 | 0.3986 | - | - | 1.84 KB |
## After back to initial ImHashMap structure but with optimized AddOrUpdate / balancing:
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 1.068 us | 0.0019 us | 0.0016 us | 1.00 | 0.00 | 0.5436 | - | - | 2.51 KB |
BmarkDryIoc | 1.155 us | 0.0032 us | 0.0030 us | 1.08 | 0.00 | 0.4253 | - | - | 1.97 KB |
BmarkGrace | 5.079 us | 0.0383 us | 0.0358 us | 4.76 | 0.03 | 1.4725 | - | - | 6.82 KB |
BmarkLightInject | 5.812 us | 0.0208 us | 0.0195 us | 5.44 | 0.02 | 3.8376 | 0.0076 | - | 17.7 KB |
BmarkAutofac | 23.668 us | 0.1853 us | 0.1642 us | 22.16 | 0.15 | 4.5471 | 0.0305 | - | 20.96 KB |
## After improvements in ImMap
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
---------------------------------- |----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkMicrosoftDependencyInjection | 1.038 us | 0.0048 us | 0.0043 us | 1.00 | 0.00 | 0.5436 | - | - | 2.51 KB |
BmarkDryIoc | 1.113 us | 0.0062 us | 0.0055 us | 1.07 | 0.00 | 0.4253 | - | - | 1.97 KB |
BmarkGrace | 5.140 us | 0.0247 us | 0.0231 us | 4.95 | 0.03 | 1.4725 | - | - | 6.82 KB |
BmarkLightInject | 5.821 us | 0.0285 us | 0.0253 us | 5.61 | 0.04 | 3.8376 | 0.0076 | - | 17.7 KB |
BmarkAutofac | 23.733 us | 0.5465 us | 0.6506 us | 22.85 | 0.60 | 4.5166 | 0.0610 | - | 20.96 KB |
*/
[MemoryDiagnoser, Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class CreateContainerAndRegister
{
[Benchmark]
public object BmarkAutofac() => PrepareAutofac();
[Benchmark]
public object BmarkDryIoc() => PrepareDryIoc();
[Benchmark(Baseline = true)]
public object BmarkMicrosoftDependencyInjection() => PrepareMsDi();
[Benchmark]
public object BmarkGrace() => PrepareGrace();
[Benchmark]
public object BmarkLightInject() => PrepareLightInject();
//[Benchmark]
//public object BmarkLamar() => Measure(PrepareLamar());
//[Benchmark]
public object BmarkSimpleInjector() => Measure(PrepareSimpleInjector());
}
[MemoryDiagnoser, Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class SecondOpenScopeResolve
{
/*
## 25.01.2019
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
----------------------------------- |-----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
BmarkDryIoc | 176.6 ns | 0.5879 ns | 0.5499 ns | 0.63 | 0.00 | 0.0896 | - | - | 424 B |
BmarkGrace | 266.3 ns | 0.8584 ns | 0.8029 ns | 0.96 | 0.00 | 0.1216 | - | - | 576 B |
BmarkMicrosoftSDependencyInjection | 278.1 ns | 1.2454 ns | 1.1041 ns | 1.00 | 0.00 | 0.0758 | - | - | 360 B |
BmarkLightInject | 1,009.5 ns | 4.3021 ns | 4.0242 ns | 3.63 | 0.02 | 0.2422 | - | - | 1144 B |
BmarkAutofac | 2,014.8 ns | 6.9735 ns | 5.8232 ns | 7.24 | 0.03 | 0.6676 | - | - | 3152 B |
*/
private static readonly IContainer _autofac = PrepareAutofac();
private static readonly DryIoc.IContainer _dryioc = PrepareDryIoc();
private static readonly IServiceProvider _msDi = PrepareMsDi();
private static readonly DependencyInjectionContainer _grace = PrepareGrace();
private static readonly ServiceContainer _lightInject = PrepareLightInject();
//private static readonly Lamar.Container _lamar = PrepareLamar();
private static readonly SimpleInjector.Container _simpleInjector = PrepareSimpleInjector();
[GlobalSetup]
public void WarmUp()
{
for (var i = 0; i < 5; i++)
{
Measure(_autofac);
Measure(_dryioc);
Measure(_msDi);
Measure(_grace);
Measure(_lightInject);
//Measure(_lamar);
}
}
[Benchmark]
public object BmarkAutofac() => Measure(_autofac);
[Benchmark]
public object BmarkDryIoc() => Measure(_dryioc);
[Benchmark(Baseline = true)]
public object BmarkMicrosoftSDependencyInjection() => Measure(_msDi);
[Benchmark]
public object BmarkGrace() => Measure(_grace);
[Benchmark]
public object BmarkLightInject() => Measure(_lightInject);
//[Benchmark]
//public object BmarkLamar() => Measure(_lamar);
//[Benchmark]
public object BmarkSimpleInjector() => Measure(_simpleInjector);
}
[MemoryDiagnoser, Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class ThirdOpenScopeResolve
{
/*
## 31.01.2019
*/
private static readonly IContainer _autofac = PrepareAutofac();
private static readonly DryIoc.IContainer _dryioc = PrepareDryIoc();
private static readonly IServiceProvider _msDi = PrepareMsDi();
private static readonly DependencyInjectionContainer _grace = PrepareGrace();
private static readonly ServiceContainer _lightInject = PrepareLightInject();
//private static readonly Lamar.Container _lamar = PrepareLamar();
private static readonly SimpleInjector.Container _simpleInjector = PrepareSimpleInjector();
[GlobalSetup]
public void WarmUp()
{
for (var i = 0; i < 5; i++)
{
Measure(_autofac);
Measure(_autofac);
Measure(_dryioc);
Measure(_dryioc);
Measure(_msDi);
Measure(_msDi);
Measure(_grace);
Measure(_grace);
Measure(_lightInject);
Measure(_lightInject);
}
}
[Benchmark]
public object BmarkAutofac() => Measure(_autofac);
[Benchmark]
public object BmarkDryIoc() => Measure(_dryioc);
[Benchmark(Baseline = true)]
public object BmarkMicrosoftSDependencyInjection() => Measure(_msDi);
[Benchmark]
public object BmarkGrace() => Measure(_grace);
[Benchmark]
public object BmarkLightInject() => Measure(_lightInject);
//[Benchmark]
//public object BmarkLamar() => Measure(_lamar);
//[Benchmark]
public object BmarkSimpleInjector() => Measure(_simpleInjector);
}
}
}
| 53.792793 | 187 | 0.435354 | [
"MIT"
] | jeuxjeux20/DryIoc | playground/Playground/OpenScopeAndResolveScopedWithSingletonTransientScopedDeps.cs | 35,826 | C# |
/*----------------------------------------------------------------
Copyright (C) 2017 Senparc
文件名:ButtonGroup.cs
文件功能描述:整个按钮设置(可以直接用ButtonGroup实例返回JSON对象)
创建标识:Senparc - 20150313
修改标识:Senparc - 20150313
修改描述:整理接口
----------------------------------------------------------------*/
using System.Collections.Generic;
namespace Senparc.Weixin.Work.Entities.Menu
{
/// <summary>
/// 整个按钮设置(可以直接用ButtonGroup实例返回JSON对象)
/// </summary>
public class ButtonGroup
{
/// <summary>
/// 按钮数组,按钮个数应为2~3个
/// </summary>
public List<BaseButton> button { get; set; }
public ButtonGroup()
{
button = new List<BaseButton>();
}
}
}
| 22.088235 | 67 | 0.472703 | [
"Apache-2.0"
] | 65717212/WeiXinMPSDK | src/Senparc.Weixin.Work/Senparc.Weixin.Work/Entities/Menu/ButtonGroup.cs | 913 | C# |
using FluentAssertions;
using PivotalServices.WebApiTemplate.CSharp.Features.Values;
using Xunit;
namespace PivotalServices.WebApiTemplate.CSharp.UnitTests.Features.Values
{
public partial class PostValuesValidator
{
public class Given_a_PostValues_Request
{
private readonly PostValues.Validator validator;
private PostValues.Request request;
public Given_a_PostValues_Request()
{
validator = new PostValues.Validator();
request = new PostValues.Request
{
Param1 = "123",
Param2 = "1234"
};
}
[Theory]
[InlineData("1234as", false)]
[InlineData("123456789asas", false)]
[InlineData("123456AA", false)]
[InlineData("", false)]
[InlineData("123", true)]
public void Should_validate_Param1(string value, bool isValid)
{
request.Param1 = value;
validator.Validate(request).IsValid.Should().Be(isValid);
}
[Theory]
[InlineData(null, false)]
[InlineData("", false)]
[InlineData("1234", true)]
public void Should_validate_Param2(string value, bool isValid)
{
request.Param2 = value;
validator.Validate(request).IsValid.Should().Be(isValid);
}
}
}
}
| 30.1 | 74 | 0.540199 | [
"MIT"
] | CedricYao/pivotal-webapi-template-csharp | PivotalServices.WebApiTemplate.CSharp/src/PivotalServices.WebApiTemplate.CSharp.UnitTests/Features/Values/Given_a_PostValues_Request.cs | 1,507 | C# |
#region MIT license
//
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
//
// 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
using System;
using System.Data;
using System.Data.Common;
namespace DbLinq.Util
{
#if !MONO_STRICT
public
#endif
static class DbDataReaderExtensions
{
// please note that sometimes (depending on driver), GetValue() returns DBNull instead of null
// so at this level, we handle both
public static string GetAsString(this DbDataReader dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
object o = dataRecord.GetValue(index);
if (o == null) // this is not supposed to happen
return null;
return o.ToString();
}
public static bool GetAsBool(this DbDataReader dataRecord, int index)
{
object b = dataRecord.GetValue(index);
return TypeConvert.ToBoolean(b);
}
public static bool? GetAsNullableBool(this DbDataReader dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
return GetAsBool(dataRecord, index);
}
public static char GetAsChar(this DbDataReader dataRecord, int index)
{
object c = dataRecord.GetValue(index);
return TypeConvert.ToChar(c);
}
public static char? GetAsNullableChar(this DbDataReader dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
return GetAsChar(dataRecord, index);
}
public static U GetAsNumeric<U>(this DbDataReader dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return default(U);
return GetAsNumeric<U>(dataRecord.GetValue(index));
}
public static U? GetAsNullableNumeric<U>(this DbDataReader dataRecord, int index)
where U : struct
{
if (dataRecord.IsDBNull(index))
return null;
// Workaround for .NET ticks stored with SQLite type 'DATETIME'
if (typeof(U) == typeof(long)) return GetAsNumeric<U>(dataRecord.GetInt64(index));
return GetAsNumeric<U>(dataRecord.GetValue(index));
}
private static U GetAsNumeric<U>(object o)
{
if (o == null || o is DBNull)
return default(U);
return TypeConvert.ToNumber<U>(o);
}
public static int GetAsEnum(this DbDataReader dataRecord, Type enumType, int index)
{
int enumAsInt = dataRecord.GetAsNumeric<int>(index);
return enumAsInt;
}
public static byte[] GetAsBytes(this DbDataReader dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return EmptyArray<byte>.Instance;
object obj = dataRecord.GetValue(index);
if (obj == null)
return EmptyArray<byte>.Instance; //nullable blob?
byte[] bytes = obj as byte[];
if (bytes != null)
return bytes; //works for BLOB field
Console.WriteLine("GetBytes: received unexpected type:" + obj);
//return _rdr.GetInt32(index);
return EmptyArray<byte>.Instance;
}
public static System.Data.Linq.Binary GetAsBinary(this DbDataReader dataRecord, int index)
{
byte[] bytes = GetAsBytes(dataRecord, index);
if (bytes.Length == 0)
return null;
return new System.Data.Linq.Binary(bytes);
}
public static object GetAsObject(this DbDataReader dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
object obj = dataRecord.GetValue(index);
return obj;
}
public static DateTime GetAsDateTime(this DbDataReader dataRecord, int index)
{
// Convert an InvalidCastException (thrown for example by Npgsql when an
// operation like "SELECT '2012-'::timestamp - NULL" that is perfectly
// legal on PostgreSQL returns a null instead of a DateTime) into the
// correct InvalidOperationException.
if (dataRecord.IsDBNull(index))
throw new InvalidOperationException("NULL found where DateTime expected");
return dataRecord.GetDateTime(index);
}
public static DateTime? GetAsNullableDateTime(this DbDataReader dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
return GetAsDateTime(dataRecord, index);
}
public static Guid GetAsGuid(this DbDataReader dataRecord, int index)
{
return dataRecord.GetGuid(index);
}
public static Guid? GetAsNullableGuid(this DbDataReader dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
return GetAsGuid(dataRecord, index);
}
public static DbDataReader Configure(this DbDataReader reader)
{
if (Data.Linq.DataContext.ConfigureDataReader != null)
Data.Linq.DataContext.ConfigureDataReader(reader);
return reader;
}
}
}
| 37.868571 | 103 | 0.601931 | [
"Apache-2.0"
] | antiufo/mono | mcs/class/System.Data.Linq/src/DbLinq/Util/IDataRecordExtensions.cs | 6,627 | C# |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEditor.U2D.Animation
{
internal interface IBoneSelection : ITransformSelection<BoneCache> {}
}
| 21.545455 | 74 | 0.776371 | [
"MIT"
] | AlePPisa/GameJamPractice1 | Cellular/Library/PackageCache/com.unity.2d.animation@4.2.4/Editor/SkinningModule/Selection/IBoneSelection.cs | 237 | C# |
using Regi.Abstractions;
using Regi.Frameworks.Identifiers;
using System.Threading.Tasks;
using Xunit;
namespace Regi.Test.Identifiers
{
public class NodeIdentifierTests : BaseIdentifierTests
{
protected override IIdentifier CreateTestClass()
{
return new NodeIdentifier(FileSystemMock.Object);
}
protected override void ShouldHaveMatched(IProject expectedProject, bool wasMatch)
{
if (expectedProject.Framework == ProjectFramework.Node)
{
Assert.True(wasMatch);
}
else
{
Assert.False(wasMatch);
}
}
[Theory]
[MemberData(nameof(NodeProjects))]
public async Task Identify_node_project(string name, IProject expectedProject)
{
var actualProject = await Identify_base_project(name, expectedProject);
Assert.Equal(ProjectFramework.Node, actualProject.Framework);
// TODO: test for type
}
}
}
| 26.820513 | 90 | 0.612811 | [
"MIT"
] | tom-mckinney/regi | test/Regi.Test/Frameworks/Identifiers/NodeIdentifierTests.cs | 1,048 | C# |
using Sdl.Core.PluginFramework;
[assembly: Plugin("Plugin_Name")]
| 12.333333 | 34 | 0.702703 | [
"MIT"
] | Impertatore/trados-studio-api-samples | TranslationStudioAutomation/Sdl.StudioAutomation.ReferencePlugin/Properties/PluginProperties.cs | 74 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace MySynchFiles.Data {
public class BindableBase : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected virtual bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null) {
return SetProperty(ref field, value, null, propertyName);
}
protected virtual bool SetProperty<T>(ref T field, T value, Action onChanged, [CallerMemberName]string propertyName = null) {
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| 35.354839 | 133 | 0.69708 | [
"MIT"
] | OSN-DEV/SynchFiles | src/Data/BindableBase.cs | 1,098 | C# |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Linq;
using EventStore.Core.Index;
using NUnit.Framework;
namespace EventStore.Core.Tests.Index
{
[TestFixture]
public class create_index_map_from_non_existing_file
{
private IndexMap _map;
[SetUp]
public void Setup()
{
_map = IndexMap.FromFile("shitbird");
}
[Test]
public void the_map_is_empty()
{
Assert.AreEqual(0, _map.InOrder().Count());
}
[Test]
public void no_file_names_are_used()
{
Assert.AreEqual(0, _map.GetAllFilenames().Count());
}
[Test]
public void prepare_checkpoint_is_equal_to_minus_one()
{
Assert.AreEqual(-1, _map.PrepareCheckpoint);
}
[Test]
public void commit_checkpoint_is_equal_to_minus_one()
{
Assert.AreEqual(-1, _map.PrepareCheckpoint);
}
}
} | 35.542857 | 73 | 0.700563 | [
"BSD-3-Clause"
] | ianbattersby/EventStore | src/EventStore/EventStore.Core.Tests/Index/create_index_map_from_non_existing_file.cs | 2,488 | C# |
#if !NOT_UNITY3D
using System;
using ModestTree;
using UnityEngine;
namespace Zenject
{
// We'd prefer to make this abstract but Unity 5.3.5 has a bug where references
// can get lost during compile errors for classes that are abstract
public class ScriptableObjectInstaller : ScriptableObjectInstallerBase
{
}
//
// Derive from this class instead to install like this:
// FooInstaller.InstallFromResource(Container);
// Or
// FooInstaller.InstallFromResource("My/Path/ToScriptableObjectInstance", Container);
//
// (Instead of needing to add the ScriptableObjectInstaller directly via inspector)
//
// This approach is needed if you want to pass in strongly typed runtime parameters too it
//
public class ScriptableObjectInstaller<TDerived> : ScriptableObjectInstaller
where TDerived : ScriptableObjectInstaller<TDerived>
{
public static TDerived InstallFromResource(DiContainer container)
{
return InstallFromResource(
ScriptableObjectInstallerUtil.GetDefaultResourcePath<TDerived>(), container);
}
public static TDerived InstallFromResource(string resourcePath, DiContainer container)
{
var installer = ScriptableObjectInstallerUtil.CreateInstaller<TDerived>(resourcePath, container);
container.Inject(installer);
installer.InstallBindings();
return installer;
}
}
public class ScriptableObjectInstaller<TParam1, TDerived> : ScriptableObjectInstallerBase
where TDerived : ScriptableObjectInstaller<TParam1, TDerived>
{
public static TDerived InstallFromResource(DiContainer container, TParam1 p1)
{
return InstallFromResource(
ScriptableObjectInstallerUtil.GetDefaultResourcePath<TDerived>(), container, p1);
}
public static TDerived InstallFromResource(string resourcePath, DiContainer container, TParam1 p1)
{
var installer = ScriptableObjectInstallerUtil.CreateInstaller<TDerived>(resourcePath, container);
container.InjectExplicit(installer, InjectUtil.CreateArgListExplicit(p1));
installer.InstallBindings();
return installer;
}
}
public class ScriptableObjectInstaller<TParam1, TParam2, TDerived> : ScriptableObjectInstallerBase
where TDerived : ScriptableObjectInstaller<TParam1, TParam2, TDerived>
{
public static TDerived InstallFromResource(DiContainer container, TParam1 p1, TParam2 p2)
{
return InstallFromResource(
ScriptableObjectInstallerUtil.GetDefaultResourcePath<TDerived>(), container, p1, p2);
}
public static TDerived InstallFromResource(string resourcePath, DiContainer container, TParam1 p1, TParam2 p2)
{
var installer = ScriptableObjectInstallerUtil.CreateInstaller<TDerived>(resourcePath, container);
container.InjectExplicit(installer, InjectUtil.CreateArgListExplicit(p1, p2));
installer.InstallBindings();
return installer;
}
}
public class ScriptableObjectInstaller<TParam1, TParam2, TParam3, TDerived> : ScriptableObjectInstallerBase
where TDerived : ScriptableObjectInstaller<TParam1, TParam2, TParam3, TDerived>
{
public static TDerived InstallFromResource(DiContainer container, TParam1 p1, TParam2 p2, TParam3 p3)
{
return InstallFromResource(
ScriptableObjectInstallerUtil.GetDefaultResourcePath<TDerived>(), container, p1, p2, p3);
}
public static TDerived InstallFromResource(string resourcePath, DiContainer container, TParam1 p1, TParam2 p2, TParam3 p3)
{
var installer = ScriptableObjectInstallerUtil.CreateInstaller<TDerived>(resourcePath, container);
container.InjectExplicit(installer, InjectUtil.CreateArgListExplicit(p1, p2, p3));
installer.InstallBindings();
return installer;
}
}
public class ScriptableObjectInstaller<TParam1, TParam2, TParam3, TParam4, TDerived> : ScriptableObjectInstallerBase
where TDerived : ScriptableObjectInstaller<TParam1, TParam2, TParam3, TParam4, TDerived>
{
public static TDerived InstallFromResource(DiContainer container, TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4)
{
return InstallFromResource(
ScriptableObjectInstallerUtil.GetDefaultResourcePath<TDerived>(), container, p1, p2, p3, p4);
}
public static TDerived InstallFromResource(string resourcePath, DiContainer container, TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4)
{
var installer = ScriptableObjectInstallerUtil.CreateInstaller<TDerived>(resourcePath, container);
container.InjectExplicit(installer, InjectUtil.CreateArgListExplicit(p1, p2, p3, p4));
installer.InstallBindings();
return installer;
}
}
public static class ScriptableObjectInstallerUtil
{
public static string GetDefaultResourcePath<TInstaller>()
where TInstaller : ScriptableObjectInstallerBase
{
return "Installers/" + typeof(TInstaller).PrettyName();
}
public static TInstaller CreateInstaller<TInstaller>(
string resourcePath, DiContainer container)
where TInstaller : ScriptableObjectInstallerBase
{
var installers = Resources.LoadAll(resourcePath);
Assert.That(installers.Length == 1,
"Could not find unique ScriptableObjectInstaller with type '{0}' at resource path '{1}'", typeof(TInstaller), resourcePath);
var installer = installers[0];
Assert.That(installer is TInstaller,
"Expected to find installer with type '{0}' at resource path '{1}'", typeof(TInstaller), resourcePath);
return (TInstaller)installer;
}
}
}
#endif
| 43.328671 | 143 | 0.673499 | [
"MIT"
] | Mateo-Panadero/Ultimate-Hero | Assets/Plugins/Zenject/Source/Install/ScriptableObjectInstaller.cs | 6,196 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace test.Data.Migrations
{
public partial class initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 18.166667 | 71 | 0.66055 | [
"MIT"
] | TrevorTheAmazing/Capstone | test/Data/Migrations/20191128155856_initial.cs | 329 | C# |
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace AutoMapper.EquivalencyExpression
{
internal class GenerateEquivalentExpressionFromTypeMap
{
private static readonly ConcurrentDictionary<TypeMap, GenerateEquivalentExpressionFromTypeMap> _EquivalentExpressionses = new ConcurrentDictionary<TypeMap, GenerateEquivalentExpressionFromTypeMap>();
internal static Expression GetExpression(TypeMap typeMap, object value)
{
return _EquivalentExpressionses.GetOrAdd(typeMap, t => new GenerateEquivalentExpressionFromTypeMap(t))
.CreateEquivalentExpression(value);
}
private readonly TypeMap _typeMap;
private GenerateEquivalentExpressionFromTypeMap(TypeMap typeMap)
{
_typeMap = typeMap;
}
private Expression CreateEquivalentExpression(object value)
{
var express = value as LambdaExpression;
var destExpr = Expression.Parameter(_typeMap.SourceType, express.Parameters[0].Name);
var result = new CustomExpressionVisitor(destExpr, _typeMap.GetPropertyMaps()).Visit(express.Body);
return Expression.Lambda(result, destExpr);
}
}
} | 38.636364 | 207 | 0.722353 | [
"MIT"
] | nphmuller/AutoMapper.Collection | src/AutoMapper.Collection/EquivalencyExpression/GenerateEquivilentExpressionFromTypeMap.cs | 1,275 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Project_2_Common
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| 23.307692 | 61 | 0.665017 | [
"MIT"
] | michailkaz/local-ea | Project 2 Common/Program.cs | 608 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace Unity.Entities.Editor
{
internal delegate void SetFilterAction(EntityListQuery entityQuery);
internal class ComponentTypeFilterUI
{
private readonly WorldSelectionGetter getWorldSelection;
private readonly SetFilterAction setFilter;
private readonly List<bool> selectedFilterTypes = new List<bool>();
private readonly List<ComponentType> filterTypes = new List<ComponentType>();
private readonly List<ComponentGroup> entityQueries = new List<ComponentGroup>();
public ComponentTypeFilterUI(SetFilterAction setFilter, WorldSelectionGetter worldSelectionGetter)
{
getWorldSelection = worldSelectionGetter;
this.setFilter = setFilter;
}
internal bool TypeListValid()
{
return selectedFilterTypes.Count == 2 * (TypeManager.GetTypeCount() - 2); // First two entries are not ComponentTypes
}
internal void GetTypes()
{
if (getWorldSelection() == null) return;
if (!TypeListValid())
{
filterTypes.Clear();
selectedFilterTypes.Clear();
var requiredTypes = new List<ComponentType>();
var subtractiveTypes = new List<ComponentType>();
var typeCount = TypeManager.GetTypeCount();
filterTypes.Capacity = typeCount;
selectedFilterTypes.Capacity = typeCount;
foreach (var type in TypeManager.AllTypes)
{
if (type.Type == typeof(Entity)) continue;
var typeIndex = TypeManager.GetTypeIndex(type.Type);
var componentType = ComponentType.FromTypeIndex(typeIndex);
if (componentType.GetManagedType() == null) continue;
requiredTypes.Add(componentType);
componentType.AccessModeType = ComponentType.AccessMode.Subtractive;
subtractiveTypes.Add(componentType);
selectedFilterTypes.Add(false);
selectedFilterTypes.Add(false);
}
filterTypes.AddRange(requiredTypes);
filterTypes.AddRange(subtractiveTypes);
filterTypes.Sort(ComponentGroupGUI.CompareTypes);
}
}
public void OnGUI()
{
GUILayout.Label("Filter: ");
var filterCount = 0;
for (var i = 0; i < selectedFilterTypes.Count; ++i)
{
if (selectedFilterTypes[i])
{
++filterCount;
var style = filterTypes[i].AccessModeType == ComponentType.AccessMode.Subtractive ? EntityDebuggerStyles.ComponentSubtractive : EntityDebuggerStyles.ComponentRequired;
GUILayout.Label(ComponentGroupGUI.SpecifiedTypeName(filterTypes[i].GetManagedType()), style);
}
}
if (filterCount == 0)
GUILayout.Label("none");
if (GUILayout.Button("Edit"))
{
ComponentTypeChooser.Open(GUIUtility.GUIToScreenPoint(GUILayoutUtility.GetLastRect().position), filterTypes, selectedFilterTypes, ComponentFilterChanged);
}
if (filterCount > 0)
{
if (GUILayout.Button("Clear"))
{
for (var i = 0; i < selectedFilterTypes.Count; ++i)
{
selectedFilterTypes[i] = false;
}
ComponentFilterChanged();
}
}
}
internal ComponentGroup GetExistingGroup(ComponentType[] components)
{
foreach (var existingGroup in entityQueries)
{
if (existingGroup.CompareComponents(components))
return existingGroup;
}
return null;
}
internal ComponentGroup GetComponentGroup(ComponentType[] components)
{
var group = GetExistingGroup(components);
if (group != null)
return group;
group = getWorldSelection().GetExistingManager<EntityManager>().CreateComponentGroup(components);
entityQueries.Add(group);
return group;
}
private void ComponentFilterChanged()
{
var selectedTypes = new List<ComponentType>();
for (var i = 0; i < selectedFilterTypes.Count; ++i)
{
if (selectedFilterTypes[i])
selectedTypes.Add(filterTypes[i]);
}
var group = GetComponentGroup(selectedTypes.ToArray());
setFilter(new EntityListQuery(group));
}
}
}
| 38.132813 | 187 | 0.564024 | [
"Apache-2.0"
] | ArttyOM/TsarJam | TsarJam/Library/PackageCache/com.unity.entities@0.0.12-preview.24/Unity.Entities.Editor/EntityDebugger/ComponentTypeFilterUI.cs | 4,883 | C# |
using System.Diagnostics.CodeAnalysis;
namespace CloudAwesome.Xrm.Core.Models
{
public enum CdsConnectionType { AppRegistration, ConnectionString, UserNameAndPassword }
/// <summary>
/// Configuration for creating a connection to the Common Data Service (aka CDS, Dynamics365, DataVerse)
/// </summary>
[ExcludeFromCodeCoverage]
public class CdsConnection
{
/// <summary>
/// Connection type. Currently supports a connection string, an AAD App registration, or username and password (not recommended)
/// </summary>
public CdsConnectionType ConnectionType { get; set; }
/// <summary>
/// CDS Connection string, required if ConnectionType == ConnectionString
/// </summary>
public string CdsConnectionString { get; set; }
/// <summary>
/// Base URL for CDS environment. Required if ConnectionType == AppRegistration or UserNameAndPassword
/// </summary>
public string CdsUrl { get; set; }
/// <summary>
/// Required if ConnectionType == UserNAmeAndPassword
/// </summary>
public string CdsUserName { get; set; }
/// <summary>
/// Required if ConnectionType == UserNAmeAndPassword
/// </summary>
public string CdsPassword { get; set; }
/// <summary>
/// Required if ConnectionType == AppRegistration
/// </summary>
public string CdsAppId { get; set; }
/// <summary>
/// Required if ConnectionType == AppRegistration
/// </summary>
public string CdsAppSecret { get; set; }
}
}
| 33.44898 | 136 | 0.61928 | [
"MIT"
] | Cloud-Awesome/cds-core | src/CloudAwesome.Xrm.Core/CloudAwesome.Xrm.Core/Models/CdsConnection.cs | 1,641 | C# |
using FluentValidation.Results;
using MediatR;
using SmartBank.Shared.Messages;
using System.Threading.Tasks;
namespace SmartBank.Shared.Mediator
{
public class MediatorHandler : IMediatorHandler
{
private readonly IMediator _mediator;
public MediatorHandler(IMediator mediator)
{
_mediator = mediator;
}
public async Task<ValidationResult> EnviarComando<T>(T comando) where T : Command
{
return await _mediator.Send(comando);
}
public async Task PublicarEvento<T>(T evento) where T : Event
{
await _mediator.Publish(evento);
}
}
}
| 23.75 | 89 | 0.642105 | [
"MIT"
] | ronilsonsilva/smartbank | src/services/SmartBank.Shared/Mediator/MediatorHandler.cs | 667 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System.Collections.Generic;
using EdFi.Ods.Common.Models;
namespace EdFi.Ods.CodeGen.Providers
{
public interface IDomainModelDefinitionsProviderProvider
{
IEnumerable<IDomainModelDefinitionsProvider> DomainModelDefinitionProviders();
IDictionary<string, IDomainModelDefinitionsProvider> DomainModelDefinitionsProvidersByProjectName();
}
}
| 35.944444 | 108 | 0.786708 | [
"Apache-2.0"
] | AxelMarquez/Ed-Fi-ODS | Utilities/CodeGeneration/EdFi.Ods.CodeGen/Providers/IDomainModelDefinitionsProviderProvider.cs | 649 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("teste_froehlichkeit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("teste_froehlichkeit")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("a2089f6b-3a23-48c2-b90e-5b051ac5d93f")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.810811 | 106 | 0.762914 | [
"Apache-2.0"
] | Ch34k0/Test-Biblio | happy_numbers/teste_froehlichkeit/Properties/AssemblyInfo.cs | 1,527 | C# |
namespace SIS.Framework.Attributes.Methods
{
public class HttpPutAttribute : HttpMethodAttribute
{
public override bool IsValid(string requestMethod)
{
if (requestMethod.ToUpper().Equals("PUT")) return true;
return false;
}
}
}
| 21.166667 | 60 | 0.708661 | [
"MIT"
] | AscenKeeprov/CSharp-Web-Basics | Exercise7-MVCFramework/SIS.Framework/Attributes/Methods/HttpPutAttribute.cs | 256 | C# |
#if (UNITY_EDITOR)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityEditor;
[CreateAssetMenu]
[CustomGridBrush(false,true,false, "Prefab Brush / HexBrush")]
public class HexBrush : GridBrushBase
{
public GameObject hexPrefab; //could we hardcode to the hexprefab but have an option for the type of hex?
public DataTypes.HexType hexType;
public bool replaceExisting = false;
public int zPos = 0;
public float xScale = 1.0f;
public float yScale = 1.0f;
[Range(1,10)]
public int health = 1;
public override void Paint(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
{
//First Check and make sure the brush Target is a HexGrid
if((brushTarget.GetComponent("HexGrid") as HexGrid) != null){
//Debug.Log("Found Hex Grid");
Vector3Int cellPosition = new Vector3Int(position.x, position.y, zPos);
Transform cellObject = GetObjectInCell(gridLayout, brushTarget.transform, new Vector3Int(position.x, position.y, position.z));
if (cellObject!=null && !replaceExisting)
{
Debug.LogWarning("Hex Already exists here, will not duplicate in this location"+ position.x + " " + position.y);
return;
}
else
{
//If we want to replace currect cells object, delete the exiting one
if (cellObject != null && replaceExisting)
DestroyImmediate(cellObject.gameObject);
//Create the new cell object using the provided hexPrefab
GameObject gameObject = PrefabUtility.InstantiatePrefab(hexPrefab) as GameObject; // instead of Instantiate(hexPrefab); in order to keep prefab link
Hex hex = (gameObject.GetComponent("Hex") as Hex);
hex.setHexType(hexType);
hex.getHexData().hexScaleFactor.x = (float)System.Math.Round(xScale,2);
hex.getHexData().hexScaleFactor.y = (float)System.Math.Round(yScale, 2);
hex.getHexData().cellLocation = cellPosition;
hex.setHealth(health);
gameObject.transform.SetParent(brushTarget.transform);//BrushTarget will be the tilemap selected
gameObject.transform.position = gridLayout.LocalToWorld(gridLayout.CellToLocalInterpolated(cellPosition));
gameObject.transform.localScale = new Vector3(((brushTarget.transform.localScale.x *gridLayout.cellSize.x) * xScale), brushTarget.transform.localScale.y *gridLayout.cellSize.y, brushTarget.transform.localScale.z *gridLayout.cellSize.z);
}
}
else
{
Debug.Log("Can only draw on GameObjects with the HexGrid attached");
}
}
public override void Erase(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
{
Transform cellObject = GetObjectInCell(gridLayout, brushTarget.transform, new Vector3Int(position.x, position.y, position.z));
if (cellObject != null)
DestroyImmediate(cellObject.gameObject);
}
private Transform GetObjectInCell(GridLayout grid, Transform parent,Vector3Int position)
{
//Get all children objects of Grid containing TileMap
int childCount = parent.childCount;
//Go through each child and check if hex exists in the clicked cell's position
for (int i=0; i < childCount; i++)
{
Transform child = parent.GetChild(i);
//Convert the location of each child into a cell position (has to be cast to int)
// Vector3 childCell_f = grid.WorldToLocal(grid.LocalToCell(child.position));
//Vector3Int childCell_i = new Vector3Int((int)childCell_f.x, (int)childCell_f.y, (int)childCell_f.z);
Vector3Int childCell_i = (child.GetComponent<Hex>()).getHexData().cellLocation;
if (((child.GetComponent("Hex") as Hex) != null) && position == childCell_i)
return child;
}
//Debug.Log("Valid P =" + position.x + " " + position.y);
return null;
}
public void lowerHealth() {
health--;
health = Mathf.Max(1, health);
}
public void raiseHealth() {
health++;
health = Mathf.Min(10, health);
}
}
#endif | 46.521277 | 252 | 0.646467 | [
"MIT"
] | Nomadjackalope/elemental-breakout | Assets/Scripts/LevelBuilder/HexBrush.cs | 4,375 | C# |
using System;
using System.Runtime.InteropServices;
namespace PlatformInvoke
{
internal class Program
{
/*
* 在平台调用过程中,引发异常或错误情形主要可分为两中类型:
* - 由非托管函数的错误托管定义导致的异常或错误
* 在为非托管函数编写托管定义时,需要知道该函数的名称、参数类型等信息,以及将其导出的DLL的名称。
* 因此,在声明非托管函数的过程中,有可能因为设置了错误的DLL名称而引发DLLNotFoundException异常,
* 也有可能由于设置了错误的函数入口点等因素导致平台调用无法在非托管DLL中找到相应的函数名,从而引
* 发EntryPointNotFoundException异常。
*
* 这种错误或异常一般都能通过【try...catch】语句进行捕获
*
* - 由非托管函数本身的错误导致的异常或错误
* 这种异常或错误一般是由非托管函数接受了错误的参数,或者在计算时由于溢出错误、下标越界、空指针等
* 一些常见的C/C++错误而导致的平台调用异常或错误。
*
* 如果异常在.NET平台上由对应的版本,则捕获为对应的.NET异常。
* 如果没有或者是使用【throw】抛出的异常只能捕获到【SEHException】异常
*/
// SomeDLL.dll 不存在
[DllImport("SomeDLL.dll")]
private static extern void DoSomeThingFunc(int paramInt);
// 这里声明一个NativeLib.dll中并不存在的除法函数
[DllImport("NativeLib.dll")]
private static extern float Divide(float factorA, float factorB);
// 不正确的参数类型或参数数目不匹配可能产生不同的结果
// 1. 引发EntryPointNotFoundException异常
// 2. 非期望值或随机值
[DllImport("NativeLib.dll")]
private static extern int Multiply(int factorA, string factorB);
private static void Main()
{
try
{
DoSomeThingFunc(100);
Console.WriteLine("Finish to call function DoSomeThingFunc.");
}
catch (DllNotFoundException dllNotFoundExc)
{
Console.WriteLine("DllNotFoundException was detected, error message: \r\n{0}", dllNotFoundExc.Message);
}
Console.WriteLine("================================================");
try
{
var result = Divide(100F, 818F);
Console.WriteLine("Divide result from unmanaged function is {0}.", result);
}
catch (EntryPointNotFoundException entryPointExc)
{
Console.WriteLine("EntryPointNotFoundException was detected, error message: \r\n{0}", entryPointExc.Message);
}
Console.WriteLine("================================================");
try
{
var result = Multiply(100, "100");
Console.WriteLine("Multiply result from unmanaged function is {0}.", result);
}
catch (EntryPointNotFoundException entryPointExc)
{
Console.WriteLine("EntryPointNotFoundException was detected, error message: \r\n{0}", entryPointExc.Message);
}
Console.WriteLine("\r\n按任意键退出...");
Console.Read();
}
}
} | 35.139241 | 125 | 0.552233 | [
"MIT"
] | zhy29563/CMakeRunPlatformInvoke | samples/sources/HandleException.cs | 3,572 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicExcelFileOpenXML
{
public class CustomersReport
{
public string Name { get; set; }
public string RegisterDate { get; set; }
public string LastBuy { get; set; }
public string Item { get; set; }
public int Quantity { get; set; }
public double ItemCost { get; set; }
public List<CustomersReport> GetRandomData()
{
List<CustomersReport> report = new List<CustomersReport>();
report.Add(new CustomersReport { Name = "Jennifer W. Odom,", RegisterDate = "August 7th, 2018", LastBuy = "December 15th, 2017", Item = "Suspendisse sagittis.", Quantity = 2, ItemCost = 52.40 });
report.Add(new CustomersReport { Name = "Jeanette K. Cleveland,", RegisterDate = "January 28th, 2018", LastBuy = "February 2nd, 2019", Item = "augue ac,", Quantity = 4, ItemCost = 26.07 });
report.Add(new CustomersReport { Name = "Odette J. Hawkins,", RegisterDate = "March 5th, 2018", LastBuy = "January 22nd, 2018", Item = "tincidunt, n", Quantity = 4, ItemCost = 35.93 });
report.Add(new CustomersReport { Name = "Adena A. Munoz,", RegisterDate = "December 28th, 2017", LastBuy = "July 27th, 2019", Item = "Vivamus molestie,", Quantity = 5, ItemCost = 35.03 });
report.Add(new CustomersReport { Name = "Gil J. Mccarthy,", RegisterDate = "January 12th, 2018", LastBuy = "August 8th, 2019", Item = "nibh. D", Quantity = 6, ItemCost = 66.26 });
report.Add(new CustomersReport { Name = "Devin E. Glover,", RegisterDate = "November 15th, 2017", LastBuy = "October 20th, 2018", Item = "Maecenas libero,", Quantity = 6, ItemCost = 61.76 });
report.Add(new CustomersReport { Name = "Vera W. Lancaster,", RegisterDate = "September 17th, 2017", LastBuy = "June 15th, 2018", Item = "iaculis aliquet,", Quantity = 3, ItemCost = 24.65 });
report.Add(new CustomersReport { Name = "Quail Y. Sanchez,", RegisterDate = "January 20th, 2018", LastBuy = "November 29th, 2017", Item = "erat semper,", Quantity = 2, ItemCost = 54.23 });
report.Add(new CustomersReport { Name = "Tobias X. Burris,", RegisterDate = "February 26th, 2018", LastBuy = "March 6th, 2018", Item = "molestie orci,", Quantity = 0, ItemCost = 96.24 });
report.Add(new CustomersReport { Name = "Dakota F. Saunders,", RegisterDate = "December 5th, 2017", LastBuy = "August 21st, 2018", Item = "mauris elit,", Quantity = 10, ItemCost = 36.82 });
report.Add(new CustomersReport { Name = "Wylie Z. Weiss,", RegisterDate = "December 11th, 2017", LastBuy = "July 10th, 2018", Item = "adipiscing lacus.", Quantity = 5, ItemCost = 23.74 });
report.Add(new CustomersReport { Name = "Nelle R. Price,", RegisterDate = "September 7th, 2017", LastBuy = "November 3rd, 2017", Item = "purus, i", Quantity = 10, ItemCost = 8.47 });
report.Add(new CustomersReport { Name = "Kamal X. Jarvis,", RegisterDate = "January 11th, 2018", LastBuy = "February 24th, 2019", Item = "Donec sollicitudin,", Quantity = 2, ItemCost = 86.42 });
report.Add(new CustomersReport { Name = "Christine Q. Johnson,", RegisterDate = "May 15th, 2018", LastBuy = "May 15th, 2019", Item = "Pellentesque habitant,", Quantity = 10, ItemCost = 67.81 });
report.Add(new CustomersReport { Name = "Aiko E. Bass,", RegisterDate = "July 5th, 2018", LastBuy = "April 6th, 2018", Item = "et magnis,", Quantity = 2, ItemCost = 84.37 });
report.Add(new CustomersReport { Name = "Rosalyn A. Decker,", RegisterDate = "September 17th, 2017", LastBuy = "August 31st, 2017", Item = "hendrerit consectetuer,", Quantity = 4, ItemCost = 93.52 });
report.Add(new CustomersReport { Name = "Leilani I. Howell,", RegisterDate = "March 12th, 2018", LastBuy = "June 16th, 2019", Item = "Suspendisse ac,", Quantity = 5, ItemCost = 66.54 });
report.Add(new CustomersReport { Name = "Echo K. Garza,", RegisterDate = "November 7th, 2017", LastBuy = "September 24th, 2018", Item = "mi, a", Quantity = 8, ItemCost = 95.27 });
report.Add(new CustomersReport { Name = "Giselle E. Savage,", RegisterDate = "August 26th, 2017", LastBuy = "August 13th, 2019", Item = "sit amet,", Quantity = 5, ItemCost = 59.48 });
report.Add(new CustomersReport { Name = "Amela A. Huff,", RegisterDate = "October 2nd, 2017", LastBuy = "May 23rd, 2018", Item = "Phasellus nulla.", Quantity = 10, ItemCost = 53.11 });
report.Add(new CustomersReport { Name = "Jarrod J. Hull,", RegisterDate = "July 21st, 2018", LastBuy = "January 12th, 2018", Item = "eu, l", Quantity = 2, ItemCost = 8.57 });
report.Add(new CustomersReport { Name = "Zorita C. Walter,", RegisterDate = "September 3rd, 2017", LastBuy = "February 4th, 2019", Item = "amet massa.", Quantity = 8, ItemCost = 31.42 });
report.Add(new CustomersReport { Name = "Yoko O. Holman,", RegisterDate = "November 15th, 2017", LastBuy = "February 6th, 2019", Item = "tincidunt aliquam,", Quantity = 4, ItemCost = 17.92 });
report.Add(new CustomersReport { Name = "Donovan S. Robles,", RegisterDate = "March 3rd, 2018", LastBuy = "April 7th, 2018", Item = "urna. N", Quantity = 2, ItemCost = 79.40 });
report.Add(new CustomersReport { Name = "Ivor N. Daugherty,", RegisterDate = "February 28th, 2018", LastBuy = "September 15th, 2018", Item = "magnis dis,", Quantity = 5, ItemCost = 53.09 });
report.Add(new CustomersReport { Name = "Dara Q. Hart,", RegisterDate = "September 20th, 2017", LastBuy = "July 10th, 2019", Item = "faucibus orci,", Quantity = 5, ItemCost = 10.94 });
report.Add(new CustomersReport { Name = "Hall A. Strickland,", RegisterDate = "December 23rd, 2017", LastBuy = "September 29th, 2017", Item = "est. N", Quantity = 6, ItemCost = 25.31 });
report.Add(new CustomersReport { Name = "Jakeem O. Williamson,", RegisterDate = "October 15th, 2017", LastBuy = "June 30th, 2018", Item = "eget varius,", Quantity = 5, ItemCost = 84.63 });
report.Add(new CustomersReport { Name = "Aurelia K. Perez,", RegisterDate = "March 18th, 2018", LastBuy = "July 30th, 2019", Item = "Phasellus vitae,", Quantity = 5, ItemCost = 80.05 });
report.Add(new CustomersReport { Name = "Shaeleigh Z. Bowen,", RegisterDate = "December 9th, 2017", LastBuy = "June 28th, 2019", Item = "ac nulla.", Quantity = 8, ItemCost = 88.51 });
report.Add(new CustomersReport { Name = "Leonard G. Guy,", RegisterDate = "October 27th, 2017", LastBuy = "March 22nd, 2019", Item = "cubilia Curae;", Quantity = 6, ItemCost = 70.25 });
report.Add(new CustomersReport { Name = "Cairo I. Gibbs,", RegisterDate = "October 8th, 2017", LastBuy = "December 21st, 2018", Item = "porttitor vulputate,", Quantity = 6, ItemCost = 67.43 });
report.Add(new CustomersReport { Name = "Leah D. Sellers,", RegisterDate = "February 24th, 2018", LastBuy = "July 1st, 2019", Item = "Nunc lectus", Quantity = 4, ItemCost = 85.41 });
report.Add(new CustomersReport { Name = "Rafael Q. Dawson,", RegisterDate = "February 19th, 2018", LastBuy = "May 7th, 2018", Item = "risus, at", Quantity = 1, ItemCost = 31.08 });
report.Add(new CustomersReport { Name = "Aurelia A. Park,", RegisterDate = "October 9th, 2017", LastBuy = "August 31st, 2017", Item = "tincidunt pede,", Quantity = 5, ItemCost = 69.95 });
report.Add(new CustomersReport { Name = "Matthew I. Baker,", RegisterDate = "January 17th, 2018", LastBuy = "June 30th, 2019", Item = "consectetuer adipiscing,", Quantity = 5, ItemCost = 93.23 });
report.Add(new CustomersReport { Name = "Yen I. Schneider,", RegisterDate = "March 30th, 2018", LastBuy = "September 12th, 2017", Item = "viverra. Ma", Quantity = 3, ItemCost = 88.45 });
report.Add(new CustomersReport { Name = "Zahir Q. Rowe,", RegisterDate = "April 19th, 2018", LastBuy = "November 8th, 2017", Item = "facilisis vitae,", Quantity = 5, ItemCost = 57.41 });
report.Add(new CustomersReport { Name = "Jasper F. Vang,", RegisterDate = "August 26th, 2017", LastBuy = "January 8th, 2019", Item = "nec, e", Quantity = 4, ItemCost = 66.54 });
report.Add(new CustomersReport { Name = "Rigel E. Foreman,", RegisterDate = "August 10th, 2018", LastBuy = "January 25th, 2018", Item = "at, l", Quantity = 3, ItemCost = 81.12 });
report.Add(new CustomersReport { Name = "Breanna T. Gonzales,", RegisterDate = "October 10th, 2017", LastBuy = "February 28th, 2019", Item = "Proin non,", Quantity = 5, ItemCost = 14.03 });
report.Add(new CustomersReport { Name = "Mikayla L. Haney,", RegisterDate = "December 19th, 2017", LastBuy = "May 26th, 2018", Item = "ligula. D", Quantity = 7, ItemCost = 66.06 });
report.Add(new CustomersReport { Name = "Hanae G. Witt,", RegisterDate = "July 23rd, 2018", LastBuy = "January 29th, 2019", Item = "augue porttitor,", Quantity = 5, ItemCost = 29.70 });
report.Add(new CustomersReport { Name = "Duncan Y. Browning,", RegisterDate = "April 20th, 2018", LastBuy = "September 13th, 2017", Item = "sociosqu ad,", Quantity = 5, ItemCost = 82.85 });
report.Add(new CustomersReport { Name = "Nissim R. Walter,", RegisterDate = "April 23rd, 2018", LastBuy = "March 25th, 2019", Item = "Cras interdum.", Quantity = 1, ItemCost = 31.84 });
report.Add(new CustomersReport { Name = "Amity T. Kline,", RegisterDate = "January 12th, 2018", LastBuy = "December 20th, 2018", Item = "eget, v", Quantity = 2, ItemCost = 63.66 });
report.Add(new CustomersReport { Name = "Quinn D. Fisher,", RegisterDate = "April 15th, 2018", LastBuy = "October 27th, 2018", Item = "Nunc commodo,", Quantity = 6, ItemCost = 23.67 });
report.Add(new CustomersReport { Name = "Castor Q. West,", RegisterDate = "August 3rd, 2018", LastBuy = "September 8th, 2017", Item = "Fusce aliquet,", Quantity = 5, ItemCost = 49.37 });
report.Add(new CustomersReport { Name = "Clio V. Reilly,", RegisterDate = "June 4th, 2018", LastBuy = "February 18th, 2019", Item = "justo. P", Quantity = 9, ItemCost = 43.05 });
report.Add(new CustomersReport { Name = "Jocelyn T. Allen,", RegisterDate = "September 16th, 2017", LastBuy = "December 23rd, 2017", Item = "libero est,", Quantity = 8, ItemCost = 37.91 });
report.Add(new CustomersReport { Name = "Beverly C. Roberson,", RegisterDate = "July 17th, 2018", LastBuy = "December 26th, 2017", Item = "Praesent eu,", Quantity = 5, ItemCost = 92.42 });
report.Add(new CustomersReport { Name = "Hermione T. Bray,", RegisterDate = "June 26th, 2018", LastBuy = "July 27th, 2018", Item = "Phasellus dapibus,", Quantity = 5, ItemCost = 53.66 });
report.Add(new CustomersReport { Name = "Leo V. Gates,", RegisterDate = "July 21st, 2018", LastBuy = "February 4th, 2018", Item = "lectus pede,", Quantity = 5, ItemCost = 45.37 });
report.Add(new CustomersReport { Name = "Lester K. Parks,", RegisterDate = "October 8th, 2017", LastBuy = "December 1st, 2017", Item = "leo elementum,", Quantity = 5, ItemCost = 29.48 });
report.Add(new CustomersReport { Name = "Minerva O. Buchanan,", RegisterDate = "January 16th, 2018", LastBuy = "May 17th, 2019", Item = "eget ipsum.", Quantity = 1, ItemCost = 50.35 });
report.Add(new CustomersReport { Name = "Nola C. Kirkland,", RegisterDate = "May 12th, 2018", LastBuy = "March 3rd, 2019", Item = "in consectetuer,", Quantity = 5, ItemCost = 10.81 });
report.Add(new CustomersReport { Name = "Ralph G. Haley,", RegisterDate = "September 1st, 2017", LastBuy = "October 14th, 2018", Item = "erat eget,", Quantity = 5, ItemCost = 3.77 });
report.Add(new CustomersReport { Name = "Colby D. Bradford,", RegisterDate = "April 22nd, 2018", LastBuy = "November 8th, 2017", Item = "Nulla interdum.", Quantity = 2, ItemCost = 56.15 });
report.Add(new CustomersReport { Name = "Paki H. Chang,", RegisterDate = "July 2nd, 2018", LastBuy = "June 30th, 2019", Item = "orci quis,", Quantity = 5, ItemCost = 35.78 });
report.Add(new CustomersReport { Name = "Timothy L. Glass,", RegisterDate = "November 1st, 2017", LastBuy = "May 22nd, 2018", Item = "sapien. N", Quantity = 6, ItemCost = 11.16 });
report.Add(new CustomersReport { Name = "Colton Q. Carney,", RegisterDate = "June 29th, 2018", LastBuy = "July 23rd, 2019", Item = "luctus. C", Quantity = 3, ItemCost = 26.85 });
report.Add(new CustomersReport { Name = "Madison Q. Townsend,", RegisterDate = "May 10th, 2018", LastBuy = "January 15th, 2018", Item = "dis parturient,", Quantity = 5, ItemCost = 46.81 });
report.Add(new CustomersReport { Name = "Hadassah U. Wright,", RegisterDate = "August 13th, 2018", LastBuy = "May 24th, 2018", Item = "leo. C", Quantity = 8, ItemCost = 71.05 });
report.Add(new CustomersReport { Name = "Shana M. Mcbride,", RegisterDate = "May 24th, 2018", LastBuy = "January 17th, 2018", Item = "blandit enim,", Quantity = 5, ItemCost = 2.20 });
report.Add(new CustomersReport { Name = "Gloria I. Miller,", RegisterDate = "May 20th, 2018", LastBuy = "October 6th, 2017", Item = "tristique senectus,", Quantity = 5, ItemCost = 51.11 });
report.Add(new CustomersReport { Name = "Brent F. Carter,", RegisterDate = "February 13th, 2018", LastBuy = "November 8th, 2017", Item = "luctus ut,", Quantity = 9, ItemCost = 27.70 });
report.Add(new CustomersReport { Name = "Garrett B. Dalton,", RegisterDate = "August 26th, 2017", LastBuy = "July 26th, 2018", Item = "eget metus.", Quantity = 10, ItemCost = 64.87 });
report.Add(new CustomersReport { Name = "Aileen Z. Lott,", RegisterDate = "December 12th, 2017", LastBuy = "September 2nd, 2018", Item = "tristique neque,", Quantity = 5, ItemCost = 24.49 });
report.Add(new CustomersReport { Name = "Megan H. Kramer,", RegisterDate = "January 10th, 2018", LastBuy = "February 9th, 2019", Item = "risus. D", Quantity = 2, ItemCost = 25.10 });
report.Add(new CustomersReport { Name = "Lane C. Haley,", RegisterDate = "November 9th, 2017", LastBuy = "November 13th, 2018", Item = "Etiam laoreet,", Quantity = 7, ItemCost = 95.30 });
report.Add(new CustomersReport { Name = "Davis X. Estes,", RegisterDate = "March 8th, 2018", LastBuy = "December 12th, 2018", Item = "tristique ac,", Quantity = 10, ItemCost = 17.83 });
report.Add(new CustomersReport { Name = "Noelle K. Bowman,", RegisterDate = "December 25th, 2017", LastBuy = "October 17th, 2018", Item = "accumsan neque,", Quantity = 5, ItemCost = 12.96 });
report.Add(new CustomersReport { Name = "Akeem L. Crosby,", RegisterDate = "November 26th, 2017", LastBuy = "October 4th, 2018", Item = "dictum eu,", Quantity = 5, ItemCost = 89.98 });
report.Add(new CustomersReport { Name = "Lillith B. Jordan,", RegisterDate = "August 25th, 2017", LastBuy = "August 13th, 2018", Item = "nulla. I", Quantity = 9, ItemCost = 95.23 });
report.Add(new CustomersReport { Name = "Kevyn A. Owens,", RegisterDate = "October 24th, 2017", LastBuy = "October 12th, 2018", Item = "mattis ornare,", Quantity = 8, ItemCost = 95.68 });
report.Add(new CustomersReport { Name = "Dorian W. Pickett,", RegisterDate = "November 8th, 2017", LastBuy = "February 13th, 2018", Item = "semper cursus.", Quantity = 8, ItemCost = 36.82 });
report.Add(new CustomersReport { Name = "Coby Q. Osborne,", RegisterDate = "July 10th, 2018", LastBuy = "October 21st, 2018", Item = "Phasellus at,", Quantity = 5, ItemCost = 22.75 });
report.Add(new CustomersReport { Name = "Peter X. Walsh,", RegisterDate = "November 7th, 2017", LastBuy = "March 14th, 2019", Item = "at augue,", Quantity = 5, ItemCost = 36.91 });
report.Add(new CustomersReport { Name = "Maryam G. Santos,", RegisterDate = "September 24th, 2017", LastBuy = "August 28th, 2018", Item = "vulputate eu,", Quantity = 1, ItemCost = 92.91 });
report.Add(new CustomersReport { Name = "Aspen P. Knowles,", RegisterDate = "February 27th, 2018", LastBuy = "March 25th, 2018", Item = "In tincidunt,", Quantity = 5, ItemCost = 50.23 });
report.Add(new CustomersReport { Name = "Jana U. Newton,", RegisterDate = "June 23rd, 2018", LastBuy = "July 29th, 2019", Item = "facilisis non,", Quantity = 4, ItemCost = 41.72 });
report.Add(new CustomersReport { Name = "Martena Y. Swanson,", RegisterDate = "September 15th, 2017", LastBuy = "August 26th, 2018", Item = "dui nec,", Quantity = 5, ItemCost = 54.90 });
report.Add(new CustomersReport { Name = "Tarik R. Carter,", RegisterDate = "July 13th, 2018", LastBuy = "February 23rd, 2018", Item = "dui nec,", Quantity = 5, ItemCost = 89.92 });
report.Add(new CustomersReport { Name = "Rinah R. Landry,", RegisterDate = "March 11th, 2018", LastBuy = "December 25th, 2017", Item = "Cras eget,", Quantity = 5, ItemCost = 44.32 });
report.Add(new CustomersReport { Name = "Kermit I. Nielsen,", RegisterDate = "December 20th, 2017", LastBuy = "November 5th, 2018", Item = "a ultricies,", Quantity = 5, ItemCost = 97.43 });
report.Add(new CustomersReport { Name = "Quinn D. Burks,", RegisterDate = "February 8th, 2018", LastBuy = "January 24th, 2019", Item = "tempor, e", Quantity = 4, ItemCost = 86.74 });
report.Add(new CustomersReport { Name = "Perry E. Marquez,", RegisterDate = "June 3rd, 2018", LastBuy = "February 13th, 2018", Item = "Curabitur egestas,", Quantity = 5, ItemCost = 66.04 });
report.Add(new CustomersReport { Name = "Summer X. Haley,", RegisterDate = "August 30th, 2017", LastBuy = "March 31st, 2018", Item = "justo faucibus,", Quantity = 5, ItemCost = 12.99 });
report.Add(new CustomersReport { Name = "Cruz Z. May,", RegisterDate = "February 3rd, 2018", LastBuy = "February 11th, 2018", Item = "magnis dis,", Quantity = 5, ItemCost = 33.70 });
report.Add(new CustomersReport { Name = "Yuri S. Blackburn,", RegisterDate = "March 23rd, 2018", LastBuy = "September 13th, 2017", Item = "Nam consequat,", Quantity = 5, ItemCost = 45.52 });
report.Add(new CustomersReport { Name = "Curran W. Dillon,", RegisterDate = "March 2nd, 2018", LastBuy = "January 31st, 2019", Item = "lectus justo,", Quantity = 5, ItemCost = 31.22 });
report.Add(new CustomersReport { Name = "Marshall F. Sharpe,", RegisterDate = "April 18th, 2018", LastBuy = "October 3rd, 2017", Item = "mollis vitae,", Quantity = 9, ItemCost = 24.15 });
report.Add(new CustomersReport { Name = "Carl X. Rasmussen,", RegisterDate = "December 5th, 2017", LastBuy = "March 6th, 2019", Item = "libero. M", Quantity = 9, ItemCost = 76.16 });
report.Add(new CustomersReport { Name = "Lawrence Z. Morgan,", RegisterDate = "December 29th, 2017", LastBuy = "March 13th, 2019", Item = "diam. P", Quantity = 9, ItemCost = 73.61 });
report.Add(new CustomersReport { Name = "Chandler C. Yang,", RegisterDate = "August 14th, 2018", LastBuy = "August 30th, 2018", Item = "natoque penatibus,", Quantity = 5, ItemCost = 41.43 });
report.Add(new CustomersReport { Name = "Rae Z. Walsh,", RegisterDate = "April 9th, 2018", LastBuy = "April 11th, 2018", Item = "ultricies ligula.", Quantity = 5, ItemCost = 40.17 });
report.Add(new CustomersReport { Name = "Nathan F. Green,", RegisterDate = "January 11th, 2018", LastBuy = "February 23rd, 2018", Item = "varius. N", Quantity = 4, ItemCost = 27.87 });
report.Add(new CustomersReport { Name = "Kiara J. Flynn,", RegisterDate = "April 14th, 2018", LastBuy = "April 23rd, 2019", Item = "Pellentesque habitant,", Quantity = 5, ItemCost = 26.24 });
report.Add(new CustomersReport { Name = "Raya H. England,", RegisterDate = "July 2nd, 2018", LastBuy = "January 5th, 2019", Item = "In mi,", Quantity = 5, ItemCost = 9.02 });
report.Add(new CustomersReport { Name = "Shellie O. Torres,", RegisterDate = "June 17th, 2018", LastBuy = "September 22nd, 2017", Item = "egestas a,", Quantity = 8, ItemCost = 50.13 });
return report;
}
}
}
| 163.712 | 212 | 0.636581 | [
"MIT"
] | Lvcios/Basic-Excel-fil-with-OpenXML-C- | BasicExcelFileOpenXML/CustomersReport.cs | 20,466 | C# |
using System;
using GW2Scratch.EVTCAnalytics.Model;
using GW2Scratch.EVTCAnalytics.Model.Agents;
using GW2Scratch.EVTCAnalytics.Model.Skills;
namespace GW2Scratch.EVTCAnalytics.Events
{
/// <summary>
/// An event relevant to a specific <see cref="Agent"/>.
/// </summary>
public abstract class AgentEvent : Event
{
public Agent Agent { get; internal set; }
protected AgentEvent(long time, Agent agent) : base(time)
{
Agent = agent;
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> entered combat.
/// </summary>
public class AgentEnterCombatEvent : AgentEvent
{
public int Subgroup { get; }
public AgentEnterCombatEvent(long time, Agent agent, int subgroup) : base(time, agent)
{
Subgroup = subgroup;
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> exited combat.
/// </summary>
public class AgentExitCombatEvent : AgentEvent
{
public AgentExitCombatEvent(long time, Agent agent) : base(time, agent)
{
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> was revived (either from downed or dead state).
/// </summary>
public class AgentRevivedEvent : AgentEvent
{
public AgentRevivedEvent(long time, Agent agent) : base(time, agent)
{
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> is now downed.
/// </summary>
public class AgentDownedEvent : AgentEvent
{
public AgentDownedEvent(long time, Agent agent) : base(time, agent)
{
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> is now dead.
/// </summary>
public class AgentDeadEvent : AgentEvent
{
public AgentDeadEvent(long time, Agent agent) : base(time, agent)
{
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> is now tracked.
/// </summary>
public class AgentSpawnEvent : AgentEvent
{
public AgentSpawnEvent(long time, Agent agent) : base(time, agent)
{
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> is no longer tracked.
/// </summary>
public class AgentDespawnEvent : AgentEvent
{
public AgentDespawnEvent(long time, Agent agent) : base(time, agent)
{
}
}
/// <summary>
/// An event specifying that the health percentage of an <see cref="Agent"/> has been changed.
/// </summary>
/// <remarks>
/// This event is typically only provided once per a period, even if health changes more often.
/// </remarks>
public class AgentHealthUpdateEvent : AgentEvent
{
public float HealthFraction { get; }
public AgentHealthUpdateEvent(long time, Agent agent, float healthFraction) : base(time, agent)
{
HealthFraction = healthFraction;
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> changed their active weapon set.
/// </summary>
/// <remarks>
/// A weapon set does not necessarily correspond to what players use the weapon swap action for.
/// Swapping to a bundle that provides a set of skills will also trigger this event.
/// </remarks>
public class AgentWeaponSwapEvent : AgentEvent
{
public WeaponSet NewWeaponSet { get; }
public AgentWeaponSwapEvent(long time, Agent agent, WeaponSet newWeaponSet) : base(time, agent)
{
NewWeaponSet = newWeaponSet;
}
}
/// <summary>
/// An event specifying that the maximum health of an <see cref="Agent"/> has been changed.
/// </summary>
public class AgentMaxHealthUpdateEvent : AgentEvent
{
public ulong NewMaxHealth { get; }
public AgentMaxHealthUpdateEvent(long time, Agent agent, ulong newMaxHealth) : base(time, agent)
{
NewMaxHealth = newMaxHealth;
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> has a tag. Typically a <see cref="Player"/> with a Commander tag.
/// </summary>
/// <remarks>
/// Introduced in EVTC20200609.
/// </remarks>
public class AgentTagEvent : AgentEvent
{
/// <summary>
/// The ID of the tag may be volatile and change with each game build.
/// </summary>
public int Id { get; }
public AgentTagEvent(long time, Agent agent, int id) : base(time, agent)
{
Id = id;
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> has an ongoing buff at the time tracking starts.
/// </summary>
public class InitialBuffEvent : AgentEvent
{
public Skill Skill { get; }
public InitialBuffEvent(long time, Agent agent, Skill skill) : base(time, agent)
{
Skill = skill;
}
}
/// <summary>
/// An event specifying that the position (3D coordinates) of an <see cref="Agent"/> has been changed.
/// </summary>
/// <remarks>
/// This event is typically only provided once per a period, even if position changes more often.
/// </remarks>
public class PositionChangeEvent : AgentEvent
{
public float X { get; }
public float Y { get; }
public float Z { get; }
public PositionChangeEvent(long time, Agent agent, float x, float y, float z) : base(time, agent)
{
X = x;
Y = y;
Z = z;
}
}
/// <summary>
/// An event specifying that the velocity (3D vector) of an <see cref="Agent"/> has been changed.
/// </summary>
/// <remarks>
/// This event is typically only provided once per a period, even if velocity changes more often.
/// </remarks>
public class VelocityChangeEvent : AgentEvent
{
public float X { get; }
public float Y { get; }
public float Z { get; }
public VelocityChangeEvent(long time, Agent agent, float x, float y, float z) : base(time, agent)
{
X = x;
Y = y;
Z = z;
}
}
/// <summary>
/// An event specifying that the facing (2D vector) of an <see cref="Agent"/> has been changed.
/// </summary>
/// <remarks>
/// This event is typically only provided once per a period, even if facing changes more often.
/// </remarks>
public class FacingChangeEvent : AgentEvent
{
public float X { get; }
public float Y { get; }
public FacingChangeEvent(long time, Agent agent, float x, float y) : base(time, agent)
{
X = x;
Y = y;
}
}
/// <summary>
/// An event specifying that an <see cref="Agent"/> changed their current team.
/// <br />
/// Teams affect hostility of targets.
/// </summary>
public class TeamChangeEvent : AgentEvent
{
public ulong NewTeamId { get; }
public TeamChangeEvent(long time, Agent agent, ulong newTeamId) : base(time, agent)
{
NewTeamId = newTeamId;
}
}
/// <summary>
/// An event specifying that an <see cref="AttackTarget"/> is now (un)targetable.
/// </summary>
public class TargetableChangeEvent : AgentEvent
{
public AttackTarget AttackTarget => (AttackTarget) Agent;
public bool IsTargetable { get; }
public TargetableChangeEvent(long time, AttackTarget agent, bool targetable) : base(time, agent)
{
IsTargetable = targetable;
}
}
} | 25.992278 | 118 | 0.673797 | [
"MIT"
] | jcogilvie/evtc | EVTCAnalytics/Events/AgentEvents.cs | 6,732 | C# |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using Amazon.Runtime;
namespace Amazon.S3.Model
{
/// <summary>
/// Returns information about the ListParts response and response metadata.
/// </summary>
public class ListPartsResponse : AmazonWebServiceResponse
{
private string bucketName;
private string key;
private string uploadId;
private Owner owner;
private Initiator initiator;
private S3StorageClass storageClass;
private int? partNumberMarker;
private int? nextPartNumberMarker;
private int? maxParts;
private bool? isTruncated;
private List<PartDetail> parts = new List<PartDetail>();
/// <summary>
/// Name of the bucketName to which the multipart upload was initiated.
///
/// </summary>
public string BucketName
{
get { return this.bucketName; }
set { this.bucketName = value; }
}
// Check to see if BucketName property is set
internal bool IsSetBucketName()
{
return this.bucketName != null;
}
/// <summary>
/// Object key for which the multipart upload was initiated.
///
/// </summary>
public string Key
{
get { return this.key; }
set { this.key = value; }
}
// Check to see if Key property is set
internal bool IsSetKey()
{
return this.key != null;
}
/// <summary>
/// Upload ID identifying the multipart upload whose parts are being listed.
///
/// </summary>
public string UploadId
{
get { return this.uploadId; }
set { this.uploadId = value; }
}
// Check to see if UploadId property is set
internal bool IsSetUploadId()
{
return this.uploadId != null;
}
/// <summary>
/// Part number after which listing begins.
///
/// </summary>
public int PartNumberMarker
{
get { return this.partNumberMarker ?? default(int); }
set { this.partNumberMarker = value; }
}
// Check to see if PartNumberMarker property is set
internal bool IsSetPartNumberMarker()
{
return this.partNumberMarker.HasValue;
}
/// <summary>
/// When a list is truncated, this element specifies the last part in the list, as well as the value to use for the part-number-marker request
/// parameter in a subsequent request.
///
/// </summary>
public int NextPartNumberMarker
{
get { return this.nextPartNumberMarker ?? default(int); }
set { this.nextPartNumberMarker = value; }
}
// Check to see if NextPartNumberMarker property is set
internal bool IsSetNextPartNumberMarker()
{
return this.nextPartNumberMarker.HasValue;
}
/// <summary>
/// Maximum number of parts that were allowed in the response.
///
/// </summary>
public int MaxParts
{
get { return this.maxParts ?? default(int); }
set { this.maxParts = value; }
}
// Check to see if MaxParts property is set
internal bool IsSetMaxParts()
{
return this.maxParts.HasValue;
}
/// <summary>
/// Indicates whether the returned list of parts is truncated.
///
/// </summary>
public bool IsTruncated
{
get { return this.isTruncated ?? default(bool); }
set { this.isTruncated = value; }
}
// Check to see if IsTruncated property is set
internal bool IsSetIsTruncated()
{
return this.isTruncated.HasValue;
}
/// <summary>
/// Gets and sets the Parts property.
/// <para>
/// PartDetails is a container for elements related to a particular part. A response can contain
/// zero or more Part elements.
/// </para>
/// </summary>
public List<PartDetail> Parts
{
get { return this.parts; }
set { this.parts = value; }
}
// Check to see if Parts property is set
internal bool IsSetParts()
{
return this.parts.Count > 0;
}
/// <summary>
/// Identifies who initiated the multipart upload.
///
/// </summary>
public Initiator Initiator
{
get { return this.initiator; }
set { this.initiator = value; }
}
// Check to see if Initiator property is set
internal bool IsSetInitiator()
{
return this.initiator != null;
}
/// <summary>
/// Gets and sets the Owner property.
/// </summary>
public Owner Owner
{
get { return this.owner; }
set { this.owner = value; }
}
// Check to see if Owner property is set
internal bool IsSetOwner()
{
return this.owner != null;
}
/// <summary>
/// The class of storage used to store the object.
///
/// </summary>
public string StorageClass
{
get { return this.storageClass; }
set { this.storageClass = value; }
}
// Check to see if StorageClass property is set
internal bool IsSetStorageClass()
{
return this.storageClass != null;
}
}
}
| 28.716216 | 150 | 0.549176 | [
"Apache-2.0"
] | amazon-archives/aws-sdk-xamarin | AWS.XamarinSDK/AWSSDK_Android/Amazon.S3/Model/ListPartsResponse.cs | 6,375 | C# |
namespace RoboSum.Services.Entities;
using AutoMapper;
using RoboSum.Domain.Entities;
using RoboSum.Domain.Repositories.Entities;
using RoboSum.DTOs;
using RoboSum.Services.Abstractions.Entities;
/// <summary>
/// Represents a service for <see cref="TeacherDto"/> type.
/// </summary>
public class TeacherService : AbstractService<ITeacherRepository, Teacher, TeacherDto>, ITeacherService
{
/// <summary>
/// Initializes a new instance of the <see cref="TeacherService"/> class.
/// </summary>
/// <param name="repository">The repository instance.</param>
/// <param name="mapper">The DTO to entity mapper instance.</param>
public TeacherService(ITeacherRepository repository, IMapper mapper)
: base(repository, mapper)
{
}
}
| 32.041667 | 103 | 0.721717 | [
"Apache-2.0"
] | DavidUrbancok/RoboSum | src/RoboSum.Services/Entities/TeacherService.cs | 771 | C# |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
namespace behaviac
{
public class DecoratorAlwaysSuccess : DecoratorNode
{
public DecoratorAlwaysSuccess()
{
}
~DecoratorAlwaysSuccess()
{
}
protected override void load(int version, string agentType, List<property_t> properties)
{
base.load(version, agentType, properties);
}
public override bool IsValid(Agent pAgent, BehaviorTask pTask)
{
if (!(pTask.GetNode() is DecoratorAlwaysSuccess))
{
return false;
}
return base.IsValid(pAgent, pTask);
}
protected override BehaviorTask createTask()
{
DecoratorAlwaysSuccessTask pTask = new DecoratorAlwaysSuccessTask();
return pTask;
}
class DecoratorAlwaysSuccessTask : DecoratorTask
{
public DecoratorAlwaysSuccessTask() : base()
{
}
public override void copyto(BehaviorTask target)
{
base.copyto(target);
}
public override void save(ISerializableNode node)
{
base.save(node);
}
public override void load(ISerializableNode node)
{
base.load(node);
}
protected override EBTStatus decorate(EBTStatus status)
{
return EBTStatus.BT_SUCCESS;
}
}
}
} | 29.064103 | 113 | 0.612704 | [
"BSD-3-Clause"
] | Manistein/behaviac | integration/BattleCityDemo/Assets/Scripts/behaviac/BehaviorTree/Nodes/Decorators/Decoratoralwayssuccess.cs | 2,267 | C# |
namespace MvcTurbine.Web.Blades {
using System.Web.Mvc;
using MvcTurbine.Blades;
/// <summary>
/// Blade for handling the registration of <see cref="IDependencyResolver"/>.
/// </summary>
public class DependencyResolverBlade : CoreBlade {
public override void Spin(IRotorContext context) {
var dependencyResolver = GetDependencyResolver(context);
DependencyResolver.SetResolver(dependencyResolver);
}
/// <summary>
/// Gets the registered <see cref="IDependencyResolver"/> that's configured with the system.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
protected virtual IDependencyResolver GetDependencyResolver(IRotorContext context) {
var serviceLocator = context.ServiceLocator;
try {
return serviceLocator.Resolve<IDependencyResolver>();
} catch {
return new TurbineDependencyResolver(serviceLocator);
}
}
}
}
| 35.033333 | 95 | 0.624167 | [
"Apache-2.0"
] | bmabdi/mvcturbine | src/Engine/MvcTurbine.Web/Blades/DependencyResolverBlade.cs | 1,053 | C# |
using System;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
namespace DrWPF.Windows.Controls
{
public static class VirtualToggleButton
{
#region attached properties
#region IsChecked
/// <summary>
/// IsChecked Attached Dependency Property
/// </summary>
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.RegisterAttached("IsChecked", typeof(Nullable<bool>), typeof(VirtualToggleButton),
new FrameworkPropertyMetadata((Nullable<bool>)false,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal,
new PropertyChangedCallback(OnIsCheckedChanged)));
/// <summary>
/// Gets the IsChecked property. This dependency property
/// indicates whether the toggle button is checked.
/// </summary>
public static Nullable<bool> GetIsChecked(DependencyObject d)
{
return (Nullable<bool>)d.GetValue(IsCheckedProperty);
}
/// <summary>
/// Sets the IsChecked property. This dependency property
/// indicates whether the toggle button is checked.
/// </summary>
public static void SetIsChecked(DependencyObject d, Nullable<bool> value)
{
d.SetValue(IsCheckedProperty, value);
}
/// <summary>
/// Handles changes to the IsChecked property.
/// </summary>
private static void OnIsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UIElement pseudobutton = d as UIElement;
if (pseudobutton != null)
{
Nullable<bool> newValue = (Nullable<bool>)e.NewValue;
if (newValue == true)
{
RaiseCheckedEvent(pseudobutton);
}
else if (newValue == false)
{
RaiseUncheckedEvent(pseudobutton);
}
else
{
RaiseIndeterminateEvent(pseudobutton);
}
}
}
#endregion
#region IsThreeState
/// <summary>
/// IsThreeState Attached Dependency Property
/// </summary>
public static readonly DependencyProperty IsThreeStateProperty =
DependencyProperty.RegisterAttached("IsThreeState", typeof(bool), typeof(VirtualToggleButton),
new FrameworkPropertyMetadata((bool)false));
/// <summary>
/// Gets the IsThreeState property. This dependency property
/// indicates whether the control supports two or three states.
/// IsChecked can be set to null as a third state when IsThreeState is true.
/// </summary>
public static bool GetIsThreeState(DependencyObject d)
{
return (bool)d.GetValue(IsThreeStateProperty);
}
/// <summary>
/// Sets the IsThreeState property. This dependency property
/// indicates whether the control supports two or three states.
/// IsChecked can be set to null as a third state when IsThreeState is true.
/// </summary>
public static void SetIsThreeState(DependencyObject d, bool value)
{
d.SetValue(IsThreeStateProperty, value);
}
#endregion
#region IsVirtualToggleButton
/// <summary>
/// IsVirtualToggleButton Attached Dependency Property
/// </summary>
public static readonly DependencyProperty IsVirtualToggleButtonProperty =
DependencyProperty.RegisterAttached("IsVirtualToggleButton", typeof(bool), typeof(VirtualToggleButton),
new FrameworkPropertyMetadata((bool)false,
new PropertyChangedCallback(OnIsVirtualToggleButtonChanged)));
/// <summary>
/// Gets the IsVirtualToggleButton property. This dependency property
/// indicates whether the object to which the property is attached is treated as a VirtualToggleButton.
/// If true, the object will respond to keyboard and mouse input the same way a ToggleButton would.
/// </summary>
public static bool GetIsVirtualToggleButton(DependencyObject d)
{
return (bool)d.GetValue(IsVirtualToggleButtonProperty);
}
/// <summary>
/// Sets the IsVirtualToggleButton property. This dependency property
/// indicates whether the object to which the property is attached is treated as a VirtualToggleButton.
/// If true, the object will respond to keyboard and mouse input the same way a ToggleButton would.
/// </summary>
public static void SetIsVirtualToggleButton(DependencyObject d, bool value)
{
d.SetValue(IsVirtualToggleButtonProperty, value);
}
/// <summary>
/// Handles changes to the IsVirtualToggleButton property.
/// </summary>
private static void OnIsVirtualToggleButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
IInputElement element = d as IInputElement;
if (element != null)
{
if ((bool)e.NewValue)
{
element.MouseLeftButtonDown += OnMouseLeftButtonDown;
element.KeyDown += OnKeyDown;
}
else
{
element.MouseLeftButtonDown -= OnMouseLeftButtonDown;
element.KeyDown -= OnKeyDown;
}
}
}
#endregion
#endregion
#region routed events
#region Checked
/// <summary>
/// A static helper method to raise the Checked event on a target element.
/// </summary>
/// <param name="target">UIElement or ContentElement on which to raise the event</param>
internal static RoutedEventArgs RaiseCheckedEvent(UIElement target)
{
if (target == null) return null;
RoutedEventArgs args = new RoutedEventArgs();
args.RoutedEvent = ToggleButton.CheckedEvent;
RaiseEvent(target, args);
return args;
}
#endregion
#region Unchecked
/// <summary>
/// A static helper method to raise the Unchecked event on a target element.
/// </summary>
/// <param name="target">UIElement or ContentElement on which to raise the event</param>
internal static RoutedEventArgs RaiseUncheckedEvent(UIElement target)
{
if (target == null) return null;
RoutedEventArgs args = new RoutedEventArgs();
args.RoutedEvent = ToggleButton.UncheckedEvent;
RaiseEvent(target, args);
return args;
}
#endregion
#region Indeterminate
/// <summary>
/// A static helper method to raise the Indeterminate event on a target element.
/// </summary>
/// <param name="target">UIElement or ContentElement on which to raise the event</param>
internal static RoutedEventArgs RaiseIndeterminateEvent(UIElement target)
{
if (target == null) return null;
RoutedEventArgs args = new RoutedEventArgs();
args.RoutedEvent = ToggleButton.IndeterminateEvent;
RaiseEvent(target, args);
return args;
}
#endregion
#endregion
#region private methods
private static void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
UpdateIsChecked(sender as DependencyObject);
}
private static void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.OriginalSource == sender)
{
if (e.Key == Key.Space)
{
// ignore alt+space which invokes the system menu
if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) return;
UpdateIsChecked(sender as DependencyObject);
e.Handled = true;
}
else if (e.Key == Key.Enter && (bool)(sender as DependencyObject).GetValue(KeyboardNavigation.AcceptsReturnProperty))
{
UpdateIsChecked(sender as DependencyObject);
e.Handled = true;
}
}
}
private static void UpdateIsChecked(DependencyObject d)
{
Nullable<bool> isChecked = GetIsChecked(d);
if (isChecked == true)
{
SetIsChecked(d, GetIsThreeState(d) ? (Nullable<bool>)null : (Nullable<bool>)false);
}
else
{
SetIsChecked(d, isChecked.HasValue);
}
}
private static void RaiseEvent(DependencyObject target, RoutedEventArgs args)
{
if (target is UIElement)
{
(target as UIElement).RaiseEvent(args);
}
else if (target is ContentElement)
{
(target as ContentElement).RaiseEvent(args);
}
}
#endregion
}
} | 35.404494 | 133 | 0.583095 | [
"MIT"
] | kamranbilgrami/IntellitraceDataCollector | IntelliTraceCPConfig/VirtualToggleButton.cs | 9,455 | C# |
namespace UglyToad.PdfPig.Fonts.TrueType.Tables.CMapSubTables
{
using System.IO;
using Core;
/// <summary>
/// The format 0 sub-table where character codes and glyph indices are restricted to a single bytes.
/// </summary>
internal class ByteEncodingCMapTable : ICMapSubTable, IWriteable
{
private const ushort Format = 0;
private const ushort DefaultLanguageId = 0;
private const int SizeOfShort = 2;
private const int GlyphMappingLength = 256;
private readonly byte[] glyphMapping;
public TrueTypeCMapPlatform PlatformId { get; }
public ushort EncodingId { get; }
public ushort LanguageId { get; }
public ByteEncodingCMapTable(TrueTypeCMapPlatform platformId, ushort encodingId, ushort languageId, byte[] glyphMapping)
{
this.glyphMapping = glyphMapping;
PlatformId = platformId;
EncodingId = encodingId;
LanguageId = languageId;
}
public static ByteEncodingCMapTable Load(TrueTypeDataBytes data, TrueTypeCMapPlatform platformId, ushort encodingId)
{
var length = data.ReadUnsignedShort();
var language = data.ReadUnsignedShort();
var glyphMapping = data.ReadByteArray(length - (SizeOfShort * 3));
return new ByteEncodingCMapTable(platformId, encodingId, language, glyphMapping);
}
public int CharacterCodeToGlyphIndex(int characterCode)
{
if (characterCode < 0 || characterCode >= GlyphMappingLength)
{
return 0;
}
return glyphMapping[characterCode];
}
public void Write(Stream stream)
{
stream.WriteUShort(Format);
stream.WriteUShort(GlyphMappingLength + (SizeOfShort * 3));
stream.WriteUShort(DefaultLanguageId);
for (var i = 0; i < glyphMapping.Length; i++)
{
stream.WriteByte(glyphMapping[i]);
}
}
}
} | 32.40625 | 128 | 0.613308 | [
"Apache-2.0"
] | BobLd/PdfP | src/UglyToad.PdfPig.Fonts/TrueType/Tables/CMapSubTables/ByteEncodingCMapTable.cs | 2,076 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace HoloToolkit.Unity
{
// Hides a field in an MRDL inspector
[AttributeUsage(AttributeTargets.Field)]
public sealed class HideInMRTKInspector : ShowIfAttribute
{
public HideInMRTKInspector() { }
#if UNITY_EDITOR
public override bool ShouldShow(object target)
{
return false;
}
#endif
}
} | 23.791667 | 91 | 0.700525 | [
"CC0-1.0"
] | AGM-GR/In-Game | Assets/HoloToolkit/Utilities/Scripts/Attributes/HideInMRTKInspector.cs | 571 | C# |
// Copyright (c) 2017 Trevor Redfern
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
namespace Tests.Utility
{
using Xunit;
using SilverNeedle.Utility;
public class ReflectorTests
{
[Fact]
public void CanFindTypesUsingStringFromOtherAssemblies()
{
var type = Reflector.FindType("Tests.Utility.ReflectorTests");
Assert.Equal(typeof(ReflectorTests), type);
}
[Fact]
public void FindAllTypesThatImplementInterface()
{
var types = Reflector.FindAllTypesThatImplement<IDummy>();
Assert.NotStrictEqual(new System.Type[] { typeof(DummyOne), typeof(DummyTwo)}, types);
}
[Fact]
public void ThrowExceptionIfTypeNotFound()
{
Assert.Throws(typeof(TypeNotFoundException), () => "SomeRandomTypeThatCantExist".Instantiate<object>());
}
[Fact]
public void FindsTypesByStringInAnyAssembly()
{
var name = typeof(DummyOne).FullName;
var type = Reflector.FindType(name);
Assert.Equal(typeof(DummyOne), type);
}
[Fact]
public void ChecksWhetherClassImplementsAParticularClassOrInterface()
{
var test = new DummyTwo();
Assert.True(test.Implements(typeof(DummyTwo)));
Assert.True(test.Implements(typeof(IDummy)));
}
public interface IDummy { }
public class DummyOne : IDummy { }
public class DummyTwo : IDummy { }
}
} | 29.943396 | 117 | 0.609326 | [
"MIT"
] | shortlegstudio/silverneedle-web | silverneedle-tests/Utility/ReflectorTests.cs | 1,587 | C# |
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
namespace TheBunniesOfVegetaria
{
public static class SaveLoad
{
private static string SaveDataPath => Application.persistentDataPath + "/save.dat";
/// <summary>
/// Save the current save data to save.dat.
/// </summary>
public static void Save()
{
BunniesToSaveData();
BinaryFormatter bf = new BinaryFormatter();
using (FileStream file = File.Create(SaveDataPath))
{
bf.Serialize(file, SaveData.current);
}
Debug.Log("DATA SAVED");
}
/// <summary>
/// Load save data from save.dat.
/// </summary>
public static void Load()
{
if (SaveExists())
{
BinaryFormatter bf = new BinaryFormatter();
using (FileStream file = File.Open(SaveDataPath, FileMode.Open))
{
SaveData.current = (SaveData)bf.Deserialize(file);
}
Debug.Log("DATA LOADED");
}
else
{
SaveData.current = new SaveData();
Debug.Log("SAVE DATA NOT FOUND! NEW SAVE DATA CREATED!");
}
}
/// <summary>
/// Delete save.dat if it exists.
/// </summary>
public static void Delete()
{
if (!SaveExists())
return;
File.Delete(SaveDataPath);
Debug.Log("SAVE DATA DELETED!");
}
/// <summary>
/// Check whether save.dat exists.
/// </summary>
/// <returns>True if save.dat exists. False otherwise.</returns>
public static bool SaveExists()
{
return File.Exists(SaveDataPath);
}
/// <summary>
/// Get save data values for the bunnies from the game manager.
/// </summary>
private static void BunniesToSaveData()
{
GameManager gameManager = GameManager.Instance;
SaveData.current.bunnightName = gameManager.Bunnight.name;
SaveData.current.bunnightExp = gameManager.Bunnight.Experience;
SaveData.current.bunnecromancerName = gameManager.Bunnecromancer.name;
SaveData.current.bunnecromancerExp = gameManager.Bunnecromancer.Experience;
SaveData.current.bunnurseName = gameManager.Bunnurse.name;
SaveData.current.bunnurseExp = gameManager.Bunnurse.Experience;
SaveData.current.bunneerdowellName = gameManager.Bunneerdowell.name;
SaveData.current.bunneerdowellExp = gameManager.Bunneerdowell.Experience;
}
}
} | 32.337209 | 91 | 0.557713 | [
"MIT"
] | AlexGarbus/The-Bunnies-of-Vegetaria | Assets/Scripts/Save Data/SaveLoad.cs | 2,783 | C# |
using System;
namespace uri1006 // Média 2
{
internal static class Program
{
private static void Main()
{
double.TryParse(Console.ReadLine(), out double a);
double.TryParse(Console.ReadLine(), out double b);
double.TryParse(Console.ReadLine(), out double c);
Console.WriteLine($"MEDIA = {(((a * 2) + (b * 3) + (c * 5)) / 10).ToString("F1")}");
}
}
} | 29 | 96 | 0.542529 | [
"MIT"
] | filimor/uri-online-judge-c-sharp | UriOnlineJudge/Iniciante/uri1006/Program.cs | 438 | C# |
// Copyright 2004-2010 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Castle.Components.Validator
{
using System;
/// <summary>
/// Abstracts a JS validation library implementation.
/// Each implementation should map the calls to their
/// own approach to enforce validation.
/// </summary>
public interface IBrowserValidationGenerator
{
/// <summary>
/// Set that a field should only accept digits.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="violationMessage">The violation message.</param>
void SetDigitsOnly(string target, string violationMessage);
/// <summary>
/// Set that a field should only accept numbers.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="violationMessage">The violation message.</param>
void SetNumberOnly(string target, string violationMessage);
/// <summary>
/// Sets that a field is required.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="violationMessage">The violation message.</param>
void SetAsRequired(string target, string violationMessage);
/// <summary>
/// Sets that a field value must match the specified regular expression.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="regExp">The reg exp.</param>
/// <param name="violationMessage">The violation message.</param>
void SetRegExp(string target, string regExp, string violationMessage);
/// <summary>
/// Sets that a field value must be a valid email address.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="violationMessage">The violation message.</param>
void SetEmail(string target, string violationMessage);
/// <summary>
/// Sets that field must have an exact lenght.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="length">The length.</param>
void SetExactLength(string target, int length);
/// <summary>
/// Sets that field must have an exact lenght.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="length">The length.</param>
/// <param name="violationMessage">The violation message.</param>
void SetExactLength(string target, int length, string violationMessage);
/// <summary>
/// Sets that field must have an minimum lenght.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="minLength">The minimum length.</param>
void SetMinLength(string target, int minLength);
/// <summary>
/// Sets that field must have an minimum lenght.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="minLength">The minimum length.</param>
/// <param name="violationMessage">The violation message.</param>
void SetMinLength(string target, int minLength, string violationMessage);
/// <summary>
/// Sets that field must have an maximum lenght.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="maxLength">The maximum length.</param>
void SetMaxLength(string target, int maxLength);
/// <summary>
/// Sets that field must have an maximum lenght.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="maxLength">The maximum length.</param>
/// <param name="violationMessage">The violation message.</param>
void SetMaxLength(string target, int maxLength, string violationMessage);
/// <summary>
/// Sets that field must be between a length range.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="minLength">The minimum length.</param>
/// <param name="maxLength">The maximum length.</param>
void SetLengthRange(string target, int minLength, int maxLength);
/// <summary>
/// Sets that field must be between a length range.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="minLength">The minimum length.</param>
/// <param name="maxLength">The maximum length.</param>
/// <param name="violationMessage">The violation message.</param>
void SetLengthRange(string target, int minLength, int maxLength, string violationMessage);
/// <summary>
/// Sets that field must be between a value range.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="minValue">Minimum value.</param>
/// <param name="maxValue">Maximum value.</param>
/// <param name="violationMessage">The violation message.</param>
void SetValueRange(string target, int minValue, int maxValue, string violationMessage);
/// <summary>
/// Sets that field must be between a value range.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="minValue">Minimum value.</param>
/// <param name="maxValue">Maximum value.</param>
/// <param name="violationMessage">The violation message.</param>
void SetValueRange(string target, decimal minValue, decimal maxValue, string violationMessage);
/// <summary>
/// Sets that field must be between a value range.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="minValue">Minimum value.</param>
/// <param name="maxValue">Maximum value.</param>
/// <param name="violationMessage">The violation message.</param>
void SetValueRange(string target, DateTime minValue, DateTime maxValue, string violationMessage);
/// <summary>
/// Sets that field must be between a value range.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="minValue">Minimum value.</param>
/// <param name="maxValue">Maximum value.</param>
/// <param name="violationMessage">The violation message.</param>
void SetValueRange(string target, string minValue, string maxValue, string violationMessage);
/// <summary>
/// Set that a field value must be the same as another field's value.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="comparisonFieldName">The name of the field to compare with.</param>
/// <param name="violationMessage">The violation message.</param>
void SetAsSameAs(string target, string comparisonFieldName, string violationMessage);
/// <summary>
/// Set that a field value must _not_ be the same as another field's value.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="comparisonFieldName">The name of the field to compare with.</param>
/// <param name="violationMessage">The violation message.</param>
void SetAsNotSameAs(string target, string comparisonFieldName, string violationMessage);
/// <summary>
/// Set that a field value must be a valid date.
/// </summary>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="violationMessage">The violation message.</param>
void SetDate(string target, string violationMessage);
/// <summary>
/// Sets that a field's value must be greater than another field's value.
/// </summary>
/// <remarks>Not implemented by the JQuery validate plugin. Done via a custom rule.</remarks>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="comparisonFieldName">The name of the field to compare with.</param>
/// <param name="validationType">The type of data to compare.</param>
/// <param name="violationMessage">The violation message.</param>
void SetAsGreaterThan(string target, string comparisonFieldName, IsGreaterValidationType validationType,string violationMessage);
/// <summary>
/// Sets that a field's value must be lesser than another field's value.
/// </summary>
/// <remarks>Not implemented by the JQuery validate plugin. Done via a custom rule.</remarks>
/// <param name="target">The target name (ie, a hint about the controller being validated)</param>
/// <param name="comparisonFieldName">The name of the field to compare with.</param>
/// <param name="validationType">The type of data to compare.</param>
/// <param name="violationMessage">The violation message.</param>
void SetAsLesserThan( string target, string comparisonFieldName, IsLesserValidationType validationType, string violationMessage );
/// <summary>
/// Sets that a flied is part of a group validation.
/// </summary>
/// <remarks>Not implemented by the JQuery validate plugin. Done via a custom rule.</remarks>
/// <param name="target">The target.</param>
/// <param name="groupName">Name of the group.</param>
/// <param name="violationMessage">The violation message.</param>
void SetAsGroupValidation(string target, string groupName, string violationMessage);
}
}
| 48.15493 | 132 | 0.706834 | [
"Apache-2.0"
] | hach-que/Castle.Core | src/Castle.Components.Validator/IBrowserValidationGenerator.cs | 10,257 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace XUnity.AutoTranslator.Plugin.Core.Utilities
{
internal static class EnumHelper
{
public static string GetNames( Type flagType, object value )
{
var attr = (FlagsAttribute)flagType.GetCustomAttributes( typeof( FlagsAttribute ), false ).FirstOrDefault();
if( attr == null )
{
return Enum.GetName( flagType, value );
}
else
{
var validEnumValues = Enum.GetValues( flagType );
var stringValues = Enum.GetNames( flagType );
var names = string.Empty;
foreach( var stringValue in stringValues )
{
var parsedEnumValue = Enum.Parse( flagType, stringValue, true );
foreach( var validEnumValue in validEnumValues )
{
long validIntegerValue = Convert.ToInt64( validEnumValue );
long integerValue = Convert.ToInt64( value );
if( ( integerValue & validIntegerValue ) != 0 && Equals( parsedEnumValue, validEnumValue ) )
{
names += stringValue + ";";
break;
}
}
}
if( names.EndsWith( ";" ) )
{
names = names.Substring( 0, names.Length - 1 );
}
return names;
}
}
public static object GetValues( Type flagType, string commaSeparatedStringValue )
{
var attr = (FlagsAttribute)flagType.GetCustomAttributes( typeof( FlagsAttribute ), false ).FirstOrDefault();
if( attr == null )
{
return Enum.Parse( flagType, commaSeparatedStringValue, true );
}
else
{
var stringValues = commaSeparatedStringValue.Split( new char[] { ';', ' ' }, StringSplitOptions.RemoveEmptyEntries );
var validEnumValues = Enum.GetValues( flagType );
var underlyingType = Enum.GetUnderlyingType( flagType );
long flagValues = 0;
foreach( var stringValue in stringValues )
{
bool found = false;
foreach( var validEnumValue in validEnumValues )
{
var validStringValue = Enum.GetName( flagType, validEnumValue );
if( string.Equals( stringValue, validStringValue, StringComparison.OrdinalIgnoreCase ) )
{
var validInteger = Convert.ToInt64( validEnumValue );
flagValues |= validInteger;
found = true;
}
}
if( !found )
{
throw new ArgumentException( $"Requested value '{stringValue}' was not found." );
}
}
return Convert.ChangeType( flagValues, Enum.GetUnderlyingType( flagType ) );
}
}
}
}
| 35.093023 | 129 | 0.532472 | [
"MIT"
] | Divers102/XUnity.AutoTranslator | src/XUnity.AutoTranslator.Plugin.Core/Utilities/EnumHelper.cs | 3,020 | C# |
/**
* Copyright 2015 Canada Health Infoway, 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.
*
* Author: $LastChangedBy: jmis $
* Last modified: $LastChangedDate: 2015-09-15 10:16:16 -0400 (Tue, 15 Sep 2015) $
* Revision: $LastChangedRevision: 9772 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2007_v02_r02.Interaction {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Model;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2007_v02_r02.Common.Comt_mt001103ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2007_v02_r02.Common.Mcai_mt700226ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_mr2007_v02_r02.Common.Mcci_mt002300ca;
/**
* <summary>Business Name: PORX_IN020090CA: Record dispense
* pickup request accepted</summary>
*
* <p>Indicates that the pickup of the prescription has been
* recorded as requested</p> Message: MCCI_MT002300CA.Message
* Control Act: MCAI_MT700226CA.ControlActEvent --> Payload:
* COMT_MT001103CA.ActEvent
*/
[Hl7PartTypeMappingAttribute(new string[] {"PORX_IN020090CA"})]
public class RecordDispensePickupRequestAccepted : HL7Message<Ca.Infoway.Messagebuilder.Model.Pcs_mr2007_v02_r02.Common.Mcai_mt700226ca.TriggerEvent<Ca.Infoway.Messagebuilder.Model.Pcs_mr2007_v02_r02.Common.Comt_mt001103ca.ReferencedRecord>>, IInteraction {
public RecordDispensePickupRequestAccepted() {
}
}
} | 45.630435 | 262 | 0.732253 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-v02_r02/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2007_v02_r02/Interaction/RecordDispensePickupRequestAccepted.cs | 2,099 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace cfg.ai
{
public sealed class UeBlackboard : ai.Decorator
{
public UeBlackboard(JSONNode _json) : base(_json)
{
{ if(!_json["notify_observer"].IsNumber) { throw new SerializationException(); } NotifyObserver = (ai.ENotifyObserverMode)_json["notify_observer"].AsInt; }
{ if(!_json["blackboard_key"].IsString) { throw new SerializationException(); } BlackboardKey = _json["blackboard_key"]; }
{ if(!_json["key_query"].IsObject) { throw new SerializationException(); } KeyQuery = ai.KeyQueryOperator.DeserializeKeyQueryOperator(_json["key_query"]); }
}
public UeBlackboard(int id, string node_name, ai.EFlowAbortMode flow_abort_mode, ai.ENotifyObserverMode notify_observer, string blackboard_key, ai.KeyQueryOperator key_query ) : base(id,node_name,flow_abort_mode)
{
this.NotifyObserver = notify_observer;
this.BlackboardKey = blackboard_key;
this.KeyQuery = key_query;
}
public static UeBlackboard DeserializeUeBlackboard(JSONNode _json)
{
return new ai.UeBlackboard(_json);
}
public ai.ENotifyObserverMode NotifyObserver { get; private set; }
public string BlackboardKey { get; private set; }
public ai.KeyQueryOperator KeyQuery { get; private set; }
public const int __ID__ = -315297507;
public override int GetTypeId() => __ID__;
public override void Resolve(Dictionary<string, object> _tables)
{
base.Resolve(_tables);
KeyQuery?.Resolve(_tables);
}
public override void TranslateText(System.Func<string, string, string> translator)
{
base.TranslateText(translator);
KeyQuery?.TranslateText(translator);
}
public override string ToString()
{
return "{ "
+ "Id:" + Id + ","
+ "NodeName:" + NodeName + ","
+ "FlowAbortMode:" + FlowAbortMode + ","
+ "NotifyObserver:" + NotifyObserver + ","
+ "BlackboardKey:" + BlackboardKey + ","
+ "KeyQuery:" + KeyQuery + ","
+ "}";
}
}
}
| 35.514286 | 218 | 0.622687 | [
"MIT"
] | focus-creative-games/luban_examples | Projects/Csharp_Unity_json/Assets/Gen/ai/UeBlackboard.cs | 2,486 | C# |
using System;
namespace UAlbion.Formats.Assets
{
[Flags]
public enum ItemSlotFlags : byte
{
ExtraInfo = 1,
Broken = 2,
Cursed = 4,
Unk3,
Unk4,
Unk5,
Unk6,
Unk7,
}
} | 14.470588 | 36 | 0.471545 | [
"MIT"
] | mrwillbarnz/ualbion | Formats/Assets/ItemSlotFlags.cs | 248 | C# |
using FluentAssertions;
using NUnit.Framework;
using TechTalk.SpecFlow.IdeIntegration.Services;
namespace TechTalk.SpecFlow.IdeIntegration.UnitTests
{
public class FileSystemTests
{
[TestCase(@"C:/PathToDirectory/", @"C:/PathToDirectory/")]
[TestCase(@"C:/PathToDirectory", @"C:/PathToDirectory/")]
[TestCase(@"C:\PathToDirectory\", @"C:\PathToDirectory\")]
[TestCase(@"C:\PathToDirectory", @"C:\PathToDirectory\")]
[TestCase(@"C:\PathToDirectory ", @"C:\PathToDirectory\")]
[TestCase(@"PathToDirectory", @"PathToDirectory\")]
public void AppendDirectorySeparatorIfNotPresent_Path_ShouldReturnCorrectPath(string inputPath, string expectedPath)
{
// ARRANGE
var fileSystem = new FileSystem();
// ACT
string actualPath = fileSystem.AppendDirectorySeparatorIfNotPresent(inputPath);
// ASSERT
actualPath.Should().Be(expectedPath);
}
}
}
| 35.642857 | 124 | 0.647295 | [
"BSD-3-Clause"
] | 304NotModified/SpecFlow.VisualStudio | UnitTests/IdeIntegration.UnitTests/FileSystemTests.cs | 1,000 | C# |
using Symbolica.Expression;
namespace Symbolica.Abstraction;
public interface ICaller
{
InstructionId Id { get; }
Bits Size { get; }
IAttributes ReturnAttributes { get; }
void Return(IState state);
}
| 16.923077 | 41 | 0.704545 | [
"MIT"
] | Symbolica/Symbolica | src/Abstraction/ICaller.cs | 222 | C# |
// SF API version v41.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// External Data Source
///<para>SObject Name: ExternalDataSource</para>
///<para>Custom Object: False</para>
///</summary>
public class SfExternalDataSource : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ExternalDataSource"; }
}
///<summary>
/// External Data Source ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Name
/// <para>Name: DeveloperName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "developerName")]
[Updateable(false), Createable(false)]
public string DeveloperName { get; set; }
///<summary>
/// Master Language
/// <para>Name: Language</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "language")]
[Updateable(false), Createable(false)]
public string Language { get; set; }
///<summary>
/// External Data Source
/// <para>Name: MasterLabel</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "masterLabel")]
[Updateable(false), Createable(false)]
public string MasterLabel { get; set; }
///<summary>
/// Namespace Prefix
/// <para>Name: NamespacePrefix</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "namespacePrefix")]
[Updateable(false), Createable(false)]
public string NamespacePrefix { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Class ID
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// URL
/// <para>Name: Endpoint</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "endpoint")]
[Updateable(false), Createable(false)]
public string Endpoint { get; set; }
///<summary>
/// Default External Repository
/// <para>Name: Repository</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "repository")]
[Updateable(false), Createable(false)]
public string Repository { get; set; }
///<summary>
/// Writable External Objects
/// <para>Name: IsWritable</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isWritable")]
[Updateable(false), Createable(false)]
public bool? IsWritable { get; set; }
///<summary>
/// Identity Type
/// <para>Name: PrincipalType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "principalType")]
[Updateable(false), Createable(false)]
public string PrincipalType { get; set; }
///<summary>
/// Authentication Protocol
/// <para>Name: Protocol</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "protocol")]
[Updateable(false), Createable(false)]
public string Protocol { get; set; }
///<summary>
/// Auth. Provider ID
/// <para>Name: AuthProviderId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "authProviderId")]
[Updateable(false), Createable(false)]
public string AuthProviderId { get; set; }
///<summary>
/// ReferenceTo: AuthProvider
/// <para>RelationshipName: AuthProvider</para>
///</summary>
[JsonProperty(PropertyName = "authProvider")]
[Updateable(false), Createable(false)]
public SfAuthProvider AuthProvider { get; set; }
///<summary>
/// Static Resource ID
/// <para>Name: LargeIconId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "largeIconId")]
[Updateable(false), Createable(false)]
public string LargeIconId { get; set; }
///<summary>
/// ReferenceTo: StaticResource
/// <para>RelationshipName: LargeIcon</para>
///</summary>
[JsonProperty(PropertyName = "largeIcon")]
[Updateable(false), Createable(false)]
public SfStaticResource LargeIcon { get; set; }
///<summary>
/// Static Resource ID
/// <para>Name: SmallIconId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "smallIconId")]
[Updateable(false), Createable(false)]
public string SmallIconId { get; set; }
///<summary>
/// ReferenceTo: StaticResource
/// <para>RelationshipName: SmallIcon</para>
///</summary>
[JsonProperty(PropertyName = "smallIcon")]
[Updateable(false), Createable(false)]
public SfStaticResource SmallIcon { get; set; }
///<summary>
/// Custom Configuration
/// <para>Name: CustomConfiguration</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "customConfiguration")]
[Updateable(false), Createable(false)]
public string CustomConfiguration { get; set; }
}
}
| 28.703971 | 55 | 0.654132 | [
"MIT"
] | keylightberlin/NetCoreForce | src/NetCoreForce.Models/SfExternalDataSource.cs | 7,951 | C# |
namespace Questar.OneRoster.Api.Models
{
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
public class DeleteParams : Params
{
[Required]
[FromRoute]
public string SourcedId { get; set; }
}
} | 22 | 48 | 0.659091 | [
"MIT"
] | QuestarAI/OneRoster | src/Questar.OneRoster.Api/Models/DeleteParams.cs | 264 | C# |
using Neo.SmartContract.Framework;
using Neo.SmartContract.Framework.Services.Neo;
using System;
using System.Numerics;
using System.Text;
namespace NeoContractTest1
{
public class Contract1 : SmartContract
{
private static bool Main(string domain, string name, string subname)
{
byte[] namehash = Hash256(domain.AsByteArray().Concat(name.AsByteArray()).Concat(subname.AsByteArray()));
var owner = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 };
byte[] zeroByte32 = new byte[32];
if (owner == zeroByte32)
{
return true;
}
else
{
return false;
}
}
}
}
| 23.4 | 134 | 0.516484 | [
"MIT"
] | combchain/cns | NeoContractTest1/Contract1.cs | 821 | C# |
using Ashirvad.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ashirvad.ServiceAPI.ServiceAPI.Area.Standard
{
public interface IStandardService
{
Task<StandardEntity> StandardMaintenance(StandardEntity standardInfo);
Task<List<StandardEntity>> GetAllStandards(long branchID);
bool RemoveStandard(long StandardID, string lastupdatedby);
Task<StandardEntity> GetStandardsByID(long schoolID);
Task<List<StandardEntity>> GetAllStandardsName(long branchid);
Task<List<StandardEntity>> GetAllStandardsID(string standardname, long branchid);
}
}
| 34.2 | 89 | 0.76462 | [
"MIT"
] | ShailUniqtech/Ashirvad | Ashirvad-main/Ashirvad.ServiceAPI/ServiceAPI/Area/Standard/IStandardService.cs | 686 | C# |
using System.Collections.Generic;
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.
*/
namespace org.camunda.bpm.engine.rest.dto.externaltask
{
/// <summary>
/// @author Thorben Lindhauer
///
/// </summary>
public class CompleteExternalTaskDto
{
protected internal string workerId;
protected internal IDictionary<string, VariableValueDto> variables;
protected internal IDictionary<string, VariableValueDto> localVariables;
public virtual string WorkerId
{
get
{
return workerId;
}
set
{
this.workerId = value;
}
}
public virtual IDictionary<string, VariableValueDto> Variables
{
get
{
return variables;
}
set
{
this.variables = value;
}
}
public virtual IDictionary<string, VariableValueDto> LocalVariables
{
get
{
return localVariables;
}
set
{
this.localVariables = value;
}
}
}
} | 22.743243 | 80 | 0.705288 | [
"Apache-2.0"
] | luizfbicalho/Camunda.NET | camunda-bpm-platform-net/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/CompleteExternalTaskDto.cs | 1,685 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using OpenCvSharp;
using OpenCvSharp.Dnn;
using System.Threading.Tasks;
public class PoseCamera : MonoBehaviour
{
int inWidth = 368;
int inHeight = 368;
int nPoints = 18;
float thresh = 0.1f;
int frameWidth = 0;
int frameHeight = 0;
Mat frameCopy = new Mat();
VideoCapture videoCapture;
Texture2D texture2D;
public static List<Point> KeyPoints { get; set; }
private Net net;
void Start()
{
this.net = CvDnn.ReadNetFromOnnx(Application.streamingAssetsPath + "/human-pose-estimation.onnx");
this.videoCapture = new VideoCapture(0);
Renderer renderer = GetComponent<Renderer>();
texture2D = new Texture2D(640, 480, TextureFormat.RGBA32, true, true);
renderer.material.mainTexture = texture2D;
}
private void Estimate(Mat frame)
{
frameWidth = frame.Width;
frameHeight = frame.Height;
frame.CopyTo(frameCopy);
Mat inpBlob = CvDnn.BlobFromImage(frame, 1.0 / 255, new Size(inWidth, inHeight), new Scalar(0, 0, 0), false, false);
net.SetInput(inpBlob);
List<Mat> outputs = new List<Mat>()
{
new Mat(),
new Mat()
};
net.Forward(outputs, new string[]{
"stage_1_output_1_heatmaps",
"stage_1_output_0_pafs"
});
GetKeyPoints(outputs[0]);
}
private List<Point> GetKeyPoints(Mat output)
{
int H = output.Size(2);
int W = output.Size(3);
// find the position of the body parts
var points = new List<Point>();
for (int n = 0; n < nPoints; n++)
{
// Probability map of corresponding body's part.
Mat probMap = new Mat(H, W, MatType.CV_32F, output.Ptr(0, n));
Point2f p = new Point2f(-1, -1);
Point maxLoc;
Point minLoc;
double prob;
double minVal;
Cv2.MinMaxLoc(probMap, out minVal, out prob, out minLoc, out maxLoc);
if (prob > thresh)
{
p = maxLoc;
p.X *= (float)frameWidth / W;
p.Y *= (float)frameHeight / H;
Cv2.Circle(frameCopy, new Point((int)p.X, (int)p.Y), 8, new Scalar(0, 255, 255), -1);
Cv2.PutText(frameCopy, n.ToString(), new Point((int)p.X, (int)p.Y), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 2);
}
points.Add((Point)p);
}
return points;
}
void Update()
{
if(videoCapture.IsOpened())
{
Mat frame = new Mat();
bool success = this.videoCapture.Read(frame);
if (success)
{
Estimate(frame);
texture2D.LoadImage(frame.ImEncode());
}
}
}
} | 25.66087 | 142 | 0.544561 | [
"Apache-2.0"
] | Wonder-Tree/PoseCamera-C-Sharp | Assets/PoseCamera.cs | 2,953 | C# |
using System.Linq;
using NUnit.Framework;
using PatternPA.Utils.Huffman.Impl;
using PatternPA.Utils.Huffman.Interface;
namespace PatternPA.Test.Utils.Huffman
{
[TestFixture]
public class CanonicalWordProbabilityTest
{
[TestCase("0010000200222", 1, 13)]
[TestCase("0010000200222", 2, 7)]
[TestCase("0010000200222", 4, 4)]
[TestCase("0010000200222", 7, 2)]
[TestCase("0010000200222", 9, 2)]
[TestCase("0010000200222", 12, 2)]
[TestCase("0010000200222", 13, 1)]
[TestCase("0010000200222", 14, 1)]
[TestCase("0010000200222", 28, 1)]
public void MapToWordsTest(string sequence, int wordSize, int expectedCount)
{
IWordProbability wp = new CanonicalWordProbability();
var map = wp.MapToWords(sequence, wordSize);
Assert.AreEqual(expectedCount, map.Count());
}
[Test]
public void ReduceToWordsProbabilityTest()
{
IWordProbability wp = new CanonicalWordProbability();
var map = wp.MapToWords("0010000200222", 2);
var result = wp.ReduceToWordsProbability(map);
Assert.AreEqual(5, result.Count);
}
}
} | 32.342105 | 84 | 0.615948 | [
"Apache-2.0"
] | o-mdr/pa-pattern-complexity | src/old/test/PatternPA.Test.Utils/Huffman/CanonicalWordProbabilityTest.cs | 1,231 | C# |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* 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;
using System.Collections.Generic;
using System.Threading;
using MindTouch.Dream;
namespace MindTouch.Threading.Timer {
/// <summary>
/// Provides a global timing mechanism that accepts registration of callback to be invoked by the clock. In most cases, a
/// <see cref="TaskTimer"/> should be used rather than registering a callback directly with the global clock.
/// </summary>
public static class GlobalClock {
//--- Constants ---
private const int INITIAL_CALLBACK_CAPACITY = 8;
//--- Class Fields ---
private static readonly object _syncRoot = new object();
private static readonly log4net.ILog _log = LogUtils.CreateLog();
private static volatile bool _running = true;
private static readonly ManualResetEvent _stopped = new ManualResetEvent(false);
private static KeyValuePair<string, Action<DateTime,TimeSpan>>[] _callbacks = new KeyValuePair<string, Action<DateTime,TimeSpan>>[INITIAL_CALLBACK_CAPACITY];
private static readonly int _intervalMilliseconds;
//--- Class Constructor ---
static GlobalClock() {
// TODO (steveb): make global clock interval configurable via app settings
_intervalMilliseconds = 100;
// start-up the tick thread for all global timed callbacks
new Thread(MasterTickThread) { Priority = ThreadPriority.Highest, IsBackground = true, Name = "GlobalClock" }.Start();
}
//--- Class Methods ---
/// <summary>
/// Add a named callback to the clock.
/// </summary>
/// <param name="name">Unique key for the callback.</param>
/// <param name="callback">Callback action.</param>
public static void AddCallback(string name, Action<DateTime,TimeSpan> callback) {
if(string.IsNullOrEmpty(name)) {
throw new ArgumentNullException("name", "name cannot be null or empty");
}
if(callback == null) {
throw new ArgumentNullException("callback");
}
// add callback
lock(_syncRoot) {
int index;
// check if there is an empty slot in the callbacks array
for(index = 0; index < _callbacks.Length; ++index) {
if(_callbacks[index].Value == null) {
_callbacks[index] = new KeyValuePair<string, Action<DateTime,TimeSpan>>(name, callback);
return;
}
}
// make room to add a new thread by doubling the array size and copying over the existing entries
var newArray = new KeyValuePair<string, Action<DateTime,TimeSpan>>[2 * _callbacks.Length];
Array.Copy(_callbacks, newArray, _callbacks.Length);
// assign new thread
newArray[index] = new KeyValuePair<string, Action<DateTime,TimeSpan>>(name, callback);
// update instance field
_callbacks = newArray;
}
}
/// <summary>
/// Remove a callback by reference.
/// </summary>
/// <param name="callback">Callback to remove.</param>
public static void RemoveCallback(Action<DateTime,TimeSpan> callback) {
// remove callback
lock(_syncRoot) {
for(int i = 0; i < _callbacks.Length; ++i) {
if(_callbacks[i].Value == callback) {
_callbacks[i] = new KeyValuePair<string, Action<DateTime, TimeSpan>>(null, null);
}
}
}
}
internal static bool Shutdown(TimeSpan timeout) {
// stop the thread timer
_running = false;
if((timeout != TimeSpan.MaxValue && !_stopped.WaitOne((int)timeout.TotalMilliseconds, true)) || (timeout == TimeSpan.MaxValue && !_stopped.WaitOne())
) {
_log.ErrorExceptionMethodCall(new TimeoutException("GlobalClock thread shutdown timed out"), "Shutdown");
return false;
}
return true;
}
private static void MasterTickThread(object _unused) {
DateTime last = DateTime.UtcNow;
while(_running) {
// wait until next iteration
Thread.Sleep(_intervalMilliseconds);
// get current time and calculate delta
DateTime now = DateTime.UtcNow;
TimeSpan elapsed = now - last;
last = now;
// execute all callbacks
lock(_syncRoot) {
var callbacks = _callbacks;
foreach(KeyValuePair<string, Action<DateTime, TimeSpan>> callback in callbacks) {
if(callback.Value != null) {
try {
callback.Value(now, elapsed);
} catch(Exception e) {
_log.ErrorExceptionMethodCall(e, "GlobalClock callback failed", callback.Key);
}
}
}
}
}
// indicate that this thread has exited
_stopped.Set();
}
}
}
| 40.596154 | 166 | 0.56403 | [
"Apache-2.0"
] | yurigorokhov/DReAM | src/mindtouch.dream/Threading/Timer/GlobalClock.cs | 6,333 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Akka.Event;
using Akka.TestKit;
using Akka.Util;
using Akka.Util.Internal;
using Xunit;
namespace Akka.Remote.Tests
{
public class AckedDeliverySpec : AkkaSpec
{
sealed class Sequenced : IHasSequenceNumber
{
public Sequenced(SeqNo seq, string body)
{
Body = body;
Seq = seq;
}
public SeqNo Seq { get; private set; }
public string Body { get; private set; }
public override string ToString()
{
return string.Format("MSG[{0}]]", Seq.RawValue);
}
}
private Sequenced Msg(long seq) { return new Sequenced(seq, "msg" + seq); }
[Fact]
public void SeqNo_must_implement_simple_ordering()
{
var sm1 = new SeqNo(-1);
var s0 = new SeqNo(0);
var s1 = new SeqNo(1);
var s2 = new SeqNo(2);
var s0b = new SeqNo(0);
Assert.True(sm1 < s0);
Assert.False(sm1 > s0);
Assert.True(s0 < s1);
Assert.False(s0 > s1);
Assert.True(s1 < s2);
Assert.False(s1 > s2);
Assert.True(s0b == s0);
}
[Fact]
public void SeqNo_must_correctly_handle_wrapping_over()
{
var s1 = new SeqNo(long.MaxValue - 1);
var s2 = new SeqNo(long.MaxValue);
var s3 = new SeqNo(long.MinValue);
var s4 = new SeqNo(long.MinValue + 1);
Assert.True(s1 < s2);
Assert.False(s1 > s2);
Assert.True(s2 < s3);
Assert.False(s2 > s3);
Assert.True(s3 < s4);
Assert.False(s3 > s4);
}
[Fact]
public void SeqNo_must_correctly_handle_large_gaps()
{
var smin = new SeqNo(long.MinValue);
var smin2 = new SeqNo(long.MinValue + 1);
var s0 = new SeqNo(0);
Assert.True(s0 < smin);
Assert.False(s0 > smin);
Assert.True(smin2 < s0);
Assert.False(smin2 > s0);
}
[Fact]
public void SeqNo_must_handle_overflow()
{
var s1 = new SeqNo(long.MaxValue - 1);
var s2 = new SeqNo(long.MaxValue);
var s3 = new SeqNo(long.MinValue);
var s4 = new SeqNo(long.MinValue + 1);
Assert.True(s1.Inc() == s2);
Assert.True(s2.Inc() == s3);
Assert.True(s3.Inc() == s4);
}
[Fact]
public void SendBuffer_must_aggregate_unacked_messages_in_order()
{
var b0 = new AckedSendBuffer<Sequenced>(10);
var msg0 = Msg(0);
var msg1 = Msg(1);
var msg2 = Msg(2);
var b1 = b0.Buffer(msg0);
Assert.True(b1.NonAcked.SequenceEqual(new[]{msg0}));
var b2 = b1.Buffer(msg1);
Assert.True(b2.NonAcked.SequenceEqual(new[] { msg0, msg1 }));
var b3 = b2.Buffer(msg2);
Assert.True(b3.NonAcked.SequenceEqual(new[] { msg0, msg1, msg2 }));
}
[Fact]
public void SendBuffer_must_refuse_buffering_new_messages_if_capacity_reached()
{
var buffer = new AckedSendBuffer<Sequenced>(4).Buffer(Msg(0)).Buffer(Msg(1)).Buffer(Msg(2)).Buffer(Msg(3));
XAssert.Throws<ResendBufferCapacityReachedException>(() => buffer.Buffer(Msg(4)));
}
[Fact]
public void SendBuffer_must_remove_messages_from_buffer_when_cumulative_ack_received()
{
var b0 = new AckedSendBuffer<Sequenced>(10);
var msg0 = Msg(0);
var msg1 = Msg(1);
var msg2 = Msg(2);
var msg3 = Msg(3);
var msg4 = Msg(4);
var b1 = b0.Buffer(msg0);
Assert.True(b1.NonAcked.SequenceEqual(new[] { msg0 }));
var b2 = b1.Buffer(msg1);
Assert.True(b2.NonAcked.SequenceEqual(new[] { msg0, msg1 }));
var b3 = b2.Buffer(msg2);
Assert.True(b3.NonAcked.SequenceEqual(new[] { msg0, msg1, msg2 }));
var b4 = b3.Acknowledge(new Ack(new SeqNo(1)));
Assert.True(b4.NonAcked.SequenceEqual(new[]{ msg2 }));
var b5 = b4.Buffer(msg3);
Assert.True(b5.NonAcked.SequenceEqual(new []{ msg2,msg3 }));
var b6 = b5.Buffer(msg4);
Assert.True(b6.NonAcked.SequenceEqual(new[] { msg2, msg3, msg4 }));
var b7 = b6.Acknowledge(new Ack(new SeqNo(1)));
Assert.True(b7.NonAcked.SequenceEqual(new[] { msg2, msg3, msg4 }));
var b8 = b7.Acknowledge(new Ack(new SeqNo(2)));
Assert.True(b8.NonAcked.SequenceEqual(new[] { msg3, msg4 }));
var b9 = b8.Acknowledge(new Ack(new SeqNo(5)));
Assert.True(b9.NonAcked.Count == 0);
}
[Fact]
public void SendBuffer_must_keep_NACKed_messages_in_buffer_if_selective_nacks_are_received()
{
var b0 = new AckedSendBuffer<Sequenced>(10);
var msg0 = Msg(0);
var msg1 = Msg(1);
var msg2 = Msg(2);
var msg3 = Msg(3);
var msg4 = Msg(4);
var b1 = b0.Buffer(msg0);
Assert.True(b1.NonAcked.SequenceEqual(new[] { msg0 }));
var b2 = b1.Buffer(msg1);
Assert.True(b2.NonAcked.SequenceEqual(new[] { msg0, msg1 }));
var b3 = b2.Buffer(msg2);
Assert.True(b3.NonAcked.SequenceEqual(new[] { msg0, msg1, msg2 }));
var b4 = b3.Acknowledge(new Ack(new SeqNo(1), new [] {new SeqNo(0)}));
Assert.True(b4.NonAcked.SequenceEqual(new []{ msg2 }));
Assert.True(b4.Nacked.SequenceEqual(new[] { msg0 }));
var b5 = b4.Buffer(msg3).Buffer(msg4);
Assert.True(b5.NonAcked.SequenceEqual(new[] { msg2, msg3, msg4 }));
Assert.True(b5.Nacked.SequenceEqual(new[] { msg0 }));
var b6 = b5.Acknowledge(new Ack(new SeqNo(4), new []{new SeqNo(2), new SeqNo(3)}));
Assert.True(b6.NonAcked.Count == 0);
Assert.True(b6.Nacked.SequenceEqual(new[] { msg2, msg3 }));
var b7 = b6.Acknowledge(new Ack(new SeqNo(5)));
Assert.True(b7.NonAcked.Count == 0);
Assert.True(b7.Nacked.Count == 0);
}
[Fact]
public void SendBuffer_must_throw_exception_if_nonbuffered_sequence_number_is_NACKed()
{
var b0 = new AckedSendBuffer<Sequenced>(10);
var msg1 = Msg(1);
var msg2 = Msg(2);
var b1 = b0.Buffer(msg1).Buffer(msg2);
XAssert.Throws<ResendUnfulfillableException>(() => b1.Acknowledge(new Ack(new SeqNo(2), new []{ new SeqNo(0) })));
}
[Fact]
public void ReceiveBuffer_must_enqueue_message_in_buffer_if_needed_return_the_list_of_deliverable_messages_and_acks()
{
var b0 = new AckedReceiveBuffer<Sequenced>();
var msg0 = Msg(0);
var msg1 = Msg(1);
var msg2 = Msg(2);
var msg3 = Msg(3);
var msg4 = Msg(4);
var msg5 = Msg(5);
var d1 = b0.Receive(msg1).ExtractDeliverable;
Assert.True(d1.Deliverables.Count == 0);
Assert.Equal(new SeqNo(1), d1.Ack.CumulativeAck);
Assert.True(d1.Ack.Nacks.SequenceEqual(new[]{ new SeqNo(0) }));
var b1 = d1.Buffer;
var d2 = b1.Receive(msg0).ExtractDeliverable;
Assert.True(d2.Deliverables.SequenceEqual(new[] { msg0, msg1 }));
Assert.Equal(new SeqNo(1), d2.Ack.CumulativeAck);
var b3 = d2.Buffer;
var d3 = b3.Receive(msg4).ExtractDeliverable;
Assert.True(d3.Deliverables.Count == 0);
Assert.Equal(new SeqNo(4), d3.Ack.CumulativeAck);
Assert.True(d3.Ack.Nacks.SequenceEqual(new[] { new SeqNo(2), new SeqNo(3) }));
var b4 = d3.Buffer;
var d4 = b4.Receive(msg2).ExtractDeliverable;
Assert.True(d4.Deliverables.SequenceEqual(new[] { msg2 }));
Assert.Equal(new SeqNo(4), d4.Ack.CumulativeAck);
Assert.True(d4.Ack.Nacks.SequenceEqual(new[] { new SeqNo(3) }));
var b5 = d4.Buffer;
var d5 = b5.Receive(msg5).ExtractDeliverable;
Assert.True(d5.Deliverables.Count == 0);
Assert.Equal(new SeqNo(5), d5.Ack.CumulativeAck);
Assert.True(d5.Ack.Nacks.SequenceEqual(new[] { new SeqNo(3) }));
var b6 = d5.Buffer;
var d6 = b6.Receive(msg3).ExtractDeliverable;
Assert.True(d6.Deliverables.SequenceEqual(new[] { msg3, msg4, msg5 }));
Assert.Equal(new SeqNo(5), d6.Ack.CumulativeAck);
}
[Fact]
public void ReceiveBuffer_must_handle_duplicate_arrivals_correctly()
{
var buf = new AckedReceiveBuffer<Sequenced>();
var msg0 = Msg(0);
var msg1 = Msg(1);
var msg2 = Msg(2);
var buf2 = buf.Receive(msg0).Receive(msg1).Receive(msg2).ExtractDeliverable.Buffer;
var buf3 = buf2.Receive(msg0).Receive(msg1).Receive(msg2);
var d = buf3.ExtractDeliverable;
Assert.True(d.Deliverables.Count == 0);
Assert.Equal(new SeqNo(2), d.Ack.CumulativeAck);
}
[Fact]
public void ReceiveBuffer_must_be_able_to_correctly_merge_with_another_receive_buffer()
{
var buf1 = new AckedReceiveBuffer<Sequenced>();
var buf2 = new AckedReceiveBuffer<Sequenced>();
var msg0 = Msg(0);
var msg1a = Msg(1);
var msg1b = Msg(1);
var msg2 = Msg(2);
var msg3 = Msg(3);
var buf = buf1.Receive(msg1a).Receive(msg2).MergeFrom(buf2.Receive(msg1b).Receive(msg3));
var d = buf.Receive(msg0).ExtractDeliverable;
Assert.True(d.Deliverables.SequenceEqual(new []{ msg0, msg1b, msg2, msg3 }));
Assert.Equal(new SeqNo(3), d.Ack.CumulativeAck);
}
#region Receive + Send Buffer Tests
public bool Happened(double p) { return ThreadLocalRandom.Current.NextDouble() < p; }
public int Geom(Double p, int limit = 5, int acc = 0)
{
while (true)
{
if (acc == limit) return acc;
if (Happened(p)) return acc;
acc = acc + 1;
}
}
[Fact]
public void SendBuffer_and_ReceiveBuffer_must_correctly_cooperate_with_each_other()
{
var msgCount = 1000;
var deliveryProbability = 0.5D;
var referenceList = Enumerable.Range(0, msgCount).Select(x => Msg(x)).ToList();
var toSend = referenceList;
var received = new List<Sequenced>();
var sndBuf = new AckedSendBuffer<Sequenced>(10);
var rcvBuf = new AckedReceiveBuffer<Sequenced>();
var log = new List<string>();
var lastAck = new Ack(new SeqNo(-1));
Action<string> dbLog = log.Add;
Action<int, double> senderSteps = (steps, p) =>
{
var resends = new List<Sequenced>(sndBuf.Nacked.Concat(sndBuf.NonAcked).Take(steps));
var sends = new List<Sequenced>();
if (steps - resends.Count > 0)
{
var tmp = toSend.Take(steps - resends.Count).ToList();
toSend = toSend.Drop(steps - resends.Count).ToList();
sends = tmp;
}
foreach (var msg in resends.Concat(sends))
{
if (sends.Contains(msg)) sndBuf = sndBuf.Buffer(msg);
if (Happened(p))
{
var del = rcvBuf.Receive(msg).ExtractDeliverable;
rcvBuf = del.Buffer;
dbLog(string.Format("{0} -- {1} --> {2}", sndBuf, msg, rcvBuf));
lastAck = del.Ack;
received.AddRange(del.Deliverables);
dbLog(string.Format("R: {0}", string.Join(",", received.Select(x => x.ToString()))));
}
else
{
dbLog(string.Format("{0} -- {1} --X {2}", sndBuf, msg, rcvBuf));
}
}
};
Action<double> receiverStep = (p) =>
{
if (Happened(p))
{
sndBuf = sndBuf.Acknowledge(lastAck);
dbLog(string.Format("{0} <-- {1} -- {2}", sndBuf, lastAck, rcvBuf));
}
else
{
dbLog(string.Format("{0} X-- {1} -- {2}", sndBuf, lastAck, rcvBuf));
}
};
//Dropping phase
global::System.Diagnostics.Debug.WriteLine("Starting unreliable delivery for {0} messages, with delivery probably P = {1}", msgCount, deliveryProbability);
var nextSteps = msgCount*2;
while (nextSteps > 0)
{
var s = Geom(0.3, limit: 5);
senderSteps(s, deliveryProbability);
receiverStep(deliveryProbability);
nextSteps--;
}
global::System.Diagnostics.Debug.WriteLine("Successfully delivered {0} messages from {1}", received.Count, msgCount);
global::System.Diagnostics.Debug.WriteLine("Entering reliable phase");
//Finalizing pahase
for (var i = 1; i <= msgCount; i++)
{
senderSteps(1, 1.0);
receiverStep(1.0);
}
if (!received.SequenceEqual(referenceList))
{
global::System.Diagnostics.Debug.WriteLine(string.Join(Environment.NewLine, log));
global::System.Diagnostics.Debug.WriteLine("Received: ");
global::System.Diagnostics.Debug.WriteLine(string.Join(Environment.NewLine, received.Select(x => x.ToString())));
Assert.True(false,"Not all messages were received");
}
global::System.Diagnostics.Debug.WriteLine("All messages have been successfully delivered");
}
#endregion
}
}
| 36.229426 | 167 | 0.528979 | [
"Apache-2.0"
] | ashutoshraina/akka.net | src/core/Akka.Remote.Tests/AckedDeliverySpec.cs | 14,530 | C# |
using System.Reflection;
[assembly: AssemblyTitle("Leak.Peer.Receiver")]
[assembly: AssemblyProduct("Leak.Peer.Receiver")]
[assembly: AssemblyCopyright("Copyright © Adrian Macal 2016")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 38.428571 | 62 | 0.758364 | [
"MIT"
] | amacal/leak | sources/Leak.Loop/Properties/AssemblyInfo.cs | 272 | C# |
using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Webi.Core.SDK;
using Webi.Wechat.SDK;
using Webi.Wechat.SDK.Enums;
using Webi.Wechat.SDK.Models.WxEE;
using Webi.Wechat.Web.Core.IService.WxEE;
using Webi.Wechat.Web.Core.Models.EFModels.MiddlewareDB;
using Webi.Wechat.Web.Core.Models.WxEE;
namespace Webi.Wechat.Web.Core.Service.WxEE
{
public class WxEE_AuthorizeService : WxEE_BaseService, IWxEE_AuthorizeService
{
private readonly OLS_MiddlewareDBContext _middleDB;
public WxEE_AuthorizeService(OLS_MiddlewareDBContext middleDB)
{
_middleDB = middleDB;
}
private object lock_token = new object();
/// <summary>
/// 获取授权地址
/// </summary>
public ServiceResult<string> GetAuthUrl(int weid, string url)
{
if (weid <= 0 || string.IsNullOrWhiteSpace(url))
{
return ServiceResult<string>.Failed(StatusCodes.Status400BadRequest, "参数不可为空");
}
var wechat = _middleDB.WechatEeappConfig.FirstOrDefault(w => w.Id == weid);
//第一步 获取静默授权code
var authUrl = WxEEContext.AuthAPI.GenerateAuthorizeLink(
wechat.CorpId,
$"{wechat.AuthDomain}/ee_oauth/authorize",
WxEE_OAuthScopeType.snsapi_privateinfo,
wechat.AgentId,
HttpUtility.UrlEncode(weid + "|" + url));
return ServiceResult<string>.Success(authUrl);
}
/// <summary>
/// 授权用户信息
/// </summary>
public async Task<ServiceResult<string>> AuthorizeUserinfo(string code, string state)
{
if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(state))
{
return ServiceResult<string>.Failed(StatusCodes.Status400BadRequest, "无效授权");
}
//验证参数
var ids = state.Split('|');
var weid = ids[0].ToInt();
if (ids.Length > 1 && weid <= 0)
{
return ServiceResult<string>.Failed(StatusCodes.Status400BadRequest, "无效授权");
}
var returnUrl = ids[1];
try
{
//读取微信配置
var wechat = _middleDB.WechatEeappConfig.FirstOrDefault(w => w.Id == weid);
if (wechat == null)
{
return ServiceResult<string>.Failed(StatusCodes.Status404NotFound, "微信配置无效");
}
//获取授权access_token
var access_token = GetAccessToken(new WxEE_AuthorizeAccessTokenInput { guid = wechat.Guid });
//code转换用户信息
var userinfo = await WxEEContext.UserApi.GetUserinfo(
access_token.data.access_token,
code);
if (userinfo.errcode != 0)
{
return ServiceResult<string>.Failed(StatusCodes.Status401Unauthorized, userinfo.errmsg);
}
//企业微信用户
var wechatUser = _middleDB.WechatEeappUser.FirstOrDefault(w => w.UserId == userinfo.UserId);
//用户已授权
if (wechatUser != null)
{
await UpdateUser(wechatUser.UserId, access_token.data.access_token);
returnUrl = $"{returnUrl}{(returnUrl.Contains("?") ? "&" : "?")}eeid={wechatUser.Guid}";
return ServiceResult<string>.Success(returnUrl);
}
//保存信息
var eeUser = await CreateUser(weid, userinfo.DeviceId, userinfo.UserId, access_token.data.access_token);
returnUrl = $"{returnUrl}{(returnUrl.Contains("?") ? "&" : "?")}eeid={eeUser.Guid}";
return ServiceResult<string>.Success(returnUrl);
}
catch (Exception ex)
{
return ServiceResult<string>.Exception(ex.Message);
}
}
private async Task UpdateUser(string userId, string access_token)
{
//查询
var first = _middleDB.WechatEeappUser.FirstOrDefault(w => w.UserId == userId);
//理论上不会出现找到的情况
if (first != null)
{
//每天更新一次
if (DateTime.Now < (first.UpdateTime ?? DateTime.Now).AddDays(1))
{
return;
}
//获取通讯录
var userGet = await WxEEContext.UserApi.GetContactUser(access_token, userId);
if (userGet.errcode != 0) { return; }
//更新
first.Name = userGet.name;
//修改岗位
first.Position = userGet.position;
first.Mobile = userGet.mobile;
first.Gender = userGet.gender == 1;
first.Email = userGet.email;
first.Avatar = userGet.avatar;
first.QrCode = userGet.qr_code;
first.UpdateTime = DateTime.Now;
if (string.IsNullOrEmpty(first.Openid))
{
//转OpenId
var convert = await WxEEContext.UserApi.UserIdToOpenId(access_token, userId);
first.Openid = convert.errcode == 0 ? convert.openid : convert.errmsg;
}
}
await _middleDB.SaveChangesAsync();
}
/// <summary>
/// 创建用户
/// </summary>
private async Task<WechatEeappUser> CreateUser(int weid, string device_id, string userId, string access_token)
{
//获取通讯录
var user = await WxEEContext.UserApi.GetContactUser(access_token, userId);
if (user.errcode != 0) { return new WechatEeappUser(); }
bool? gender = null;
if (user.gender == 1)
{
gender = true;
}
else if (user.gender == 2)
{
gender = false;
}
//查询
var first = _middleDB.WechatEeappUser.FirstOrDefault(w => w.UserId == user.userid);
//理论上不会出现找到的情况
if (first != null)
{
//更新
first.DeviceId = device_id;
first.Name = user.name;
first.Mobile = user.mobile;
first.Gender = gender;
first.Email = user.email;
first.Avatar = user.avatar;
first.QrCode = user.qr_code;
}
else
{
first = new WechatEeappUser
{
Guid = Guid.NewGuid(),
WxeeId = weid,
UserId = user.userid,
DeviceId = device_id,
Name = user.name,
Mobile = user.mobile,
Position = user.position,
Gender = gender,
Email = user.email,
Avatar = user.avatar,
QrCode = user.qr_code,
CreateTime = DateTime.Now
};
//转OpenId
var convert = await WxEEContext.UserApi.UserIdToOpenId(access_token, first.UserId);
first.Openid = convert.errcode == 0 ? convert.openid : convert.errmsg;
//创建
_middleDB.WechatEeappUser.Add(first);
}
await _middleDB.SaveChangesAsync();
return first;
}
/// <summary>
/// 获取企业微信应用配置
/// </summary>
public ServiceResult<WxEE_AuthorizeAccessTokenOutput> GetAccessToken(WxEE_AuthorizeAccessTokenInput input)
{
input.CheckNull(nameof(WxEE_AuthorizeAccessTokenInput));
var result = new ServiceResult<WxEE_AuthorizeAccessTokenOutput>();
result.data = new WxEE_AuthorizeAccessTokenOutput();
WechatEeappConfig wechatEEAppConfig = null;
//微信配置
if (input.aid == 0)
{
input.guid.CheckEmpty(nameof(input.guid));
wechatEEAppConfig = _middleDB.WechatEeappConfig.FirstOrDefault(w => w.Guid == input.guid);
}
else
{
wechatEEAppConfig = _middleDB.WechatEeappConfig.FirstOrDefault(w => w.Id == input.aid);
}
if (wechatEEAppConfig == null)
{
return ServiceResult<WxEE_AuthorizeAccessTokenOutput>.Failed(StatusCodes.Status404NotFound, "企业微信应用配置获取失败,请联系系统客服");
}
//过期时间
if (!string.IsNullOrEmpty(wechatEEAppConfig.AccessToken) &&
DateTime.Now < (wechatEEAppConfig.TokenExpireTime ?? DateTime.Now.AddMinutes(-1)))
{
result.data.access_token = wechatEEAppConfig.AccessToken;
result.data.expire_stamp = new DateTimeOffset(wechatEEAppConfig.TokenExpireTime.Value).ToUnixTimeMilliseconds();
}
else
{
//双重验证
if (string.IsNullOrEmpty(result.data.access_token))
{
lock (lock_token)
{
if (string.IsNullOrEmpty(result.data.access_token))
{
//从企业微信获取
var token = WxEEContext.BaseAPI.GetAccessToken(wechatEEAppConfig.CorpId, wechatEEAppConfig.Secret);
if (token.errcode != 0)
{
result.data.access_token = token.errmsg;
return result;
}
//修改
wechatEEAppConfig.AccessToken = token.access_token;
wechatEEAppConfig.TokenExpireTime = DateTime.Now.AddMinutes(90);
_middleDB.SaveChanges();
result.data.access_token = token.access_token;
result.data.expire_stamp = new DateTimeOffset(wechatEEAppConfig.TokenExpireTime.Value).ToUnixTimeMilliseconds();
}
}
}
}
return result;
}
}
} | 39.849421 | 140 | 0.512547 | [
"MIT"
] | amwitx/Amw.Core | Common/Webi.Wechat.Web.Core/Service/WxEE/WxEE_AuthorizeService.cs | 10,697 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using ApiPeek.Core.Extensions;
namespace ApiPeek.Core.Model;
[DataContract]
public class ApiField : ApiBaseItem, IDetail
{
[DataMember]
public string Type { get; set; }
[DataMember]
public bool IsStatic { get; set; }
[IgnoreDataMember]
public override string SortName => ShortString;
[IgnoreDataMember]
public override string ShortString => string.Format("{1}{0} : {2}", PrefixString, Name, Type);
[IgnoreDataMember]
private string PrefixString => IsStatic ? " static" : "";
public static IEqualityComparer<ApiField> DetailComparer =
ProjectionEqualityComparer<ApiField>.Create(x => x.Detail);
[IgnoreDataMember]
public string Detail => InDetail();
private string detail;
public string InDetail(string indent = "")
{
if (detail == null)
{
StringBuilder sb = new StringBuilder("public ");
if (IsStatic) sb.Append("static ");
sb.AppendFormat("{0} {1};", Type, Name);
detail = sb.ToString();
}
return indent + detail;
}
} | 27.232558 | 98 | 0.645602 | [
"MIT"
] | martinsuchan/ApiPeek | Source/ApiPeek.Core/Model/ApiField.cs | 1,171 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.