content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System.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("FirstMenuCommand")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FirstMenuCommand")]
[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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.588235 | 85 | 0.725352 | [
"MIT"
] | jcouv/VsVimExt | VsVimExtCommands/Properties/AssemblyInfo.cs | 1,280 | C# |
using STRINGS;
using UnityEngine;
public class IronCometConfig : IEntityConfig
{
public static string ID = "IronComet";
public string[] GetDlcIds()
{
return DlcManager.AVAILABLE_ALL_VERSIONS;
}
public GameObject CreatePrefab()
{
GameObject gameObject = EntityTemplates.CreateEntity(ID, UI.SPACEDESTINATIONS.COMETS.IRONCOMET.NAME);
gameObject.AddOrGet<SaveLoadRoot>();
gameObject.AddOrGet<LoopingSounds>();
Comet comet = gameObject.AddOrGet<Comet>();
comet.massRange = new Vector2(3f, 20f);
comet.temperatureRange = new Vector2(323.15f, 423.15f);
comet.explosionOreCount = new Vector2I(2, 4);
comet.entityDamage = 15;
comet.totalTileDamage = 0.5f;
comet.splashRadius = 1;
comet.impactSound = "Meteor_Medium_Impact";
comet.flyingSoundID = 1;
comet.explosionEffectHash = SpawnFXHashes.MeteorImpactMetal;
PrimaryElement primaryElement = gameObject.AddOrGet<PrimaryElement>();
primaryElement.SetElement(SimHashes.Iron);
primaryElement.Temperature = (comet.temperatureRange.x + comet.temperatureRange.y) / 2f;
KBatchedAnimController kBatchedAnimController = gameObject.AddOrGet<KBatchedAnimController>();
kBatchedAnimController.AnimFiles = new KAnimFile[1] { Assets.GetAnim("meteor_metal_kanim") };
kBatchedAnimController.isMovable = true;
kBatchedAnimController.initialAnim = "fall_loop";
kBatchedAnimController.initialMode = KAnim.PlayMode.Loop;
kBatchedAnimController.visibilityType = KAnimControllerBase.VisibilityType.OffscreenUpdate;
gameObject.AddOrGet<KCircleCollider2D>().radius = 0.5f;
gameObject.transform.localScale = new Vector3(0.6f, 0.6f, 1f);
gameObject.AddTag(GameTags.Comet);
return gameObject;
}
public void OnPrefabInit(GameObject go)
{
}
public void OnSpawn(GameObject go)
{
}
}
| 34.627451 | 103 | 0.779728 | [
"MIT"
] | undancer/oni-data | Managed/main/IronCometConfig.cs | 1,766 | C# |
using System.Net.Http;
using System.Threading.Tasks;
#nullable enable
namespace Guppi.Domain.Interfaces
{
public interface IHttpRestService
{
HttpClient Client { get; }
Task<T?> GetData<T>(string url);
void AddHeader(string name, string? value);
Task<HttpResponseMessage> SendAsync(HttpRequestMessage request);
Task<string> GetStringAsync(string? requestUri);
}
}
| 20.095238 | 72 | 0.687204 | [
"MIT"
] | rprouse/guppi | Guppi.Domain/Interfaces/IHttpRestService.cs | 422 | C# |
using System.Collections.Generic;
using Abp.Application.Features;
using Abp.AutoMapper;
using Abp.UI.Inputs;
using Castle.Components.DictionaryAdapter;
using NorthLion.Zero.Editions.CustomEditionManager.CustomObj;
namespace NorthLion.Zero.Editions.Dto
{
[AutoMap(typeof(Feature), typeof(TenantFeature))]
public class FeatureForEditionInput
{
public string Name { get; set; }
public string DisplayName { get; set; }
public bool Selected { get; set; }
public string DefaultValue { get; set; }
public int EditionId { get; set; }
public IInputType InputType { get; set; }
public List<FeatureForEditionInput> ChildFeatures { get; set; } = new EditableList<FeatureForEditionInput>();
}
} | 35.952381 | 117 | 0.709934 | [
"MIT"
] | CodefyMX/NorthLionAbpZero | NorthLion.Zero.Application/Editions/Dto/FeatureForEditionInput.cs | 757 | C# |
using System;
using System.Drawing;
namespace MSR.CVE.BackMaker.ImagePipeline
{
public class SizeParameter : ImmutableParameter<Size>
{
public SizeParameter(Size value) : base(value)
{
}
public override void AccumulateRobustHash(IRobustHash hash)
{
hash.Accumulate(base.value);
}
}
}
| 19.8125 | 62 | 0.709779 | [
"MIT"
] | QualitySolution/-GMap.NET | Tools/MapCruncher/MSR.CVE.BackMaker.ImagePipeline/SizeParameter.cs | 317 | C# |
using CSharpFunctionalExtensions;
using System.Text.RegularExpressions;
namespace SimpleValidatorBuilder.Parser;
public sealed class StringContainsOnlyAlphabetCharacters<TError> : IParser<string, TError>
{
private readonly Func<TError> _errorFactory;
internal StringContainsOnlyAlphabetCharacters(Func<TError> errorFactory)
=> _errorFactory = errorFactory;
public Result<string, TError> Parse(string value)
=> !IsAlphabetCharactersOnly(value) ? Result.Failure<string, TError>(_errorFactory.Invoke()) : Result.Success<string, TError>(value);
public static bool IsAlphabetCharactersOnly(string str)
=> RegexAlphabetCharactersOnly.IsMatch(str);
private static readonly Regex RegexAlphabetCharactersOnly =
new Regex("^[a-z]+$", RegexOptions.IgnoreCase | RegexOptions.Compiled, TimeSpan.FromMilliseconds(300));
}
| 39.5 | 141 | 0.76985 | [
"MIT"
] | gagnedavid25/SimpleValidatorBuilder | src/SimpleValidatorBuilder/Parser/StringContainsOnlyAlphabetCharacters.cs | 871 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.multimediaai;
using Aliyun.Acs.multimediaai.Transform;
using Aliyun.Acs.multimediaai.Transform.V20190810;
namespace Aliyun.Acs.multimediaai.Model.V20190810
{
public class CreateFaceGroupRequest : RpcAcsRequest<CreateFaceGroupResponse>
{
public CreateFaceGroupRequest()
: base("multimediaai", "2019-08-10", "CreateFaceGroup")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.multimediaai.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.multimediaai.Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string description;
private string faceGroupName;
public string Description
{
get
{
return description;
}
set
{
description = value;
DictionaryUtil.Add(QueryParameters, "Description", value);
}
}
public string FaceGroupName
{
get
{
return faceGroupName;
}
set
{
faceGroupName = value;
DictionaryUtil.Add(QueryParameters, "FaceGroupName", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override CreateFaceGroupResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return CreateFaceGroupResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 30.4 | 142 | 0.69969 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-multimediaai/Multimediaai/Model/V20190810/CreateFaceGroupRequest.cs | 2,584 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using SharpGL.SceneGraph.Core;
namespace SharpGL.SceneGraph.Primitives
{
/// <summary>
/// A simple cube polygon.
/// </summary>
[Serializable]
public class Cube : Polygon
{
/// <summary>
/// Initializes a new instance of the <see cref="PolyCubegon"/> class.
/// </summary>
public Cube()
{
// Set the name.
Name = "Cube";
// Create the cube geometry.
CreateCubeGeometry();
}
/// <summary>
/// This function makes a simple cube shape.
/// </summary>
private void CreateCubeGeometry()
{
UVs.Add(new UV(0, 0));
UVs.Add(new UV(0, 1));
UVs.Add(new UV(1, 1));
UVs.Add(new UV(1, 0));
// Add the vertices.
Vertices.Add(new Vertex(-1, -1, -1));
Vertices.Add(new Vertex( 1, -1, -1));
Vertices.Add(new Vertex( 1, -1, 1));
Vertices.Add(new Vertex(-1, -1, 1));
Vertices.Add(new Vertex(-1, 1, -1));
Vertices.Add(new Vertex( 1, 1, -1));
Vertices.Add(new Vertex( 1, 1, 1));
Vertices.Add(new Vertex(-1, 1, 1));
// Add the faces.
Face face = new Face(); // bottom
face.Indices.Add(new Index(1, 0));
face.Indices.Add(new Index(2, 1));
face.Indices.Add(new Index(3, 2));
face.Indices.Add(new Index(0, 3));
Faces.Add(face);
face = new Face(); // top
face.Indices.Add(new Index(7, 0));
face.Indices.Add(new Index(6, 1));
face.Indices.Add(new Index(5, 2));
face.Indices.Add(new Index(4, 3));
Faces.Add(face);
face = new Face(); // right
face.Indices.Add(new Index(5, 0));
face.Indices.Add(new Index(6, 1));
face.Indices.Add(new Index(2, 2));
face.Indices.Add(new Index(1, 3));
Faces.Add(face);
face = new Face(); // left
face.Indices.Add(new Index(7, 0));
face.Indices.Add(new Index(4, 1));
face.Indices.Add(new Index(0, 2));
face.Indices.Add(new Index(3, 3));
Faces.Add(face);
face = new Face(); // front
face.Indices.Add(new Index(4, 0));
face.Indices.Add(new Index(5, 1));
face.Indices.Add(new Index(1, 2));
face.Indices.Add(new Index(0, 3));
Faces.Add(face);
face = new Face(); // back
face.Indices.Add(new Index(6, 0));
face.Indices.Add(new Index(7, 1));
face.Indices.Add(new Index(3, 2));
face.Indices.Add(new Index(2, 3));
Faces.Add(face);
}
}
}
| 33.376344 | 79 | 0.465206 | [
"MIT"
] | DanFTRX/sharpgl | source/SharpGL/Core/SharpGL.SceneGraph/Primitives/Cube.cs | 3,104 | C# |
namespace AGS.API
{
/// <summary>
/// Event arguments for inventory interaction
/// </summary>
public class InventoryInteractEventArgs : ObjectEventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="T:AGS.API.InventoryInteractEventArgs"/> class.
/// </summary>
/// <param name="obj">Object.</param>
/// <param name="item">Item.</param>
public InventoryInteractEventArgs (IObject obj, IInventoryItem item) : base(obj)
{
Item = item;
}
/// <summary>
/// The inventory item being interacted with.
/// </summary>
/// <value>The item.</value>
public IInventoryItem Item { get; private set; }
public override string ToString ()
{
return $"{base.ToString()} interacted with {(Item == null ? "null" : Item.ToString())}";
}
}
}
| 27.483871 | 103 | 0.600939 | [
"Artistic-2.0"
] | OwenMcDonnell/MonoAGS | Source/AGS.API/Objects/Interactions/InventoryInteractEventArgs.cs | 854 | C# |
#region Copyright
//
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2017
// by DotNetNuke Corporation
//
// 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 DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Framework;
using DotNetNuke.Modules;
using DotNetNuke.Security;
using DotNetNuke.Services;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using System.Web.Security;
using System.Web.Profile;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace DotNetNuke.Providers.RadEditorProvider
{
public partial class ImageTester : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
string strResult = "NOTFOUND";
string strFile = Request.QueryString["file"];
if (strFile != null && IsImageFile(strFile))
{
string path = strFile.Replace("http://", "");
path = path.Substring(path.IndexOf("/"));
strFile = Server.MapPath(path);
if (System.IO.File.Exists(strFile))
{
strResult = "OK";
}
}
Response.Write(strResult);
Response.Flush();
}
private static bool IsImageFile(string relativePath)
{
var acceptedExtensions = new List<string> { "jpg", "png", "gif", "jpe", "jpeg", "tiff", "bmp" };
var extension = relativePath.Substring(relativePath.LastIndexOf(".",
StringComparison.Ordinal) + 1).ToLower();
return acceptedExtensions.Contains(extension);
}
override protected void OnInit(EventArgs e)
{
base.OnInit(e);
//INSTANT C# NOTE: Converted event handler wireups:
this.Load += new System.EventHandler(Page_Load);
}
}
}
| 34.464646 | 116 | 0.703986 | [
"MIT"
] | DnnSoftwarePersian/Dnn.Platform | DNN Platform/Providers/HtmlEditorProviders/RadEditorProvider/ImageTester.aspx.cs | 3,415 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Mspr.Reseau.Auth.Api.Services;
using Mspr.Reseau.Auth.Api.Services.Interfaces;
namespace Mspr.Reseau.Auth.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
// configure DI for application services
services.AddScoped<IAuthService, AuthService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
// Global CORS Policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 28.745455 | 106 | 0.609108 | [
"Apache-2.0"
] | MidiasAndromeda/mspr-reseau-interface-auth | Mspr.Reseau.Auth.Api/Startup.cs | 1,581 | C# |
using System;
namespace UnleashedDDD.Sales.Domain.Model
{
public class MonetaryValue
{
public decimal Amount { get; private set; }
public Currency Currency { get; private set; }
public MonetaryValue(decimal amount, Currency currency)
{
Amount = amount;
Currency = currency;
}
public static MonetaryValue operator +(MonetaryValue c1, MonetaryValue c2)
{
if (c1.Currency != c2.Currency)
throw new Exception("Currencies have to match to add MonetaryValues");
return new MonetaryValue(c1.Amount + c2.Amount, c1.Currency);
}
}
} | 28.791667 | 87 | 0.586107 | [
"MIT"
] | zdeneksejcek/DDDwithOrleans | src/UnleashedDDD/Sales/Domain.Model/MonetaryValue.cs | 693 | C# |
using System;
namespace DbTransmogrifier.Database
{
public class DbTransmogrifierException : Exception
{
public DbTransmogrifierException(string message)
: this(message, null)
{
}
public DbTransmogrifierException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | 22.411765 | 82 | 0.629921 | [
"BSD-2-Clause"
] | jeffdoolittle/DbTransmogrifier | src/DbTransmogrifier/Database/DbTransmogrifierException.cs | 383 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using GFDLibrary.Common;
using GFDLibrary.IO;
namespace GFDLibrary.Models
{
public sealed class Model : Resource
{
public override ResourceType ResourceType => ResourceType.Model;
private ModelFlags mFlags;
public ModelFlags Flags
{
get => mFlags;
set
{
mFlags = value;
ValidateFlags();
}
}
private List<Bone> mBones;
public List<Bone> Bones
{
get => mBones;
set
{
mBones = value;
ValidateFlags();
}
}
private BoundingBox? mBoundingBox;
public BoundingBox? BoundingBox
{
get => mBoundingBox;
set
{
mBoundingBox = value;
ValidateFlags();
}
}
private BoundingSphere? mBoundingSphere;
public BoundingSphere? BoundingSphere
{
get => mBoundingSphere;
set
{
mBoundingSphere = value;
ValidateFlags();
}
}
public Node RootNode { get; set; }
public IEnumerable<Node> Nodes
{
get
{
IEnumerable<Node> RecursivelyAddToList( Node node )
{
yield return node;
foreach ( var childNode in node.Children )
{
foreach ( var childChildNode in RecursivelyAddToList( childNode ) )
yield return childChildNode;
}
}
return RecursivelyAddToList( RootNode );
}
}
public Model()
{
}
public Model(uint version) : base(version)
{
}
internal override void Read( ResourceReader reader, long endPosition = -1 )
{
var flags = ( ModelFlags ) reader.ReadInt32();
if ( flags.HasFlag( ModelFlags.HasSkinning ) )
{
int boneCount = reader.ReadInt32();
var inverseBindMatrices = new Matrix4x4[boneCount];
var boneToNodeIndices = new ushort[boneCount];
for ( int i = 0; i < boneCount; i++ )
inverseBindMatrices[i] = reader.ReadMatrix4x4();
for ( int i = 0; i < boneCount; i++ )
boneToNodeIndices[i] = reader.ReadUInt16();
Bones = new List<Bone>( boneCount );
for ( int i = 0; i < boneCount; i++ )
Bones.Add( new Bone( boneToNodeIndices[ i ], inverseBindMatrices[ i ] ) );
}
if ( flags.HasFlag( ModelFlags.HasBoundingBox ) )
BoundingBox = reader.ReadBoundingBox();
if ( flags.HasFlag( ModelFlags.HasBoundingSphere ) )
BoundingSphere = reader.ReadBoundingSphere();
RootNode = Node.ReadRecursive( reader, Version, endPosition );
Flags = flags;
}
internal override void Write( ResourceWriter writer )
{
writer.WriteInt32( ( int ) Flags );
if ( Flags.HasFlag( ModelFlags.HasSkinning ) )
{
writer.WriteInt32( Bones.Count );
foreach ( var bone in Bones )
writer.WriteMatrix4x4( bone.InverseBindMatrix );
foreach ( var bone in Bones )
writer.WriteUInt16( bone.NodeIndex );
}
if ( Flags.HasFlag( ModelFlags.HasBoundingBox ) )
writer.WriteBoundingBox( BoundingBox.Value );
if ( Flags.HasFlag( ModelFlags.HasBoundingSphere ) )
writer.WriteBoundingSphere( BoundingSphere.Value );
Node.WriteRecursive( writer, RootNode );
}
public Node GetNode( int nodeIndex )
{
var i = 0;
return Nodes.FirstOrDefault( node => i++ == nodeIndex );
}
public void ReplaceWith( Model other )
{
// Remove geometries from this scene
RemoveGeometryAttachments();
Bones = other.Bones;
BoundingBox = other.BoundingBox;
BoundingSphere = other.BoundingSphere;
Flags = other.Flags;
var otherNodes = other.Nodes.ToList();
// Replace common nodes and get the unique nodes
var uniqueNodes = ReplaceCommonNodesAndGetUniqueNodes( otherNodes );
// Remove nodes that dont have attachments
uniqueNodes.RemoveAll( x => !x.HasAttachments );
// Fix unique nodes
FixUniqueNodes( other.RootNode, otherNodes, uniqueNodes );
// Add unique nodes to root.
foreach ( var uniqueNode in uniqueNodes )
RootNode.AddChildNode( uniqueNode );
// Rebuild matrix palette
RebuildBonePalette( otherNodes );
}
private List<Node> ReplaceCommonNodesAndGetUniqueNodes( IEnumerable<Node> otherNodes )
{
var uniqueNodes = new List<Node>();
foreach ( var otherNode in otherNodes )
{
if ( otherNode.Name == "RootNode" || ( otherNode.Parent == null || otherNode.Parent == otherNodes.First() ) && otherNode.Name.EndsWith( "_root" ) )
{
continue;
}
if ( !Nodes.Any( x => x.Name == "Bip01 雜ウ霍。" ) )
{
// Hacks to fix enemy/persona models
if ( otherNode.Name == "Bip01 閼頑、・" )
otherNode.Name = "Bip01 Spine";
else if ( otherNode.Parent != null && otherNode.Parent.Name == "Bip01 Spine" && otherNode.Name == "Bip01 閼頑、・" )
otherNode.Name = "Bip01 Spine1";
else if ( otherNode.Name == "Bip01 鬥・" )
otherNode.Name = "Bip01 Neck";
else if ( otherNode.Name == "Bip01 雜ウ霍。" )
otherNode.Name = "Bip01 Footsteps";
}
var thisNode = Nodes.SingleOrDefault( x => x.Name.Equals( otherNode.Name ) );
if ( thisNode == null )
{
// Node not present, can't merge
uniqueNodes.Add( otherNode );
continue;
}
// Merge attachments
if ( otherNode.HasAttachments )
{
Matrix4x4.Invert( thisNode.WorldTransform, out var thisNodeWorldTransformInv );
var offsetMatrix = otherNode.WorldTransform * thisNodeWorldTransformInv;
foreach ( var attachment in otherNode.Attachments )
{
switch ( attachment.Type )
{
case NodeAttachmentType.Mesh:
{
var mesh = attachment.GetValue<Mesh>();
for ( int i = 0; i < mesh.Vertices.Length; i++ )
{
var position = mesh.Vertices[ i ];
var newPosition = mesh.Vertices[ i ] = Vector3.Transform( position, offsetMatrix );
if ( mesh.MorphTargets != null )
{
foreach ( var morphTarget in mesh.MorphTargets )
{
Trace.Assert( morphTarget.VertexCount == mesh.VertexCount );
morphTarget.Vertices[ i ] = Vector3.Transform( ( position + morphTarget.Vertices[ i ] ), offsetMatrix ) - newPosition;
}
}
}
if ( mesh.Normals != null )
{
for ( int i = 0; i < mesh.Normals.Length; i++ )
mesh.Normals[i] = Vector3.TransformNormal( mesh.Normals[i], offsetMatrix );
}
}
break;
case NodeAttachmentType.Epl:
continue;
case NodeAttachmentType.Light:
if ( thisNode.Attachments.Any( x => x.Type == NodeAttachmentType.Light ) )
{
// Don't replace lights, likely not what we want to do
continue;
}
break;
}
thisNode.Attachments.Add( attachment );
}
}
// Replace properties
foreach ( var property in otherNode.Properties )
thisNode.Properties[property.Key] = property.Value;
}
return uniqueNodes;
}
private void FixUniqueNodes( Node otherRootNode, List<Node> otherNodes, List<Node> uniqueNodes )
{
foreach ( var uniqueNode in uniqueNodes.ToList() )
{
if ( uniqueNode.Parent == otherRootNode )
continue;
// Find the last unique node in the hierarchy chain (going up the hierarchy)
var lastUniqueNode = uniqueNode;
while ( true )
{
var parent = lastUniqueNode.Parent;
if ( parent == null || parent == otherRootNode || Nodes.SingleOrDefault( x => x.Name.Equals( parent.Name ) ) != null )
break;
lastUniqueNode = parent;
}
// Get unweighted geometries
var unweightedGeometries = uniqueNode.Attachments.Where( x => x.Type == NodeAttachmentType.Mesh )
.Select( x => x.GetValue<Mesh>() ).Where( x => x.VertexWeights == null ).ToList();
if ( unweightedGeometries.Any() )
{
// If we have unweighted geometries, we have to assign vertex weights to them so that they
// properly animate.
// The node we are going to assign the weights to is the shared ancestor (between this model and the replacement one)
// in the hopes that it will work out.
// Find the bone index of this node
int lastUniqueNodeIndex = -1;
for ( int i = 0; i < otherNodes.Count; i++ )
{
if ( otherNodes[i].Name == lastUniqueNode.Parent.Name )
{
lastUniqueNodeIndex = i;
break;
}
}
Trace.Assert( lastUniqueNodeIndex != -1 );
if ( Bones == null )
{
Bones = new List<Bone>();
}
int boneIndex = Bones.FindIndex( x => x.NodeIndex == lastUniqueNodeIndex );
if ( boneIndex == -1 )
{
Trace.Assert( Bones.Count < 255 );
// Node wasn't used as a bone, so we add it
// TODO: This is a lazy hack. This should be done during the Bones fixup
boneIndex = Bones.Count;
Bones.Add( new Bone( ( ushort ) lastUniqueNodeIndex, Matrix4x4.Identity ) );
}
// Set vertex weights
foreach ( var geometry in unweightedGeometries )
{
geometry.VertexWeights = new VertexWeight[geometry.VertexCount];
for ( int i = 0; i < geometry.VertexWeights.Length; i++ )
{
ref var weight = ref geometry.VertexWeights[i];
weight.Indices = new byte[4];
weight.Indices[0] = ( byte )boneIndex;
weight.Weights = new float[4];
weight.Weights[0] = 1f;
}
}
}
//// Fix morphs
//var morphs = uniqueNode.Attachments.Where( x => x.Type == NodeAttachmentType.Morph ).Select( x => x.GetValue<Morph>() );
//foreach ( var morph in morphs )
//{
// // All unique nodes get assigned to the root node
// morph.NodeName = "RootNode";
//}
// Fix transform for the node
var worldTransform = uniqueNode.WorldTransform;
uniqueNode.Parent?.RemoveChildNode( uniqueNode );
uniqueNode.LocalTransform = worldTransform;
}
}
private void RebuildBonePalette( List<Node> otherNodes )
{
var uniqueBones = new List<Bone>();
// Recalculate inverse bind matrices & update bone indices
var nodes = Nodes.ToList();
foreach ( var node in nodes )
{
if ( !node.HasAttachments )
continue;
Matrix4x4.Invert( node.WorldTransform, out var nodeInvWorldTransform );
foreach ( var geometry in node.Attachments.Where( x => x.Type == NodeAttachmentType.Mesh ).Select( x => x.GetValue<Mesh>() )
.Where( x => x.VertexWeights != null ) )
{
foreach ( var weight in geometry.VertexWeights )
{
for ( int i = 0; i < weight.Indices.Length; i++ )
{
var boneIndex = weight.Indices[i];
var boneWeight = weight.Weights[i];
if ( boneWeight == 0 )
continue;
var otherNodeIndex = Bones[boneIndex].NodeIndex;
var otherBoneNode = otherNodes[otherNodeIndex];
var thisBoneNode = nodes.FirstOrDefault( x => x.Name == otherBoneNode.Name );
if ( thisBoneNode == null )
{
// Find parent that does exist
var curOtherBoneNode = otherBoneNode.Parent;
while ( thisBoneNode == null && curOtherBoneNode != null )
{
thisBoneNode = nodes.FirstOrDefault( x => x.Name == curOtherBoneNode.Name );
curOtherBoneNode = curOtherBoneNode.Parent;
}
if ( thisBoneNode == null )
thisBoneNode = RootNode;
}
var boneTransform = thisBoneNode.WorldTransform;
// Attempt to fix spaghetti fingers
//if ( thisBoneNode.Name.Contains( "Finger" ) || thisBoneNode.Name.Contains( "Hand" ) ||
// thisBoneNode.Name.Contains( "hand" ) )
// boneTransform = otherBoneNode.WorldTransform;
var thisNodeIndex = nodes.IndexOf( thisBoneNode );
Trace.Assert( thisNodeIndex != -1 );
var bindMatrix = boneTransform * nodeInvWorldTransform;
Matrix4x4.Invert( bindMatrix, out var inverseBindMatrix );
var newBoneIndex =
uniqueBones.FindIndex( x => x.NodeIndex == thisNodeIndex && x.InverseBindMatrix.Equals( inverseBindMatrix ) );
if ( newBoneIndex == -1 )
{
// Add if unique
Trace.Assert( uniqueBones.Count < 255 );
uniqueBones.Add( new Bone( (ushort)thisNodeIndex, inverseBindMatrix ) );
newBoneIndex = uniqueBones.Count - 1;
}
// Update bone index
weight.Indices[ i ] = ( byte ) newBoneIndex;
}
}
}
}
Bones = uniqueBones;
}
private void RemoveGeometryAttachments()
{
foreach ( var node in Nodes )
{
if ( node.HasAttachments )
foreach ( var geometryAttachment in node.Attachments.Where( x => x.Type == NodeAttachmentType.Mesh ).ToList() )
node.Attachments.Remove( geometryAttachment );
}
}
private void ValidateFlags()
{
if ( Bones == null || Bones.Count == 0 )
mFlags &= ~ModelFlags.HasSkinning;
else
mFlags |= ModelFlags.HasSkinning;
if ( BoundingBox == null )
mFlags &= ~ModelFlags.HasBoundingBox;
else
mFlags |= ModelFlags.HasBoundingBox;
if ( BoundingSphere == null )
mFlags &= ~ModelFlags.HasBoundingSphere;
else
mFlags |= ModelFlags.HasBoundingSphere;
}
}
[Flags]
public enum ModelFlags
{
HasBoundingBox = 1 << 0,
HasBoundingSphere = 1 << 1,
HasSkinning = 1 << 2,
HasMorphs = 1 << 3
}
} | 38.991543 | 166 | 0.447107 | [
"MIT"
] | D3fau4/image2gnf | GFD-Studio/GFDLibrary/Models/Model.cs | 18,481 | 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 secretsmanager-2017-10-17.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.SecretsManager.Model
{
/// <summary>
/// The request failed because it would exceed one of the Secrets Manager internal limits.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class LimitExceededException : AmazonSecretsManagerException
{
/// <summary>
/// Constructs a new LimitExceededException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public LimitExceededException(string message)
: base(message) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public LimitExceededException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="innerException"></param>
public LimitExceededException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public LimitExceededException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public LimitExceededException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the LimitExceededException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected LimitExceededException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 47.298387 | 178 | 0.680477 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/SecretsManager/Generated/Model/LimitExceededException.cs | 5,865 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Graph.Rbac;
using Azure.ResourceManager.KeyVault.Models;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.TestFramework;
namespace Azure.ResourceManager.KeyVault.Tests
{
[ClientTestFixture]
public abstract class VaultOperationsTestsBase : ManagementRecordedTestBase<KeyVaultManagementTestEnvironment>
{
protected ArmClient Client { get; private set; }
private const string ObjectIdKey = "ObjectId";
public static TimeSpan ZeroPollingInterval { get; } = TimeSpan.FromSeconds(0);
public string ObjectId { get; set; }
//Could not use TestEnvironment.Location since Location is got dynamically
public string Location { get; set; }
public Subscription Subscription { get; private set; }
public AccessPolicyEntry AccessPolicy { get; internal set; }
public string ResGroupName { get; internal set; }
public Dictionary<string, string> Tags { get; internal set; }
public Guid TenantIdGuid { get; internal set; }
public string VaultName { get; internal set; }
public VaultProperties VaultProperties { get; internal set; }
public ManagedHsmProperties ManagedHsmProperties { get; internal set; }
public VaultCollection VaultCollection { get; set; }
public DeletedVaultCollection DeletedVaultCollection { get; set; }
public ManagedHsmCollection ManagedHsmCollection { get; set; }
public ResourceGroup ResourceGroup { get; set; }
protected VaultOperationsTestsBase(bool isAsync)
: base(isAsync)
{
}
protected async Task Initialize()
{
Location = "westcentralus";
Client = GetArmClient();
Subscription = await Client.GetDefaultSubscriptionAsync();
DeletedVaultCollection = Subscription.GetDeletedVaults();
if (Mode == RecordedTestMode.Playback)
{
this.ObjectId = Recording.GetVariable(ObjectIdKey, string.Empty);
}
else if (Mode == RecordedTestMode.Record)
{
var spClient = new RbacManagementClient(TestEnvironment.TenantId, TestEnvironment.Credential).ServicePrincipals;
var servicePrincipalList = spClient.ListAsync($"appId eq '{TestEnvironment.ClientId}'").ToEnumerableAsync().Result;
foreach (var servicePrincipal in servicePrincipalList)
{
this.ObjectId = servicePrincipal.ObjectId;
Recording.GetVariable(ObjectIdKey, this.ObjectId);
break;
}
}
ResGroupName = Recording.GenerateAssetName("sdktestrg-kv-");
var rgResponse = await Subscription.GetResourceGroups().CreateOrUpdateAsync(true, ResGroupName, new ResourceGroupData(Location)).ConfigureAwait(false);
ResourceGroup = rgResponse.Value;
VaultCollection = ResourceGroup.GetVaults();
VaultName = Recording.GenerateAssetName("sdktest-vault-");
TenantIdGuid = new Guid(TestEnvironment.TenantId);
Tags = new Dictionary<string, string> { { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" } };
var permissions = new AccessPermissions
{
Keys = { new KeyPermissions("all") },
Secrets = { new SecretPermissions("all") },
Certificates = { new CertificatePermissions("all") },
Storage = { new StoragePermissions("all") },
};
AccessPolicy = new AccessPolicyEntry(TenantIdGuid, ObjectId, permissions);
VaultProperties = new VaultProperties(TenantIdGuid, new Sku(SkuFamily.A, SkuName.Standard));
VaultProperties.EnabledForDeployment = true;
VaultProperties.EnabledForDiskEncryption = true;
VaultProperties.EnabledForTemplateDeployment = true;
VaultProperties.EnableSoftDelete = true;
VaultProperties.VaultUri = "";
VaultProperties.NetworkAcls = new NetworkRuleSet() {
Bypass = "AzureServices",
DefaultAction = "Allow",
IpRules =
{
new IPRule("1.2.3.4/32"),
new IPRule("1.0.0.0/25")
}
};
VaultProperties.AccessPolicies.Add(AccessPolicy);
ManagedHsmCollection = ResourceGroup.GetManagedHsms();
ManagedHsmProperties = new ManagedHsmProperties();
ManagedHsmProperties.InitialAdminObjectIds.Add(ObjectId);
ManagedHsmProperties.CreateMode = CreateMode.Default;
ManagedHsmProperties.EnablePurgeProtection = false;
ManagedHsmProperties.EnableSoftDelete = true;
ManagedHsmProperties.NetworkAcls = new MhsmNetworkRuleSet()
{
Bypass = "AzureServices",
DefaultAction = "Deny" //Property properties.networkAcls.ipRules is not supported currently and must be set to null.
};
ManagedHsmProperties.PublicNetworkAccess = PublicNetworkAccess.Disabled;
ManagedHsmProperties.SoftDeleteRetentionInDays = 10;
ManagedHsmProperties.TenantId = TenantIdGuid;
}
}
}
| 44.95935 | 163 | 0.640868 | [
"MIT"
] | BaherAbdullah/azure-sdk-for-net | sdk/keyvault/Azure.ResourceManager.KeyVault/tests/VaultOperationsTestsBase.cs | 5,530 | C# |
using System.Threading;
using FinancialTransactionsApi.V1.UseCase;
using Bogus;
using FluentAssertions;
using Microsoft.Extensions.HealthChecks;
using Moq;
using Xunit;
namespace FinancialTransactionsApi.Tests.V1.UseCase
{
public class DbHealthCheckUseCaseTests
{
private Mock<IHealthCheckService> _mockHealthCheckService;
private DbHealthCheckUseCase _classUnderTest;
private readonly Faker _faker = new Faker();
private string _description;
public DbHealthCheckUseCaseTests()
{
_description = _faker.Random.Words();
_mockHealthCheckService = new Mock<IHealthCheckService>();
CompositeHealthCheckResult compositeHealthCheckResult = new CompositeHealthCheckResult(CheckStatus.Healthy);
compositeHealthCheckResult.Add("test", CheckStatus.Healthy, _description);
_mockHealthCheckService.Setup(s =>
s.CheckHealthAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(compositeHealthCheckResult);
_classUnderTest = new DbHealthCheckUseCase(_mockHealthCheckService.Object);
}
[Fact]
public void ReturnsResponseWithStatus()
{
var response = _classUnderTest.Execute();
response.Should().NotBeNull();
response.Success.Should().BeTrue();
response.Message.Should().BeEquivalentTo("test: " + _description);
}
}
}
| 31.170213 | 120 | 0.681911 | [
"MIT"
] | LBHackney-IT/financial-transactions-api | FinancialTransactionsApi.Tests/V1/UseCase/DbHealthCheckUseCaseTests.cs | 1,465 | C# |
using AventStack.ExtentReports.Core;
using AventStack.ExtentReports.MediaStorage;
using AventStack.ExtentReports.Model;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AventStack.ExtentReports.Reporter
{
public class ExtentKlovReporter : AbstractReporter
{
public override string ReporterName => "klov";
public override AnalysisStrategy AnalysisStrategy { get; set; }
public override ReportStatusStats ReportStatusStats { get; protected internal set; }
public string ReportName { get; set; }
public ObjectId ReportId { get; private set; }
public string ProjectName { get; set; }
public ObjectId ProjectId { get; private set; }
private const string DefaultProjectName = "Default";
private const string DefaultKlovServerName = "klov";
private const string DatabaseName = "klov";
public ExtentKlovReporter()
{
_startTime = DateTime.Now;
}
public ExtentKlovReporter(string projectName, string reportName) : this()
{
ProjectName = string.IsNullOrEmpty(projectName) ? DefaultProjectName : projectName;
ReportName = string.IsNullOrEmpty(reportName) ? "Build " + DateTime.Now : reportName;
}
/// <summary>
/// Connects to MongoDB default settings, localhost:27017
/// </summary>
public void InitMongoDbConnection()
{
_mongoClient = new MongoClient();
}
public void InitMongoDbConnection(string host, int port = -1)
{
var conn = "mongodb://" + host;
conn += port > -1 ? ":" + port : "";
_mongoClient = new MongoClient(conn);
}
/// <summary>
/// Connects to MongoDB using a connection string.
/// Example: mongodb://host:27017,host2:27017/?replicaSet=rs0
/// </summary>
/// <param name="connectionString"></param>
public void InitMongoDbConnection(string connectionString)
{
_mongoClient = new MongoClient(connectionString);
}
public void InitMongoDbConnection(MongoClientSettings settings)
{
_mongoClient = new MongoClient(settings);
}
public void InitKlovServerConnection(string url)
{
_url = url;
}
public override void Start()
{
var db = _mongoClient.GetDatabase(DatabaseName);
InitializeCollections(db);
SetupProject();
}
private void InitializeCollections(IMongoDatabase db)
{
_projectCollection = db.GetCollection<BsonDocument>("project");
_reportCollection = db.GetCollection<BsonDocument>("report");
_testCollection = db.GetCollection<BsonDocument>("test");
_logCollection = db.GetCollection<BsonDocument>("log");
_exceptionCollection = db.GetCollection<BsonDocument>("exception");
_mediaCollection = db.GetCollection<BsonDocument>("media");
_categoryCollection = db.GetCollection<BsonDocument>("category");
_authorCollection = db.GetCollection<BsonDocument>("author");
_deviceCollection = db.GetCollection<BsonDocument>("device");
_environmentCollection = db.GetCollection<BsonDocument>("environment");
}
private void SetupProject()
{
ProjectName = string.IsNullOrEmpty(ProjectName) ? DefaultProjectName : ProjectName;
var document = new BsonDocument
{
{ "name", ProjectName }
};
var bsonProject = _projectCollection.Find(document).FirstOrDefault();
if (bsonProject != null)
{
ProjectId = bsonProject["_id"].AsObjectId;
}
else
{
document.Add("createdAt", DateTime.Now);
_projectCollection.InsertOne(document);
ProjectId = document["_id"].AsObjectId;
}
SetupReport();
}
private void SetupReport()
{
ReportName = string.IsNullOrEmpty(ReportName) ? "Build " + DateTime.Now : ReportName;
var document = new BsonDocument
{
{ "name", ReportName },
{ "project", ProjectId },
{ "projectName", ProjectName },
{ "startTime", DateTime.Now }
};
_reportCollection.InsertOne(document);
ReportId = document["_id"].AsObjectId;
}
public override void Stop() { }
public override void Flush(ReportAggregates reportAggregates)
{
if (reportAggregates.TestList == null || reportAggregates.TestList.Count == 0)
{
return;
}
this._reportAggregates = reportAggregates;
var filter = Builders<BsonDocument>.Filter.Eq("_id", ReportId);
var update = Builders<BsonDocument>.Update
.Set("endTime", DateTime.Now)
.Set("duration", (DateTime.Now - _startTime).Milliseconds)
.Set("status", StatusHierarchy.GetHighestStatus(reportAggregates.StatusList).ToString().ToLower())
.Set("parentLength", reportAggregates.ReportStatusStats.ParentCount)
.Set("passParentLength", reportAggregates.ReportStatusStats.ParentCountPass)
.Set("failParentLength", reportAggregates.ReportStatusStats.ParentCountFail)
.Set("fatalParentLength", reportAggregates.ReportStatusStats.ParentCountFatal)
.Set("errorParentLength", reportAggregates.ReportStatusStats.ParentCountError)
.Set("warningParentLength", reportAggregates.ReportStatusStats.ParentCountWarning)
.Set("skipParentLength", reportAggregates.ReportStatusStats.ParentCountSkip)
.Set("exceptionsParentLength", reportAggregates.ReportStatusStats.ParentCountExceptions)
.Set("childLength", reportAggregates.ReportStatusStats.ChildCount)
.Set("passChildLength", reportAggregates.ReportStatusStats.ChildCountPass)
.Set("failChildLength", reportAggregates.ReportStatusStats.ChildCountFail)
.Set("fatalChildLength", reportAggregates.ReportStatusStats.ChildCountFatal)
.Set("errorChildLength", reportAggregates.ReportStatusStats.ChildCountError)
.Set("warningChildLength", reportAggregates.ReportStatusStats.ChildCountWarning)
.Set("skipChildLength", reportAggregates.ReportStatusStats.ChildCountSkip)
.Set("infoChildLength", reportAggregates.ReportStatusStats.ChildCountInfo)
.Set("exceptionsChildLength", reportAggregates.ReportStatusStats.ChildCountExceptions)
.Set("grandChildLength", reportAggregates.ReportStatusStats.GrandChildCount)
.Set("passGrandChildLength", reportAggregates.ReportStatusStats.GrandChildCountPass)
.Set("failGrandChildLength", reportAggregates.ReportStatusStats.GrandChildCountFail)
.Set("fatalGrandChildLength", reportAggregates.ReportStatusStats.GrandChildCountFatal)
.Set("errorGrandChildLength", reportAggregates.ReportStatusStats.GrandChildCountError)
.Set("warningGrandChildLength", reportAggregates.ReportStatusStats.GrandChildCountWarning)
.Set("skipGrandChildLength", reportAggregates.ReportStatusStats.GrandChildCountSkip)
.Set("exceptionsGrandChildLength", reportAggregates.ReportStatusStats.GrandChildCountExceptions)
.Set("analysisStrategy", AnalysisStrategy.ToString().ToUpper());
_reportCollection.UpdateOne(filter, update);
}
public override void OnAuthorAssigned(Test test, Author author)
{
}
public override void OnCategoryAssigned(Test test, Category category)
{
}
public override void OnDeviceAssigned(Test test, Device device)
{
}
public override void OnLogAdded(Test test, Log log)
{
var document = new BsonDocument
{
{ "test", test.ObjectId },
{ "project", ProjectId },
{ "report", ReportId },
{ "testName", test.Name },
{ "sequence", log.Sequence },
{ "status", log.Status.ToString().ToLower() },
{ "timestamp", log.Timestamp },
{ "details", log.Details }
};
if (log.HasScreenCapture && log.ScreenCaptureContext.FirstOrDefault().IsBase64)
{
document["details"] = log.Details + log.ScreenCaptureContext.FirstOrDefault().Source;
}
_logCollection.InsertOne(document);
var id = document["_id"].AsObjectId;
log.ObjectId = id;
if (test.HasException)
{
if (_exceptionNameObjectIdCollection == null)
_exceptionNameObjectIdCollection = new Dictionary<string, ObjectId>();
var ex = test.ExceptionInfoContext.FirstOrDefault();
document = new BsonDocument
{
{ "report", ReportId },
{ "project", ProjectId },
{ "name", ex.Name }
};
var findResult = _exceptionCollection.Find(document).FirstOrDefault();
if (!_exceptionNameObjectIdCollection.ContainsKey(ex.Name))
{
if (findResult != null)
{
_exceptionNameObjectIdCollection.Add(ex.Name, findResult["_id"].AsObjectId);
}
else
{
document = new BsonDocument
{
{ "project", ProjectId },
{ "report", ReportId },
{ "name", ex.Name },
{ "stacktrace", ((ExceptionInfo)ex).Exception.StackTrace },
{ "testCount", 0 }
};
_exceptionCollection.InsertOne(document);
var exId = document["_id"].AsObjectId;
document = new BsonDocument
{
{ "_id", exId }
};
findResult = _exceptionCollection.Find(document).FirstOrDefault();
_exceptionNameObjectIdCollection.Add(ex.Name, exId);
}
}
var testCount = ((int)(findResult["testCount"])) + 1;
var filter = Builders<BsonDocument>.Filter.Eq("_id", findResult["_id"].AsObjectId);
var update = Builders<BsonDocument>.Update.Set("testCount", testCount);
_exceptionCollection.UpdateOne(filter, update);
filter = Builders<BsonDocument>.Filter.Eq("_id", test.ObjectId);
update = Builders<BsonDocument>.Update.Set("exception", _exceptionNameObjectIdCollection[ex.Name]);
_testCollection.UpdateOne(filter, update);
}
EndTestRecursive(test);
}
private void EndTestRecursive(Test test)
{
var filter = Builders<BsonDocument>.Filter.Eq("_id", test.ObjectId);
var update = Builders<BsonDocument>.Update
.Set("status", test.Status.ToString().ToLower())
.Set("endTime", test.EndTime)
.Set("duration", test.RunDuration.Milliseconds)
.Set("leaf", test.HasChildren)
.Set("childNodesLength", test.NodeContext.Count)
.Set("categorized", test.HasCategory)
.Set("description", test.Description);
_testCollection.FindOneAndUpdate(filter, update);
if (test.Level > 0)
{
EndTestRecursive(test.Parent);
}
}
public override void OnScreenCaptureAdded(Test test, ScreenCapture screenCapture)
{
SaveScreenCapture(test, screenCapture);
}
public override void OnScreenCaptureAdded(Log log, ScreenCapture screenCapture)
{
SaveScreenCapture(log, screenCapture);
}
private void SaveScreenCapture(BasicMongoReportElement el, ScreenCapture screenCapture)
{
if (_mediaStorageHandler == null)
{
KlovMedia klovMedia = new KlovMedia()
{
ProjectId = ProjectId,
ReportId = ReportId,
MediaCollection = _mediaCollection
};
_mediaStorageHandler = new KlovMediaStorageHandler(_url, klovMedia);
}
_mediaStorageHandler.SaveScreenCapture(el, screenCapture);
}
public override void OnTestRemoved(Test test)
{
}
public override void OnTestStarted(Test test)
{
OnTestStartedHelper(test);
}
public override void OnNodeStarted(Test node)
{
OnTestStartedHelper(node);
}
private void OnTestStartedHelper(Test test)
{
var document = new BsonDocument
{
{ "project", ProjectId },
{ "report", ReportId },
{ "reportName", ReportName },
{ "level", test.Level },
{ "name", test.Name },
{ "status", test.Status.ToString().ToLower() },
{ "description", test.Description },
{ "startTime", test.StartTime },
{ "endTime", test.EndTime },
{ "bdd", test.IsBehaviorDrivenType },
{ "leaf", test.HasChildren },
{ "childNodesLength", test.NodeContext.Count }
};
if (test.IsBehaviorDrivenType)
{
document.Add("bddType", test.BehaviorDrivenType.GetType().Name);
}
if (test.Parent != null)
{
document.Add("parent", test.Parent.ObjectId);
document.Add("parentName", test.Parent.Name);
UpdateTestChildrenCount(test.Parent);
UpdateTestDescription(test.Parent);
}
_testCollection.InsertOne(document);
test.ObjectId = document["_id"].AsObjectId;
}
private void UpdateTestChildrenCount(Test test)
{
var filter = Builders<BsonDocument>.Filter.Eq("_id", test.ObjectId);
var update = Builders<BsonDocument>.Update
.Set("childNodesLength", test.NodeContext.Count);
_testCollection.FindOneAndUpdate(filter, update);
}
private void UpdateTestDescription(Test test)
{
var filter = Builders<BsonDocument>.Filter.Eq("_id", test.ObjectId);
var update = Builders<BsonDocument>.Update
.Set("description", test.Description);
_testCollection.FindOneAndUpdate(filter, update);
}
private string _url;
private KlovMediaStorageHandler _mediaStorageHandler;
private ReportAggregates _reportAggregates;
private DateTime _startTime;
private MongoClient _mongoClient;
private IMongoCollection<BsonDocument> _projectCollection;
private IMongoCollection<BsonDocument> _reportCollection;
private IMongoCollection<BsonDocument> _testCollection;
private IMongoCollection<BsonDocument> _logCollection;
private IMongoCollection<BsonDocument> _exceptionCollection;
private IMongoCollection<BsonDocument> _mediaCollection;
private IMongoCollection<BsonDocument> _categoryCollection;
private IMongoCollection<BsonDocument> _authorCollection;
private IMongoCollection<BsonDocument> _deviceCollection;
private IMongoCollection<BsonDocument> _environmentCollection;
private Dictionary<string, ObjectId> _exceptionNameObjectIdCollection;
}
}
| 40.021898 | 115 | 0.583926 | [
"Apache-2.0"
] | JeevaSanthosh/AutomationPractice | ExtentReports/Reporter/ExtentKlovReporter.cs | 16,451 | C# |
/* Copyright © 2010 Richard G. Todd.
* Licensed under the terms of the Microsoft Public License (Ms-PL).
*/
using System;
using System.Windows;
namespace Prolog
{
/// <summary>
/// Contains state information passed to a <see cref="RoutedClauseEventHandler"/>.
/// </summary>
public class RoutedClauseEventArgs : RoutedEventArgs
{
#region Fields
private Clause m_clause;
#endregion
#region Constructors
public RoutedClauseEventArgs(Clause clause, RoutedEvent routedEvent, object source)
: base(routedEvent, source)
{
if (clause == null)
{
throw new ArgumentNullException("clause");
}
m_clause = clause;
}
public RoutedClauseEventArgs(Clause clause, RoutedEvent routedEvent)
: base(routedEvent)
{
if (clause == null)
{
throw new ArgumentNullException("clause");
}
m_clause = clause;
}
public RoutedClauseEventArgs(Clause clause)
{
if (clause == null)
{
throw new ArgumentNullException("clause");
}
m_clause = clause;
}
#endregion
#region Public Properties
public Clause Clause
{
get { return m_clause; }
}
#endregion
}
}
| 21.507463 | 91 | 0.536433 | [
"MIT"
] | craigbridges/TaskFlow.NET | docs/Research/AI/Prolog/Prolog.NET/Prolog/Prolog/RoutedClauseEventArgs.cs | 1,444 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using CsvHelper.Configuration;
namespace MOE.Common.Models
{
public class ApproachYellowRedActivationAggregation : Aggregation
{
//[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//public int Id { get; set; }
[Key]
[Required]
[Column(Order = 0)]
public override DateTime BinStartTime { get; set; }
[Key]
[Required]
[Column(Order= 1)]
public int ApproachId { get; set; }
public virtual Approach Approach { get; set; }
[Required]
[Column(Order = 2)]
public int SevereRedLightViolations { get; set; }
[Required]
[Column(Order = 3)]
public int TotalRedLightViolations { get; set; }
[Key]
[Required]
[Column(Order = 4)]
public bool IsProtectedPhase { get; set; }
public sealed class
ApproachYellowRedActivationAggregationClassMap : ClassMap<ApproachYellowRedActivationAggregation>
{
public ApproachYellowRedActivationAggregationClassMap()
{
Map(m => m.Approach).Ignore();
//Map(m => m.Id).Name("Record Number");
Map(m => m.BinStartTime).Name("Bin Start Time");
Map(m => m.ApproachId).Name("Approach ID");
Map(m => m.SevereRedLightViolations).Name("Severe Red Light Violations");
Map(m => m.TotalRedLightViolations).Name("Total Red Light Violations");
Map(m => m.IsProtectedPhase).Name("Is Protected Phase");
}
}
}
} | 31.833333 | 109 | 0.588714 | [
"Apache-2.0"
] | AndreRSanchez/ATSPM | MOE.Common/Models/ApproachYellowRedActivationsAggregation.cs | 1,721 | C# |
namespace Adapter
{
public interface ITarget
{
string GetRequest();
}
} | 13.142857 | 29 | 0.586957 | [
"MIT"
] | luiscarlosjunior/courses-content-dotnet | .Net core/DesignPattern/Adapter/ITarget.cs | 92 | C# |
namespace CAS.Master
{
partial class FrmMasterProsenBOP
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.label3 = new System.Windows.Forms.Label();
this.gcPeriod = new KASLibrary.GridControlEx();
this.casDataSet = new CAS.casDataSet();
this.prosenbopBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.prosenbopTableAdapter = new CAS.casDataSetTableAdapters.prosenbopTableAdapter();
((System.ComponentModel.ISupportInitialize)(this.casDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.prosenbopBindingSource)).BeginInit();
this.SuspendLayout();
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Tahoma", 14F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))));
this.label3.Location = new System.Drawing.Point(15, 7);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(232, 23);
this.label3.TabIndex = 4;
this.label3.Text = "Master Prosentase BOP";
//
// gcPeriod
//
this.gcPeriod.BestFitColumn = true;
this.gcPeriod.ExAutoSize = false;
this.gcPeriod.Location = new System.Drawing.Point(15, 45);
this.gcPeriod.Name = "gcPeriod";
this.gcPeriod.Size = new System.Drawing.Size(363, 304);
this.gcPeriod.TabIndex = 3;
//
// casDataSet
//
this.casDataSet.DataSetName = "casDataSet";
this.casDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// prosenbopBindingSource
//
this.prosenbopBindingSource.DataMember = "prosenbop";
this.prosenbopBindingSource.DataSource = this.casDataSet;
//
// prosenbopTableAdapter
//
this.prosenbopTableAdapter.ClearBeforeFill = true;
//
// FrmMasterProsenBOP
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(390, 362);
this.Controls.Add(this.label3);
this.Controls.Add(this.gcPeriod);
this.Name = "FrmMasterProsenBOP";
this.Text = "FrmMasterProsenBOP";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmMasterProsenBOP_FormClosing);
this.Load += new System.EventHandler(this.FrmMasterProsenBOP_Load);
((System.ComponentModel.ISupportInitialize)(this.casDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.prosenbopBindingSource)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label3;
private KASLibrary.GridControlEx gcPeriod;
private casDataSet casDataSet;
private System.Windows.Forms.BindingSource prosenbopBindingSource;
private CAS.casDataSetTableAdapters.prosenbopTableAdapter prosenbopTableAdapter;
}
} | 43.08 | 167 | 0.604225 | [
"MIT"
] | husniaditya/it-inventory | Master/FrmMasterProsenBOP.Designer.cs | 4,308 | C# |
using System;
using System.Threading.Tasks;
using AspNetCore.Proxy.Builders;
using AspNetCore.Proxy.Options;
using Xunit;
namespace AspNetCore.Proxy.Tests.Unit
{
public class HttpProxy
{
[Fact]
public async Task CanExerciseHttpProxyBuilder()
{
const string endpoint = "any";
const string clientName = "bogus";
var httpProxyOptions = HttpProxyOptionsBuilder.Instance.WithHttpClientName(clientName).New();
// Exercise methods by calling them multiple times.
var httpProxy = HttpProxyBuilder.Instance
.New()
.WithEndpoint(endpoint)
.WithOptions(null as Action<IHttpProxyOptionsBuilder>)
.WithOptions(null as IHttpProxyOptionsBuilder)
.WithOptions(b => b.New())
.WithOptions(httpProxyOptions)
.New().Build();
Assert.Equal(endpoint, await httpProxy.EndpointComputer.Invoke(null, null));
Assert.Equal(clientName, httpProxy.Options.HttpClientName);
}
[Fact]
public void CanHttpProxyBuilderFailOnNullEndpointComputer()
{
Assert.ThrowsAny<Exception>(() => {
var httpProxy = HttpProxyBuilder.Instance.Build();
});
}
}
} | 32.341463 | 105 | 0.607843 | [
"MIT"
] | scherenhaenden/AspNetCore.Proxy | src/Test/Unit/HttpProxy.cs | 1,326 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace PhoneManagementSystem.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
} | 47.247748 | 229 | 0.586758 | [
"MIT"
] | andrei-bozhilov/Phone-Management-System | PhoneManagementSystem.WebApi/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs | 20,978 | C# |
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using MyServiceBroker;
using Newtonsoft.Json;
using OpenServiceBroker;
using OpenServiceBroker.Catalogs;
using OpenServiceBroker.Instances;
var builder = WebApplication.CreateBuilder(args);
// Catalog of available services
string catalogPath = File.ReadAllText(Path.Combine(ApplicationEnvironment.ApplicationBasePath, "catalog.json"));
builder.Services.AddSingleton(JsonConvert.DeserializeObject<Catalog>(catalogPath)!);
// Database for storing provisioned service instances
builder.Services.AddDbContext<MyServiceBroker.DbContext>(options => options.UseSqlite(builder.Configuration.GetConnectionString("Database")));
// Implementations of OpenServiceBroker.Server interfaces
builder.Services.AddTransient<ICatalogService, CatalogService>()
.AddTransient<IServiceInstanceBlocking, ServiceInstanceService>();
// Open Service Broker REST API
builder.Services.AddControllers()
.AddOpenServiceBroker();
// Swagger/OpenAPI
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My Service Broker",
Version = "v1"
});
}).AddSwaggerGenNewtonsoftSupport();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
| 29.833333 | 143 | 0.750466 | [
"MIT"
] | AXOOM/OpenServiceBroker | template/Program.cs | 1,611 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("ExtensionMethods.Library")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("ExtensionMethods.Library")]
[assembly: System.Reflection.AssemblyTitleAttribute("ExtensionMethods.Library")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.583333 | 82 | 0.658513 | [
"MIT"
] | SamIge7/SideWork | ExtensionMethods/ExtensionMethods.Library/obj/Debug/netstandard2.0/ExtensionMethods.Library.AssemblyInfo.cs | 1,022 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace InterativeErosionProject
{
/// <summary>
/// Represents 1 layer
/// </summary>
[System.Serializable]
public class Layer
{
///<summary>r - height; g, b - velocity; a - temperature. Can't be negative!!</summary>
[SerializeField]//readonly
public DoubleDataTexture main;
[SerializeField]//readonly
public DoubleDataTexture outFlow;
[SerializeField]
private float damping;
protected readonly ErosionSim link;
protected float size;
///<summary> Forces absolute fluidity</summary>
[SerializeField]
private readonly float overwriteFluidity;
///<summary>Fluidity coefficient</summary>
[SerializeField]//readonly
private float fluidity;
public Layer(string name, int size, float damping, ErosionSim link, float overwriteFluidity, float fluidity)
{
main = new DoubleDataTexture(name, size, RenderTextureFormat.ARGBFloat, FilterMode.Point); // was RFloat
main.ClearColor();
outFlow = new DoubleDataTexture(name, size, RenderTextureFormat.ARGBFloat, FilterMode.Point); //was ARGBHalf
outFlow.ClearColor();
this.damping = damping;
this.link = link;
this.size = size;
this.overwriteFluidity = overwriteFluidity;
this.fluidity = fluidity;
}
public float getFluidity()
{
return fluidity;
}
/// <summary>
/// Calculates flow of field
/// </summary>
public void Flow(RenderTexture onWhat)
{
//main.SetFilterMode(FilterMode.Point);
link.m_outFlowMat.SetFloat("_TexSize", (float)ErosionSim.TEX_SIZE);
link.m_outFlowMat.SetFloat("T", link.timeStep);
link.m_outFlowMat.SetFloat("L", link.PIPE_LENGTH);
link.m_outFlowMat.SetFloat("A", link.CELL_AREA);
link.m_outFlowMat.SetFloat("G", ErosionSim.GRAVITY);
link.m_outFlowMat.SetFloat("_Layers", 4);
link.m_outFlowMat.SetFloat("_Damping", damping);
link.m_outFlowMat.SetTexture("_TerrainField", onWhat);
link.m_outFlowMat.SetTexture("_Field", main.READ);
link.m_outFlowMat.SetFloat("_OverwriteFluidity", overwriteFluidity);
link.m_outFlowMat.SetFloat("_Fluidity", fluidity);
Graphics.Blit(outFlow.READ, outFlow.WRITE, link.m_outFlowMat);
outFlow.Swap(); ;
link.m_fieldUpdateMat.SetFloat("_TexSize", size);
link.m_fieldUpdateMat.SetFloat("T", link.timeStep);
link.m_fieldUpdateMat.SetFloat("L", 1f);
link.m_fieldUpdateMat.SetTexture("_OutFlowField", outFlow.READ);
Graphics.Blit(main.READ, main.WRITE, link.m_fieldUpdateMat);
main.Swap();
//main.SetFilterMode(FilterMode.Bilinear);
}
virtual public void OnDestroy()
{
main.Destroy();
outFlow.Destroy();
}
public void SetFilterMode(FilterMode mode)
{
main.SetFilterMode(mode);
}
}
[System.Serializable]
public class LayerWithTemperature : Layer
{
private static readonly float StefanBoltzmannConstant = 5.670367e-8f;
///<summary>Must be in 0..1 range</summary>
[SerializeField]//readonly
private float emissivity;
///<summary> Joule per kelvin, J/K</summary>
[SerializeField]//readonly
private float heatCapacity;
public LayerWithTemperature(string name, int size, float damping, ErosionSim link, float emissivity
, float heatCapacity, float overwriteFluidity, float fluidity) : base(name, size, damping, link, overwriteFluidity, fluidity)
{
this.emissivity = Mathf.Clamp01(emissivity);
this.heatCapacity = heatCapacity;
}
internal void HeatExchange()
{
link.heatExchangeMat.SetFloat("_StefanBoltzmannConstant", StefanBoltzmannConstant);
link.heatExchangeMat.SetFloat("_Emissivity", emissivity);
link.heatExchangeMat.SetFloat("_HeatCapacity", heatCapacity);
link.heatExchangeMat.SetFloat("T", link.timeStep);
//link.heatExchangeMat.SetTexture("_OutFlowField", outFlow.READ);
Graphics.Blit(main.READ, main.WRITE, link.heatExchangeMat);
main.Swap();
}
}
[System.Serializable]
public class LayerWithVelocity : LayerWithTemperature
{
///<summary> Water speed (2 channels). Used for sediment movement and dissolution</summary>
[SerializeField]
public DoubleDataTexture velocity;
public LayerWithVelocity(string name, int size, float viscosity, ErosionSim link) : base(name, size, viscosity, link, 0.96f, 4181f, 1f, 1f)
{
velocity = new DoubleDataTexture("Water Velocity", size, RenderTextureFormat.ARGBFloat, FilterMode.Bilinear);// was RGHalf
velocity.ClearColor();
}
public override void OnDestroy()
{
base.OnDestroy();
velocity.Destroy();
}
/// <summary>
/// Calculates water velocity
/// </summary>
public void CalcWaterVelocity(float TIME_STEP)
{
link.m_waterVelocityMat.SetFloat("_TexSize", size);
link.m_waterVelocityMat.SetFloat("L", 1f);
link.m_waterVelocityMat.SetTexture("_WaterField", main.READ);
link.m_waterVelocityMat.SetTexture("_WaterFieldOld", main.WRITE);
link.m_waterVelocityMat.SetTexture("_OutFlowField", outFlow.READ);
Graphics.Blit(null, velocity.READ, link.m_waterVelocityMat);
const float viscosity = 10.5f;
const int iterations = 2;
link.m_diffuseVelocityMat.SetFloat("_TexSize", size);
link.m_diffuseVelocityMat.SetFloat("_Alpha", 1f / (viscosity * TIME_STEP));// CELL_AREA == 1f
for (int i = 0; i < iterations; i++)
{
Graphics.Blit(velocity.READ, velocity.WRITE, link.m_diffuseVelocityMat);
velocity.Swap();
}
}
}
[System.Serializable]
public class LayerWithErosion : LayerWithVelocity
{
[SerializeField]
///<summary></summary>
private DoubleDataTexture advectSediment;
[SerializeField]
///<summary> Actual amount of dissolved sediment in water</summary>
public DoubleDataTexture sedimentField;
[SerializeField]
///<summary> Actual amount of dissolved sediment in water</summary>
public DoubleDataTexture sedimentDeposition;
///<summary> Contains surface angels for each point. Used in water erosion only (Why?)</summary>
[SerializeField]
private RenderTexture tiltAngle;
//[SerializeField]
//private RenderTexture sedimentOutFlow;
/// <summary> Rate the sediment is deposited on top layer </summary>
[SerializeField]
private float depositionConstant = 0.015f;
/// <summary> Terrain wouldn't dissolve if water level in cell is lower than this</summary>
[SerializeField]
private float dissolveLimit = 0.001f;
/// <summary> How much sediment the water can carry per 1 unit of water </summary>
[SerializeField]
private float sedimentCapacity = 0.2f;
public LayerWithErosion(string name, int size, float viscosity, ErosionSim link) : base(name, size, viscosity, link)
{
//waterField = new DoubleDataTexture("Water Field", TEX_SIZE, RenderTextureFormat.RFloat, FilterMode.Point);
//waterOutFlow = new DoubleDataTexture("Water outflow", TEX_SIZE, RenderTextureFormat.ARGBHalf, FilterMode.Point);
sedimentField = new DoubleDataTexture("Sediment Field", size, RenderTextureFormat.ARGBFloat, FilterMode.Bilinear);// was RHalf
sedimentField.ClearColor();
advectSediment = new DoubleDataTexture("Sediment Advection", size, RenderTextureFormat.RHalf, FilterMode.Bilinear);// was RHalf
advectSediment.ClearColor();
sedimentDeposition = new DoubleDataTexture("Sediment Deposition", size, RenderTextureFormat.ARGBFloat, FilterMode.Point);// was RHalf
sedimentDeposition.ClearColor();
tiltAngle = DoubleDataTexture.Create("Tilt Angle", size, RenderTextureFormat.RHalf, FilterMode.Point);// was RHalf
//sedimentOutFlow = DoubleDataTexture.Create("sedimentOutFlow", size, RenderTextureFormat.ARGBHalf, FilterMode.Point);// was ARGBHalf
//sedimentOutFlow.ClearColor();
}
/// <summary>
/// Calculates how much ground should go in sediment flow aka force-based erosion
/// Transfers m_terrainField to m_sedimentField basing on
/// m_waterVelocity, m_sedimentCapacity, m_dissolvingConstant,
/// m_depositionConstant, m_tiltAngle, m_minTiltAngle
/// Also calculates m_tiltAngle
/// </summary>
private void DissolveAndDeposition(DoubleDataTexture terrainField, Vector4 dissolvingConstant, float minTiltAngle, int TERRAIN_LAYERS)
{
link.m_tiltAngleMat.SetFloat("_TexSize", size);
link.m_tiltAngleMat.SetFloat("_Layers", TERRAIN_LAYERS);
link.m_tiltAngleMat.SetTexture("_TerrainField", terrainField.READ);
Graphics.Blit(null, tiltAngle, link.m_tiltAngleMat);
link.dissolutionAndDepositionMat.SetTexture("_TerrainField", terrainField.READ);
link.dissolutionAndDepositionMat.SetTexture("_SedimentField", sedimentField.READ);
link.dissolutionAndDepositionMat.SetTexture("_VelocityField", velocity.READ);
link.dissolutionAndDepositionMat.SetTexture("_WaterField", main.READ);
link.dissolutionAndDepositionMat.SetTexture("_TiltAngle", tiltAngle);
link.dissolutionAndDepositionMat.SetFloat("_MinTiltAngle", minTiltAngle);
link.dissolutionAndDepositionMat.SetFloat("_SedimentCapacity", sedimentCapacity);
link.dissolutionAndDepositionMat.SetVector("_DissolvingConstant", dissolvingConstant);
link.dissolutionAndDepositionMat.SetFloat("_DepositionConstant", depositionConstant);
link.dissolutionAndDepositionMat.SetFloat("_Layers", (float)TERRAIN_LAYERS);
link.dissolutionAndDepositionMat.SetFloat("_DissolveLimit", dissolveLimit); //nash added it
RenderTexture[] terrainAndSediment = new RenderTexture[3] { terrainField.WRITE, sedimentField.WRITE, sedimentDeposition.WRITE };
RTUtility.MultiTargetBlit(terrainAndSediment, link.dissolutionAndDepositionMat);
terrainField.Swap();
sedimentField.Swap();
sedimentDeposition.Swap();
}
///// <summary>
///// Moves sediment
///// </summary>
//private void AlternativeAdvectSediment()
//{
// moveByLiquidMat.SetFloat("T", TIME_STEP);
// moveByLiquidMat.SetTexture("_OutFlow", outFlow.READ);
// moveByLiquidMat.SetTexture("_LuquidLevel", main.READ);
// Graphics.Blit(sedimentField.READ, sedimentOutFlow, moveByLiquidMat);
// m_fieldUpdateMat.SetFloat("_TexSize", (float)TEX_SIZE);
// m_fieldUpdateMat.SetFloat("T", TIME_STEP);
// m_fieldUpdateMat.SetFloat("L", PIPE_LENGTH);
// m_fieldUpdateMat.SetTexture("_OutFlowField", sedimentOutFlow);
// Graphics.Blit(sedimentField.READ, sedimentField.WRITE, m_fieldUpdateMat);
// sedimentField.Swap();
//}
/// <summary>
/// Moves sediment
/// </summary>
private void AdvectSediment(float TIME_STEP)
{
link.m_advectSedimentMat.SetFloat("_TexSize", size);
link.m_advectSedimentMat.SetFloat("T", TIME_STEP);
link.m_advectSedimentMat.SetFloat("_VelocityFactor", 1.0f);
link.m_advectSedimentMat.SetTexture("_VelocityField", velocity.READ);
//is bug? No its no
Graphics.Blit(sedimentField.READ, advectSediment.READ, link.m_advectSedimentMat);
link.m_advectSedimentMat.SetFloat("_VelocityFactor", -1.0f);
Graphics.Blit(advectSediment.READ, advectSediment.WRITE, link.m_advectSedimentMat);
link.m_processMacCormackMat.SetFloat("_TexSize", size);
link.m_processMacCormackMat.SetFloat("T", TIME_STEP);
link.m_processMacCormackMat.SetTexture("_VelocityField", velocity.READ);
link.m_processMacCormackMat.SetTexture("_InterField1", advectSediment.READ);
link.m_processMacCormackMat.SetTexture("_InterField2", advectSediment.WRITE);
Graphics.Blit(sedimentField.READ, sedimentField.WRITE, link.m_processMacCormackMat);
sedimentField.Swap();
}
public override void OnDestroy()
{
base.OnDestroy();
advectSediment.Destroy();
sedimentField.Destroy();
sedimentDeposition.Destroy();
//sedimentOutFlow.Destroy();
GameObject.Destroy(tiltAngle);
}
internal void SimulateErosion(DoubleDataTexture terrainField, Vector4 dissolvingConstant, float minTiltAngle, int TERRAIN_LAYERS, float TIME_STEP)
{
DissolveAndDeposition(terrainField, dissolvingConstant, minTiltAngle, TERRAIN_LAYERS);
AdvectSediment(TIME_STEP);
//AlternativeAdvectSediment();
}
public void SetSedimentDepositionRate(float value)
{
depositionConstant = value;
}
public void SetSedimentCapacity(float value)
{
sedimentCapacity = value;
}
}
}
| 43.286154 | 154 | 0.644655 | [
"MIT"
] | LiamFallon213/Interactive-Erosion | Assets/InteractiveErosion/Scripts/Layer.cs | 14,070 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes.ErrorCases
{
public class ExceptionInRegisterMethodAsync : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(CodeFixServiceTests.MockFixer.Id); }
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
throw new Exception($"Exception thrown in register method of {nameof(ExceptionInRegisterMethodAsync)}");
}
}
}
| 35.833333 | 116 | 0.749767 | [
"MIT"
] | 333fred/roslyn | src/EditorFeatures/Test/CodeFixes/ErrorCases/CodeFixExceptionInRegisterMethodAsync.cs | 1,077 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ShareLink.Areas.AutoTool.ViewModels
{
public class NhanDienShareLinkViewModel
{
public List<ShareLinkSimple> ListLink { get; set; }
public string Template { get; set; }
public NhanDienShareLinkViewModel(List<ShareLinkSimple> ListLink, string Template)
{
this.ListLink = ListLink;
this.Template = Template;
}
}
}
| 22.772727 | 91 | 0.670659 | [
"MIT"
] | HoangnguyenDev/ShareLink | Code/ShareLink/ShareLink/Areas/AutoTool/ViewModels/NhanDienShareLinkViewModel.cs | 503 | C# |
#region License
// /*
// * ######
// * ######
// * ############ ####( ###### #####. ###### ############ ############
// * ############# #####( ###### #####. ###### ############# #############
// * ###### #####( ###### #####. ###### ##### ###### ##### ######
// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
// * ###### ###### #####( ###### #####. ###### ##### ##### ######
// * ############# ############# ############# ############# ##### ######
// * ############ ############ ############# ############ ##### ######
// * ######
// * #############
// * ############
// *
// * Adyen Dotnet API Library
// *
// * Copyright (c) 2019 Adyen B.V.
// * This file is open source and available under the MIT license.
// * See the LICENSE file for more info.
// */
#endregion
using Adyen.CloudApiSerialization;
namespace Adyen.Model.Nexo
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class CardReaderInitResponse : IMessagePayload
{
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Response Response;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("TrackData", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public TrackData[] TrackData;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public ICCResetData ICCResetData;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public EntryModeType[] EntryMode;
}
} | 39.346154 | 119 | 0.424242 | [
"MIT"
] | AlexandrosMor/adyen-dotnet-api-library | Adyen/Model/Nexo/CardReaderInitResponse.cs | 2,048 | C# |
#region MIT License
//
// Filename: ICellBitmapCell.cs
//
// Copyright © 2011-2013 Felix Concordia SARL. All rights reserved.
// Felix Concordia SARL, 400 avenue Roumanille, Bat 7 - BP 309, 06906 Sophia-Antipolis Cedex, FRANCE.
//
// Copyright © 2005-2011 MEDIT S.A. All rights reserved.
// MEDIT S.A., 2 rue du Belvedere, 91120 Palaiseau, FRANCE.
//
// Copyright © 2005 www.devage.com, Davide Icardi
//
// 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.Drawing;
using System.Runtime.InteropServices;
namespace Fr.Medit.MedDataGrid.Cells
{
/// <summary>
/// Interface for informations about a bitmap cell.
/// </summary>
[ComVisible(false)]
public interface ICellBitmapCell
{
/// <summary>
/// return image (equal to the Value property but returns a Bitmap). Call the GetValue
/// </summary>
/// <param name="position">The position.</param>
/// <returns></returns>
Bitmap GetBitmap(Position position);
/// <summary>
/// Set Image, call the Model.SetCellValue.
/// Can be called only if EnableEdit is true
/// </summary>
/// <param name="position">The position.</param>
/// <param name="bitmap">The checked bitmap.</param>
void SetBitmap(Position position, Bitmap bitmap);
}
} | 39.517241 | 101 | 0.72164 | [
"MIT"
] | stewartadcock/meddatagrid | Cells/ICellBitmapCell.cs | 2,295 | C# |
using System;
using System.Linq;
using SystemDot.Messaging.Packaging;
using SystemDot.Messaging.RequestReply.ExceptionHandling;
using SystemDot.Messaging.Specifications.publishing;
using SystemDot.Messaging.Storage;
using Machine.Specifications;
namespace SystemDot.Messaging.Specifications.exception_replying_for_request_reply
{
[Subject(SpecificationGroup.Description)]
public class when_failing_the_handling_of_a_request : WithMessageConfigurationSubject
{
const string ReceiverAddress = "ReceiverAddress";
static Exception exception;
Establish context = () =>
Configuration.Configure.Messaging()
.UsingInProcessTransport()
.OpenChannel(ReceiverAddress)
.ForRequestReplyReceiving()
.WithDurability()
.RegisterHandlers(r => r.RegisterHandler(new FailingMessageHandler<Int64>()))
.Initialise();
Because of = () => exception = Catch.Exception(
() => GetServer().ReceiveMessage(
new MessagePayload()
.SetMessageBody(1)
.SetFromChannel("SenderAddress")
.SetToChannel(ReceiverAddress)
.SetChannelType(PersistenceUseType.RequestSend)
.Sequenced()));
It should_reply_with_an_exception_occurred_message = () =>
GetServer().SentMessages.ExcludeAcknowledgements()
.First().DeserialiseTo<ExceptionOccured>().Message.ShouldEqual(exception.Message);
}
}
| 39.375 | 98 | 0.654603 | [
"Apache-2.0"
] | SystemDot/SystemDotServiceBus | SystemDotMessaging/Projects/SystemDot.Messaging.Specifications/exception_replying_for_request_reply/when_failing_the_handling_of_a_request.cs | 1,577 | C# |
// Copyright (c) 2011-2019 Roland Pheasant. All rights reserved.
// Roland Pheasant licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using DynamicData.Kernel;
namespace DynamicData.Cache.Internal
{
internal sealed class SizeLimiter<TObject, TKey>
{
private readonly ChangeAwareCache<ExpirableItem<TObject, TKey>, TKey> _cache = new ChangeAwareCache<ExpirableItem<TObject, TKey>, TKey>();
private readonly int _sizeLimit;
public SizeLimiter(int size)
{
_sizeLimit = size;
}
public IChangeSet<TObject, TKey> Change(IChangeSet<ExpirableItem<TObject, TKey>, TKey> updates)
{
_cache.Clone(updates);
var itemstoexpire = _cache.KeyValues
.OrderByDescending(exp => exp.Value.ExpireAt)
.Skip(_sizeLimit)
.Select(exp => new Change<TObject, TKey>(ChangeReason.Remove, exp.Key, exp.Value.Value))
.ToList();
if (itemstoexpire.Count > 0)
{
_cache.Remove(itemstoexpire.Select(exp => exp.Key));
}
var notifications = _cache.CaptureChanges();
var changed = notifications.Select(update => new Change<TObject, TKey>
(
update.Reason,
update.Key,
update.Current.Value,
update.Previous.HasValue ? update.Previous.Value.Value : Optional<TObject>.None
));
return new ChangeSet<TObject, TKey>(changed);
}
public KeyValuePair<TKey, TObject>[] CloneAndReturnExpiredOnly(IChangeSet<ExpirableItem<TObject, TKey>, TKey> updates)
{
_cache.Clone(updates);
_cache.CaptureChanges(); //Clear any changes
return _cache.KeyValues.OrderByDescending(exp => exp.Value.Index)
.Skip(_sizeLimit)
.Select(kvp => new KeyValuePair<TKey, TObject>(kvp.Key, kvp.Value.Value))
.ToArray();
}
}
}
| 41.245902 | 146 | 0.516693 | [
"MIT"
] | EmilienDup/DynamicData | src/DynamicData/Cache/Internal/SizeLimiter.cs | 2,518 | C# |
using NServiceBus;
public class Usage
{
void Basic(Configure configure)
{
#region rabbitmq-config-basic
configure.UseTransport<NServiceBus.RabbitMQ>();
#endregion
}
void CustomConnectionString(Configure configure)
{
#region rabbitmq-config-connectionstring-in-code
configure.UseTransport<NServiceBus.RabbitMQ>(() => "My custom connection string");
#endregion
}
void CustomConnectionStringName(Configure configure)
{
#region rabbitmq-config-connectionstringname
configure.UseTransport<NServiceBus.RabbitMQ>("MyConnectionStringName");
#endregion
}
}
| 23.1 | 91 | 0.650794 | [
"Apache-2.0"
] | A-Franklin/docs.particular.net | Snippets/Rabbit/Rabbit_1/Usage.cs | 666 | C# |
using System;
using RuneForge.Game.Entities;
namespace RuneForge.Game.Components.Implementations
{
public class MeleeCombatComponent : Component
{
public decimal AttackPower { get; }
public TimeSpan CycleTime { get; }
public TimeSpan ActionTime { get; }
public Entity TargetEntity { get; set; }
public TimeSpan TimeElapsed { get; set; }
public bool CycleInProgress { get; set; }
public bool ActionTaken { get; set; }
public MeleeCombatComponent(decimal attackPower, TimeSpan cycleTime, TimeSpan actionTime)
{
AttackPower = attackPower;
CycleTime = cycleTime;
ActionTime = actionTime;
TimeElapsed = TimeSpan.Zero;
CycleInProgress = false;
ActionTaken = false;
}
public void Reset()
{
TargetEntity = null;
TimeElapsed = TimeSpan.Zero;
CycleInProgress = false;
ActionTaken = false;
}
}
}
| 24.571429 | 97 | 0.592054 | [
"MIT"
] | RuneForge/RuneForge | Source/RuneForge.Game/Components/Implementations/MeleeCombatComponent.cs | 1,034 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Cloud.Governance.Client.Client.OpenAPIDateConverter;
namespace Cloud.Governance.Client.Model
{
/// <summary>
/// ApplyGroupPolicyModel
/// </summary>
[DataContract(Name = "ApplyGroupPolicyModel")]
public partial class ApplyGroupPolicyModel : IEquatable<ApplyGroupPolicyModel>, IValidatableObject
{
/// <summary>
/// Gets or Sets SubType
/// </summary>
[DataMember(Name = "subType", EmitDefaultValue = false)]
public GroupPolicySubType? SubType { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ApplyGroupPolicyModel" /> class.
/// </summary>
/// <param name="subType">subType.</param>
/// <param name="policyId">policyId.</param>
/// <param name="isApplyAllSetting">isApplyAllSetting (default to false).</param>
/// <param name="isApplyQuota">isApplyQuota (default to false).</param>
/// <param name="isApplySharing">isApplySharing (default to false).</param>
/// <param name="isApplyQuotaThreshold">isApplyQuotaThreshold (default to false).</param>
/// <param name="isApplyDeactivatedElection">isApplyDeactivatedElection (default to false).</param>
/// <param name="isApplyLifecycle">isApplyLifecycle (default to false).</param>
/// <param name="lifecycleRenewalSetting">lifecycleRenewalSetting.</param>
/// <param name="filter">filter.</param>
/// <param name="selectedObjects">selectedObjects.</param>
/// <param name="hasOngoingTasks">hasOngoingTasks (default to false).</param>
/// <param name="isApplyUniqueAccess">isApplyUniqueAccess (default to false).</param>
public ApplyGroupPolicyModel(GroupPolicySubType? subType = default(GroupPolicySubType?), Guid policyId = default(Guid), bool isApplyAllSetting = false, bool isApplyQuota = false, bool isApplySharing = false, bool isApplyQuotaThreshold = false, bool isApplyDeactivatedElection = false, bool isApplyLifecycle = false, LifecycleRenewalSetting lifecycleRenewalSetting = default(LifecycleRenewalSetting), string filter = default(string), List<string> selectedObjects = default(List<string>), bool hasOngoingTasks = false, bool isApplyUniqueAccess = false)
{
this.SubType = subType;
this.PolicyId = policyId;
this.IsApplyAllSetting = isApplyAllSetting;
this.IsApplyQuota = isApplyQuota;
this.IsApplySharing = isApplySharing;
this.IsApplyQuotaThreshold = isApplyQuotaThreshold;
this.IsApplyDeactivatedElection = isApplyDeactivatedElection;
this.IsApplyLifecycle = isApplyLifecycle;
this.LifecycleRenewalSetting = lifecycleRenewalSetting;
this.Filter = filter;
this.SelectedObjects = selectedObjects;
this.HasOngoingTasks = hasOngoingTasks;
this.IsApplyUniqueAccess = isApplyUniqueAccess;
}
/// <summary>
/// Gets or Sets PolicyId
/// </summary>
[DataMember(Name = "policyId", EmitDefaultValue = false)]
public Guid PolicyId { get; set; }
/// <summary>
/// Gets or Sets IsApplyAllSetting
/// </summary>
[DataMember(Name = "isApplyAllSetting", EmitDefaultValue = false)]
public bool IsApplyAllSetting { get; set; }
/// <summary>
/// Gets or Sets IsApplyQuota
/// </summary>
[DataMember(Name = "isApplyQuota", EmitDefaultValue = false)]
public bool IsApplyQuota { get; set; }
/// <summary>
/// Gets or Sets IsApplySharing
/// </summary>
[DataMember(Name = "isApplySharing", EmitDefaultValue = false)]
public bool IsApplySharing { get; set; }
/// <summary>
/// Gets or Sets IsApplyQuotaThreshold
/// </summary>
[DataMember(Name = "isApplyQuotaThreshold", EmitDefaultValue = false)]
public bool IsApplyQuotaThreshold { get; set; }
/// <summary>
/// Gets or Sets IsApplyDeactivatedElection
/// </summary>
[DataMember(Name = "isApplyDeactivatedElection", EmitDefaultValue = false)]
public bool IsApplyDeactivatedElection { get; set; }
/// <summary>
/// Gets or Sets IsApplyLifecycle
/// </summary>
[DataMember(Name = "isApplyLifecycle", EmitDefaultValue = false)]
public bool IsApplyLifecycle { get; set; }
/// <summary>
/// Gets or Sets LifecycleRenewalSetting
/// </summary>
[DataMember(Name = "lifecycleRenewalSetting", EmitDefaultValue = true)]
public LifecycleRenewalSetting LifecycleRenewalSetting { get; set; }
/// <summary>
/// Gets or Sets Filter
/// </summary>
[DataMember(Name = "filter", EmitDefaultValue = true)]
public string Filter { get; set; }
/// <summary>
/// Gets or Sets SelectedObjects
/// </summary>
[DataMember(Name = "selectedObjects", EmitDefaultValue = true)]
public List<string> SelectedObjects { get; set; }
/// <summary>
/// Gets or Sets HasOngoingTasks
/// </summary>
[DataMember(Name = "hasOngoingTasks", EmitDefaultValue = false)]
public bool HasOngoingTasks { get; set; }
/// <summary>
/// Gets or Sets IsApplyUniqueAccess
/// </summary>
[DataMember(Name = "isApplyUniqueAccess", EmitDefaultValue = false)]
public bool IsApplyUniqueAccess { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ApplyGroupPolicyModel {\n");
sb.Append(" SubType: ").Append(SubType).Append("\n");
sb.Append(" PolicyId: ").Append(PolicyId).Append("\n");
sb.Append(" IsApplyAllSetting: ").Append(IsApplyAllSetting).Append("\n");
sb.Append(" IsApplyQuota: ").Append(IsApplyQuota).Append("\n");
sb.Append(" IsApplySharing: ").Append(IsApplySharing).Append("\n");
sb.Append(" IsApplyQuotaThreshold: ").Append(IsApplyQuotaThreshold).Append("\n");
sb.Append(" IsApplyDeactivatedElection: ").Append(IsApplyDeactivatedElection).Append("\n");
sb.Append(" IsApplyLifecycle: ").Append(IsApplyLifecycle).Append("\n");
sb.Append(" LifecycleRenewalSetting: ").Append(LifecycleRenewalSetting).Append("\n");
sb.Append(" Filter: ").Append(Filter).Append("\n");
sb.Append(" SelectedObjects: ").Append(SelectedObjects).Append("\n");
sb.Append(" HasOngoingTasks: ").Append(HasOngoingTasks).Append("\n");
sb.Append(" IsApplyUniqueAccess: ").Append(IsApplyUniqueAccess).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ApplyGroupPolicyModel);
}
/// <summary>
/// Returns true if ApplyGroupPolicyModel instances are equal
/// </summary>
/// <param name="input">Instance of ApplyGroupPolicyModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ApplyGroupPolicyModel input)
{
if (input == null)
return false;
return
(
this.SubType == input.SubType ||
this.SubType.Equals(input.SubType)
) &&
(
this.PolicyId == input.PolicyId ||
(this.PolicyId != null &&
this.PolicyId.Equals(input.PolicyId))
) &&
(
this.IsApplyAllSetting == input.IsApplyAllSetting ||
this.IsApplyAllSetting.Equals(input.IsApplyAllSetting)
) &&
(
this.IsApplyQuota == input.IsApplyQuota ||
this.IsApplyQuota.Equals(input.IsApplyQuota)
) &&
(
this.IsApplySharing == input.IsApplySharing ||
this.IsApplySharing.Equals(input.IsApplySharing)
) &&
(
this.IsApplyQuotaThreshold == input.IsApplyQuotaThreshold ||
this.IsApplyQuotaThreshold.Equals(input.IsApplyQuotaThreshold)
) &&
(
this.IsApplyDeactivatedElection == input.IsApplyDeactivatedElection ||
this.IsApplyDeactivatedElection.Equals(input.IsApplyDeactivatedElection)
) &&
(
this.IsApplyLifecycle == input.IsApplyLifecycle ||
this.IsApplyLifecycle.Equals(input.IsApplyLifecycle)
) &&
(
this.LifecycleRenewalSetting == input.LifecycleRenewalSetting ||
(this.LifecycleRenewalSetting != null &&
this.LifecycleRenewalSetting.Equals(input.LifecycleRenewalSetting))
) &&
(
this.Filter == input.Filter ||
(this.Filter != null &&
this.Filter.Equals(input.Filter))
) &&
(
this.SelectedObjects == input.SelectedObjects ||
this.SelectedObjects != null &&
input.SelectedObjects != null &&
this.SelectedObjects.SequenceEqual(input.SelectedObjects)
) &&
(
this.HasOngoingTasks == input.HasOngoingTasks ||
this.HasOngoingTasks.Equals(input.HasOngoingTasks)
) &&
(
this.IsApplyUniqueAccess == input.IsApplyUniqueAccess ||
this.IsApplyUniqueAccess.Equals(input.IsApplyUniqueAccess)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.SubType.GetHashCode();
if (this.PolicyId != null)
hashCode = hashCode * 59 + this.PolicyId.GetHashCode();
hashCode = hashCode * 59 + this.IsApplyAllSetting.GetHashCode();
hashCode = hashCode * 59 + this.IsApplyQuota.GetHashCode();
hashCode = hashCode * 59 + this.IsApplySharing.GetHashCode();
hashCode = hashCode * 59 + this.IsApplyQuotaThreshold.GetHashCode();
hashCode = hashCode * 59 + this.IsApplyDeactivatedElection.GetHashCode();
hashCode = hashCode * 59 + this.IsApplyLifecycle.GetHashCode();
if (this.LifecycleRenewalSetting != null)
hashCode = hashCode * 59 + this.LifecycleRenewalSetting.GetHashCode();
if (this.Filter != null)
hashCode = hashCode * 59 + this.Filter.GetHashCode();
if (this.SelectedObjects != null)
hashCode = hashCode * 59 + this.SelectedObjects.GetHashCode();
hashCode = hashCode * 59 + this.HasOngoingTasks.GetHashCode();
hashCode = hashCode * 59 + this.IsApplyUniqueAccess.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 44.736301 | 558 | 0.586236 | [
"Apache-2.0"
] | AvePoint/cloud-governance-client | csharp-netstandard/src/Cloud.Governance.Client/Model/ApplyGroupPolicyModel.cs | 13,063 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("04. ExtractIntrNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04. ExtractIntrNumbers")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8882c8be-7125-4498-8307-c8d737713084")]
// 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.138889 | 84 | 0.745084 | [
"MIT"
] | PhilipYordanov/Software-University-C-Fundamentals-track | CSharpAdvance/Regular Expressions - Lab/RegularExpressions - Lab/04. ExtractIntrNumbers/Properties/AssemblyInfo.cs | 1,376 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2019
//
// 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.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk.Interop.Khronos
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct DisplayPresentInfo
{
/// <summary>
/// The type of this structure.
/// </summary>
public SharpVk.StructureType SType;
/// <summary>
/// Null or an extension-specific structure.
/// </summary>
public void* Next;
/// <summary>
/// A rectangular region of pixels to present. It must be a subset of
/// the image being presented. If DisplayPresentInfoKHR is not
/// specified, this region will be assumed to be the entire presentable
/// image.
/// </summary>
public SharpVk.Rect2D SourceRect;
/// <summary>
/// A rectangular region within the visible region of the swapchain's
/// display mode. If DisplayPresentInfoKHR is not specified, this
/// region will be assumed to be the entire visible region of the
/// visible region of the swapchain's mode. If the specified rectangle
/// is a subset of the display mode's visible region, content from
/// display planes below the swapchain's plane will be visible outside
/// the rectangle. If there are no planes below the swapchain's, the
/// area outside the specified rectangle will be black. If portions of
/// the specified rectangle are outside of the display's visible
/// region, pixels mapping only to those portions of the rectangle will
/// be discarded.
/// </summary>
public SharpVk.Rect2D DestinationRect;
/// <summary>
/// persistent: If this is true, the display engine will enable
/// buffered mode on displays that support it. This allows the display
/// engine to stop sending content to the display until a new image is
/// presented. The display will instead maintain a copy of the last
/// presented image. This allows less power to be used, but may
/// increase presentation latency. If DisplayPresentInfoKHR is not
/// specified, persistent mode will not be used.
/// </summary>
public Bool32 Persistent;
}
}
| 44.259259 | 81 | 0.67364 | [
"MIT"
] | Y-Less/SharpVk | src/SharpVk/Interop/Khronos/DisplayPresentInfo.gen.cs | 3,585 | C# |
namespace EntityFramework.Utilities
{
public class QueryInformation
{
public string Schema { get; set; }
public string Table { get; set; }
public string Alias { get; set; }
public string WhereSql { get; set; }
}
}
| 22.583333 | 45 | 0.575646 | [
"Apache-2.0"
] | mvondracek/NetfoxDetective | Misc/EntityFramework.Utilities/EntityFramework.Utilities/EntityFramework.Utilities/QueryInformation.cs | 273 | C# |
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// AlipayCommerceIotMdeviceprodDevicelogUploadResponse.
/// </summary>
public class AlipayCommerceIotMdeviceprodDevicelogUploadResponse : AlipayResponse
{
}
}
| 24.5 | 85 | 0.734694 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/AlipayCommerceIotMdeviceprodDevicelogUploadResponse.cs | 247 | C# |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* 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.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
#if (COGBOT_LIBOMV || USE_STHREADS)
using ThreadPoolUtil;
using Thread = ThreadPoolUtil.Thread;
using ThreadPool = ThreadPoolUtil.ThreadPool;
using Monitor = ThreadPoolUtil.Monitor;
#endif
using System.Threading;
using System.IO;
using System.Net;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
using Nwc.XmlRpc;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Http;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
#region Enums
/// <summary>
///
/// </summary>
public enum LoginStatus
{
/// <summary></summary>
Failed = -1,
/// <summary></summary>
None = 0,
/// <summary></summary>
ConnectingToLogin,
/// <summary></summary>
ReadingResponse,
/// <summary></summary>
ConnectingToSim,
/// <summary></summary>
Redirecting,
/// <summary></summary>
Success
}
/// <summary>
/// Status of the last application run.
/// Used for error reporting to the grid login service for statistical purposes.
/// </summary>
public enum LastExecStatus
{
/// <summary> Application exited normally </summary>
Normal = 0,
/// <summary> Application froze </summary>
Froze,
/// <summary> Application detected error and exited abnormally </summary>
ForcedCrash,
/// <summary> Other crash </summary>
OtherCrash,
/// <summary> Application froze during logout </summary>
LogoutFroze,
/// <summary> Application crashed during logout </summary>
LogoutCrash
}
#endregion Enums
#region Structs
/// <summary>
/// Login Request Parameters
/// </summary>
public class LoginParams
{
/// <summary>The URL of the Login Server</summary>
public string URI;
/// <summary>The number of milliseconds to wait before a login is considered
/// failed due to timeout</summary>
public int Timeout;
/// <summary>The request method</summary>
/// <remarks>login_to_simulator is currently the only supported method</remarks>
public string MethodName;
/// <summary>The Agents First name</summary>
public string FirstName;
/// <summary>The Agents Last name</summary>
public string LastName;
/// <summary>A md5 hashed password</summary>
/// <remarks>plaintext password will be automatically hashed</remarks>
public string Password;
/// <summary>The agents starting location once logged in</summary>
/// <remarks>Either "last", "home", or a string encoded URI
/// containing the simulator name and x/y/z coordinates e.g: uri:hooper&128&152&17</remarks>
public string Start;
/// <summary>A string containing the client software channel information</summary>
/// <example>Second Life Release</example>
public string Channel;
/// <summary>The client software version information</summary>
/// <remarks>The official viewer uses: Second Life Release n.n.n.n
/// where n is replaced with the current version of the viewer</remarks>
public string Version;
/// <summary>A string containing the platform information the agent is running on</summary>
public string Platform;
/// <summary>A string hash of the network cards Mac Address</summary>
public string MAC;
/// <summary>Unknown or deprecated</summary>
public string ViewerDigest;
/// <summary>A string hash of the first disk drives ID used to identify this clients uniqueness</summary>
public string ID0;
/// <summary>A string containing the viewers Software, this is not directly sent to the login server but
/// instead is used to generate the Version string</summary>
public string UserAgent;
/// <summary>A string representing the software creator. This is not directly sent to the login server but
/// is used by the library to generate the Version information</summary>
public string Author;
/// <summary>If true, this agent agrees to the Terms of Service of the grid its connecting to</summary>
public bool AgreeToTos;
/// <summary>Unknown</summary>
public bool ReadCritical;
/// <summary>Status of the last application run sent to the grid login server for statistical purposes</summary>
public LastExecStatus LastExecEvent = LastExecStatus.Normal;
/// <summary>An array of string sent to the login server to enable various options</summary>
public string[] Options;
/// <summary>A randomly generated ID to distinguish between login attempts. This value is only used
/// internally in the library and is never sent over the wire</summary>
internal UUID LoginID;
/// <summary>
/// Default constuctor, initializes sane default values
/// </summary>
public LoginParams()
{
List<string> options = new List<string>(16);
options.Add("inventory-root");
options.Add("inventory-skeleton");
options.Add("inventory-lib-root");
options.Add("inventory-lib-owner");
options.Add("inventory-skel-lib");
options.Add("initial-outfit");
options.Add("gestures");
options.Add("event_categories");
options.Add("event_notifications");
options.Add("classified_categories");
options.Add("buddy-list");
options.Add("ui-config");
options.Add("tutorial_settings");
options.Add("login-flags");
options.Add("global-textures");
options.Add("adult_compliant");
this.Options = options.ToArray();
this.MethodName = "login_to_simulator";
this.Start = "last";
this.Platform = NetworkManager.GetPlatform();
this.MAC = NetworkManager.GetMAC();
this.ViewerDigest = String.Empty;
this.ID0 = NetworkManager.GetMAC();
this.AgreeToTos = true;
this.ReadCritical = true;
this.LastExecEvent = LastExecStatus.Normal;
}
/// <summary>
/// Instantiates new LoginParams object and fills in the values
/// </summary>
/// <param name="client">Instance of GridClient to read settings from</param>
/// <param name="firstName">Login first name</param>
/// <param name="lastName">Login last name</param>
/// <param name="password">Password</param>
/// <param name="channel">Login channnel (application name)</param>
/// <param name="version">Client version, should be application name + version number</param>
public LoginParams(GridClient client, string firstName, string lastName, string password, string channel, string version)
: this()
{
this.URI = client.Settings.LOGIN_SERVER;
this.Timeout = client.Settings.LOGIN_TIMEOUT;
this.FirstName = firstName;
this.LastName = lastName;
this.Password = password;
this.Channel = channel;
this.Version = version;
}
/// <summary>
/// Instantiates new LoginParams object and fills in the values
/// </summary>
/// <param name="client">Instance of GridClient to read settings from</param>
/// <param name="firstName">Login first name</param>
/// <param name="lastName">Login last name</param>
/// <param name="password">Password</param>
/// <param name="channel">Login channnel (application name)</param>
/// <param name="version">Client version, should be application name + version number</param>
/// <param name="loginURI">URI of the login server</param>
public LoginParams(GridClient client, string firstName, string lastName, string password, string channel, string version, string loginURI)
: this(client, firstName, lastName, password, channel, version)
{
this.URI = loginURI;
}
}
public struct BuddyListEntry
{
public int buddy_rights_given;
public string buddy_id;
public int buddy_rights_has;
}
/// <summary>
/// The decoded data returned from the login server after a successful login
/// </summary>
public struct LoginResponseData
{
/// <summary>true, false, indeterminate</summary>
//[XmlRpcMember("login")]
public string Login;
public bool Success;
public string Reason;
/// <summary>Login message of the day</summary>
public string Message;
public UUID AgentID;
public UUID SessionID;
public UUID SecureSessionID;
public string FirstName;
public string LastName;
public string StartLocation;
/// <summary>M or PG, also agent_region_access and agent_access_max</summary>
public string AgentAccess;
public Vector3 LookAt;
public ulong HomeRegion;
public Vector3 HomePosition;
public Vector3 HomeLookAt;
public int CircuitCode;
public int RegionX;
public int RegionY;
public int SimPort;
public IPAddress SimIP;
public string SeedCapability;
public BuddyListEntry[] BuddyList;
public int SecondsSinceEpoch;
public string UDPBlacklist;
#region Inventory
public UUID InventoryRoot;
public UUID LibraryRoot;
public InventoryFolder[] InventorySkeleton;
public InventoryFolder[] LibrarySkeleton;
public UUID LibraryOwner;
#endregion
#region Redirection
public string NextMethod;
public string NextUrl;
public string[] NextOptions;
public int NextDuration;
#endregion
// These aren't currently being utilized by the library
public string AgentAccessMax;
public string AgentRegionAccess;
public int AOTransition;
public string InventoryHost;
public int MaxAgentGroups;
public string OpenIDUrl;
public string AgentAppearanceServiceURL;
/// <summary>
/// Parse LLSD Login Reply Data
/// </summary>
/// <param name="reply">An <seealso cref="OSDMap"/>
/// contaning the login response data</param>
/// <remarks>XML-RPC logins do not require this as XML-RPC.NET
/// automatically populates the struct properly using attributes</remarks>
public void Parse(OSDMap reply)
{
try
{
AgentID = ParseUUID("agent_id", reply);
SessionID = ParseUUID("session_id", reply);
SecureSessionID = ParseUUID("secure_session_id", reply);
FirstName = ParseString("first_name", reply).Trim('"');
LastName = ParseString("last_name", reply).Trim('"');
StartLocation = ParseString("start_location", reply);
AgentAccess = ParseString("agent_access", reply);
LookAt = ParseVector3("look_at", reply);
Reason = ParseString("reason", reply);
Message = ParseString("message", reply);
Login = reply["login"].AsString();
Success = reply["login"].AsBoolean();
}
catch (OSDException e)
{
Logger.Log("Login server returned (some) invalid data: " + e.Message, Helpers.LogLevel.Warning);
}
// Home
OSDMap home = null;
OSD osdHome = OSDParser.DeserializeLLSDNotation(reply["home"].AsString());
if (osdHome.Type == OSDType.Map)
{
home = (OSDMap)osdHome;
OSD homeRegion;
if (home.TryGetValue("region_handle", out homeRegion) && homeRegion.Type == OSDType.Array)
{
OSDArray homeArray = (OSDArray)homeRegion;
if (homeArray.Count == 2)
HomeRegion = Utils.UIntsToLong((uint)homeArray[0].AsInteger(), (uint)homeArray[1].AsInteger());
else
HomeRegion = 0;
}
HomePosition = ParseVector3("position", home);
HomeLookAt = ParseVector3("look_at", home);
}
else
{
HomeRegion = 0;
HomePosition = Vector3.Zero;
HomeLookAt = Vector3.Zero;
}
CircuitCode = (int)ParseUInt("circuit_code", reply);
RegionX = (int)ParseUInt("region_x", reply);
RegionY = (int)ParseUInt("region_y", reply);
SimPort = (short)ParseUInt("sim_port", reply);
string simIP = ParseString("sim_ip", reply);
IPAddress.TryParse(simIP, out SimIP);
SeedCapability = ParseString("seed_capability", reply);
// Buddy list
OSD buddyLLSD;
if (reply.TryGetValue("buddy-list", out buddyLLSD) && buddyLLSD.Type == OSDType.Array)
{
List<BuddyListEntry> buddys = new List<BuddyListEntry>();
OSDArray buddyArray = (OSDArray)buddyLLSD;
for (int i = 0; i < buddyArray.Count; i++)
{
if (buddyArray[i].Type == OSDType.Map)
{
BuddyListEntry bud = new BuddyListEntry();
OSDMap buddy = (OSDMap)buddyArray[i];
bud.buddy_id = buddy["buddy_id"].AsString();
bud.buddy_rights_given = (int)ParseUInt("buddy_rights_given", buddy);
bud.buddy_rights_has = (int)ParseUInt("buddy_rights_has", buddy);
buddys.Add(bud);
}
BuddyList = buddys.ToArray();
}
}
SecondsSinceEpoch = (int)ParseUInt("seconds_since_epoch", reply);
InventoryRoot = ParseMappedUUID("inventory-root", "folder_id", reply);
InventorySkeleton = ParseInventorySkeleton("inventory-skeleton", reply);
LibraryOwner = ParseMappedUUID("inventory-lib-owner", "agent_id", reply);
LibraryRoot = ParseMappedUUID("inventory-lib-root", "folder_id", reply);
LibrarySkeleton = ParseInventorySkeleton("inventory-skel-lib", reply);
}
public void Parse(Hashtable reply)
{
try
{
AgentID = ParseUUID("agent_id", reply);
SessionID = ParseUUID("session_id", reply);
SecureSessionID = ParseUUID("secure_session_id", reply);
FirstName = ParseString("first_name", reply).Trim('"');
LastName = ParseString("last_name", reply).Trim('"');
// "first_login" for brand new accounts
StartLocation = ParseString("start_location", reply);
AgentAccess = ParseString("agent_access", reply);
LookAt = ParseVector3("look_at", reply);
Reason = ParseString("reason", reply);
Message = ParseString("message", reply);
if (reply.ContainsKey("login"))
{
Login = (string)reply["login"];
Success = Login == "true";
// Parse redirect options
if (Login == "indeterminate")
{
NextUrl = ParseString("next_url", reply);
NextDuration = (int)ParseUInt("next_duration", reply);
NextMethod = ParseString("next_method", reply);
NextOptions = (string[])((ArrayList)reply["next_options"]).ToArray(typeof(string));
}
}
}
catch (Exception e)
{
Logger.Log("Login server returned (some) invalid data: " + e.Message, Helpers.LogLevel.Warning);
}
if (!Success)
return;
// Home
OSDMap home = null;
if (reply.ContainsKey("home"))
{
OSD osdHome = OSDParser.DeserializeLLSDNotation(reply["home"].ToString());
if (osdHome.Type == OSDType.Map)
{
home = (OSDMap)osdHome;
OSD homeRegion;
if (home.TryGetValue("region_handle", out homeRegion) && homeRegion.Type == OSDType.Array)
{
OSDArray homeArray = (OSDArray)homeRegion;
if (homeArray.Count == 2)
HomeRegion = Utils.UIntsToLong((uint)homeArray[0].AsInteger(),
(uint)homeArray[1].AsInteger());
else
HomeRegion = 0;
}
HomePosition = ParseVector3("position", home);
HomeLookAt = ParseVector3("look_at", home);
}
}
else
{
HomeRegion = 0;
HomePosition = Vector3.Zero;
HomeLookAt = Vector3.Zero;
}
CircuitCode = (int)ParseUInt("circuit_code", reply);
RegionX = (int)ParseUInt("region_x", reply);
RegionY = (int)ParseUInt("region_y", reply);
SimPort = (short)ParseUInt("sim_port", reply);
string simIP = ParseString("sim_ip", reply);
IPAddress.TryParse(simIP, out SimIP);
SeedCapability = ParseString("seed_capability", reply);
// Buddy list
if (reply.ContainsKey("buddy-list") && reply["buddy-list"] is ArrayList)
{
List<BuddyListEntry> buddys = new List<BuddyListEntry>();
ArrayList buddyArray = (ArrayList)reply["buddy-list"];
for (int i = 0; i < buddyArray.Count; i++)
{
if (buddyArray[i] is Hashtable)
{
BuddyListEntry bud = new BuddyListEntry();
Hashtable buddy = (Hashtable)buddyArray[i];
bud.buddy_id = ParseString("buddy_id", buddy);
bud.buddy_rights_given = (int)ParseUInt("buddy_rights_given", buddy);
bud.buddy_rights_has = (int)ParseUInt("buddy_rights_has", buddy);
buddys.Add(bud);
}
}
BuddyList = buddys.ToArray();
}
SecondsSinceEpoch = (int)ParseUInt("seconds_since_epoch", reply);
InventoryRoot = ParseMappedUUID("inventory-root", "folder_id", reply);
InventorySkeleton = ParseInventorySkeleton("inventory-skeleton", reply);
LibraryOwner = ParseMappedUUID("inventory-lib-owner", "agent_id", reply);
LibraryRoot = ParseMappedUUID("inventory-lib-root", "folder_id", reply);
LibrarySkeleton = ParseInventorySkeleton("inventory-skel-lib", reply);
// UDP Blacklist
if (reply.ContainsKey("udp_blacklist"))
{
UDPBlacklist = ParseString("udp_blacklist", reply);
}
if (reply.ContainsKey("max-agent-groups"))
{
MaxAgentGroups = (int)ParseUInt("max-agent-groups", reply);
}
else
{
MaxAgentGroups = -1;
}
if (reply.ContainsKey("openid_url"))
{
OpenIDUrl = ParseString("openid_url", reply);
}
if (reply.ContainsKey("agent_appearance_service"))
{
AgentAppearanceServiceURL = ParseString("agent_appearance_service", reply);
}
}
#region Parsing Helpers
public static uint ParseUInt(string key, OSDMap reply)
{
OSD osd;
if (reply.TryGetValue(key, out osd))
return osd.AsUInteger();
else
return 0;
}
public static uint ParseUInt(string key, Hashtable reply)
{
if (reply.ContainsKey(key))
{
object value = reply[key];
if (value is int)
return (uint)(int)value;
}
return 0;
}
public static UUID ParseUUID(string key, OSDMap reply)
{
OSD osd;
if (reply.TryGetValue(key, out osd))
return osd.AsUUID();
else
return UUID.Zero;
}
public static UUID ParseUUID(string key, Hashtable reply)
{
if (reply.ContainsKey(key))
{
UUID value;
if (UUID.TryParse((string)reply[key], out value))
return value;
}
return UUID.Zero;
}
public static string ParseString(string key, OSDMap reply)
{
OSD osd;
if (reply.TryGetValue(key, out osd))
return osd.AsString();
else
return String.Empty;
}
public static string ParseString(string key, Hashtable reply)
{
if (reply.ContainsKey(key))
return String.Format("{0}", reply[key]);
return String.Empty;
}
public static Vector3 ParseVector3(string key, OSDMap reply)
{
OSD osd;
if (reply.TryGetValue(key, out osd))
{
if (osd.Type == OSDType.Array)
{
return ((OSDArray)osd).AsVector3();
}
else if (osd.Type == OSDType.String)
{
OSDArray array = (OSDArray)OSDParser.DeserializeLLSDNotation(osd.AsString());
return array.AsVector3();
}
}
return Vector3.Zero;
}
public static Vector3 ParseVector3(string key, Hashtable reply)
{
if (reply.ContainsKey(key))
{
object value = reply[key];
if (value is IList)
{
IList list = (IList)value;
if (list.Count == 3)
{
float x, y, z;
Single.TryParse((string)list[0], out x);
Single.TryParse((string)list[1], out y);
Single.TryParse((string)list[2], out z);
return new Vector3(x, y, z);
}
}
else if (value is string)
{
OSDArray array = (OSDArray)OSDParser.DeserializeLLSDNotation((string)value);
return array.AsVector3();
}
}
return Vector3.Zero;
}
public static UUID ParseMappedUUID(string key, string key2, OSDMap reply)
{
OSD folderOSD;
if (reply.TryGetValue(key, out folderOSD) && folderOSD.Type == OSDType.Array)
{
OSDArray array = (OSDArray)folderOSD;
if (array.Count == 1 && array[0].Type == OSDType.Map)
{
OSDMap map = (OSDMap)array[0];
OSD folder;
if (map.TryGetValue(key2, out folder))
return folder.AsUUID();
}
}
return UUID.Zero;
}
public static UUID ParseMappedUUID(string key, string key2, Hashtable reply)
{
if (reply.ContainsKey(key) && reply[key] is ArrayList)
{
ArrayList array = (ArrayList)reply[key];
if (array.Count == 1 && array[0] is Hashtable)
{
Hashtable map = (Hashtable)array[0];
return ParseUUID(key2, map);
}
}
return UUID.Zero;
}
public static InventoryFolder[] ParseInventoryFolders(string key, UUID owner, OSDMap reply)
{
List<InventoryFolder> folders = new List<InventoryFolder>();
OSD skeleton;
if (reply.TryGetValue(key, out skeleton) && skeleton.Type == OSDType.Array)
{
OSDArray array = (OSDArray)skeleton;
for (int i = 0; i < array.Count; i++)
{
if (array[i].Type == OSDType.Map)
{
OSDMap map = (OSDMap)array[i];
InventoryFolder folder = new InventoryFolder(map["folder_id"].AsUUID());
folder.PreferredType = (AssetType)map["type_default"].AsInteger();
folder.Version = map["version"].AsInteger();
folder.OwnerID = owner;
folder.ParentUUID = map["parent_id"].AsUUID();
folder.Name = map["name"].AsString();
folders.Add(folder);
}
}
}
return folders.ToArray();
}
public InventoryFolder[] ParseInventorySkeleton(string key, OSDMap reply)
{
List<InventoryFolder> folders = new List<InventoryFolder>();
OSD skeleton;
if (reply.TryGetValue(key, out skeleton) && skeleton.Type == OSDType.Array)
{
OSDArray array = (OSDArray)skeleton;
for (int i = 0; i < array.Count; i++)
{
if (array[i].Type == OSDType.Map)
{
OSDMap map = (OSDMap)array[i];
InventoryFolder folder = new InventoryFolder(map["folder_id"].AsUUID());
folder.Name = map["name"].AsString();
folder.ParentUUID = map["parent_id"].AsUUID();
folder.PreferredType = (AssetType)map["type_default"].AsInteger();
folder.Version = map["version"].AsInteger();
folders.Add(folder);
}
}
}
return folders.ToArray();
}
public InventoryFolder[] ParseInventorySkeleton(string key, Hashtable reply)
{
UUID ownerID;
if (key.Equals("inventory-skel-lib"))
ownerID = LibraryOwner;
else
ownerID = AgentID;
List<InventoryFolder> folders = new List<InventoryFolder>();
if (reply.ContainsKey(key) && reply[key] is ArrayList)
{
ArrayList array = (ArrayList)reply[key];
for (int i = 0; i < array.Count; i++)
{
if (array[i] is Hashtable)
{
Hashtable map = (Hashtable)array[i];
InventoryFolder folder = new InventoryFolder(ParseUUID("folder_id", map));
folder.Name = ParseString("name", map);
folder.ParentUUID = ParseUUID("parent_id", map);
folder.PreferredType = (AssetType)ParseUInt("type_default", map);
folder.Version = (int)ParseUInt("version", map);
folder.OwnerID = ownerID;
folders.Add(folder);
}
}
}
return folders.ToArray();
}
#endregion Parsing Helpers
}
#endregion Structs
/// <summary>
/// Login Routines
/// </summary>
public partial class NetworkManager
{
#region Delegates
//////LoginProgress
//// LoginProgress
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<LoginProgressEventArgs> m_LoginProgress;
///<summary>Raises the LoginProgress Event</summary>
/// <param name="e">A LoginProgressEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnLoginProgress(LoginProgressEventArgs e)
{
EventHandler<LoginProgressEventArgs> handler = m_LoginProgress;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_LoginProgressLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<LoginProgressEventArgs> LoginProgress
{
add { lock (m_LoginProgressLock) { m_LoginProgress += value; } }
remove { lock (m_LoginProgressLock) { m_LoginProgress -= value; } }
}
///// <summary>The event subscribers, null of no subscribers</summary>
//private EventHandler<LoggedInEventArgs> m_LoggedIn;
/////<summary>Raises the LoggedIn Event</summary>
///// <param name="e">A LoggedInEventArgs object containing
///// the data sent from the simulator</param>
//protected virtual void OnLoggedIn(LoggedInEventArgs e)
//{
// EventHandler<LoggedInEventArgs> handler = m_LoggedIn;
// if (handler != null)
// handler(this, e);
//}
///// <summary>Thread sync lock object</summary>
//private readonly object m_LoggedInLock = new object();
///// <summary>Raised when the simulator sends us data containing
///// ...</summary>
//public event EventHandler<LoggedInEventArgs> LoggedIn
//{
// add { lock (m_LoggedInLock) { m_LoggedIn += value; } }
// remove { lock (m_LoggedInLock) { m_LoggedIn -= value; } }
//}
/// <summary>
///
/// </summary>
/// <param name="loginSuccess"></param>
/// <param name="redirect"></param>
/// <param name="replyData"></param>
/// <param name="message"></param>
/// <param name="reason"></param>
public delegate void LoginResponseCallback(bool loginSuccess, bool redirect, string message, string reason, LoginResponseData replyData);
#endregion Delegates
#region Events
/// <summary>Called when a reply is received from the login server, the
/// login sequence will block until this event returns</summary>
private event LoginResponseCallback OnLoginResponse;
#endregion Events
#region Public Members
/// <summary>Seed CAPS URL returned from the login server</summary>
public string LoginSeedCapability = String.Empty;
/// <summary>Current state of logging in</summary>
public LoginStatus LoginStatusCode { get { return InternalStatusCode; } }
/// <summary>Upon login failure, contains a short string key for the
/// type of login error that occurred</summary>
public string LoginErrorKey { get { return InternalErrorKey; } }
/// <summary>The raw XML-RPC reply from the login server, exactly as it
/// was received (minus the HTTP header)</summary>
public string RawLoginReply { get { return InternalRawLoginReply; } }
/// <summary>During login this contains a descriptive version of
/// LoginStatusCode. After a successful login this will contain the
/// message of the day, and after a failed login a descriptive error
/// message will be returned</summary>
public string LoginMessage { get { return InternalLoginMessage; } }
/// <summary>Maximum number of groups an agent can belong to, -1 for unlimited</summary>
public int MaxAgentGroups = -1;
/// <summary>Server side baking service URL</summary>
public string AgentAppearanceServiceURL;
#endregion
#region Private Members
private LoginParams CurrentContext = null;
private AutoResetEvent LoginEvent = new AutoResetEvent(false);
private LoginStatus InternalStatusCode = LoginStatus.None;
private string InternalErrorKey = String.Empty;
private string InternalLoginMessage = String.Empty;
private string InternalRawLoginReply = String.Empty;
private Dictionary<LoginResponseCallback, string[]> CallbackOptions = new Dictionary<LoginResponseCallback, string[]>();
/// <summary>A list of packets obtained during the login process which
/// networkmanager will log but not process</summary>
private readonly List<string> UDPBlacklist = new List<string>();
#endregion
#region Public Methods
/// <summary>
/// Generate sane default values for a login request
/// </summary>
/// <param name="firstName">Account first name</param>
/// <param name="lastName">Account last name</param>
/// <param name="password">Account password</param>
/// <param name="channel">Client application name (channel)</param>
/// <param name="version">Client application name + version</param>
/// <returns>A populated <seealso cref="LoginParams"/> struct containing
/// sane defaults</returns>
public LoginParams DefaultLoginParams(string firstName, string lastName, string password,
string channel, string version)
{
return new LoginParams(Client, firstName, lastName, password, channel, version);
}
/// <summary>
/// Simplified login that takes the most common and required fields
/// </summary>
/// <param name="firstName">Account first name</param>
/// <param name="lastName">Account last name</param>
/// <param name="password">Account password</param>
/// <param name="channel">Client application name (channel)</param>
/// <param name="version">Client application name + version</param>
/// <returns>Whether the login was successful or not. On failure the
/// LoginErrorKey string will contain the error code and LoginMessage
/// will contain a description of the error</returns>
public bool Login(string firstName, string lastName, string password, string channel, string version)
{
return Login(firstName, lastName, password, channel, "last", version);
}
/// <summary>
/// Simplified login that takes the most common fields along with a
/// starting location URI, and can accept an MD5 string instead of a
/// plaintext password
/// </summary>
/// <param name="firstName">Account first name</param>
/// <param name="lastName">Account last name</param>
/// <param name="password">Account password or MD5 hash of the password
/// such as $1$1682a1e45e9f957dcdf0bb56eb43319c</param>
/// <param name="channel">Client application name (channel)</param>
/// <param name="start">Starting location URI that can be built with
/// StartLocation()</param>
/// <param name="version">Client application name + version</param>
/// <returns>Whether the login was successful or not. On failure the
/// LoginErrorKey string will contain the error code and LoginMessage
/// will contain a description of the error</returns>
public bool Login(string firstName, string lastName, string password, string channel, string start,
string version)
{
LoginParams loginParams = DefaultLoginParams(firstName, lastName, password, channel, version);
loginParams.Start = start;
return Login(loginParams);
}
/// <summary>
/// Login that takes a struct of all the values that will be passed to
/// the login server
/// </summary>
/// <param name="loginParams">The values that will be passed to the login
/// server, all fields must be set even if they are String.Empty</param>
/// <returns>Whether the login was successful or not. On failure the
/// LoginErrorKey string will contain the error code and LoginMessage
/// will contain a description of the error</returns>
public bool Login(LoginParams loginParams)
{
BeginLogin(loginParams);
LoginEvent.WaitOne(loginParams.Timeout, false);
if (CurrentContext != null)
{
CurrentContext = null; // Will force any pending callbacks to bail out early
InternalStatusCode = LoginStatus.Failed;
InternalLoginMessage = "Timed out";
return false;
}
return (InternalStatusCode == LoginStatus.Success);
}
public void BeginLogin(LoginParams loginParams)
{
// FIXME: Now that we're using CAPS we could cancel the current login and start a new one
if (CurrentContext != null)
throw new Exception("Login already in progress");
LoginEvent.Reset();
CurrentContext = loginParams;
BeginLogin();
}
public void RegisterLoginResponseCallback(LoginResponseCallback callback)
{
RegisterLoginResponseCallback(callback, null);
}
public void RegisterLoginResponseCallback(LoginResponseCallback callback, string[] options)
{
CallbackOptions.Add(callback, options);
OnLoginResponse += callback;
}
public void UnregisterLoginResponseCallback(LoginResponseCallback callback)
{
CallbackOptions.Remove(callback);
OnLoginResponse -= callback;
}
/// <summary>
/// Build a start location URI for passing to the Login function
/// </summary>
/// <param name="sim">Name of the simulator to start in</param>
/// <param name="x">X coordinate to start at</param>
/// <param name="y">Y coordinate to start at</param>
/// <param name="z">Z coordinate to start at</param>
/// <returns>String with a URI that can be used to login to a specified
/// location</returns>
public static string StartLocation(string sim, int x, int y, int z)
{
return String.Format("uri:{0}&{1}&{2}&{3}", sim, x, y, z);
}
public void AbortLogin()
{
LoginParams loginParams = CurrentContext;
CurrentContext = null; // Will force any pending callbacks to bail out early
// FIXME: Now that we're using CAPS we could cancel the current login and start a new one
if (loginParams == null)
{
Logger.DebugLog("No Login was in progress: " + CurrentContext, Client);
}
else
{
InternalStatusCode = LoginStatus.Failed;
InternalLoginMessage = "Aborted";
}
UpdateLoginStatus(LoginStatus.Failed, "Abort Requested");
}
#endregion
#region Private Methods
private void BeginLogin()
{
LoginParams loginParams = CurrentContext;
// Generate a random ID to identify this login attempt
loginParams.LoginID = UUID.Random();
CurrentContext = loginParams;
#region Sanity Check loginParams
if (loginParams.Options == null)
loginParams.Options = new List<string>().ToArray();
if (loginParams.Password == null)
loginParams.Password = String.Empty;
// Convert the password to MD5 if it isn't already
if (loginParams.Password.Length != 35 && !loginParams.Password.StartsWith("$1$"))
loginParams.Password = Utils.MD5(loginParams.Password);
if (loginParams.ViewerDigest == null)
loginParams.ViewerDigest = String.Empty;
if (loginParams.Version == null)
loginParams.Version = String.Empty;
if (loginParams.UserAgent == null)
loginParams.UserAgent = String.Empty;
if (loginParams.Platform == null)
loginParams.Platform = String.Empty;
if (loginParams.MAC == null)
loginParams.MAC = String.Empty;
if (string.IsNullOrEmpty(loginParams.Channel))
{
Logger.Log("Viewer channel not set. This is a TOS violation on some grids.", Helpers.LogLevel.Warning);
loginParams.Channel = "libopenmetaverse generic client";
}
if (loginParams.Author == null)
loginParams.Author = String.Empty;
#endregion
// TODO: Allow a user callback to be defined for handling the cert
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
// Even though this will compile on Mono 2.4, it throws a runtime exception
//ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificatePolicy.TrustAllCertificateHandler;
if (Client.Settings.USE_LLSD_LOGIN)
{
#region LLSD Based Login
// Create the CAPS login structure
OSDMap loginLLSD = new OSDMap();
loginLLSD["first"] = OSD.FromString(loginParams.FirstName);
loginLLSD["last"] = OSD.FromString(loginParams.LastName);
loginLLSD["passwd"] = OSD.FromString(loginParams.Password);
loginLLSD["start"] = OSD.FromString(loginParams.Start);
loginLLSD["channel"] = OSD.FromString(loginParams.Channel);
loginLLSD["version"] = OSD.FromString(loginParams.Version);
loginLLSD["platform"] = OSD.FromString(loginParams.Platform);
loginLLSD["mac"] = OSD.FromString(loginParams.MAC);
loginLLSD["agree_to_tos"] = OSD.FromBoolean(loginParams.AgreeToTos);
loginLLSD["read_critical"] = OSD.FromBoolean(loginParams.ReadCritical);
loginLLSD["viewer_digest"] = OSD.FromString(loginParams.ViewerDigest);
loginLLSD["id0"] = OSD.FromString(loginParams.ID0);
loginLLSD["last_exec_event"] = OSD.FromInteger((int)loginParams.LastExecEvent);
// Create the options LLSD array
OSDArray optionsOSD = new OSDArray();
for (int i = 0; i < loginParams.Options.Length; i++)
optionsOSD.Add(OSD.FromString(loginParams.Options[i]));
foreach (string[] callbackOpts in CallbackOptions.Values)
{
if (callbackOpts != null)
{
for (int i = 0; i < callbackOpts.Length; i++)
{
if (!optionsOSD.Contains(callbackOpts[i]))
optionsOSD.Add(callbackOpts[i]);
}
}
}
loginLLSD["options"] = optionsOSD;
// Make the CAPS POST for login
Uri loginUri;
try
{
loginUri = new Uri(loginParams.URI);
}
catch (Exception ex)
{
Logger.Log(String.Format("Failed to parse login URI {0}, {1}", loginParams.URI, ex.Message),
Helpers.LogLevel.Error, Client);
return;
}
CapsClient loginRequest = new CapsClient(loginUri);
loginRequest.OnComplete += new CapsClient.CompleteCallback(LoginReplyLLSDHandler);
loginRequest.UserData = CurrentContext;
UpdateLoginStatus(LoginStatus.ConnectingToLogin, String.Format("Logging in as {0} {1}...", loginParams.FirstName, loginParams.LastName));
loginRequest.BeginGetResponse(loginLLSD, OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT);
#endregion
}
else
{
#region XML-RPC Based Login Code
// Create the Hashtable for XmlRpcCs
Hashtable loginXmlRpc = new Hashtable();
loginXmlRpc["first"] = loginParams.FirstName;
loginXmlRpc["last"] = loginParams.LastName;
loginXmlRpc["passwd"] = loginParams.Password;
loginXmlRpc["start"] = loginParams.Start;
loginXmlRpc["channel"] = loginParams.Channel;
loginXmlRpc["version"] = loginParams.Version;
loginXmlRpc["platform"] = loginParams.Platform;
loginXmlRpc["mac"] = loginParams.MAC;
if (loginParams.AgreeToTos)
loginXmlRpc["agree_to_tos"] = "true";
if (loginParams.ReadCritical)
loginXmlRpc["read_critical"] = "true";
loginXmlRpc["id0"] = loginParams.ID0;
loginXmlRpc["last_exec_event"] = (int)loginParams.LastExecEvent;
// Create the options array
ArrayList options = new ArrayList();
for (int i = 0; i < loginParams.Options.Length; i++)
options.Add(loginParams.Options[i]);
foreach (string[] callbackOpts in CallbackOptions.Values)
{
if (callbackOpts != null)
{
for (int i = 0; i < callbackOpts.Length; i++)
{
if (!options.Contains(callbackOpts[i]))
options.Add(callbackOpts[i]);
}
}
}
loginXmlRpc["options"] = options;
try
{
ArrayList loginArray = new ArrayList(1);
loginArray.Add(loginXmlRpc);
XmlRpcRequest request = new XmlRpcRequest(CurrentContext.MethodName, loginArray);
var cc = CurrentContext;
// Start the request
Thread requestThread = new Thread(
delegate()
{
try
{
LoginReplyXmlRpcHandler(
request.Send(cc.URI, cc.Timeout),
loginParams);
}
catch (Exception e)
{
UpdateLoginStatus(LoginStatus.Failed, "Error opening the login server connection: " + e.Message);
}
});
requestThread.Name = "XML-RPC Login";
requestThread.Start();
}
catch (Exception e)
{
UpdateLoginStatus(LoginStatus.Failed, "Error opening the login server connection: " + e);
}
#endregion
}
}
private void UpdateLoginStatus(LoginStatus status, string message)
{
InternalStatusCode = status;
InternalLoginMessage = message;
Logger.DebugLog("Login status: " + status.ToString() + ": " + message, Client);
// If we reached a login resolution trigger the event
if (status == LoginStatus.Success || status == LoginStatus.Failed)
{
CurrentContext = null;
LoginEvent.Set();
}
// Fire the login status callback
if (m_LoginProgress != null)
{
OnLoginProgress(new LoginProgressEventArgs(status, message, InternalErrorKey));
}
}
/// <summary>
/// LoginParams and the initial login XmlRpcRequest were made on a remote machine.
/// This method now initializes libomv with the results.
/// </summary>
public void RemoteLoginHandler(LoginResponseData response, LoginParams newContext)
{
CurrentContext = newContext;
LoginReplyXmlRpcHandler(response, newContext);
}
/// <summary>
/// Handles response from XML-RPC login replies
/// </summary>
private void LoginReplyXmlRpcHandler(XmlRpcResponse response, LoginParams context)
{
LoginResponseData reply = new LoginResponseData();
// Fetch the login response
if (response == null || !(response.Value is Hashtable))
{
UpdateLoginStatus(LoginStatus.Failed, "Invalid or missing login response from the server");
Logger.Log("Invalid or missing login response from the server", Helpers.LogLevel.Warning);
return;
}
try
{
reply.Parse((Hashtable)response.Value);
if (context.LoginID != CurrentContext.LoginID)
{
Logger.Log("Login response does not match login request. Only one login can be attempted at a time",
Helpers.LogLevel.Error);
return;
}
}
catch (Exception e)
{
UpdateLoginStatus(LoginStatus.Failed, "Error retrieving the login response from the server: " + e.Message);
Logger.Log("Login response failure: " + e.Message + " " + e.StackTrace, Helpers.LogLevel.Warning);
return;
}
LoginReplyXmlRpcHandler(reply, context);
}
/// <summary>
/// Handles response from XML-RPC login replies with already parsed LoginResponseData
/// </summary>
private void LoginReplyXmlRpcHandler(LoginResponseData reply, LoginParams context)
{
ushort simPort = 0;
uint regionX = 0;
uint regionY = 0;
string reason = reply.Reason;
string message = reply.Message;
if (reply.Login == "true")
{
// Remove the quotes around our first name.
if (reply.FirstName[0] == '"')
reply.FirstName = reply.FirstName.Remove(0, 1);
if (reply.FirstName[reply.FirstName.Length - 1] == '"')
reply.FirstName = reply.FirstName.Remove(reply.FirstName.Length - 1);
#region Critical Information
try
{
// Networking
Client.Network.CircuitCode = (uint)reply.CircuitCode;
regionX = (uint)reply.RegionX;
regionY = (uint)reply.RegionY;
simPort = (ushort)reply.SimPort;
LoginSeedCapability = reply.SeedCapability;
}
catch (Exception)
{
UpdateLoginStatus(LoginStatus.Failed, "Login server failed to return critical information");
return;
}
#endregion Critical Information
/* Add any blacklisted UDP packets to the blacklist
* for exclusion from packet processing */
if (reply.UDPBlacklist != null)
UDPBlacklist.AddRange(reply.UDPBlacklist.Split(','));
// Misc:
MaxAgentGroups = reply.MaxAgentGroups;
AgentAppearanceServiceURL = reply.AgentAppearanceServiceURL;
//uint timestamp = (uint)reply.seconds_since_epoch;
//DateTime time = Helpers.UnixTimeToDateTime(timestamp); // TODO: Do something with this?
// Unhandled:
// reply.gestures
// reply.event_categories
// reply.classified_categories
// reply.event_notifications
// reply.ui_config
// reply.login_flags
// reply.global_textures
// reply.inventory_lib_root
// reply.inventory_lib_owner
// reply.inventory_skeleton
// reply.inventory_skel_lib
// reply.initial_outfit
}
bool redirect = (reply.Login == "indeterminate");
try
{
if (OnLoginResponse != null)
{
try { OnLoginResponse(reply.Success, redirect, message, reason, reply); }
catch (Exception ex) { Logger.Log(ex.ToString(), Helpers.LogLevel.Error); }
}
}
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
// Make the next network jump, if needed
if (redirect)
{
UpdateLoginStatus(LoginStatus.Redirecting, "Redirecting login...");
LoginParams loginParams = CurrentContext;
loginParams.URI = reply.NextUrl;
loginParams.MethodName = reply.NextMethod;
loginParams.Options = reply.NextOptions;
// Sleep for some amount of time while the servers work
int seconds = reply.NextDuration;
Logger.Log("Sleeping for " + seconds + " seconds during a login redirect",
Helpers.LogLevel.Info);
Thread.Sleep(seconds * 1000);
CurrentContext = loginParams;
BeginLogin();
}
else if (reply.Success)
{
UpdateLoginStatus(LoginStatus.ConnectingToSim, "Connecting to simulator...");
ulong handle = Utils.UIntsToLong(regionX, regionY);
// Connect to the sim given in the login reply
if (Connect(reply.SimIP, simPort, handle, true, LoginSeedCapability) != null)
{
// Request the economy data right after login
SendPacket(new EconomyDataRequestPacket());
// Update the login message with the MOTD returned from the server
UpdateLoginStatus(LoginStatus.Success, message);
}
else
{
UpdateLoginStatus(LoginStatus.Failed, "Unable to connect to simulator");
}
}
else
{
// Make sure a usable error key is set
if (!String.IsNullOrEmpty(reason))
InternalErrorKey = reason;
else
InternalErrorKey = "unknown";
UpdateLoginStatus(LoginStatus.Failed, message);
}
}
/// <summary>
/// Handle response from LLSD login replies
/// </summary>
/// <param name="client"></param>
/// <param name="result"></param>
/// <param name="error"></param>
private void LoginReplyLLSDHandler(CapsClient client, OSD result, Exception error)
{
if (error == null)
{
if (result != null && result.Type == OSDType.Map)
{
OSDMap map = (OSDMap)result;
OSD osd;
LoginResponseData data = new LoginResponseData();
data.Parse(map);
if (map.TryGetValue("login", out osd))
{
bool loginSuccess = osd.AsBoolean();
bool redirect = (osd.AsString() == "indeterminate");
if (redirect)
{
// Login redirected
// Make the next login URL jump
UpdateLoginStatus(LoginStatus.Redirecting, data.Message);
LoginParams loginParams = CurrentContext;
loginParams.URI = LoginResponseData.ParseString("next_url", map);
//CurrentContext.Params.MethodName = LoginResponseData.ParseString("next_method", map);
// Sleep for some amount of time while the servers work
int seconds = (int)LoginResponseData.ParseUInt("next_duration", map);
Logger.Log("Sleeping for " + seconds + " seconds during a login redirect",
Helpers.LogLevel.Info);
Thread.Sleep(seconds * 1000);
// Ignore next_options for now
CurrentContext = loginParams;
BeginLogin();
}
else if (loginSuccess)
{
// Login succeeded
// Fire the login callback
if (OnLoginResponse != null)
{
try { OnLoginResponse(loginSuccess, redirect, data.Message, data.Reason, data); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }
}
// These parameters are stored in NetworkManager, so instead of registering
// another callback for them we just set the values here
CircuitCode = (uint)data.CircuitCode;
LoginSeedCapability = data.SeedCapability;
UpdateLoginStatus(LoginStatus.ConnectingToSim, "Connecting to simulator...");
ulong handle = Utils.UIntsToLong((uint)data.RegionX, (uint)data.RegionY);
if (data.SimIP != null && data.SimPort != 0)
{
// Connect to the sim given in the login reply
if (Connect(data.SimIP, (ushort)data.SimPort, handle, true, LoginSeedCapability) != null)
{
// Request the economy data right after login
SendPacket(new EconomyDataRequestPacket());
// Update the login message with the MOTD returned from the server
UpdateLoginStatus(LoginStatus.Success, data.Message);
}
else
{
UpdateLoginStatus(LoginStatus.Failed,
"Unable to establish a UDP connection to the simulator");
}
}
else
{
UpdateLoginStatus(LoginStatus.Failed,
"Login server did not return a simulator address");
}
}
else
{
// Login failed
// Make sure a usable error key is set
if (data.Reason != String.Empty)
InternalErrorKey = data.Reason;
else
InternalErrorKey = "unknown";
UpdateLoginStatus(LoginStatus.Failed, data.Message);
}
}
else
{
// Got an LLSD map but no login value
UpdateLoginStatus(LoginStatus.Failed, "login parameter missing in the response");
}
}
else
{
// No LLSD response
InternalErrorKey = "bad response";
UpdateLoginStatus(LoginStatus.Failed, "Empty or unparseable login response");
}
}
else
{
// Connection error
InternalErrorKey = "no connection";
UpdateLoginStatus(LoginStatus.Failed, error.Message);
}
}
/// <summary>
/// Get current OS
/// </summary>
/// <returns>Either "Win" or "Linux"</returns>
public static string GetPlatform()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Unix:
return "Linux";
default:
return "Win";
}
}
/// <summary>
/// Get clients default Mac Address
/// </summary>
/// <returns>A string containing the first found Mac Address</returns>
public static string GetMAC()
{
string mac = String.Empty;
System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
if (nics != null && nics.Length > 0)
{
for (int i = 0; i < nics.Length; i++)
{
string adapterMac = nics[i].GetPhysicalAddress().ToString().ToUpper();
if (adapterMac.Length == 12 && adapterMac != "000000000000")
{
mac = adapterMac;
continue;
}
}
}
if (mac.Length < 12)
mac = UUID.Random().ToString().Substring(24, 12);
return String.Format("{0}:{1}:{2}:{3}:{4}:{5}",
mac.Substring(0, 2),
mac.Substring(2, 2),
mac.Substring(4, 2),
mac.Substring(6, 2),
mac.Substring(8, 2),
mac.Substring(10, 2));
}
#endregion
}
#region EventArgs
public class LoginProgressEventArgs : EventArgs
{
private readonly LoginStatus m_Status;
private readonly String m_Message;
private readonly String m_FailReason;
public LoginStatus Status { get { return m_Status; } }
public String Message { get { return m_Message; } }
public string FailReason { get { return m_FailReason; } }
public LoginProgressEventArgs(LoginStatus login, String message, String failReason)
{
this.m_Status = login;
this.m_Message = message;
this.m_FailReason = failReason;
}
}
#endregion EventArgs
} | 41.405996 | 154 | 0.526014 | [
"BSD-3-Clause"
] | logicmoo/libopenmetaverse | OpenMetaverse/Login.cs | 66,291 | C# |
namespace NirDobovizki.PiGpio
{
public enum PullMode
{
None,
PullUp,
PullDown
}
} | 13.111111 | 30 | 0.533898 | [
"MIT"
] | nirdobovizki/PiGpio | PiGpio/PullMode.cs | 120 | 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("08.MetricConverter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("08.MetricConverter")]
[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("33994581-75b2-47c5-892d-ba676806d711")]
// 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.081081 | 84 | 0.745919 | [
"MIT"
] | yangra/SoftUni | ProgrammingBasics/03.SimpleConditions/08.MetricConverter/Properties/AssemblyInfo.cs | 1,412 | C# |
using System;
namespace UltimaOnline.Items
{
public class BarrelLid : Item
{
[Constructable]
public BarrelLid() : base(0x1DB8)
{
Weight = 2;
}
public BarrelLid(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[FlipableAttribute(0x1EB1, 0x1EB2, 0x1EB3, 0x1EB4)]
public class BarrelStaves : Item
{
[Constructable]
public BarrelStaves() : base(0x1EB1)
{
Weight = 1;
}
public BarrelStaves(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class BarrelHoops : Item
{
public override int LabelNumber { get { return 1011228; } } // Barrel hoops
[Constructable]
public BarrelHoops() : base(0x1DB7)
{
Weight = 5;
}
public BarrelHoops(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class BarrelTap : Item
{
[Constructable]
public BarrelTap() : base(0x1004)
{
Weight = 1;
}
public BarrelTap(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | 21.982609 | 84 | 0.498418 | [
"MIT"
] | netcode-gamer/game.ultimaonline.io | UltimaOnline.Data/Items/Construction/Misc/BarrelParts.cs | 2,528 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.imageseg.Transform;
using Aliyun.Acs.imageseg.Transform.V20191230;
namespace Aliyun.Acs.imageseg.Model.V20191230
{
public class SegmentAnimalRequest : RpcAcsRequest<SegmentAnimalResponse>
{
public SegmentAnimalRequest()
: base("imageseg", "2019-12-30", "SegmentAnimal", "imageseg", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.imageseg.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.imageseg.Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string imageURL;
public string ImageURL
{
get
{
return imageURL;
}
set
{
imageURL = value;
DictionaryUtil.Add(QueryParameters, "ImageURL", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override SegmentAnimalResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return SegmentAnimalResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 33.115942 | 138 | 0.701094 | [
"Apache-2.0"
] | chys0404/aliyun-openapi-net-sdk | aliyun-net-sdk-imageseg/Imageseg/Model/V20191230/SegmentAnimalRequest.cs | 2,285 | C# |
using System;
using System.ComponentModel;
using NLua;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions;
using BizHawk.Common.BufferExtensions;
// ReSharper disable UnusedMember.Global
namespace BizHawk.Client.Common
{
[Description("These functions behavior identically to the mainmemory functions but the user can set the memory domain to read and write from. The default domain is the system bus. Use getcurrentmemorydomain(), and usememorydomain() to control which domain is used. Each core has its own set of valid memory domains. Use getmemorydomainlist() to get a list of memory domains for the current core loaded.")]
public sealed class MemoryLuaLibrary : LuaMemoryBase
{
private MemoryDomain _currentMemoryDomain;
public MemoryLuaLibrary(Lua lua)
: base(lua)
{
}
public MemoryLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback)
{
}
public override string Name => "memory";
protected override MemoryDomain Domain
{
get
{
if (MemoryDomainCore != null)
{
if (_currentMemoryDomain == null)
{
_currentMemoryDomain = MemoryDomainCore.HasSystemBus
? MemoryDomainCore.SystemBus
: MemoryDomainCore.MainMemory;
}
return _currentMemoryDomain;
}
var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
Log(error);
throw new NotImplementedException(error);
}
}
#region Unique Library Methods
[LuaMethodExample("local nlmemget = memory.getmemorydomainlist();")]
[LuaMethod("getmemorydomainlist", "Returns a string of the memory domains for the loaded platform core. List will be a single string delimited by line feeds")]
public LuaTable GetMemoryDomainList()
{
var table = Lua.NewTable();
int i = 0;
foreach (var domain in DomainList)
{
table[i] = domain.Name;
i++;
}
return table;
}
[LuaMethodExample("local uimemget = memory.getmemorydomainsize( mainmemory.getname( ) );")]
[LuaMethod("getmemorydomainsize", "Returns the number of bytes of the specified memory domain. If no domain is specified, or the specified domain doesn't exist, returns the current domain size")]
public uint GetMemoryDomainSize(string name = "")
{
if (string.IsNullOrEmpty(name))
{
return (uint)Domain.Size;
}
return (uint)DomainList[VerifyMemoryDomain(name)].Size;
}
[LuaMethodExample("local stmemget = memory.getcurrentmemorydomain( );")]
[LuaMethod("getcurrentmemorydomain", "Returns a string name of the current memory domain selected by Lua. The default is Main memory")]
public string GetCurrentMemoryDomain()
{
return Domain.Name;
}
[LuaMethodExample("local uimemget = memory.getcurrentmemorydomainsize( );")]
[LuaMethod("getcurrentmemorydomainsize", "Returns the number of bytes of the current memory domain selected by Lua. The default is Main memory")]
public uint GetCurrentMemoryDomainSize()
{
return (uint)Domain.Size;
}
[LuaMethodExample("if ( memory.usememorydomain( mainmemory.getname( ) ) ) then\r\n\tconsole.log( \"Attempts to set the current memory domain to the given domain. If the name does not match a valid memory domain, the function returns false, else it returns true\" );\r\nend;")]
[LuaMethod("usememorydomain", "Attempts to set the current memory domain to the given domain. If the name does not match a valid memory domain, the function returns false, else it returns true")]
public bool UseMemoryDomain(string domain)
{
try
{
if (DomainList[domain] != null)
{
_currentMemoryDomain = DomainList[domain];
return true;
}
Log($"Unable to find domain: {domain}");
return false;
}
catch // Just in case
{
Log($"Unable to find domain: {domain}");
}
return false;
}
[LuaMethodExample("local stmemhas = memory.hash_region( 0x100, 50, mainmemory.getname( ) );")]
[LuaMethod("hash_region", "Returns a hash as a string of a region of memory, starting from addr, through count bytes. If the domain is unspecified, it uses the current region.")]
public string HashRegion(int addr, int count, string domain = null)
{
var d = string.IsNullOrEmpty(domain) ? Domain : DomainList[VerifyMemoryDomain(domain)];
// checks
if (addr < 0 || addr >= d.Size)
{
string error = $"Address {addr} is outside the bounds of domain {d.Name}";
Log(error);
throw new ArgumentOutOfRangeException(error);
}
if (addr + count > d.Size)
{
string error = $"Address {addr} + count {count} is outside the bounds of domain {d.Name}";
Log(error);
throw new ArgumentOutOfRangeException(error);
}
byte[] data = new byte[count];
for (int i = 0; i < count; i++)
{
data[i] = d.PeekByte(addr + i);
}
using var hasher = System.Security.Cryptography.SHA256.Create();
return hasher.ComputeHash(data).BytesToHexString();
}
#endregion
#region Common Special and Legacy Methods
[LuaMethodExample("local uimemrea = memory.readbyte( 0x100, mainmemory.getname( ) );")]
[LuaMethod("readbyte", "gets the value from the given address as an unsigned byte")]
public uint ReadByte(int addr, string domain = null)
{
return ReadUnsignedByte(addr, domain);
}
[LuaMethodExample("memory.writebyte( 0x100, 1000, mainmemory.getname( ) );")]
[LuaMethod("writebyte", "Writes the given value to the given address as an unsigned byte")]
public void WriteByte(int addr, uint value, string domain = null)
{
WriteUnsignedByte(addr, value, domain);
}
[LuaMethodExample("local nlmemrea = memory.readbyterange( 0x100, 30, mainmemory.getname( ) );")]
[LuaMethod("readbyterange", "Reads the address range that starts from address, and is length long. Returns the result into a table of key value pairs (where the address is the key).")]
public new LuaTable ReadByteRange(int addr, int length, string domain = null)
{
return base.ReadByteRange(addr, length, domain);
}
[LuaMethodExample("")]
[LuaMethod("writebyterange", "Writes the given values to the given addresses as unsigned bytes")]
public new void WriteByteRange(LuaTable memoryblock, string domain = null)
{
base.WriteByteRange(memoryblock, domain);
}
[LuaMethodExample("local simemrea = memory.readfloat( 0x100, false, mainmemory.getname( ) );")]
[LuaMethod("readfloat", "Reads the given address as a 32-bit float value from the main memory domain with th e given endian")]
public new float ReadFloat(int addr, bool bigendian, string domain = null)
{
return base.ReadFloat(addr, bigendian, domain);
}
[LuaMethodExample("memory.writefloat( 0x100, 10.0, false, mainmemory.getname( ) );")]
[LuaMethod("writefloat", "Writes the given 32-bit float value to the given address and endian")]
public new void WriteFloat(int addr, double value, bool bigendian, string domain = null)
{
base.WriteFloat(addr, value, bigendian, domain);
}
#endregion
#region 1 Byte
[LuaMethodExample("local inmemrea = memory.read_s8( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_s8", "read signed byte")]
public int ReadS8(int addr, string domain = null)
{
return (sbyte)ReadUnsignedByte(addr, domain);
}
[LuaMethodExample("memory.write_s8( 0x100, 1000, mainmemory.getname( ) );")]
[LuaMethod("write_s8", "write signed byte")]
public void WriteS8(int addr, uint value, string domain = null)
{
WriteUnsignedByte(addr, value, domain);
}
[LuaMethodExample("local uimemrea = memory.read_u8( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_u8", "read unsigned byte")]
public uint ReadU8(int addr, string domain = null)
{
return ReadUnsignedByte(addr, domain);
}
[LuaMethodExample("memory.write_u8( 0x100, 1000, mainmemory.getname( ) );")]
[LuaMethod("write_u8", "write unsigned byte")]
public void WriteU8(int addr, uint value, string domain = null)
{
WriteUnsignedByte(addr, value, domain);
}
#endregion
#region 2 Byte
[LuaMethodExample("local inmemrea = memory.read_s16_le( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_s16_le", "read signed 2 byte value, little endian")]
public int ReadS16Little(int addr, string domain = null)
{
return ReadSignedLittleCore(addr, 2, domain);
}
[LuaMethodExample("memory.write_s16_le( 0x100, -1000, mainmemory.getname( ) );")]
[LuaMethod("write_s16_le", "write signed 2 byte value, little endian")]
public void WriteS16Little(int addr, int value, string domain = null)
{
WriteSignedLittle(addr, value, 2, domain);
}
[LuaMethodExample("local inmemrea = memory.read_s16_be( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_s16_be", "read signed 2 byte value, big endian")]
public int ReadS16Big(int addr, string domain = null)
{
return ReadSignedBig(addr, 2, domain);
}
[LuaMethodExample("memory.write_s16_be( 0x100, -1000, mainmemory.getname( ) );")]
[LuaMethod("write_s16_be", "write signed 2 byte value, big endian")]
public void WriteS16Big(int addr, int value, string domain = null)
{
WriteSignedBig(addr, value, 2, domain);
}
[LuaMethodExample("local uimemrea = memory.read_u16_le( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_u16_le", "read unsigned 2 byte value, little endian")]
public uint ReadU16Little(int addr, string domain = null)
{
return ReadUnsignedLittle(addr, 2, domain);
}
[LuaMethodExample("memory.write_u16_le( 0x100, 1000, mainmemory.getname( ) );")]
[LuaMethod("write_u16_le", "write unsigned 2 byte value, little endian")]
public void WriteU16Little(int addr, uint value, string domain = null)
{
WriteUnsignedLittle(addr, value, 2, domain);
}
[LuaMethodExample("local uimemrea = memory.read_u16_be( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_u16_be", "read unsigned 2 byte value, big endian")]
public uint ReadU16Big(int addr, string domain = null)
{
return ReadUnsignedBig(addr, 2, domain);
}
[LuaMethodExample("memory.write_u16_be( 0x100, 1000, mainmemory.getname( ) );")]
[LuaMethod("write_u16_be", "write unsigned 2 byte value, big endian")]
public void WriteU16Big(int addr, uint value, string domain = null)
{
WriteUnsignedBig(addr, value, 2, domain);
}
#endregion
#region 3 Byte
[LuaMethodExample("local inmemrea = memory.read_s24_le( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_s24_le", "read signed 24 bit value, little endian")]
public int ReadS24Little(int addr, string domain = null)
{
return ReadSignedLittleCore(addr, 3, domain);
}
[LuaMethodExample("memory.write_s24_le( 0x100, -1000, mainmemory.getname( ) );")]
[LuaMethod("write_s24_le", "write signed 24 bit value, little endian")]
public void WriteS24Little(int addr, int value, string domain = null)
{
WriteSignedLittle(addr, value, 3, domain);
}
[LuaMethodExample("local inmemrea = memory.read_s24_be( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_s24_be", "read signed 24 bit value, big endian")]
public int ReadS24Big(int addr, string domain = null)
{
return ReadSignedBig(addr, 3, domain);
}
[LuaMethodExample("memory.write_s24_be( 0x100, -1000, mainmemory.getname( ) );")]
[LuaMethod("write_s24_be", "write signed 24 bit value, big endian")]
public void WriteS24Big(int addr, int value, string domain = null)
{
WriteSignedBig(addr, value, 3, domain);
}
[LuaMethodExample("local uimemrea = memory.read_u24_le( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_u24_le", "read unsigned 24 bit value, little endian")]
public uint ReadU24Little(int addr, string domain = null)
{
return ReadUnsignedLittle(addr, 3, domain);
}
[LuaMethodExample("memory.write_u24_le( 0x100, 1000, mainmemory.getname( ) );")]
[LuaMethod("write_u24_le", "write unsigned 24 bit value, little endian")]
public void WriteU24Little(int addr, uint value, string domain = null)
{
WriteUnsignedLittle(addr, value, 3, domain);
}
[LuaMethodExample("local uimemrea = memory.read_u24_be( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_u24_be", "read unsigned 24 bit value, big endian")]
public uint ReadU24Big(int addr, string domain = null)
{
return ReadUnsignedBig(addr, 3, domain);
}
[LuaMethodExample("memory.write_u24_be( 0x100, 1000, mainmemory.getname( ) );")]
[LuaMethod("write_u24_be", "write unsigned 24 bit value, big endian")]
public void WriteU24Big(int addr, uint value, string domain = null)
{
WriteUnsignedBig(addr, value, 3, domain);
}
#endregion
#region 4 Byte
[LuaMethodExample("local inmemrea = memory.read_s32_le( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_s32_le", "read signed 4 byte value, little endian")]
public int ReadS32Little(int addr, string domain = null)
{
return ReadSignedLittleCore(addr, 4, domain);
}
[LuaMethodExample("memory.write_s32_le( 0x100, -1000, mainmemory.getname( ) );")]
[LuaMethod("write_s32_le", "write signed 4 byte value, little endian")]
public void WriteS32Little(int addr, int value, string domain = null)
{
WriteSignedLittle(addr, value, 4, domain);
}
[LuaMethodExample("local inmemrea = memory.read_s32_be( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_s32_be", "read signed 4 byte value, big endian")]
public int ReadS32Big(int addr, string domain = null)
{
return ReadSignedBig(addr, 4, domain);
}
[LuaMethodExample("memory.write_s32_be( 0x100, -1000, mainmemory.getname( ) );")]
[LuaMethod("write_s32_be", "write signed 4 byte value, big endian")]
public void WriteS32Big(int addr, int value, string domain = null)
{
WriteSignedBig(addr, value, 4, domain);
}
[LuaMethodExample("local uimemrea = memory.read_u32_le( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_u32_le", "read unsigned 4 byte value, little endian")]
public uint ReadU32Little(int addr, string domain = null)
{
return ReadUnsignedLittle(addr, 4, domain);
}
[LuaMethodExample("memory.write_u32_le( 0x100, 1000, mainmemory.getname( ) );")]
[LuaMethod("write_u32_le", "write unsigned 4 byte value, little endian")]
public void WriteU32Little(int addr, uint value, string domain = null)
{
WriteUnsignedLittle(addr, value, 4, domain);
}
[LuaMethodExample("local uimemrea = memory.read_u32_be( 0x100, mainmemory.getname( ) );")]
[LuaMethod("read_u32_be", "read unsigned 4 byte value, big endian")]
public uint ReadU32Big(int addr, string domain = null)
{
return ReadUnsignedBig(addr, 4, domain);
}
[LuaMethodExample("memory.write_u32_be( 0x100, 1000, mainmemory.getname( ) );")]
[LuaMethod("write_u32_be", "write unsigned 4 byte value, big endian")]
public void WriteU32Big(int addr, uint value, string domain = null)
{
WriteUnsignedBig(addr, value, 4, domain);
}
#endregion
}
}
| 37.163814 | 407 | 0.691316 | [
"MIT"
] | warmCabin/BizHawk | BizHawk.Client.Common/lua/EmuLuaLibrary.Memory.cs | 15,202 | C# |
namespace Stump.DofusProtocol.Messages
{
using System;
using System.Linq;
using System.Text;
using Stump.DofusProtocol.Types;
using Stump.Core.IO;
[Serializable]
public class ClientUIOpenedByObjectMessage : ClientUIOpenedMessage
{
public new const uint Id = 6463;
public override uint MessageId
{
get { return Id; }
}
public uint Uid { get; set; }
public ClientUIOpenedByObjectMessage(sbyte type, uint uid)
{
this.Type = type;
this.Uid = uid;
}
public ClientUIOpenedByObjectMessage() { }
public override void Serialize(IDataWriter writer)
{
base.Serialize(writer);
writer.WriteVarUInt(Uid);
}
public override void Deserialize(IDataReader reader)
{
base.Deserialize(reader);
Uid = reader.ReadVarUInt();
}
}
}
| 23.292683 | 70 | 0.579058 | [
"Apache-2.0"
] | Daymortel/Stump | src/Stump.DofusProtocol/Messages/Messages/Game/Ui/ClientUIOpenedByObjectMessage.cs | 957 | C# |
using System;
using UnityEngine;
using System.Collections.Generic;
using SCIP_library;
using System.Threading;
using System.Text;
using System.IO.Ports;
namespace URG
{
[Serializable]
public class SerialURG : URGDevice
{
[SerializeField]
readonly string portName;
[SerializeField]
readonly int baudRate;
readonly static public URGType DeviceType = URGType.Serial;
SerialPort serialPort;
Thread listenThread = null;
bool isConnected = false;
public override bool IsConnected { get { return isConnected; } }
public override int StartStep { get { return 300; } } //300
public override int EndStep { get { return 450; } } //450
public override int StepCount360 {
get
{
return 1024;
}
set
{
SetStepCount = value;
}
}
public int SetStepCount;
/// <summary>
/// Initialize serial-type URG device.
/// </summary>
/// <param name="_portName">Port name of the URG device.</param>
/// <param name="_baudRate">Baud rate of the URG device.</param>
public SerialURG(string _portName = "COM3", int _baudRate = 115200)
{
portName = _portName;
baudRate = _baudRate;
distances = new List<long>();
intensities = new List<long>();
}
/// <summary>
/// Establish connection with the URG device.
/// </summary>
public override void Open()
{
try
{
serialPort = new SerialPort(portName, baudRate);
serialPort.NewLine = "\n\n";
serialPort.Open();
listenThread = new Thread(new ParameterizedThreadStart(HandleClient));
isConnected = true;
listenThread.IsBackground = true;
listenThread.Start(serialPort);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
/// <summary>
/// End connection with the URG device.
/// </summary>
public override void Close()
{
if (listenThread != null)
{
isConnected = false;
listenThread.Join();
listenThread = null;
}
if (serialPort != null)
{
serialPort.Close();
serialPort.Dispose();
}
}
void HandleClient(object obj)
{
try
{
using (SerialPort client = (SerialPort)obj)
{
while (isConnected)
{
try
{
long timeStamp = 0;
string receivedData = ReadLine(client);
string parsedCommand = ParseCommand(receivedData);
SCIPCommands command = (SCIPCommands)Enum.Parse(typeof(SCIPCommands), parsedCommand);
switch (command)
{
case SCIPCommands.QT:
distances.Clear();
intensities.Clear();
isConnected = false;
break;
case SCIPCommands.MD:
distances.Clear();
SCIP_Reader.MD(receivedData, ref timeStamp, ref distances);
break;
case SCIPCommands.GD:
distances.Clear();
SCIP_Reader.GD(receivedData, ref timeStamp, ref distances);
break;
case SCIPCommands.ME:
distances.Clear();
intensities.Clear();
SCIP_Reader.ME(receivedData, ref timeStamp, ref distances, ref intensities);
break;
default:
Debug.Log(receivedData);
isConnected = false;
break;
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
string ParseCommand(string receivedData)
{
string[] split_command = receivedData.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
return split_command[0].Substring(0, 2);
}
/// <summary>
/// Read to "\n\n" from NetworkStream
/// </summary>
/// <returns>receive data</returns>
protected static string ReadLine(SerialPort serialport)
{
if (serialport.IsOpen)
{
StringBuilder sb = new StringBuilder();
bool is_NL2 = false;
bool is_NL = false;
do
{
char buf = (char)serialport.ReadByte();
if (buf == '\n')
{
if (is_NL)
{
is_NL2 = true;
}
else
{
is_NL = true;
}
}
else
{
is_NL = false;
}
sb.Append(buf);
} while (!is_NL2);
return sb.ToString();
}
else
{
return null;
}
}
/// <summary>
/// Write data to the URG device.
/// </summary>
/// <param name="data"></param>
public override void Write(string data)
{
try {
if (!isConnected) {
Open();
}
if (Enum.IsDefined(typeof(SCIPCommands), ParseCommand(data))) {
var buffer = Encoding.ASCII.GetBytes(data);
serialPort.Write(buffer, 0, buffer.Length);
}
}
catch (Exception e) {
Debug.LogException(e);
}
}
}
} | 31.884793 | 116 | 0.401214 | [
"MIT"
] | PetitDevil/ShinnUST | Assets/Plugin/URG_org/Scripts/SerialURG.cs | 6,921 | C# |
namespace DELTation.UI.Screens.Raycasts
{
public sealed class NullRaycastBlocker : IRaycastBlocker
{
public bool Active { get; set; }
}
} | 22.571429 | 60 | 0.677215 | [
"MIT"
] | Delt06/computer-battle | Assets/Plugins/DELTation/UI/Screens/Raycasts/NullRaycastBlocker.cs | 160 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Uno
{
public static class Extensions
{
public static char First(this string str)
{
return str[0];
}
public static char Last(this string str)
{
return str[str.Length - 1];
}
public static T First<T>(this T[] list)
{
return list[0];
}
public static T Last<T>(this T[] list)
{
return list[list.Length - 1];
}
public static T First<T>(this IReadOnlyList<T> list)
{
return list[0];
}
public static T Last<T>(this IReadOnlyList<T> list)
{
return list[list.Count - 1];
}
public static T First<T>(this List<T> list)
{
return list[0];
}
public static T Last<T>(this List<T> list)
{
return list[list.Count - 1];
}
public static T RemoveLast<T>(this List<T> list)
{
var index = list.Count - 1;
var result = list[index];
list.RemoveAt(index);
return result;
}
public static void AddRange<T>(this HashSet<T> set, IEnumerable<T> items)
{
foreach (var e in items)
set.Add(e);
}
public static bool StartsWith(this string str, char a, char b = '\0')
{
if (str.Length > 0)
{
var first = str[0];
if (a == first || b == first)
return true;
}
return false;
}
public static bool EndsWith(this string str, char a, char b = '\0')
{
if (str.Length > 0)
{
var last = str[str.Length - 1];
if (a == last || b == last)
return true;
}
return false;
}
public static string[] PathSplit(this string str)
{
var parts = str.Split(':');
// Workaround for Windows drive letter
if (parts.Length > 1 && parts[0].Length == 1 && parts[1].StartsWith('/', '\\'))
{
var oldParts = parts;
parts = new string[oldParts.Length - 1];
parts[0] = oldParts[0] + ":" + oldParts[1];
for (int i = 2; i < oldParts.Length; i++)
parts[i - 1] = oldParts[i];
}
return parts;
}
public static string GetPathComponent(this string str, int offset)
{
var parts = str.Split(Path.DirectorySeparatorChar);
return offset < 0
? parts[parts.Length + offset]
: parts[offset];
}
public static string Trailing(this string str, char c)
{
return string.IsNullOrEmpty(str) || str.EndsWith(c)
? str
: str + c.ToString(CultureInfo.InvariantCulture);
}
public static string Truncate(this string str, int length)
{
return str != null && str.Length > length
? str.Substring(0, length)
: str;
}
public static void AppendWhen(this StringBuilder sb, bool cond, char arg)
{
if (cond) sb.Append(arg);
}
public static void AppendWhen(this StringBuilder sb, bool cond, object arg)
{
if (cond) sb.Append(arg);
}
public static void AppendWhen(this StringBuilder sb, bool cond, string arg)
{
if (cond) sb.Append(arg);
}
public static void CommaWhen(this StringBuilder sb, bool cond)
{
if (cond) sb.Append(", ");
}
public static string NativeToUnix(this string str)
{
return Path.DirectorySeparatorChar != '/' && str != null
? str.Replace(Path.DirectorySeparatorChar, '/')
: str;
}
public static string UnixToNative(this string str)
{
return Path.DirectorySeparatorChar != '/' && str != null
? str.Replace('/', Path.DirectorySeparatorChar)
: str;
}
public static string UnixBaseName(this string f)
{
return f.Substring(f.LastIndexOf('/') + 1);
}
public static string UnixDirectoryName(this string f)
{
return f.Substring(0, Math.Max(0, f.LastIndexOf('/')));
}
public static string Printable(this string str)
{
return str.FirstLine().Trim().Quote();
}
public static string FirstLine(this string str)
{
var i = str.IndexOf('\n');
return i != -1
? str.Substring(0, i)
: str;
}
public static string Plural<T>(this string str, ICollection<T> collection)
{
return collection.Count == 1
? str
: str + "s";
}
public static string Plural(this string str, int count)
{
return count == 1
? str
: str + "s";
}
public static string Quote(this object obj, object arg = null)
{
return ("" + obj + arg).Quote();
}
public static string Quote(this string str)
{
return str == null
? "(null)"
: str.IndexOf(' ') != -1 ||
str.Length == 0 ||
NeedsQuote(str[0]) ||
NeedsQuote(str[str.Length - 1]) ||
str.IsIdentifier()
? "'" + str + "'"
: str;
}
static bool NeedsQuote(char c)
{
// Avoid quoting full paths and qualified generic types
return c != '/' && c != '>' && !char.IsLetterOrDigit(c);
}
public static string QuoteSpace(this string str)
{
var hasNonAlphaNumeric = false;
foreach (var c in str ?? "")
switch (c)
{
// See if character is allowed in non-quoted string
case '.':
case '-':
case '_':
case '/':
case ':':
case '\\':
continue;
default:
if (c >= 'a' && c <= 'z' ||
c >= 'A' && c <= 'Z' ||
c >= '0' && c <= '9')
continue;
hasNonAlphaNumeric = true;
goto RETURN;
}
RETURN:
return hasNonAlphaNumeric || string.IsNullOrEmpty(str)
? "\"" + (str ?? "").Replace("\"", "\\\"") + "\""
: str;
}
public static string EscapeSpace(this string str)
{
if (str.IndexOf(' ') == -1)
return str;
var sb = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
var c = str[i];
if (c == ' ' || c == '\'')
{
var bc = 0;
for (int j = i - 1; j >= 0 && str[j] == '\\'; j--)
bc++;
if ((bc & 2) == 0)
sb.Append('\\');
}
sb.Append(c);
}
return sb.ToString();
}
public static string EscapeCommand(this string str)
{
var q = '\0';
var sb = new StringBuilder();
foreach (var c in str.NativeToUnix())
{
switch (c)
{
case '"':
case '\'':
{
if (q == c)
q = '\0';
else if (q == '\0')
q = c;
break;
}
case ' ':
{
if (q != '\0')
sb.Append('\\');
sb.Append(c);
break;
}
default:
{
sb.Append(c);
break;
}
}
}
return sb.ToString();
}
public static int UnquotedIndexOf(this string str, char c, int start = 0)
{
char q = '\0';
for (int i = start; i < str.Length; i++)
{
if (str[i] == c && q == '\0')
return i;
switch (str[i])
{
case '\n':
// Reset quote mode on newline
q = '\0';
break;
case '"':
case '\'':
{
// Count backslashes
int bsCount = 0;
for (int bi = i - 1; bi >= 0 && str[bi] == '\\'; bi--)
bsCount++;
// Escape backslashes and set quote mode
if ((bsCount & 1) == 0)
{
if (q == str[i])
q = '\0';
else if (q == '\0')
q = str[i];
}
break;
}
}
}
return -1;
}
static bool IsNegativeZero(double v)
{
return v == 0.0 && double.IsNegativeInfinity(1.0 / v);
}
public static string ToLiteral(this float f, bool suffix = true, bool minify = false)
{
if (float.IsNaN(f))
return suffix ? "(.0f/.0f)" : "(.0/.0)";
if (float.IsPositiveInfinity(f))
return suffix ? "(1.f/0.f)" : "(1./0.)";
if (float.IsNegativeInfinity(f))
return suffix ? "(-1.f/0.f)" : "(-1./0.)";
if (IsNegativeZero(f))
return suffix ? "-0.f" : "-0.";
var s = f.ToString("r", CultureInfo.InvariantCulture).ToLower();
if (s.IndexOf('.') == -1 && s.IndexOf('e') == -1)
s += ".0";
if (minify)
{
if (s.StartsWith("0.", StringComparison.InvariantCulture))
s = s.Substring(1);
else if (s.EndsWith(".0", StringComparison.InvariantCulture))
s = s.Substring(0, s.Length - 1);
}
if (suffix)
s += "f";
return s;
}
public static string ToLiteral(this double f)
{
if (double.IsNaN(f))
return "(.0/.0)";
if (double.IsPositiveInfinity(f))
return "(1./0.)";
if (double.IsNegativeInfinity(f))
return "(-1./0.)";
if (IsNegativeZero(f))
return "-0.";
var s = f.ToString("r", CultureInfo.InvariantCulture).ToLower();
if (s.IndexOf('.') == -1 && s.IndexOf('e') == -1)
s += ".0";
return s;
}
public static string Escape(this char c, char q)
{
switch (c)
{
case '\'': return c == q ? "\\'" : "'";
case '\"': return c == q ? "\\\"" : "\"";
case '\\': return "\\\\";
case '\0': return "\\0";
case '\b': return "\\b";
case '\f': return "\\f";
case '\n': return "\\n";
case '\r': return "\\r";
case '\t': return "\\t";
case '\v': return "\\v";
case ' ': return " ";
default: return
char.IsLetterOrDigit(c) ||
char.IsPunctuation(c) ||
char.IsSymbol(c)
? c.ToString(CultureInfo.InvariantCulture)
: $"\\u{(int)c:X4}";
}
}
public static string ToLiteral(this char c)
{
return "'" + c.Escape('\'') + "'";
}
public static string ToLiteral(this string str)
{
if (str == null)
return "null";
var sb = new StringBuilder();
sb.Append("\"");
foreach (var c in str)
sb.Append(c.Escape('"'));
sb.Append("\"");
return sb.ToString();
}
public static string ToLiteral(this bool c)
{
return c ? "true" : "false";
}
public static string ToLiteral(this int c)
{
return c.ToString();
}
public static string ToLiteral(this Enum e)
{
return e.Equals(Enum.ToObject(e.GetType(), 0))
// Return empty string when value is 0
? ""
// Convert string to look better in disasm ('Public, Static' => 'public static')
: e.ToString().ToLower().Replace(", ", " ");
}
public static string ToLiteral(this Enum e, bool space)
{
var str = e.ToLiteral();
return space && str.Length > 0 ? str + " " : str;
}
public static string ToLiteral(this object obj)
{
if (obj is bool)
return ((bool) obj).ToLiteral();
if (obj is float)
return ((float) obj).ToLiteral();
if (obj is double)
return ((double) obj).ToLiteral();
if (obj is char)
return ((char) obj).ToLiteral();
if (obj == null || obj is string)
return ((string) obj).ToLiteral();
if (obj is Enum)
return ((Enum) obj).ToLiteral();
return obj.ToString();
}
public static string MagicString(this uint magic)
{
var a = (char)(magic >> 0 & 0xff);
var b = (char)(magic >> 8 & 0xff);
var c = (char)(magic >> 16 & 0xff);
var d = (int)(magic >> 24 & 0xff);
return (a.ToString() + b + c + d).ToLowerInvariant();
}
public static bool IsIdentifier(this string str)
{
if (string.IsNullOrEmpty(str) || char.IsNumber(str[0]))
return false;
foreach (var c in str)
if (c != '_' && !char.IsLetterOrDigit(c))
return false;
return true;
}
public static string ToIdentifier(this string str, bool qualified = false)
{
if (str.IsIdentifier())
return str;
if (string.IsNullOrEmpty(str))
return "_";
if (!qualified && str.StartsWith('.'))
return str.Substring(1).ToIdentifier() + "_";
var sb = new StringBuilder();
if (str.Length > 0 && char.IsDigit(str[0]))
sb.Append('_');
foreach (char c in str)
if (char.IsLetterOrDigit(c) || c == '_' ||
qualified && c == '.')
sb.Append(c);
if (sb.Length == 0 ||
qualified && sb[sb.Length - 1] == '.')
sb.Append('_');
return sb.ToString();
}
public static int FindIdentifier(this string str, out string identifier, int start = 0)
{
// Set start to next letter or underscore
while (start < str.Length && !char.IsLetter(str[start]) && str[start] != '_')
start++;
if (start < str.Length)
{
// Set end to next non-identifier character
int end = start + 1;
while (end < str.Length && (char.IsLetterOrDigit(str[end]) || str[end] == '_'))
end++;
identifier = str.Substring(start, end - start);
return start;
}
identifier = null;
return -1;
}
public static string ReplaceWord(this string input, string from, string to)
{
return input == null
? null :
input == from
? to
: Regex.Replace(input, "\\b" + Regex.Escape(from) + "\\b", to);
}
public static int NullableHashCode<T>(this T? self) where T : struct
{
return self == null
? -1
: self.GetHashCode();
}
public static int NullableHashCode<T>(this T self) where T : class
{
return self?.GetHashCode() ?? -1;
}
}
}
| 29.354839 | 96 | 0.401677 | [
"MIT"
] | devadiab/uno | src/common/Uno.Common/Extensions.cs | 17,292 | C# |
using UnityEngine;
using MoreMountains.Tools;
using System.Collections;
using UnityEngine.UI;
namespace MoreMountains.Tools
{
/// <summary>
/// Add this component to an object and it will show a healthbar above it
/// You can either use a prefab for it, or have the component draw one at the start
/// </summary>
[AddComponentMenu("More Mountains/Tools/GUI/MMHealthBar")]
public class MMHealthBar : MonoBehaviour
{
/// the possible health bar types
public enum HealthBarTypes { Prefab, Drawn }
/// the possible timescales the bar can work on
public enum TimeScales { UnscaledTime, Time }
[MMInformation("Add this component to an object and it'll add a healthbar next to it to reflect its health level in real time. You can decide here whether the health bar should be drawn automatically or use a prefab.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)]
/// whether the healthbar uses a prefab or is drawn automatically
public HealthBarTypes HealthBarType = HealthBarTypes.Drawn;
/// defines whether the bar will work on scaled or unscaled time (whether or not it'll keep moving if time is slowed down for example)
public TimeScales TimeScale = TimeScales.UnscaledTime;
[Header("Select a Prefab")]
[MMInformation("Select a prefab with a progress bar script on it. There is one example of such a prefab in Common/Prefabs/GUI.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)]
/// the prefab to use as the health bar
public MMProgressBar HealthBarPrefab;
[Header("Drawn Healthbar Settings ")]
[MMInformation("Set the size (in world units), padding, back and front colors of the healthbar.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)]
/// if the healthbar is drawn, its size in world units
public Vector2 Size = new Vector2(1f,0.2f);
/// if the healthbar is drawn, the padding to apply to the foreground, in world units
public Vector2 BackgroundPadding = new Vector2(0.01f,0.01f);
/// the rotation to apply to the MMHealthBarContainer when drawing it
public Vector3 InitialRotationAngles;
/// if the healthbar is drawn, the color of its foreground
public Gradient ForegroundColor = new Gradient()
{
colorKeys = new GradientColorKey[2] {
new GradientColorKey(MMColors.BestRed, 0),
new GradientColorKey(MMColors.BestRed, 1f)
},
alphaKeys = new GradientAlphaKey[2] {new GradientAlphaKey(1, 0),new GradientAlphaKey(1, 1)}};
/// if the healthbar is drawn, the color of its delayed bar
public Gradient DelayedColor = new Gradient()
{
colorKeys = new GradientColorKey[2] {
new GradientColorKey(MMColors.Orange, 0),
new GradientColorKey(MMColors.Orange, 1f)
},
alphaKeys = new GradientAlphaKey[2] { new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 1) }
};
/// if the healthbar is drawn, the color of its border
public Gradient BorderColor = new Gradient()
{
colorKeys = new GradientColorKey[2] {
new GradientColorKey(MMColors.AntiqueWhite, 0),
new GradientColorKey(MMColors.AntiqueWhite, 1f)
},
alphaKeys = new GradientAlphaKey[2] { new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 1) }
};
/// if the healthbar is drawn, the color of its background
public Gradient BackgroundColor = new Gradient()
{
colorKeys = new GradientColorKey[2] {
new GradientColorKey(MMColors.Black, 0),
new GradientColorKey(MMColors.Black, 1f)
},
alphaKeys = new GradientAlphaKey[2] { new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 1) }
};
/// the name of the sorting layer to put this health bar on
public string SortingLayerName = "UI";
/// the delay to apply to the delayed bar if drawn
public float Delay = 0.5f;
/// whether or not the front bar should lerp
public bool LerpFrontBar = true;
/// the speed at which the front bar lerps
public float LerpFrontBarSpeed = 15f;
/// whether or not the delayed bar should lerp
public bool LerpDelayedBar = true;
/// the speed at which the delayed bar lerps
public float LerpDelayedBarSpeed = 15f;
/// if this is true, bumps the scale of the healthbar when its value changes
public bool BumpScaleOnChange = true;
/// the duration of the bump animation
public float BumpDuration = 0.2f;
/// the animation curve to map the bump animation on
public AnimationCurve BumpAnimationCurve = AnimationCurve.Constant(0,1,1);
/// the mode the bar should follow the target in
public MMFollowTarget.UpdateModes FollowTargetMode = MMFollowTarget.UpdateModes.LateUpdate;
public bool NestDrawnHealthBar = false;
[Header("Death")]
/// a gameobject (usually a particle system) to instantiate when the healthbar reaches zero
public GameObject InstantiatedOnDeath;
[Header("Offset")]
[MMInformation("Set the offset (in world units), relative to the object's center, to which the health bar will be displayed.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)]
/// the offset to apply to the healthbar compared to the object's center
public Vector3 HealthBarOffset = new Vector3(0f,1f,0f);
[Header("Display")]
[MMInformation("Here you can define whether or not the healthbar should always be visible. If not, you can set here how long after a hit it'll remain visible.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)]
/// whether or not the bar should be permanently displayed
public bool AlwaysVisible = true;
/// the duration (in seconds) during which to display the bar
public float DisplayDurationOnHit = 1f;
/// if this is set to true the bar will hide itself when it reaches zero
public bool HideBarAtZero = true;
/// the delay (in seconds) after which to hide the bar
public float HideBarAtZeroDelay = 1f;
protected MMProgressBar _progressBar;
protected MMFollowTarget _followTransform;
protected float _lastShowTimestamp = 0f;
protected bool _showBar = false;
protected Image _backgroundImage = null;
protected Image _borderImage = null;
protected Image _foregroundImage = null;
protected Image _delayedImage = null;
protected bool _finalHideStarted = false;
/// <summary>
/// On Start, creates or sets the health bar up
/// </summary>
protected virtual void Awake()
{
Initialization();
}
public virtual void Initialization()
{
_finalHideStarted = false;
if (_progressBar != null)
{
_progressBar.gameObject.SetActive(AlwaysVisible);
return;
}
if (HealthBarType == HealthBarTypes.Prefab)
{
if (HealthBarPrefab == null)
{
Debug.LogWarning(this.name + " : the HealthBar has no prefab associated to it, nothing will be displayed.");
return;
}
_progressBar = Instantiate(HealthBarPrefab, transform.position + HealthBarOffset, transform.rotation) as MMProgressBar;
_progressBar.transform.SetParent(this.transform);
_progressBar.gameObject.name = "HealthBar";
}
if (HealthBarType == HealthBarTypes.Drawn)
{
DrawHealthBar();
UpdateDrawnColors();
}
if (!AlwaysVisible)
{
_progressBar.gameObject.SetActive(false);
}
if (_progressBar != null)
{
_progressBar.SetBar(100f, 0f, 100f);
}
}
/// <summary>
/// Draws the health bar.
/// </summary>
protected virtual void DrawHealthBar()
{
GameObject newGameObject = new GameObject();
newGameObject.name = "HealthBar|"+this.gameObject.name;
if (NestDrawnHealthBar)
{
newGameObject.transform.SetParent(this.transform);
}
_progressBar = newGameObject.AddComponent<MMProgressBar>();
_followTransform = newGameObject.AddComponent<MMFollowTarget>();
_followTransform.Offset = HealthBarOffset;
_followTransform.Target = this.transform;
_followTransform.InterpolatePosition = false;
_followTransform.InterpolateRotation = false;
_followTransform.UpdateMode = FollowTargetMode;
Canvas newCanvas = newGameObject.AddComponent<Canvas>();
newCanvas.renderMode = RenderMode.WorldSpace;
newCanvas.transform.localScale = Vector3.one;
newCanvas.GetComponent<RectTransform>().sizeDelta = Size;
if (!string.IsNullOrEmpty(SortingLayerName))
{
newCanvas.sortingLayerName = SortingLayerName;
}
GameObject container = new GameObject();
container.transform.SetParent(newGameObject.transform);
container.name = "MMProgressBarContainer";
container.transform.localScale = Vector3.one;
GameObject borderImageGameObject = new GameObject();
borderImageGameObject.transform.SetParent(container.transform);
borderImageGameObject.name = "HealthBar Border";
_borderImage = borderImageGameObject.AddComponent<Image>();
_borderImage.transform.position = Vector3.zero;
_borderImage.transform.localScale = Vector3.one;
_borderImage.GetComponent<RectTransform>().sizeDelta = Size;
_borderImage.GetComponent<RectTransform>().anchoredPosition = Vector3.zero;
GameObject bgImageGameObject = new GameObject();
bgImageGameObject.transform.SetParent(container.transform);
bgImageGameObject.name = "HealthBar Background";
_backgroundImage = bgImageGameObject.AddComponent<Image>();
_backgroundImage.transform.position = Vector3.zero;
_backgroundImage.transform.localScale = Vector3.one;
_backgroundImage.GetComponent<RectTransform>().sizeDelta = Size - BackgroundPadding*2;
_backgroundImage.GetComponent<RectTransform>().anchoredPosition = -_backgroundImage.GetComponent<RectTransform>().sizeDelta/2;
_backgroundImage.GetComponent<RectTransform>().pivot = Vector2.zero;
GameObject delayedImageGameObject = new GameObject();
delayedImageGameObject.transform.SetParent(container.transform);
delayedImageGameObject.name = "HealthBar Delayed Foreground";
_delayedImage = delayedImageGameObject.AddComponent<Image>();
_delayedImage.transform.position = Vector3.zero;
_delayedImage.transform.localScale = Vector3.one;
_delayedImage.GetComponent<RectTransform>().sizeDelta = Size - BackgroundPadding*2;
_delayedImage.GetComponent<RectTransform>().anchoredPosition = -_delayedImage.GetComponent<RectTransform>().sizeDelta/2;
_delayedImage.GetComponent<RectTransform>().pivot = Vector2.zero;
GameObject frontImageGameObject = new GameObject();
frontImageGameObject.transform.SetParent(container.transform);
frontImageGameObject.name = "HealthBar Foreground";
_foregroundImage = frontImageGameObject.AddComponent<Image>();
_foregroundImage.transform.position = Vector3.zero;
_foregroundImage.transform.localScale = Vector3.one;
_foregroundImage.color = ForegroundColor.Evaluate(1);
_foregroundImage.GetComponent<RectTransform>().sizeDelta = Size - BackgroundPadding*2;
_foregroundImage.GetComponent<RectTransform>().anchoredPosition = -_foregroundImage.GetComponent<RectTransform>().sizeDelta/2;
_foregroundImage.GetComponent<RectTransform>().pivot = Vector2.zero;
_progressBar.LerpDecreasingDelayedBar = LerpDelayedBar;
_progressBar.LerpForegroundBar = LerpFrontBar;
_progressBar.LerpDecreasingDelayedBarSpeed = LerpDelayedBarSpeed;
_progressBar.LerpForegroundBarSpeedIncreasing = LerpFrontBarSpeed;
_progressBar.ForegroundBar = _foregroundImage.transform;
_progressBar.DelayedBarDecreasing = _delayedImage.transform;
_progressBar.DecreasingDelay = Delay;
_progressBar.BumpScaleOnChange = BumpScaleOnChange;
_progressBar.BumpDuration = BumpDuration;
_progressBar.BumpScaleAnimationCurve = BumpAnimationCurve;
_progressBar.TimeScale = (TimeScale == TimeScales.Time) ? MMProgressBar.TimeScales.Time : MMProgressBar.TimeScales.UnscaledTime;
container.transform.localEulerAngles = InitialRotationAngles;
_progressBar.Initialization();
}
/// <summary>
/// On Update, we hide or show our healthbar based on our current status
/// </summary>
protected virtual void Update()
{
if (_progressBar == null)
{
return;
}
if (_finalHideStarted)
{
return;
}
UpdateDrawnColors();
if (AlwaysVisible)
{
return;
}
if (_showBar)
{
_progressBar.gameObject.SetActive(true);
float currentTime = (TimeScale == TimeScales.UnscaledTime) ? Time.unscaledTime : Time.time;
if (currentTime - _lastShowTimestamp > DisplayDurationOnHit)
{
_showBar = false;
}
}
else
{
_progressBar.gameObject.SetActive(false);
}
}
/// <summary>
/// Hides the bar when it reaches zero
/// </summary>
/// <returns>The hide bar.</returns>
protected virtual IEnumerator FinalHideBar()
{
_finalHideStarted = true;
if (InstantiatedOnDeath != null)
{
Instantiate(InstantiatedOnDeath, this.transform.position + HealthBarOffset, this.transform.rotation);
}
if (HideBarAtZeroDelay == 0)
{
_showBar = false;
_progressBar.gameObject.SetActive(false);
yield return null;
}
else
{
_progressBar.HideBar(HideBarAtZeroDelay);
}
}
/// <summary>
/// Updates the colors of the different bars
/// </summary>
protected virtual void UpdateDrawnColors()
{
if (HealthBarType != HealthBarTypes.Drawn)
{
return;
}
if (_progressBar.Bumping)
{
return;
}
if (_borderImage != null)
{
_borderImage.color = BorderColor.Evaluate(_progressBar.BarProgress);
}
if (_backgroundImage != null)
{
_backgroundImage.color = BackgroundColor.Evaluate(_progressBar.BarProgress);
}
if (_delayedImage != null)
{
_delayedImage.color = DelayedColor.Evaluate(_progressBar.BarProgress);
}
if (_foregroundImage != null)
{
_foregroundImage.color = ForegroundColor.Evaluate(_progressBar.BarProgress);
}
}
/// <summary>
/// Updates the bar
/// </summary>
/// <param name="currentHealth">Current health.</param>
/// <param name="minHealth">Minimum health.</param>
/// <param name="maxHealth">Max health.</param>
/// <param name="show">Whether or not we should show the bar.</param>
public virtual void UpdateBar(float currentHealth, float minHealth, float maxHealth, bool show)
{
// if the healthbar isn't supposed to be always displayed, we turn it on for the specified duration
if (!AlwaysVisible && show)
{
_showBar = true;
_lastShowTimestamp = (TimeScale == TimeScales.UnscaledTime) ? Time.unscaledTime : Time.time;
}
if (_progressBar != null)
{
_progressBar.UpdateBar(currentHealth, minHealth, maxHealth) ;
if (HideBarAtZero && _progressBar.BarTarget <= 0)
{
StartCoroutine(FinalHideBar());
}
if (BumpScaleOnChange)
{
_progressBar.Bump();
}
}
}
}
} | 40.204082 | 291 | 0.680838 | [
"MIT"
] | DuLovell/Battle-Simulator | Assets/Imported Assets/Feel/MMTools/Tools/MMGUI/MMHealthBar.cs | 15,762 | C# |
using Sitecore.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using Sitecore.ExperienceForms.Models;
using System;
namespace Sitecore.HabitatHome.Feature.Forms.SubmitActions
{
internal static class FormFieldExtensions
{
internal static string GetValue(this IViewModel fieldModel)
{
if (fieldModel == null)
{
throw new ArgumentNullException(nameof(fieldModel));
}
var property = fieldModel.GetType().GetProperty("Value");
var postedValue = property.GetValue(fieldModel);
return postedValue != null ? ParseFieldValue(postedValue) : null;
}
private static string ParseFieldValue(object postedValue)
{
Assert.ArgumentNotNull(postedValue, nameof(postedValue));
List<string> stringList = new List<string>();
IList list = postedValue as IList;
if (list != null)
{
foreach (object obj in list)
{
stringList.Add(obj.ToString());
}
}
else
{
stringList.Add(postedValue.ToString());
}
return string.Join(",", stringList);
}
}
} | 29.522727 | 77 | 0.56736 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | DmytroYachnyi/Sitecore.HabitatHome.Platform | src/Feature/Forms/code/Extensions/FormFieldExtensions.cs | 1,301 | C# |
using Mono.Cecil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Generater
{
public class TypeResolver
{
public static bool WrapperSide;
public static BaseTypeResolver Resolve(TypeReference _type, IMemberDefinition context = null)
{
var type = _type.Resolve();
if (Utils.IsDelegate(_type))
return new DelegateResolver(_type, context);
if (_type.Name.Equals("Void"))
return new VoidResolver(_type);
// if (_type.Name.StartsWith("List`"))
// return new ListResolver(_type);
if (_type.Name.Equals("String") || _type.FullName.Equals("System.Object"))
return new StringResolver(_type);
if (type != null && type.IsEnum)
return new EnumResolver(_type);
if (_type.IsGenericParameter || _type.IsGenericInstance || type == null)
return new GenericResolver(_type);
if (_type.IsPrimitive || _type.IsPointer)
return new BaseTypeResolver(_type);
if (_type.FullName.StartsWith("System."))
return new SystemResolver(_type);
if (_type.IsValueType || (_type.IsByReference && _type.GetElementType().IsValueType))
return new StructResolver(_type);
return new ClassResolver(_type);
}
}
public class BaseTypeResolver
{
protected TypeReference type;
public object data;
public BaseTypeResolver(TypeReference _type)
{
type = _type;
}
public virtual string Paramer(string name)
{
return $"{TypeName()} {name}";
}
public virtual string LocalVariable(string name)
{
return Paramer(name);
}
public virtual string TypeName()
{
return RealTypeName();
}
protected string Alias()
{
var tName = type.FullName;
var et = type.GetElementType();
if (et != null)
tName = et.FullName;
switch (tName)
{
case "System.Void":
tName = "void";
break;
case "System.Int32":
tName = "int";
break;
case "System.Object":
tName = "object";
break;
default:
if (!tName.StartsWith("System") && !type.IsGeneric())
tName = "global::" + tName;
break;
}
if (et != null)
tName = type.FullName.Replace(et.FullName, tName);
var genericIndex = tName.IndexOf('`');
if(genericIndex > 0)
{
tName = tName.Remove(genericIndex, 2);
}
return tName.Replace("/",".");
}
public virtual string Unbox(string name,bool previous = false)
{
if (type.IsByReference)
return "ref " + name;
else
return name;
}
public virtual string Box(string name)
{
if (type.IsByReference)
return "ref " + name;
else
return name;
}
public string RealTypeName()
{
var et = type.GetElementType();
var tName = Alias();
if (type.IsByReference && (et.IsValueType || et.IsGeneric()))
tName = "ref " + tName.Replace("&", "");
return tName;
}
}
public class VoidResolver : BaseTypeResolver
{
public VoidResolver(TypeReference type) : base(type)
{
}
public override string Box(string name)
{
return "";
}
public override string TypeName()
{
return $"void";
}
}
public class EnumResolver : BaseTypeResolver
{
public EnumResolver(TypeReference type) : base(type)
{
}
public override string TypeName()
{
return "int";
}
/// <summary>
/// var type_e = (PrimitiveType)type;
/// </summary>
/// <returns> type_e </returns>
public override string Box(string name)
{
CS.Writer.WriteLine($"var {name}_e = (int) {name}");
return $"{name}_e";
}
/// <summary>
/// var type_e = (int) type;
/// </summary>
/// <returns> type_e </returns>
public override string Unbox(string name,bool previous)
{
var unboxCmd = $"var {name}_e = ({RealTypeName()}){name}";
if (previous)
CS.Writer.WritePreviousLine(unboxCmd);
else
CS.Writer.WriteLine(unboxCmd);
return $"{name}_e";
}
}
public class ClassResolver : BaseTypeResolver
{
public ClassResolver(TypeReference type) : base(type)
{
}
public override string Paramer(string name)
{
return $"{TypeName()} {name}_h";
}
public override string TypeName()
{
return "IntPtr";
}
/// <summary>
/// var value_h = ObjectStore.Store(value);
/// </summary>
/// <returns> value_h </returns>
public override string Box(string name)
{
if(TypeResolver.WrapperSide)
CS.Writer.WriteLine($"var {name}_h = {name}.__GetHandle()");
else
CS.Writer.WriteLine($"var {name}_h = ObjectStore.Store({name})");
return $"{name}_h";
}
/// <summary>
/// var resObj = ObjectStore.Get<GameObject>(res);
/// </summary>
/// <returns> resObj </returns>
public override string Unbox(string name, bool previous)
{
var unboxCmd = $"var {name}Obj = ObjectStore.Get<{RealTypeName()}>({name}_h)";
if (previous)
CS.Writer.WritePreviousLine(unboxCmd);
else
CS.Writer.WriteLine(unboxCmd);
return $"{name}Obj";
}
}
public class ListResolver : BaseTypeResolver
{
BaseTypeResolver resolver;
TypeReference genericType;
public ListResolver(TypeReference type) : base(type)
{
var genericInstace = type as GenericInstanceType;
genericType = genericInstace.GenericArguments.First();
resolver = TypeResolver.Resolve(genericType);
}
public override string TypeName()
{
return $"List<{resolver.TypeName()}>";
}
public override string Box(string name)
{
CS.Writer.WriteLine($"{TypeName()} {name}_h = new {TypeName()}()");
CS.Writer.Start($"foreach (var item in { name})");
var res = resolver.Box("item");
CS.Writer.WriteLine($"{name}_h.add({res})");
CS.Writer.End();
return $"{name}_h";
}
public override string Unbox(string name, bool previous)
{
using (new LP(CS.Writer.CreateLinePoint("//list unbox", previous)))
{
var relTypeName = $"List<{TypeResolver.Resolve(genericType).RealTypeName()}>";
CS.Writer.WriteLine($"{relTypeName} {name}_r = new {relTypeName}()");
CS.Writer.Start($"foreach (var item in { name})");
var res = resolver.Unbox("item");
CS.Writer.WriteLine($"{name}_r.add({res})");
CS.Writer.End();
}
return $"{name}_r";
}
}
public class DelegateResolver : BaseTypeResolver
{
bool isStaticMember;
TypeReference declarType;
MethodDefinition contextMember;
string uniqueName;
int paramCount;
bool returnValue;
static HashSet<string> BoxedMemberSet = new HashSet<string>();
static HashSet<string> UnBoxedMemberSet = new HashSet<string>();
private static string _Member(string name)
{
return $"_{name}";
}
private static string _Action(string name)
{
return $"{name}Action";
}
public static string LocalMamberName(string name, MethodDefinition context)
{
var uniq = FullMemberName(context);
return _Member($"{uniq}_{name}");
}
public DelegateResolver(TypeReference type, IMemberDefinition context) : base(type)
{
if(context != null)
{
var method = context as MethodDefinition;
contextMember = method;
isStaticMember = method.IsStatic;
declarType = method.DeclaringType;
paramCount = method.Parameters.Count;
returnValue = !method.ReturnType.IsVoid();
uniqueName = FullMemberName(method);
}
}
static string FullMemberName(MethodDefinition method)
{
var methodName = method.Name;
if (method.IsAddOn || method.IsSetter || method.IsGetter)
methodName = methodName.Substring("add_".Length);//trim "add_" or "set_"
else if (method.IsRemoveOn)
methodName = methodName.Substring("remove_".Length);//trim "remove_"
// Special to AddListener / RemoveListener
else if (method.Parameters.Count == 1 && methodName.StartsWith("Add"))
methodName = methodName.Substring("Add".Length);// trim "Add"
else if (method.Parameters.Count == 1 && methodName.StartsWith("Remove"))
methodName = methodName.Substring("Remove".Length);// trim "Remove"
return method.DeclaringType.Name.Replace("/", "_") + "_" + methodName.Replace(".", "_");
}
public override string Paramer(string name)
{
return $"{TypeName()} {name}_p";
}
public override string TypeName()
{
return "IntPtr";
}
/*
static event global::UnityEngine.Application.LogCallback _logMessageReceived;
static Action<int, int, int> logMessageReceivedAction = OnlogMessageReceived;
static void OnlogMessageReceived(int arg0,int arg1,int arg2)
{
_logMessageReceived(unbox(arg0), unbox(arg1), unbox(arg2));
}
*/
void WriteBoxedMember(string name)
{
if (contextMember == null)
return;
if (BoxedMemberSet.Contains(uniqueName))
return;
BoxedMemberSet.Add(uniqueName);
string _member = _Member(name);// _logMessageReceived
string _action = _Action(name);// logMessageReceivedAction
var flag = isStaticMember ? "static" : "";
var eventTypeName = TypeResolver.Resolve(type).RealTypeName();
if (type.IsGenericInstance)
eventTypeName = Utils.GetGenericTypeName(type);
var eventDeclear = Utils.GetDelegateWrapTypeName(type, isStaticMember ? null : declarType); //Action <int,int,int>
var paramTpes = Utils.GetDelegateParams(type, isStaticMember ? null : declarType, out var returnType); // string , string , LogType ,returnType
var returnTypeName = returnType != null ? TypeResolver.Resolve(returnType).RealTypeName() : "void";
//static event global::UnityEngine.Application.LogCallback _logMessageReceived;
CS.Writer.WriteLine($"public {flag} {eventTypeName} {_member}");
if(!isStaticMember)
CS.Writer.WriteLine($"public GCHandle {_member}_ref"); // resist gc
//static Action<int, int, int> logMessageReceivedAction = OnlogMessageReceived;
CS.Writer.WriteLine($"static {eventDeclear} {_action} = On{name}");
//static void OnlogMessageReceived(int arg0,int arg1,int arg2)
var eventFuncDeclear = $"static {returnTypeName} On{name}(";
for (int i = 0; i < paramTpes.Count; i++)
{
var p = paramTpes[i];
eventFuncDeclear += TypeResolver.Resolve(p).LocalVariable($"arg{i}");
if (i != paramTpes.Count - 1)
{
eventFuncDeclear += ",";
}
}
eventFuncDeclear += ")";
CS.Writer.Start(eventFuncDeclear);
CS.Writer.WriteLine("Exception __e = null");
CS.Writer.Start("try");
//_logMessageReceived(unbox(arg0), unbox(arg1), unbox(arg2));
var callCmd = $"{_member}(";
var targetObj = "";
for (int i = 0; i < paramTpes.Count; i++)
{
var p = paramTpes[i];
var param = TypeResolver.Resolve(p).Unbox($"arg{i}");
if (i == 0 && !isStaticMember)
{
targetObj = param + ".";
continue;
}
callCmd += param;
if (i != paramTpes.Count - 1)
callCmd += ",";
}
callCmd += ")";
if (!string.IsNullOrEmpty(targetObj))
callCmd = targetObj + callCmd;
if (returnType != null)
callCmd = $"var res = " + callCmd;
CS.Writer.WriteLine(callCmd);
if (returnType != null)
{
var res = TypeResolver.Resolve(returnType).Box("res");
CS.Writer.WriteLine($"return {res}");
}
CS.Writer.End();//try
CS.Writer.Start("catch(Exception e)");
CS.Writer.WriteLine("__e = e");
CS.Writer.End();//catch
CS.Writer.WriteLine("if(__e != null)", false);
CS.Writer.WriteLine("ScriptEngine.OnException(__e.ToString())");
if (returnType != null)
CS.Writer.WriteLine($"return default({returnTypeName})");
CS.Writer.End();//method
}
/*
static Action <int,int,int> logMessageReceived;
static Action <int,int,int> logMessageReceivedAction;
static void OnlogMessageReceived(string arg0, string arg1, LogType arg2)
{
logMessageReceived(box(arg0), box(arg1), box(arg2));
}
*/
void WriteUnboxedMember(string name)
{
if (contextMember == null)
return;
if (UnBoxedMemberSet.Contains(uniqueName))
return;
UnBoxedMemberSet.Add(uniqueName);
string _member = _Member(name);// _logMessageReceived
var paramTpes = Utils.GetDelegateParams(type, isStaticMember ? null : declarType, out var returnType); // string , string , LogType ,returnType
var returnTypeName = returnType != null ? TypeResolver.Resolve(returnType).RealTypeName() : "void";
var eventDeclear = Utils.GetDelegateWrapTypeName(type, isStaticMember ? null : declarType); //Action <int,int,int>
//static void OnlogMessageReceived(string arg0, string arg1, LogType arg2)
var eventFuncDeclear = $"static {returnTypeName} On{name}(";
for (int i = 0; i < paramTpes.Count; i++)
{
var p = paramTpes[i];
if (!isStaticMember && i == 0)
eventFuncDeclear += "this ";
eventFuncDeclear += $"{TypeResolver.Resolve(p).RealTypeName()} arg{i}";
if (i != paramTpes.Count - 1)
{
eventFuncDeclear += ",";
}
}
eventFuncDeclear += ")";
CS.Writer.WriteLine($"static {eventDeclear} {_member}");
CS.Writer.Start(eventFuncDeclear);
var callCmd = $"{_member}(";
if (returnType != null)
callCmd = "var res = " + callCmd;
for (int i = 0; i < paramTpes.Count; i++)
{
var p = paramTpes[i];
callCmd += TypeResolver.Resolve(p).Box($"arg{i}");
if (i != paramTpes.Count - 1)
callCmd += ",";
}
callCmd += ")";
CS.Writer.WriteLine(callCmd);
CS.Writer.WriteLine("ScriptEngine.CheckException()");
if (returnType != null)
{
var res = TypeResolver.Resolve(returnType).Box("res");
CS.Writer.WriteLine($"return {res}");
}
CS.Writer.End();
}
public override string Box(string name)
{
var memberUniqueName = $"{uniqueName}_{name}";
using (new LP(CS.Writer.GetLinePoint("//member")))
{
WriteBoxedMember(memberUniqueName);
}
var _action = _Action(memberUniqueName);
var _member = _Member(memberUniqueName);
CS.Writer.WriteLine($"var {memberUniqueName}_p = Marshal.GetFunctionPointerForDelegate({_action})");
return $"{memberUniqueName}_p";
}
public override string Unbox(string name, bool previous)
{
var memberUniqueName = $"{uniqueName}_{name}";
if(!contextMember.IsRemoveOn)
{
using (new LP(CS.Writer.GetLinePoint("//Method")))
{
WriteUnboxedMember(memberUniqueName);
}
string _member = _Member(memberUniqueName);// _logMessageReceived
string ptrName = $"{name}_p";
var eventDeclear = Utils.GetDelegateWrapTypeName(type, isStaticMember ? null : declarType);
var unboxCmd = $"{_member} = {ptrName} == IntPtr.Zero ? null: Marshal.GetDelegateForFunctionPointer<{eventDeclear}>({ptrName})";
if (previous)
CS.Writer.WritePreviousLine(unboxCmd);
else
CS.Writer.WriteLine(unboxCmd);
}
var resCmd = $"On{memberUniqueName}";
if (!isStaticMember)
resCmd = "thizObj." + resCmd;
return resCmd;
}
}
public class StructResolver : BaseTypeResolver
{
public StructResolver(TypeReference type) : base(type)
{
}
public override string Paramer(string name)
{
if(type.IsByReference)
return base.Paramer(name);
else
return "ref " + base.Paramer(name);
}
public override string LocalVariable(string name)
{
return base.Paramer(name);
}
public override string Box(string name)
{
name = base.Box(name);
if (TypeResolver.WrapperSide && !name.StartsWith("ref "))
name = "ref " + name;
return name;
}
}
public class StringResolver : BaseTypeResolver
{
public StringResolver(TypeReference type) : base(type)
{
}
/*public override string TypeName()
{
if (type.Name.Equals("Object"))
return "object";
return base.TypeName();
}*/
}
public class SystemResolver : BaseTypeResolver
{
public SystemResolver(TypeReference type) : base(type)
{
}
/* public override string TypeName()
{
if (type.Name.Equals("Object"))
return "object";
return base.TypeName();
}*/
}
public class GenericResolver : BaseTypeResolver
{
public GenericResolver(TypeReference type) : base(type)
{
}
}
}
| 31.907643 | 155 | 0.521509 | [
"MIT"
] | kkvskkkk/PureScript | BindGenerater/Generater/CSharp/TypeResolver.cs | 20,040 | C# |
namespace Keyboard_Locker
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.MainButton = new System.Windows.Forms.Button();
this.WarningLabel = new System.Windows.Forms.Label();
this.LicenseLabel = new System.Windows.Forms.Label();
this.NotifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
this.ContextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.OpenWindowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LockToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ExitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.TipLabel = new System.Windows.Forms.Label();
this.ContextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// MainButton
//
this.MainButton.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.MainButton.Font = new System.Drawing.Font("Consolas", 36F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.MainButton.Location = new System.Drawing.Point(70, 20);
this.MainButton.Name = "MainButton";
this.MainButton.Size = new System.Drawing.Size(270, 100);
this.MainButton.TabIndex = 0;
this.MainButton.Text = "Lock";
this.MainButton.UseVisualStyleBackColor = true;
this.MainButton.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainButton_Click);
//
// WarningLabel
//
this.WarningLabel.AutoSize = true;
this.WarningLabel.Font = new System.Drawing.Font("Consolas", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.WarningLabel.ForeColor = System.Drawing.SystemColors.ControlText;
this.WarningLabel.Location = new System.Drawing.Point(46, 164);
this.WarningLabel.Name = "WarningLabel";
this.WarningLabel.Size = new System.Drawing.Size(320, 18);
this.WarningLabel.TabIndex = 1;
this.WarningLabel.Text = "※ (Ctrl + Alt + Delete) Still working.";
this.WarningLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// LicenseLabel
//
this.LicenseLabel.AutoSize = true;
this.LicenseLabel.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LicenseLabel.ForeColor = System.Drawing.SystemColors.ControlText;
this.LicenseLabel.Location = new System.Drawing.Point(120, 192);
this.LicenseLabel.Name = "LicenseLabel";
this.LicenseLabel.Size = new System.Drawing.Size(168, 14);
this.LicenseLabel.TabIndex = 2;
this.LicenseLabel.Text = "Create by Villan © 2019";
this.LicenseLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// NotifyIcon1
//
this.NotifyIcon1.ContextMenuStrip = this.ContextMenuStrip1;
this.NotifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("NotifyIcon1.Icon")));
this.NotifyIcon1.Text = "Keyboard Locker";
this.NotifyIcon1.Visible = true;
this.NotifyIcon1.DoubleClick += new System.EventHandler(this.NotifyIcon1_DoubleClick);
//
// ContextMenuStrip1
//
this.ContextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.OpenWindowToolStripMenuItem,
this.LockToolStripMenuItem,
this.ExitToolStripMenuItem});
this.ContextMenuStrip1.Name = "ContextMenuStrip1";
this.ContextMenuStrip1.Size = new System.Drawing.Size(151, 70);
this.ContextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.ContextMenuStrip1_Opening);
//
// OpenWindowToolStripMenuItem
//
this.OpenWindowToolStripMenuItem.Name = "OpenWindowToolStripMenuItem";
this.OpenWindowToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.OpenWindowToolStripMenuItem.Text = "Open Window";
this.OpenWindowToolStripMenuItem.Click += new System.EventHandler(this.OpenWindowToolStripMenuItem_Click);
//
// LockToolStripMenuItem
//
this.LockToolStripMenuItem.Name = "LockToolStripMenuItem";
this.LockToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.LockToolStripMenuItem.Text = "Lock";
this.LockToolStripMenuItem.Click += new System.EventHandler(this.LockToolStripMenuItem_Click);
//
// ExitToolStripMenuItem
//
this.ExitToolStripMenuItem.Name = "ExitToolStripMenuItem";
this.ExitToolStripMenuItem.Size = new System.Drawing.Size(150, 22);
this.ExitToolStripMenuItem.Text = "Exit";
this.ExitToolStripMenuItem.Click += new System.EventHandler(this.ExitToolStripMenuItem_Click);
//
// TipLabel
//
this.TipLabel.AutoSize = true;
this.TipLabel.Font = new System.Drawing.Font("Consolas", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.TipLabel.ForeColor = System.Drawing.SystemColors.ControlText;
this.TipLabel.Location = new System.Drawing.Point(11, 136);
this.TipLabel.Name = "TipLabel";
this.TipLabel.Size = new System.Drawing.Size(384, 18);
this.TipLabel.TabIndex = 3;
this.TipLabel.Text = "Quickly triple press \"Caps Lock\" to lock/unlock";
this.TipLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Menu;
this.ClientSize = new System.Drawing.Size(404, 215);
this.Controls.Add(this.TipLabel);
this.Controls.Add(this.LicenseLabel);
this.Controls.Add(this.WarningLabel);
this.Controls.Add(this.MainButton);
this.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.HelpButton = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Keyboard Locker";
this.TopMost = true;
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
this.SizeChanged += new System.EventHandler(this.Form1_SizeChanged);
this.ContextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.Button MainButton;
private System.Windows.Forms.Label WarningLabel;
private System.Windows.Forms.Label LicenseLabel;
private System.Windows.Forms.NotifyIcon NotifyIcon1;
private System.Windows.Forms.ToolStripMenuItem OpenWindowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem LockToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem ExitToolStripMenuItem;
private System.Windows.Forms.ContextMenuStrip ContextMenuStrip1;
private System.Windows.Forms.Label TipLabel;
}
}
| 55.15528 | 163 | 0.643468 | [
"MIT"
] | limanson/Keyboard-Locker | Project/Keyboard Locker/Form1.Designer.cs | 8,885 | 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 eventbridge-2015-10-07.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.EventBridge.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.EventBridge.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribePartnerEventSource operation
/// </summary>
public class DescribePartnerEventSourceResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribePartnerEventSourceResponse response = new DescribePartnerEventSourceResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Arn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Arn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Name", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Name = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalException"))
{
return InternalExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonEventBridgeException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DescribePartnerEventSourceResponseUnmarshaller _instance = new DescribePartnerEventSourceResponseUnmarshaller();
internal static DescribePartnerEventSourceResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribePartnerEventSourceResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.6 | 194 | 0.643998 | [
"Apache-2.0"
] | Melvinerall/aws-sdk-net | sdk/src/Services/EventBridge/Generated/Model/Internal/MarshallTransformations/DescribePartnerEventSourceResponseUnmarshaller.cs | 4,632 | C# |
using JetBrains.Annotations;
namespace GenericExtensions.Interfaces
{
public interface ILoader
{
bool State { get; }
void Loading(bool state);
void Flush();
}
}
| 14.357143 | 38 | 0.616915 | [
"MIT"
] | arijoon/FreeFall-Unity3D-Game | Assets/GenericExtensions/Interfaces/ILoader.cs | 203 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface IWorkbookChartFontRequest.
/// </summary>
public partial interface IWorkbookChartFontRequest : IBaseRequest
{
/// <summary>
/// Creates the specified WorkbookChartFont using PUT.
/// </summary>
/// <param name="workbookChartFontToCreate">The WorkbookChartFont to create.</param>
/// <returns>The created WorkbookChartFont.</returns>
System.Threading.Tasks.Task<WorkbookChartFont> CreateAsync(WorkbookChartFont workbookChartFontToCreate); /// <summary>
/// Creates the specified WorkbookChartFont using PUT.
/// </summary>
/// <param name="workbookChartFontToCreate">The WorkbookChartFont to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartFont.</returns>
System.Threading.Tasks.Task<WorkbookChartFont> CreateAsync(WorkbookChartFont workbookChartFontToCreate, CancellationToken cancellationToken);
/// <summary>
/// Deletes the specified WorkbookChartFont.
/// </summary>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync();
/// <summary>
/// Deletes the specified WorkbookChartFont.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets the specified WorkbookChartFont.
/// </summary>
/// <returns>The WorkbookChartFont.</returns>
System.Threading.Tasks.Task<WorkbookChartFont> GetAsync();
/// <summary>
/// Gets the specified WorkbookChartFont.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartFont.</returns>
System.Threading.Tasks.Task<WorkbookChartFont> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Updates the specified WorkbookChartFont using PATCH.
/// </summary>
/// <param name="workbookChartFontToUpdate">The WorkbookChartFont to update.</param>
/// <returns>The updated WorkbookChartFont.</returns>
System.Threading.Tasks.Task<WorkbookChartFont> UpdateAsync(WorkbookChartFont workbookChartFontToUpdate);
/// <summary>
/// Updates the specified WorkbookChartFont using PATCH.
/// </summary>
/// <param name="workbookChartFontToUpdate">The WorkbookChartFont to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartFont.</returns>
System.Threading.Tasks.Task<WorkbookChartFont> UpdateAsync(WorkbookChartFont workbookChartFontToUpdate, CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookChartFontRequest Expand(string value);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
IWorkbookChartFontRequest Expand(Expression<Func<WorkbookChartFont, object>> expandExpression);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookChartFontRequest Select(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
IWorkbookChartFontRequest Select(Expression<Func<WorkbookChartFont, object>> selectExpression);
}
}
| 47.349057 | 153 | 0.644551 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookChartFontRequest.cs | 5,019 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Day21
{
public static class Program
{
private static readonly Item[] ShopItems = new[]
{
// ReSharper disable StringLiteralTypo
new Item(ItemType.Weapon, "Dagger", 8, 4, 0),
new Item(ItemType.Weapon, "Shortsword", 10, 5, 0),
new Item(ItemType.Weapon, "Warhammer", 25, 6, 0),
new Item(ItemType.Weapon, "Longsword", 40, 7, 0),
new Item(ItemType.Weapon, "Greataxe", 74, 8, 0),
new Item(ItemType.Armor, "Leather", 13, 0, 1),
new Item(ItemType.Armor, "Chainmail", 31, 0, 2),
new Item(ItemType.Armor, "Splitmail", 53, 0, 3),
new Item(ItemType.Armor, "Bandedmail", 75, 0, 4),
new Item(ItemType.Armor, "Platemail", 102, 0, 5),
new Item(ItemType.Ring, "Damage +1", 25, 1, 0),
new Item(ItemType.Ring, "Damage +2", 50, 2, 0),
new Item(ItemType.Ring, "Damage +3", 100, 3, 0),
new Item(ItemType.Ring, "Defense +1", 20, 0, 1),
new Item(ItemType.Ring, "Defense +2", 40, 0, 2),
new Item(ItemType.Ring, "Defense +3", 80, 0, 3)
};
static void Main(string[] args)
{
var input = File.ReadAllText("input.txt");
var playerHitPoints = 100;
var partA = SolvePartA(playerHitPoints, input);
Console.WriteLine($"Least amount of gold you can spend: {partA}");
var partB = SolvePartB(playerHitPoints, input);
Console.WriteLine($"Most amount of gold you can spend (and still lose): {partB}");
}
private static int SolvePartB(int playerHitPoints, string input)
{
var boss = Parse(input);
var combinations = Combinations(playerHitPoints);
return combinations
.Where(x => !Victorious(x, boss))
.Select(x => x.Cost)
.Max();
}
private static int SolvePartA(int playerHitPoints, string input)
{
var boss = Parse(input);
var combinations = Combinations(playerHitPoints);
return combinations
.Where(x => Victorious(x, boss))
.Select(x => x.Cost)
.Min();
}
private static bool Victorious(Loadout x, Stats boss)
{
var (result, _) = SimulateBattle(new Stats(x.HitPoints, x.Damage, x.Armor), boss);
return result == BattleResult.Victory;
}
private static List<Loadout> Combinations(int playerHitPoints)
{
// combination rules: exactly 1 weapon
// optional armor (maximum of 1)
// optional rings (maximum of 2)
var weapons = ShopItems.Where(x => x.Type == ItemType.Weapon).ToArray();
var armors = ShopItems.Where(x => x.Type == ItemType.Armor).ToArray();
var rings = ShopItems.Where(x => x.Type == ItemType.Ring).ToArray();
var weaponChoices = weapons;
var armorChoices = armors
.Select(x => new Item[] { x })
.Append(Array.Empty<Item>())
.ToArray();
var ringChoices = GetKCombs(rings, 2)
.Concat(GetKCombs(rings, 1))
.Append(Array.Empty<Item>())
.ToArray();
var loadouts = new List<Loadout>();
foreach (var weaponChoice in weaponChoices)
foreach (var armorChoice in armorChoices)
foreach (var ringChoice in ringChoices)
{
var damage = weaponChoice.Damage
+ armorChoice.Sum(x => x.Damage)
+ ringChoice.Sum(x => x.Damage);
var armor = weaponChoice.Armor
+ armorChoice.Sum(x => x.Armor)
+ ringChoice.Sum(x => x.Armor);
var cost = weaponChoice.Cost
+ armorChoice.Sum(x => x.Cost)
+ ringChoice.Sum(x => x.Cost);
loadouts.Add(new Loadout(playerHitPoints, damage, armor, cost));
}
return loadouts;
}
// Adapted from https://stackoverflow.com/a/10629938
static IEnumerable<IEnumerable<Item>> GetKCombs(IEnumerable<Item> list, int length)
{
if (length == 1) return list.Select(t => new Item[] { t });
return GetKCombs(list, length - 1)
.SelectMany(t => list.Where(o => String.CompareOrdinal(o.Name, t.Last()?.Name) > 0),
(t1, t2) => t1.Concat(new Item[] { t2 }));
}
private static Stats Parse(string input)
{
var stats = input
.Split("\n")
.Select(x => x.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.ToDictionary(x => x.Split(":")[0], x => x.Split(" ")[^1]);
var hitPoints = int.Parse(stats["Hit Points"]);
var damage = int.Parse(stats["Damage"]);
var armor = int.Parse(stats["Armor"]);
return new Stats(hitPoints, damage, armor);
}
public static (BattleResult, string[]) SimulateBattle(Stats player, Stats boss)
{
var log = new List<string>();
int playerHitPoints = player.HitPoints;
int bossHitPoints = boss.HitPoints;
bool playerTurn = true;
while (playerHitPoints > 0 && bossHitPoints > 0)
{
var weaponDamage = playerTurn ? player.Damage : boss.Damage;
var targetArmor = playerTurn ? boss.Armor : player.Armor;
var damage = weaponDamage - targetArmor;
// simulate the round
if (playerTurn)
bossHitPoints -= damage;
else
{
playerHitPoints -= damage;
}
var targetHitPoints = playerTurn ? bossHitPoints : playerHitPoints;
// log the results
var attacker = playerTurn ? "player" : "boss";
var target = playerTurn ? "boss" : "player";
log.Add($"The {attacker} deals {weaponDamage}-{targetArmor} = {damage} damage; the {target} goes down to {targetHitPoints} hit points.");
playerTurn = !playerTurn;
}
var result = playerHitPoints > 0 ? BattleResult.Victory : BattleResult.Defeat;
return (result, log.ToArray());
}
}
public enum BattleResult
{
Victory,
Defeat
}
public enum ItemType
{
Weapon,
Armor,
Ring
}
public record Item(ItemType Type, string Name, int Cost, int Damage, int Armor);
public record Stats(int HitPoints, int Damage, int Armor);
public record Loadout(int HitPoints, int Damage, int Armor, int Cost);
} | 37.515957 | 153 | 0.525308 | [
"MIT"
] | pseale/advent-of-advent-of-code | 2015-csharp/Day21/Program.cs | 7,055 | C# |
// Copyright 2021 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Retail.V2Alpha.Snippets
{
using Google.Api.Gax;
using Google.Cloud.Retail.V2Alpha;
using System;
public sealed partial class GeneratedProductServiceClientStandaloneSnippets
{
/// <summary>Snippet for ListProducts</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ListProducts()
{
// Create client
ProductServiceClient productServiceClient = ProductServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/branches/[BRANCH]";
// Make the request
PagedEnumerable<ListProductsResponse, Product> response = productServiceClient.ListProducts(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Product item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListProductsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Product item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Product> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Product item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
}
| 40.821918 | 120 | 0.622483 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/retail/v2alpha/google-cloud-retail-v2alpha-csharp/Google.Cloud.Retail.V2Alpha.StandaloneSnippets/ProductServiceClient.ListProductsSnippet.g.cs | 2,980 | C# |
using Microsoft.Extensions.Options;
using OrchardCore.Environment.Extensions;
namespace OrchardCore.Tests.Stubs
{
public class StubManifestOptions : IOptions<ManifestOptions>
{
private ManifestOption[] _options;
public StubManifestOptions(params ManifestOption[] options)
{
_options = options;
}
public ManifestOptions Value
{
get
{
var options = new ManifestOptions();
foreach (var option in _options)
{
options.ManifestConfigurations.Add(option);
}
return options;
}
}
}
} | 23.965517 | 67 | 0.548201 | [
"BSD-3-Clause"
] | VladislavPPetrov/Moa-CMS | test/OrchardCore.Tests/Stubs/StubManifestOptions.cs | 697 | C# |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Alipay.AopSdk.Domain
{
/// <summary>
/// KbdishInfo Data Structure.
/// </summary>
[Serializable]
public class KbdishInfo : AopObject
{
/// <summary>
/// 分类字典大类的id
/// </summary>
[XmlElement("catetory_big_id")]
public string CatetoryBigId { get; set; }
/// <summary>
/// 小类,商家自定义配置表例如 肉,酒水,素菜
/// </summary>
[XmlElement("catetory_small_id")]
public string CatetorySmallId { get; set; }
/// <summary>
/// 操作员
/// </summary>
[XmlElement("create_user")]
public string CreateUser { get; set; }
/// <summary>
/// 是否是价 Y:是 N否
/// </summary>
[XmlElement("cur_price_flag")]
public string CurPriceFlag { get; set; }
/// <summary>
/// 菜系,商家自定义
/// </summary>
[XmlElement("dish_cuisine")]
public string DishCuisine { get; set; }
/// <summary>
/// 口碑的菜品id,新增的时候可以为空
/// </summary>
[XmlElement("dish_id")]
public string DishId { get; set; }
/// <summary>
/// 商品图片,需要先调用素材的图片上传api得到图片id
/// </summary>
[XmlElement("dish_img")]
public string DishImg { get; set; }
/// <summary>
/// 菜品的名称
/// </summary>
[XmlElement("dish_name")]
public string DishName { get; set; }
/// <summary>
/// 做法加价列表
/// </summary>
[XmlArray("dish_practice_list")]
[XmlArrayItem("kbdish_practice_info")]
public List<KbdishPracticeInfo> DishPracticeList { get; set; }
/// <summary>
/// 菜品sku列表
/// </summary>
[XmlArray("dish_sku_list")]
[XmlArrayItem("kbdish_sku_info")]
public List<KbdishSkuInfo> DishSkuList { get; set; }
/// <summary>
/// 版本号 就是一个数据操作的时间戳
/// </summary>
[XmlElement("dish_version")]
public string DishVersion { get; set; }
/// <summary>
/// 拼音助记码
/// </summary>
[XmlElement("en_remember_code")]
public string EnRememberCode { get; set; }
/// <summary>
/// 扩展字段,json串
/// </summary>
[XmlElement("ext_content")]
public string ExtContent { get; set; }
/// <summary>
/// 口碑的商品id,用于营销透传
/// </summary>
[XmlElement("goods_id")]
public string GoodsId { get; set; }
/// <summary>
/// 商家id
/// </summary>
[XmlElement("merchant_id")]
public string MerchantId { get; set; }
/// <summary>
/// 起点分数
/// </summary>
[XmlElement("min_serving")]
public string MinServing { get; set; }
/// <summary>
/// 数字助记码
/// </summary>
[XmlElement("nb_remember_code")]
public string NbRememberCode { get; set; }
/// <summary>
/// 菜品的描述
/// </summary>
[XmlElement("remarks")]
public string Remarks { get; set; }
/// <summary>
/// open 启动 stop 停用
/// </summary>
[XmlElement("status")]
public string Status { get; set; }
/// <summary>
/// 口碑枚举定义 single:单品;packages:套餐
/// </summary>
[XmlElement("type_big")]
public string TypeBig { get; set; }
/// <summary>
/// 小类,口碑枚举定义 fixed:固定套餐;choose:选N套餐 几选几
/// </summary>
[XmlElement("type_small")]
public string TypeSmall { get; set; }
/// <summary>
/// 单位id 字典的id
/// </summary>
[XmlElement("unit_id")]
public string UnitId { get; set; }
/// <summary>
/// 修改操作小二
/// </summary>
[XmlElement("update_user")]
public string UpdateUser { get; set; }
}
}
| 25.428571 | 70 | 0.498723 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk/Domain/KbdishInfo.cs | 4,294 | C# |
using Content.Shared.ActionBlocker;
using Content.Shared.Hands.Components;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Events;
using Content.Shared.Popups;
using Content.Shared.Sound;
using Content.Shared.Verbs;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
using Robust.Shared.Player;
using Robust.Shared.Timing;
using System.Diagnostics.CodeAnalysis;
using Content.Shared.Destructible;
namespace Content.Shared.Containers.ItemSlots
{
/// <summary>
/// A class that handles interactions related to inserting/ejecting items into/from an item slot.
/// </summary>
public sealed class ItemSlotsSystem : EntitySystem
{
[Dependency] private readonly ActionBlockerSystem _actionBlockerSystem = default!;
[Dependency] private readonly SharedContainerSystem _containers = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly SharedHandsSystem _handsSystem = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ItemSlotsComponent, MapInitEvent>(OnMapInit);
SubscribeLocalEvent<ItemSlotsComponent, ComponentInit>(Oninitialize);
SubscribeLocalEvent<ItemSlotsComponent, InteractUsingEvent>(OnInteractUsing);
SubscribeLocalEvent<ItemSlotsComponent, InteractHandEvent>(OnInteractHand);
SubscribeLocalEvent<ItemSlotsComponent, UseInHandEvent>(OnUseInHand);
SubscribeLocalEvent<ItemSlotsComponent, GetVerbsEvent<AlternativeVerb>>(AddEjectVerbs);
SubscribeLocalEvent<ItemSlotsComponent, GetVerbsEvent<InteractionVerb>>(AddInteractionVerbsVerbs);
SubscribeLocalEvent<ItemSlotsComponent, BreakageEventArgs>(OnBreak);
SubscribeLocalEvent<ItemSlotsComponent, DestructionEventArgs>(OnBreak);
SubscribeLocalEvent<ItemSlotsComponent, ComponentGetState>(GetItemSlotsState);
SubscribeLocalEvent<ItemSlotsComponent, ComponentHandleState>(HandleItemSlotsState);
SubscribeLocalEvent<ItemSlotsComponent, ItemSlotButtonPressedEvent>(HandleButtonPressed);
}
#region ComponentManagement
/// <summary>
/// Spawn in starting items for any item slots that should have one.
/// </summary>
private void OnMapInit(EntityUid uid, ItemSlotsComponent itemSlots, MapInitEvent args)
{
foreach (var slot in itemSlots.Slots.Values)
{
if (slot.HasItem || string.IsNullOrEmpty(slot.StartingItem))
continue;
var item = EntityManager.SpawnEntity(slot.StartingItem, EntityManager.GetComponent<TransformComponent>(itemSlots.Owner).Coordinates);
slot.ContainerSlot?.Insert(item);
}
}
/// <summary>
/// Ensure item slots have containers.
/// </summary>
private void Oninitialize(EntityUid uid, ItemSlotsComponent itemSlots, ComponentInit args)
{
foreach (var (id, slot) in itemSlots.Slots)
{
slot.ContainerSlot = _containers.EnsureContainer<ContainerSlot>(itemSlots.Owner, id);
}
}
/// <summary>
/// Given a new item slot, store it in the <see cref="ItemSlotsComponent"/> and ensure the slot has an item
/// container.
/// </summary>
public void AddItemSlot(EntityUid uid, string id, ItemSlot slot)
{
var itemSlots = EntityManager.EnsureComponent<ItemSlotsComponent>(uid);
slot.ContainerSlot = _containers.EnsureContainer<ContainerSlot>(itemSlots.Owner, id);
if (itemSlots.Slots.ContainsKey(id))
Logger.Error($"Duplicate item slot key. Entity: {EntityManager.GetComponent<MetaDataComponent>(itemSlots.Owner).EntityName} ({uid}), key: {id}");
itemSlots.Slots[id] = slot;
}
/// <summary>
/// Remove an item slot. This should generally be called whenever a component that added a slot is being
/// removed.
/// </summary>
public void RemoveItemSlot(EntityUid uid, ItemSlot slot, ItemSlotsComponent? itemSlots = null)
{
if (slot.ContainerSlot == null)
return;
slot.ContainerSlot.Shutdown();
// Don't log missing resolves. when an entity has all of its components removed, the ItemSlotsComponent may
// have been removed before some other component that added an item slot (and is now trying to remove it).
if (!Resolve(uid, ref itemSlots, logMissing: false))
return;
itemSlots.Slots.Remove(slot.ContainerSlot.ID);
if (itemSlots.Slots.Count == 0)
EntityManager.RemoveComponent(uid, itemSlots);
}
#endregion
#region Interactions
/// <summary>
/// Attempt to take an item from a slot, if any are set to EjectOnInteract.
/// </summary>
private void OnInteractHand(EntityUid uid, ItemSlotsComponent itemSlots, InteractHandEvent args)
{
if (args.Handled)
return;
foreach (var slot in itemSlots.Slots.Values)
{
if (slot.Locked || !slot.EjectOnInteract || slot.Item == null)
continue;
args.Handled = true;
TryEjectToHands(uid, slot, args.User);
break;
}
}
/// <summary>
/// Attempt to eject an item from the first valid item slot.
/// </summary>
private void OnUseInHand(EntityUid uid, ItemSlotsComponent itemSlots, UseInHandEvent args)
{
if (args.Handled)
return;
foreach (var slot in itemSlots.Slots.Values)
{
if (slot.Locked || !slot.EjectOnUse || slot.Item == null)
continue;
args.Handled = true;
TryEjectToHands(uid, slot, args.User);
break;
}
}
/// <summary>
/// Tries to insert a held item in any fitting item slot. If a valid slot already contains an item, it will
/// swap it out and place the old one in the user's hand.
/// </summary>
/// <remarks>
/// This only handles the event if the user has an applicable entity that can be inserted. This allows for
/// other interactions to still happen (e.g., open UI, or toggle-open), despite the user holding an item.
/// Maybe this is undesirable.
/// </remarks>
private void OnInteractUsing(EntityUid uid, ItemSlotsComponent itemSlots, InteractUsingEvent args)
{
if (args.Handled)
return;
if (!EntityManager.TryGetComponent(args.User, out SharedHandsComponent? hands))
return;
foreach (var slot in itemSlots.Slots.Values)
{
if (!slot.InsertOnInteract)
continue;
if (!CanInsert(uid, args.Used, slot, swap: slot.Swap, popup: args.User))
continue;
// Drop the held item onto the floor. Return if the user cannot drop.
if (!_handsSystem.TryDrop(args.User, args.Used, handsComp: hands))
return;
if (slot.Item != null)
_handsSystem.TryPickupAnyHand(args.User, slot.Item.Value, handsComp: hands);
Insert(uid, slot, args.Used, args.User, excludeUserAudio: true);
args.Handled = true;
return;
}
}
#endregion
#region Insert
/// <summary>
/// Insert an item into a slot. This does not perform checks, so make sure to also use <see
/// cref="CanInsert"/> or just use <see cref="TryInsert"/> instead.
/// </summary>
/// <param name="excludeUserAudio">If true, will exclude the user when playing sound. Does nothing client-side.
/// Useful for predicted interactions</param>
private void Insert(EntityUid uid, ItemSlot slot, EntityUid item, EntityUid? user, bool excludeUserAudio = false)
{
slot.ContainerSlot?.Insert(item);
// ContainerSlot automatically raises a directed EntInsertedIntoContainerMessage
PlaySound(uid, slot.InsertSound, slot.SoundOptions, excludeUserAudio ? user : null);
var ev = new ItemSlotChangedEvent();
RaiseLocalEvent(uid, ref ev);
}
/// <summary>
/// Plays a sound
/// </summary>
/// <param name="uid">Source of the sound</param>
/// <param name="sound">The sound</param>
/// <param name="excluded">Optional (server-side) argument used to prevent sending the audio to a specific
/// user. When run client-side, exclusion does nothing.</param>
private void PlaySound(EntityUid uid, SoundSpecifier? sound, AudioParams audioParams, EntityUid? excluded)
{
if (sound == null || !_gameTiming.IsFirstTimePredicted)
return;
var filter = Filter.Pvs(uid);
if (excluded != null)
filter = filter.RemoveWhereAttachedEntity(entity => entity == excluded.Value);
SoundSystem.Play(sound.GetSound(), filter, uid, audioParams);
}
/// <summary>
/// Check whether a given item can be inserted into a slot. Unless otherwise specified, this will return
/// false if the slot is already filled.
/// </summary>
/// <remarks>
/// If a popup entity is given, and if the item slot is set to generate a popup message when it fails to
/// pass the whitelist, then this will generate a popup.
/// </remarks>
public bool CanInsert(EntityUid uid, EntityUid usedUid, ItemSlot slot, bool swap = false, EntityUid? popup = null)
{
if (slot.Locked)
return false;
if (!swap && slot.HasItem)
return false;
if (slot.Whitelist != null && !slot.Whitelist.IsValid(usedUid))
{
if (popup.HasValue && !string.IsNullOrWhiteSpace(slot.WhitelistFailPopup))
_popupSystem.PopupEntity(Loc.GetString(slot.WhitelistFailPopup), uid, Filter.Entities(popup.Value));
return false;
}
return slot.ContainerSlot?.CanInsertIfEmpty(usedUid, EntityManager) ?? false;
}
/// <summary>
/// Tries to insert item into a specific slot.
/// </summary>
/// <returns>False if failed to insert item</returns>
public bool TryInsert(EntityUid uid, string id, EntityUid item, EntityUid? user, ItemSlotsComponent? itemSlots = null)
{
if (!Resolve(uid, ref itemSlots))
return false;
if (!itemSlots.Slots.TryGetValue(id, out var slot))
return false;
return TryInsert(uid, slot, item, user);
}
/// <summary>
/// Tries to insert item into a specific slot.
/// </summary>
/// <returns>False if failed to insert item</returns>
public bool TryInsert(EntityUid uid, ItemSlot slot, EntityUid item, EntityUid? user)
{
if (!CanInsert(uid, item, slot))
return false;
Insert(uid, slot, item, user);
return true;
}
/// <summary>
/// Tries to insert item into a specific slot from an entity's hand.
/// Does not check action blockers.
/// </summary>
/// <returns>False if failed to insert item</returns>
public bool TryInsertFromHand(EntityUid uid, ItemSlot slot, EntityUid user, SharedHandsComponent? hands = null)
{
if (!Resolve(user, ref hands, false))
return false;
if (hands.ActiveHand?.HeldEntity is not EntityUid held)
return false;
if (!CanInsert(uid, held, slot))
return false;
// hands.Drop(item) checks CanDrop action blocker
if (!_handsSystem.TryDrop(user, hands.ActiveHand))
return false;
Insert(uid, slot, held, user);
return true;
}
#endregion
#region Eject
public bool CanEject(ItemSlot slot)
{
if (slot.Locked || slot.Item == null)
return false;
return slot.ContainerSlot?.CanRemove(slot.Item.Value, EntityManager) ?? false;
}
/// <summary>
/// Eject an item into a slot. This does not perform checks (e.g., is the slot locked?), so you should
/// probably just use <see cref="TryEject"/> instead.
/// </summary>
/// <param name="excludeUserAudio">If true, will exclude the user when playing sound. Does nothing client-side.
/// Useful for predicted interactions</param>
private void Eject(EntityUid uid, ItemSlot slot, EntityUid item, EntityUid? user, bool excludeUserAudio = false)
{
slot.ContainerSlot?.Remove(item);
// ContainerSlot automatically raises a directed EntRemovedFromContainerMessage
PlaySound(uid, slot.EjectSound, slot.SoundOptions, excludeUserAudio ? user : null);
var ev = new ItemSlotChangedEvent();
RaiseLocalEvent(uid, ref ev);
}
/// <summary>
/// Try to eject an item from a slot.
/// </summary>
/// <returns>False if item slot is locked or has no item inserted</returns>
public bool TryEject(EntityUid uid, ItemSlot slot, EntityUid? user, [NotNullWhen(true)] out EntityUid? item, bool excludeUserAudio = false)
{
item = null;
// This handles logic with the slot itself
if (!CanEject(slot))
return false;
item = slot.Item;
// This handles user logic
if (user != null && item != null && !_actionBlockerSystem.CanPickup(user.Value, item.Value))
return false;
Eject(uid, slot, item!.Value, user, excludeUserAudio);
return true;
}
/// <summary>
/// Try to eject item from a slot.
/// </summary>
/// <returns>False if the id is not valid, the item slot is locked, or it has no item inserted</returns>
public bool TryEject(EntityUid uid, string id, EntityUid? user,
[NotNullWhen(true)] out EntityUid? item, ItemSlotsComponent? itemSlots = null, bool excludeUserAudio = false)
{
item = null;
if (!Resolve(uid, ref itemSlots))
return false;
if (!itemSlots.Slots.TryGetValue(id, out var slot))
return false;
return TryEject(uid, slot, user, out item, excludeUserAudio);
}
/// <summary>
/// Try to eject item from a slot directly into a user's hands. If they have no hands, the item will still
/// be ejected onto the floor.
/// </summary>
/// <returns>
/// False if the id is not valid, the item slot is locked, or it has no item inserted. True otherwise, even
/// if the user has no hands.
/// </returns>
public bool TryEjectToHands(EntityUid uid, ItemSlot slot, EntityUid? user, bool excludeUserAudio = false)
{
if (!TryEject(uid, slot, user, out var item, excludeUserAudio))
return false;
if (user != null)
_handsSystem.PickupOrDrop(user.Value, item.Value);
return true;
}
#endregion
#region Verbs
private void AddEjectVerbs(EntityUid uid, ItemSlotsComponent itemSlots, GetVerbsEvent<AlternativeVerb> args)
{
if (args.Hands == null || !args.CanAccess ||!args.CanInteract)
{
return;
}
foreach (var slot in itemSlots.Slots.Values)
{
if (slot.EjectOnInteract)
// For this item slot, ejecting/inserting is a primary interaction. Instead of an eject category
// alt-click verb, there will be a "Take item" primary interaction verb.
continue;
if (!CanEject(slot))
continue;
if (!_actionBlockerSystem.CanPickup(args.User, slot.Item!.Value))
continue;
var verbSubject = slot.Name != string.Empty
? Loc.GetString(slot.Name)
: EntityManager.GetComponent<MetaDataComponent>(slot.Item.Value).EntityName ?? string.Empty;
AlternativeVerb verb = new();
verb.IconEntity = slot.Item;
verb.Act = () => TryEjectToHands(uid, slot, args.User, excludeUserAudio: true);
if (slot.EjectVerbText == null)
{
verb.Text = verbSubject;
verb.Category = VerbCategory.Eject;
}
else
{
verb.Text = Loc.GetString(slot.EjectVerbText);
}
verb.Priority = slot.Priority;
args.Verbs.Add(verb);
}
}
private void AddInteractionVerbsVerbs(EntityUid uid, ItemSlotsComponent itemSlots, GetVerbsEvent<InteractionVerb> args)
{
if (args.Hands == null || !args.CanAccess || !args.CanInteract)
return;
// If there are any slots that eject on left-click, add a "Take <item>" verb.
foreach (var slot in itemSlots.Slots.Values)
{
if (!slot.EjectOnInteract || !CanEject(slot))
continue;
if (!_actionBlockerSystem.CanPickup(args.User, slot.Item!.Value))
continue;
var verbSubject = slot.Name != string.Empty
? Loc.GetString(slot.Name)
: EntityManager.GetComponent<MetaDataComponent>(slot.Item!.Value).EntityName ?? string.Empty;
InteractionVerb takeVerb = new();
takeVerb.IconEntity = slot.Item;
takeVerb.Act = () => TryEjectToHands(uid, slot, args.User, excludeUserAudio: true);
if (slot.EjectVerbText == null)
takeVerb.Text = Loc.GetString("take-item-verb-text", ("subject", verbSubject));
else
takeVerb.Text = Loc.GetString(slot.EjectVerbText);
takeVerb.Priority = slot.Priority;
args.Verbs.Add(takeVerb);
}
// Next, add the insert-item verbs
if (args.Using == null || !_actionBlockerSystem.CanDrop(args.User))
return;
foreach (var slot in itemSlots.Slots.Values)
{
if (!CanInsert(uid, args.Using.Value, slot))
continue;
var verbSubject = slot.Name != string.Empty
? Loc.GetString(slot.Name)
: Name(args.Using.Value) ?? string.Empty;
InteractionVerb insertVerb = new();
insertVerb.IconEntity = args.Using;
insertVerb.Act = () => Insert(uid, slot, args.Using.Value, args.User, excludeUserAudio: true);
if (slot.InsertVerbText != null)
{
insertVerb.Text = Loc.GetString(slot.InsertVerbText);
insertVerb.IconTexture = "/Textures/Interface/VerbIcons/insert.svg.192dpi.png";
}
else if(slot.EjectOnInteract)
{
// Inserting/ejecting is a primary interaction for this entity. Instead of using the insert
// category, we will use a single "Place <item>" verb.
insertVerb.Text = Loc.GetString("place-item-verb-text", ("subject", verbSubject));
insertVerb.IconTexture = "/Textures/Interface/VerbIcons/drop.svg.192dpi.png";
}
else
{
insertVerb.Category = VerbCategory.Insert;
insertVerb.Text = verbSubject;
}
insertVerb.Priority = slot.Priority;
args.Verbs.Add(insertVerb);
}
}
#endregion
#region BUIs
private void HandleButtonPressed(EntityUid uid, ItemSlotsComponent component, ItemSlotButtonPressedEvent args)
{
if (!component.Slots.TryGetValue(args.SlotId, out var slot))
return;
if (args.TryEject && slot.HasItem)
TryEjectToHands(uid, slot, args.Session.AttachedEntity);
else if (args.TryInsert && !slot.HasItem && args.Session.AttachedEntity is EntityUid user)
TryInsertFromHand(uid, slot, user);
}
#endregion
/// <summary>
/// Eject items from (some) slots when the entity is destroyed.
/// </summary>
private void OnBreak(EntityUid uid, ItemSlotsComponent component, EntityEventArgs args)
{
foreach (var slot in component.Slots.Values)
{
if (slot.EjectOnBreak && slot.HasItem)
TryEject(uid, slot, null, out var _);
}
}
/// <summary>
/// Get the contents of some item slot.
/// </summary>
public EntityUid? GetItem(EntityUid uid, string id, ItemSlotsComponent? itemSlots = null)
{
if (!Resolve(uid, ref itemSlots))
return null;
return itemSlots.Slots.GetValueOrDefault(id)?.Item;
}
/// <summary>
/// Lock an item slot. This stops items from being inserted into or ejected from this slot.
/// </summary>
public void SetLock(EntityUid uid, string id, bool locked, ItemSlotsComponent? itemSlots = null)
{
if (!Resolve(uid, ref itemSlots))
return;
if (!itemSlots.Slots.TryGetValue(id, out var slot))
return;
SetLock(uid, slot, locked, itemSlots);
}
/// <summary>
/// Lock an item slot. This stops items from being inserted into or ejected from this slot.
/// </summary>
public void SetLock(EntityUid uid, ItemSlot slot, bool locked, ItemSlotsComponent? itemSlots = null)
{
if (!Resolve(uid, ref itemSlots))
return;
slot.Locked = locked;
itemSlots.Dirty();
}
/// <summary>
/// Update the locked state of the managed item slots.
/// </summary>
/// <remarks>
/// Note that the slot's ContainerSlot performs its own networking, so we don't need to send information
/// about the contained entity.
/// </remarks>
private void HandleItemSlotsState(EntityUid uid, ItemSlotsComponent component, ref ComponentHandleState args)
{
if (args.Current is not ItemSlotsComponentState state)
return;
foreach (var (id, locked) in state.SlotLocked)
{
component.Slots[id].Locked = locked;
}
}
private void GetItemSlotsState(EntityUid uid, ItemSlotsComponent component, ref ComponentGetState args)
{
args.State = new ItemSlotsComponentState(component.Slots);
}
}
/// <summary>
/// Raised directed on an entity when one of its item slots changes.
/// </summary>
[ByRefEvent]
public readonly struct ItemSlotChangedEvent {}
}
| 40.067881 | 161 | 0.577579 | [
"MIT"
] | KIBORG04/space-station-14 | Content.Shared/Containers/ItemSlot/ItemSlotsSystem.cs | 24,201 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.PrometheusService")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Prometheus Service. (New Service) Amazon Managed Service for Prometheus is a fully managed Prometheus-compatible monitoring service that makes it easy to monitor containerized applications securely and at scale.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.7.2.36")] | 49.03125 | 298 | 0.758445 | [
"Apache-2.0"
] | aws/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/PrometheusService/Properties/AssemblyInfo.cs | 1,569 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Duality.Animation
{
/// <summary>
/// The keyframe of an <see cref="AnimationTrack{T}"/>, which is essentially a key/value pair mapped from time to value.
/// </summary>
/// <typeparam name="T">The Type of the animated value.</typeparam>
public struct AnimationKeyFrame<T> : IComparable<AnimationKeyFrame<T>>, IAnimationKeyFrame
{
/// <summary>
/// Time in seconds, at which this keyframe is set.
/// </summary>
public float Time;
/// <summary>
/// Value of the animated entity at the specified time.
/// </summary>
public T Value;
/// <summary>
/// Creates a new keyframe from time and value.
/// </summary>
/// <param name="time">Time in seconds.</param>
/// <param name="value"></param>
public AnimationKeyFrame(float time, T value)
{
this.Time = time;
this.Value = value;
}
public override string ToString()
{
return string.Format("[{0:F}: {1:F}]", this.Time, this.Value);
}
int IComparable<AnimationKeyFrame<T>>.CompareTo(AnimationKeyFrame<T> other)
{
return this.Time.CompareTo(other.Time);
}
float IAnimationKeyFrame.Time
{
get { return this.Time; }
set { this.Time = value; }
}
object IAnimationKeyFrame.Value
{
get { return this.Value; }
set { this.Value = (T)value; }
}
U IAnimationKeyFrame.GetValue<U>()
{
return GenericOperator.Convert<T,U>(this.Value);
}
void IAnimationKeyFrame.SetValue<U>(U value)
{
this.Value = GenericOperator.Convert<U,T>(value);
}
}
}
| 24.65625 | 121 | 0.665399 | [
"MIT"
] | BraveSirAndrew/duality_onikira | Duality/Utility/Animation/AnimationKeyFrame.cs | 1,580 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using Microsoft.Azure;
using Microsoft.Azure.Graph.RBAC.Models;
namespace Microsoft.Azure.Graph.RBAC.Models
{
/// <summary>
/// Server response for Get group information API call
/// </summary>
public partial class GroupGetResult : AzureOperationResponse
{
private Group _group;
/// <summary>
/// Optional. Active Directory group information
/// </summary>
public Group Group
{
get { return this._group; }
set { this._group = value; }
}
/// <summary>
/// Initializes a new instance of the GroupGetResult class.
/// </summary>
public GroupGetResult()
{
}
}
}
| 29.245283 | 76 | 0.652258 | [
"MIT"
] | AzCisHelsinki/azure-sdk-for-net | src/Graph.RBAC/Graph.RBAC/Generated/Models/GroupGetResult.cs | 1,550 | C# |
using Discord;
using Discord.Commands;
using Kotocorn.Extensions;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Kotocorn.Common.Attributes;
namespace Kotocorn.Modules.Administration
{
public partial class Administration
{
[Group]
public class LocalizationCommands : KotocornSubmodule
{
private static readonly ImmutableDictionary<string, string> supportedLocales = new Dictionary<string, string>()
{
{"ar", "العربية" },
{"zh-TW", "繁體中文, 台灣" },
{"zh-CN", "简体中文, 中华人民共和国"},
{"nl-NL", "Nederlands, Nederland"},
{"en-US", "English, United States"},
{"fr-FR", "Français, France"},
{"cs-CZ", "Čeština, Česká republika" },
{"da-DK", "Dansk, Danmark" },
{"de-DE", "Deutsch, Deutschland"},
{"he-IL", "עברית, ישראל"},
{"hu-HU", "Magyar, Magyarország" },
{"id-ID", "Bahasa Indonesia, Indonesia" },
{"it-IT", "Italiano, Italia" },
{"ja-JP", "日本語, 日本"},
{"ko-KR", "한국어, 대한민국" },
{"nb-NO", "Norsk, Norge"},
{"pl-PL", "Polski, Polska" },
{"pt-BR", "Português Brasileiro, Brasil"},
{"ro-RO", "Română, România" },
{"ru-RU", "Русский, Россия"},
{"sr-Cyrl-RS", "Српски, Србија"},
{"es-ES", "Español, España"},
{"sv-SE", "Svenska, Sverige"},
{"tr-TR", "Türkçe, Türkiye"},
{"ts-TS", "Tsundere, You Baka"},
{"uk-UA", "Українська, Україна" }
}.ToImmutableDictionary();
[KotocornCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[Priority(0)]
public async Task LanguageSet()
{
var cul = _localization.GetCultureInfo(Context.Guild);
await ReplyConfirmLocalized("lang_set_show", Format.Bold(cul.ToString()), Format.Bold(cul.NativeName))
.ConfigureAwait(false);
}
[KotocornCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.Administrator)]
[Priority(1)]
public async Task LanguageSet(string name)
{
try
{
CultureInfo ci;
if (name.Trim().ToLowerInvariant() == "default")
{
_localization.RemoveGuildCulture(Context.Guild);
ci = _localization.DefaultCultureInfo;
}
else
{
ci = new CultureInfo(name);
_localization.SetGuildCulture(Context.Guild, ci);
}
await ReplyConfirmLocalized("lang_set", Format.Bold(ci.ToString()), Format.Bold(ci.NativeName)).ConfigureAwait(false);
}
catch(Exception)
{
await ReplyErrorLocalized("lang_set_fail").ConfigureAwait(false);
}
}
[KotocornCommand, Usage, Description, Aliases]
public async Task LanguageSetDefault()
{
var cul = _localization.DefaultCultureInfo;
await ReplyConfirmLocalized("lang_set_bot_show", cul, cul.NativeName).ConfigureAwait(false);
}
[KotocornCommand, Usage, Description, Aliases]
[OwnerOnly]
public async Task LanguageSetDefault(string name)
{
try
{
CultureInfo ci;
if (name.Trim().ToLowerInvariant() == "default")
{
_localization.ResetDefaultCulture();
ci = _localization.DefaultCultureInfo;
}
else
{
ci = new CultureInfo(name);
_localization.SetDefaultCulture(ci);
}
await ReplyConfirmLocalized("lang_set_bot", Format.Bold(ci.ToString()), Format.Bold(ci.NativeName)).ConfigureAwait(false);
}
catch (Exception)
{
await ReplyErrorLocalized("lang_set_fail").ConfigureAwait(false);
}
}
[KotocornCommand, Usage, Description, Aliases]
public async Task LanguagesList()
{
await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithTitle(GetText("lang_list"))
.WithDescription(string.Join("\n",
supportedLocales.Select(x => $"{Format.Code(x.Key), -10} => {x.Value}"))));
}
}
}
}
/* list of language codes for reference.
* taken from https://github.com/dotnet/coreclr/blob/ee5862c6a257e60e263537d975ab6c513179d47f/src/mscorlib/src/System/Globalization/CultureData.cs#L192
{ "029", "en-029" },
{ "AE", "ar-AE" },
{ "AF", "prs-AF" },
{ "AL", "sq-AL" },
{ "AM", "hy-AM" },
{ "AR", "es-AR" },
{ "AT", "de-AT" },
{ "AU", "en-AU" },
{ "AZ", "az-Cyrl-AZ" },
{ "BA", "bs-Latn-BA" },
{ "BD", "bn-BD" },
{ "BE", "nl-BE" },
{ "BG", "bg-BG" },
{ "BH", "ar-BH" },
{ "BN", "ms-BN" },
{ "BO", "es-BO" },
{ "BR", "pt-BR" },
{ "BY", "be-BY" },
{ "BZ", "en-BZ" },
{ "CA", "en-CA" },
{ "CH", "it-CH" },
{ "CL", "es-CL" },
{ "CN", "zh-CN" },
{ "CO", "es-CO" },
{ "CR", "es-CR" },
{ "CS", "sr-Cyrl-CS" },
{ "CZ", "cs-CZ" },
{ "DE", "de-DE" },
{ "DK", "da-DK" },
{ "DO", "es-DO" },
{ "DZ", "ar-DZ" },
{ "EC", "es-EC" },
{ "EE", "et-EE" },
{ "EG", "ar-EG" },
{ "ES", "es-ES" },
{ "ET", "am-ET" },
{ "FI", "fi-FI" },
{ "FO", "fo-FO" },
{ "FR", "fr-FR" },
{ "GB", "en-GB" },
{ "GE", "ka-GE" },
{ "GL", "kl-GL" },
{ "GR", "el-GR" },
{ "GT", "es-GT" },
{ "HK", "zh-HK" },
{ "HN", "es-HN" },
{ "HR", "hr-HR" },
{ "HU", "hu-HU" },
{ "ID", "id-ID" },
{ "IE", "en-IE" },
{ "IL", "he-IL" },
{ "IN", "hi-IN" },
{ "IQ", "ar-IQ" },
{ "IR", "fa-IR" },
{ "IS", "is-IS" },
{ "IT", "it-IT" },
{ "IV", "" },
{ "JM", "en-JM" },
{ "JO", "ar-JO" },
{ "JP", "ja-JP" },
{ "KE", "sw-KE" },
{ "KG", "ky-KG" },
{ "KH", "km-KH" },
{ "KR", "ko-KR" },
{ "KW", "ar-KW" },
{ "KZ", "kk-KZ" },
{ "LA", "lo-LA" },
{ "LB", "ar-LB" },
{ "LI", "de-LI" },
{ "LK", "si-LK" },
{ "LT", "lt-LT" },
{ "LU", "lb-LU" },
{ "LV", "lv-LV" },
{ "LY", "ar-LY" },
{ "MA", "ar-MA" },
{ "MC", "fr-MC" },
{ "ME", "sr-Latn-ME" },
{ "MK", "mk-MK" },
{ "MN", "mn-MN" },
{ "MO", "zh-MO" },
{ "MT", "mt-MT" },
{ "MV", "dv-MV" },
{ "MX", "es-MX" },
{ "MY", "ms-MY" },
{ "NG", "ig-NG" },
{ "NI", "es-NI" },
{ "NL", "nl-NL" },
{ "NO", "nn-NO" },
{ "NP", "ne-NP" },
{ "NZ", "en-NZ" },
{ "OM", "ar-OM" },
{ "PA", "es-PA" },
{ "PE", "es-PE" },
{ "PH", "en-PH" },
{ "PK", "ur-PK" },
{ "PL", "pl-PL" },
{ "PR", "es-PR" },
{ "PT", "pt-PT" },
{ "PY", "es-PY" },
{ "QA", "ar-QA" },
{ "RO", "ro-RO" },
{ "RS", "sr-Latn-RS" },
{ "RU", "ru-RU" },
{ "RW", "rw-RW" },
{ "SA", "ar-SA" },
{ "SE", "sv-SE" },
{ "SG", "zh-SG" },
{ "SI", "sl-SI" },
{ "SK", "sk-SK" },
{ "SN", "wo-SN" },
{ "SV", "es-SV" },
{ "SY", "ar-SY" },
{ "TH", "th-TH" },
{ "TJ", "tg-Cyrl-TJ" },
{ "TM", "tk-TM" },
{ "TN", "ar-TN" },
{ "TR", "tr-TR" },
{ "TT", "en-TT" },
{ "TW", "zh-TW" },
{ "UA", "uk-UA" },
{ "US", "en-US" },
{ "UY", "es-UY" },
{ "UZ", "uz-Cyrl-UZ" },
{ "VE", "es-VE" },
{ "VN", "vi-VN" },
{ "YE", "ar-YE" },
{ "ZA", "af-ZA" },
{ "ZW", "en-ZW" }
*/
| 36.272031 | 151 | 0.367593 | [
"MIT"
] | Erencorn/Kotocorn | NadekoBot.Core/Modules/Administration/LocalizationCommands.cs | 9,601 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Bson.TestHelpers.XunitExtensions;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Core;
using MongoDB.Driver.Core.Clusters;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.TestHelpers.XunitExtensions;
using Xunit;
namespace MongoDB.Driver.Tests.Operations
{
public class BulkWriteOperationTests
{
private MongoServer _server;
private MongoServerInstance _primary;
private MongoCollection<BsonDocument> _collection;
public BulkWriteOperationTests()
{
_server = LegacyTestConfiguration.Server;
_primary = _server.Instances.First(x => x.IsPrimary);
_collection = LegacyTestConfiguration.Database.GetCollection(GetType().Name);
}
[Fact]
public void TestBatchSplittingBySizeWithErrorsOrdered()
{
_collection.Drop();
var documents = new BsonDocument[8];
for (var i = 0; i < 6; i++)
{
documents[i] = new BsonDocument { { "_id", i }, { "a", new string('x', 4 * 1024 * 1024) } };
}
documents[6] = new BsonDocument("_id", 0); // will fail
documents[7] = new BsonDocument("_id", 100);
var bulk = _collection.InitializeOrderedBulkOperation();
for (var i = 0; i < 8; i++)
{
bulk.Insert(documents[i]);
}
var exception = Assert.Throws<MongoBulkWriteException<BsonDocument>>(() => { bulk.Execute(); });
var result = exception.Result;
Assert.Null(exception.WriteConcernError);
Assert.Equal(1, exception.WriteErrors.Count);
var writeError = exception.WriteErrors[0];
Assert.Equal(6, writeError.Index);
Assert.Equal(11000, writeError.Code);
var expectedResult = new ExpectedResult
{
InsertedCount = 6,
ProcessedRequestsCount = 7,
RequestCount = 8
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = documents.Take(6);
Assert.Equal(expectedDocuments, _collection.FindAll());
}
[Fact]
public void TestBatchSplittingBySizeWithErrorsUnordered()
{
_collection.Drop();
var documents = new BsonDocument[8];
for (var i = 0; i < 6; i++)
{
documents[i] = new BsonDocument { { "_id", i }, { "a", new string('x', 4 * 1024 * 1024) } };
}
documents[6] = new BsonDocument("_id", 0); // will fail
documents[7] = new BsonDocument("_id", 100);
var bulk = _collection.InitializeUnorderedBulkOperation();
for (var i = 0; i < 8; i++)
{
bulk.Insert(documents[i]);
}
var exception = Assert.Throws<MongoBulkWriteException<BsonDocument>>(() => { bulk.Execute(); });
var result = exception.Result;
Assert.Null(exception.WriteConcernError);
Assert.Equal(1, exception.WriteErrors.Count);
var writeError = exception.WriteErrors[0];
Assert.Equal(6, writeError.Index);
Assert.Equal(11000, writeError.Code);
var expectedResult = new ExpectedResult
{
InsertedCount = 7,
RequestCount = 8
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = Enumerable.Range(0, 8).Where(i => i != 6).Select(i => documents[i]);
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void TestBatchSplittingDeletesNearMaxWriteBatchCount(int maxBatchCountDelta)
{
var count = _primary.MaxBatchCount + maxBatchCountDelta;
_collection.Drop();
_collection.InsertBatch(Enumerable.Range(0, count).Select(n => new BsonDocument("_id", n)));
var bulk = _collection.InitializeOrderedBulkOperation();
for (var n = 0; n < count; n++)
{
bulk.Find(Query.EQ("_id", n)).RemoveOne();
}
var result = bulk.Execute();
Assert.Equal(count, result.DeletedCount);
Assert.Equal(0, _collection.Count());
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void TestBatchSplittingInsertsNearMaxWriteBatchCount(int maxBatchCountDelta)
{
var count = _primary.MaxBatchCount + maxBatchCountDelta;
_collection.Drop();
var bulk = _collection.InitializeOrderedBulkOperation();
for (var n = 0; n < count; n++)
{
bulk.Insert(new BsonDocument("_id", n));
}
var result = bulk.Execute();
Assert.Equal(count, result.InsertedCount);
Assert.Equal(count, _collection.Count());
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void TestBatchSplittingUpdatesNearMaxWriteBatchCount(int maxBatchCountDelta)
{
var count = _primary.MaxBatchCount + maxBatchCountDelta;
_collection.Drop();
_collection.InsertBatch(Enumerable.Range(0, count).Select(n => new BsonDocument { { "_id", n }, { "n", 0 } }));
var bulk = _collection.InitializeOrderedBulkOperation();
for (var n = 0; n < count; n++)
{
bulk.Find(Query.EQ("_id", n)).UpdateOne(Update.Set("n", 1));
}
var result = bulk.Execute();
if (_primary.Supports(FeatureId.WriteCommands))
{
Assert.Equal(true, result.IsModifiedCountAvailable);
Assert.Equal(count, result.ModifiedCount);
}
else
{
Assert.Equal(false, result.IsModifiedCountAvailable);
}
Assert.Equal(count, _collection.Count());
Assert.Equal(count, _collection.Count(Query.EQ("n", 1)));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestExecuteTwice(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(new BsonDocument());
bulk.Execute();
Assert.Throws<InvalidOperationException>(() => bulk.Execute());
}
[Theory]
[InlineData(false, 0)]
[InlineData(false, 1)]
[InlineData(true, 0)]
[InlineData(true, 1)]
public void TestExecuteWithExplicitWriteConcern(bool ordered, int w)
{
// use RequestStart because some of the test cases use { w : 0 }
using (_server.RequestStart())
{
_collection.Drop();
var document = new BsonDocument("_id", 1);
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(document);
var result = bulk.Execute(new WriteConcern(w));
var expectedResult = new ExpectedResult { IsAcknowledged = w > 0, InsertedCount = 1 };
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[] { document };
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestExecuteWithNoRequests(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
Assert.Throws<InvalidOperationException>(() => bulk.Execute());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestFindAfterExecute(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(new BsonDocument("x", 1));
bulk.Execute();
Assert.Throws<InvalidOperationException>(() => bulk.Find(new QueryDocument()));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestFindWithNullQuery(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
Assert.Throws<ArgumentNullException>(() => bulk.Find(null));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestInsertAfterExecute(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(new BsonDocument("x", 1));
bulk.Execute();
Assert.Throws<InvalidOperationException>(() => bulk.Insert(new BsonDocument()));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestInsertKeyValidation(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(new BsonDocument("$key", 1));
Assert.Throws<BsonSerializationException>(() => bulk.Execute());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestInsertMultipleDocuments(bool ordered)
{
_collection.Drop();
var documents = new BsonDocument[]
{
new BsonDocument("_id", 1),
new BsonDocument("_id", 2),
new BsonDocument("_id", 3)
};
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(documents[0]);
bulk.Insert(documents[1]);
bulk.Insert(documents[2]);
var result = bulk.Execute();
var expectedResult = new ExpectedResult { InsertedCount = 3, RequestCount = 3 };
CheckExpectedResult(expectedResult, result);
_collection.FindAll().Should().BeEquivalentTo(documents);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestInsertOneDocument(bool ordered)
{
_collection.Drop();
var document = new BsonDocument("_id", 1);
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(document);
var result = bulk.Execute();
var expectedResult = new ExpectedResult { InsertedCount = 1 };
CheckExpectedResult(expectedResult, result);
_collection.FindAll().Should().BeEquivalentTo(new[] { document });
}
[Fact]
public void TestMixedOperationsOrdered()
{
_collection.Drop();
var bulk = _collection.InitializeOrderedBulkOperation();
bulk.Insert(new BsonDocument("a", 1));
bulk.Find(Query.EQ("a", 1)).UpdateOne(Update.Set("b", 1));
bulk.Find(Query.EQ("a", 2)).Upsert().UpdateOne(Update.Set("b", 2));
bulk.Insert(new BsonDocument("a", 3));
bulk.Find(Query.EQ("a", 3)).Remove();
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
DeletedCount = 1,
InsertedCount = 2,
MatchedCount = 1,
ModifiedCount = 1,
RequestCount = 5,
UpsertsCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var upserts = result.Upserts;
Assert.Equal(1, upserts.Count);
Assert.IsType<BsonObjectId>(upserts[0].Id);
Assert.Equal(2, upserts[0].Index);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "a", 1 }, { "b", 1 } },
new BsonDocument { { "a", 2 }, { "b", 2 } }
};
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Fact]
public void TestMixedOperationsUnordered()
{
_collection.Drop();
_collection.Insert(new BsonDocument { { "a", 1 } });
_collection.Insert(new BsonDocument { { "a", 2 } });
var bulk = _collection.InitializeUnorderedBulkOperation();
bulk.Find(Query.EQ("a", 1)).Update(Update.Set("b", 1));
bulk.Find(Query.EQ("a", 2)).Remove();
bulk.Insert(new BsonDocument("a", 3));
bulk.Find(Query.EQ("a", 4)).Upsert().UpdateOne(Update.Set("b", 4));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
DeletedCount = 1,
InsertedCount = 1,
MatchedCount = 1,
ModifiedCount = 1,
RequestCount = 4,
UpsertsCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var upserts = result.Upserts;
Assert.Equal(1, upserts.Count);
Assert.IsType<BsonObjectId>(upserts[0].Id);
Assert.Equal(3, upserts[0].Index);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "a", 1 }, { "b", 1 } },
new BsonDocument { { "a", 3 } },
new BsonDocument { { "a", 4 }, { "b", 4 } }
};
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Fact]
public void TestMixedUpsertsOrdered()
{
_collection.Drop();
var bulk = _collection.InitializeOrderedBulkOperation();
var id = ObjectId.GenerateNewId();
bulk.Find(Query.EQ("_id", id)).Upsert().UpdateOne(Update.Set("y", 1));
bulk.Find(Query.EQ("_id", id)).RemoveOne();
bulk.Find(Query.EQ("_id", id)).Upsert().UpdateOne(Update.Set("y", 1));
bulk.Find(Query.EQ("_id", id)).RemoveOne();
bulk.Find(Query.EQ("_id", id)).Upsert().UpdateOne(Update.Set("y", 1));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
DeletedCount = 2,
RequestCount = 5,
UpsertsCount = 3,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[] { new BsonDocument { { "_id", id }, { "y", 1 } } };
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
[Fact]
public void TestMixedUpsertsUnordered()
{
_collection.Drop();
var bulk = _collection.InitializeUnorderedBulkOperation();
bulk.Find(Query.EQ("x", 1)).Upsert().UpdateOne(Update.Set("y", 1));
bulk.Find(Query.EQ("x", 1)).RemoveOne();
bulk.Find(Query.EQ("x", 1)).Upsert().UpdateOne(Update.Set("y", 1));
bulk.Find(Query.EQ("x", 1)).RemoveOne();
bulk.Find(Query.EQ("x", 1)).Upsert().UpdateOne(Update.Set("y", 1));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
DeletedCount = 1,
MatchedCount = 2,
RequestCount = 5,
UpsertsCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[0];
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
[SkippableTheory]
[InlineData(false)]
[InlineData(true)]
public void TestNonDefaultWriteConcern(bool ordered)
{
RequireServer.Check().ClusterType(ClusterType.Standalone);
_collection.Drop();
var documents = new[]
{
new BsonDocument("_id", 1).Add("x", 1)
};
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(documents[0]);
var writeConcern = WriteConcern.W2;
if (_primary.BuildInfo.Version < new Version(2, 6, 0))
{
Assert.Throws<MongoBulkWriteException<BsonDocument>>(() => { bulk.Execute(writeConcern); });
Assert.Equal(1, _collection.Count());
}
else
{
Assert.Throws<MongoCommandException>(() => { bulk.Execute(writeConcern); });
Assert.Equal(0, _collection.Count());
}
}
[Fact]
public void TestOrderedBatchWithErrors()
{
_collection.Drop();
_collection.CreateIndex(IndexKeys.Ascending("a"), IndexOptions.SetUnique(true));
var bulk = _collection.InitializeOrderedBulkOperation();
bulk.Insert(new BsonDocument { { "b", 1 }, { "a", 1 } });
bulk.Find(Query.EQ("b", 2)).Upsert().UpdateOne(Update.Set("a", 1)); // will fail
bulk.Find(Query.EQ("b", 3)).Upsert().UpdateOne(Update.Set("a", 2));
bulk.Find(Query.EQ("b", 2)).Upsert().UpdateOne(Update.Set("a", 1));
bulk.Insert(new BsonDocument { { "b", 4 }, { "a", 3 } });
bulk.Insert(new BsonDocument { { "b", 5 }, { "a", 1 } });
var exception = Assert.Throws<MongoBulkWriteException<BsonDocument>>(() => { bulk.Execute(); });
var result = exception.Result;
var expectedResult = new ExpectedResult
{
InsertedCount = 1,
ProcessedRequestsCount = 2,
RequestCount = 6,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var upserts = result.Upserts;
Assert.Equal(0, upserts.Count);
Assert.Null(exception.WriteConcernError);
Assert.Equal(4, exception.UnprocessedRequests.Count);
var writeErrors = exception.WriteErrors;
Assert.Equal(1, writeErrors.Count);
Assert.Equal(1, writeErrors[0].Index);
Assert.Equal(11000, writeErrors[0].Code);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "b", 1 }, { "a", 1 } }
};
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestRemoveMultiple(bool ordered)
{
_collection.Drop();
var documents = new BsonDocument[]
{
new BsonDocument("_id", 1),
new BsonDocument("_id", 2),
new BsonDocument("_id", 3)
};
_collection.Insert(documents[0]);
_collection.Insert(documents[1]);
_collection.Insert(documents[2]);
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(Query.EQ("_id", 1)).RemoveOne();
bulk.Find(Query.EQ("_id", 3)).RemoveOne();
var result = bulk.Execute();
var expectedResult = new ExpectedResult { DeletedCount = 2, RequestCount = 2 };
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[] { documents[1] };
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestRemoveOneOnlyRemovesOneDocument(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("key", 1));
_collection.Insert(new BsonDocument("key", 1));
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(new QueryDocument()).RemoveOne();
var result = bulk.Execute();
var expectedResult = new ExpectedResult { DeletedCount = 1 };
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[] { new BsonDocument("key", 1) };
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestRemoveWithEmptyQueryRemovesAllDocuments(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("key", 1));
_collection.Insert(new BsonDocument("key", 1));
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(new QueryDocument()).Remove();
var result = bulk.Execute();
var expectedResult = new ExpectedResult { DeletedCount = 2 };
CheckExpectedResult(expectedResult, result);
Assert.Equal(0, _collection.Count());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestRemoveWithQueryRemovesOnlyMatchingDocuments(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("key", 1));
_collection.Insert(new BsonDocument("key", 2));
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(Query.EQ("key", 1)).Remove();
var result = bulk.Execute();
var expectedResult = new ExpectedResult { DeletedCount = 1 };
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[] { new BsonDocument("key", 2) };
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestReplaceOneKeyValidation(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("_id", 1));
var bulk = InitializeBulkOperation(_collection, ordered);
var query = Query.EQ("_id", 1);
var replacement = new BsonDocument { { "_id", 1 }, { "$key", 1 } };
bulk.Find(query).ReplaceOne(replacement);
Assert.Throws<BsonSerializationException>(() => bulk.Execute());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestReplaceOneWithMultipleMatchingDocuments(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("key", 1));
_collection.Insert(new BsonDocument("key", 1));
var bulk = InitializeBulkOperation(_collection, ordered);
var query = Query.EQ("key", 1);
bulk.Find(query).ReplaceOne(new BsonDocument("key", 3));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
MatchedCount = 1,
ModifiedCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument("key", 1),
new BsonDocument("key", 3)
};
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Fact]
public void TestUnorderedBatchWithErrors()
{
_collection.Drop();
_collection.CreateIndex(IndexKeys.Ascending("a"), IndexOptions.SetUnique(true));
var bulk = _collection.InitializeUnorderedBulkOperation();
bulk.Insert(new BsonDocument { { "b", 1 }, { "a", 1 } });
bulk.Find(Query.EQ("b", 2)).Upsert().UpdateOne(Update.Set("a", 1));
bulk.Find(Query.EQ("b", 3)).Upsert().UpdateOne(Update.Set("a", 2));
bulk.Find(Query.EQ("b", 2)).Upsert().UpdateOne(Update.Set("a", 1));
bulk.Insert(new BsonDocument { { "b", 4 }, { "a", 3 } });
bulk.Insert(new BsonDocument { { "b", 5 }, { "a", 1 } });
var exception = Assert.Throws<MongoBulkWriteException<BsonDocument>>(() => { bulk.Execute(); });
var result = exception.Result;
var expectedResult = new ExpectedResult
{
InsertedCount = 2,
RequestCount = 6,
UpsertsCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var upserts = result.Upserts;
Assert.Equal(1, upserts.Count);
Assert.IsType<BsonObjectId>(upserts[0].Id);
Assert.Equal(2, upserts[0].Index);
Assert.Null(exception.WriteConcernError);
Assert.Equal(0, exception.UnprocessedRequests.Count);
var writeErrors = exception.WriteErrors;
Assert.Equal(3, writeErrors.Count);
Assert.Equal(1, writeErrors[0].Index);
Assert.Equal(3, writeErrors[1].Index);
Assert.Equal(5, writeErrors[2].Index);
Assert.True(writeErrors.All(e => e.Code == 11000));
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "b", 1 }, { "a", 1 } },
_primary.BuildInfo.Version < new Version(2, 6, 0) ?
new BsonDocument { { "a", 2 }, { "b", 3 } } : // servers prior to 2.6 rewrite field order on update
new BsonDocument { { "b", 3 }, { "a", 2 } },
new BsonDocument { { "b", 4 }, { "a", 3 } }
};
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpdateChecksThatAllTopLevelFieldNamesAreOperators(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
var query = Query.EQ("_id", 1);
var update = new UpdateDocument { { "key", 1 } };
bulk.Find(query).Update(update);
Assert.Throws<BsonSerializationException>(() => bulk.Execute());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpdateOneBasic(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("key", 1));
_collection.Insert(new BsonDocument("key", 1));
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(new QueryDocument()).UpdateOne(Update.Set("key", 3));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
MatchedCount = 1,
ModifiedCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "key", 1 } },
new BsonDocument { { "key", 3 } }
};
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpdateOneKeyValidation(bool ordered)
{
var updates = new IMongoUpdate[]
{
new UpdateDocument { { "key", 1 } },
new UpdateDocument { { "key", 1 }, { "$key", 1 } }
};
foreach (var update in updates)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
var query = Query.EQ("_id", 1);
bulk.Find(query).UpdateOne(update);
Assert.Throws<BsonSerializationException>(() => bulk.Execute());
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpdateOnlyAffectsDocumentsThatMatch(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("key", 1));
_collection.Insert(new BsonDocument("key", 2));
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(Query.EQ("key", 1)).Update(Update.Set("x", 1));
bulk.Find(Query.EQ("key", 2)).Update(Update.Set("x", 2));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
MatchedCount = 2,
ModifiedCount = 2,
RequestCount = 2,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "key", 1 }, { "x", 1 } },
new BsonDocument { { "key", 2 }, { "x", 2 } }
};
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpdateUpdatesAllMatchingDocuments(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("key", 1));
_collection.Insert(new BsonDocument("key", 2));
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(new QueryDocument()).Update(Update.Set("x", 3));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
MatchedCount = 2,
ModifiedCount = 2,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "key", 1 }, { "x", 3 } },
new BsonDocument { { "key", 2 }, { "x", 3 } }
};
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpsertOneVeryLargeDocument(bool ordered)
{
if (_primary.BuildInfo.Version >= new Version(2, 6, 0))
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
var bigString = new string('x', 16 * 1024 * 1024 - 22);
bulk.Find(Query.EQ("_id", 1)).Upsert().Update(Update.Set("x", bigString)); // resulting document will be exactly 16MiB
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
UpsertsCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "_id", 1 }, { "x", bigString } }
};
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpsertReplaceOneDoesNotAffectNonUpsertsInTheSameOperation(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(Query.EQ("key", 1)).ReplaceOne(new BsonDocument("x", 1)); // not an upsert
bulk.Find(Query.EQ("key", 2)).Upsert().ReplaceOne(new BsonDocument("x", 2));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
RequestCount = 2,
UpsertsCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[] { new BsonDocument { { "x", 2 } } };
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpsertReplaceOneOnlyReplacesOneMatchingDocument(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("key", 1));
_collection.Insert(new BsonDocument("key", 1));
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(Query.EQ("key", 1)).Upsert().ReplaceOne(new BsonDocument("x", 1));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
MatchedCount = 1,
ModifiedCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[]
{
new BsonDocument { { "x", 1 } },
new BsonDocument { { "key", 1 } }
};
Assert.Equal(2, _collection.Count());
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpsertUpdateOneDoesNotAffectNonUpsertsInTheSameOperation(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(Query.EQ("key", 1)).UpdateOne(Update.Set("x", 1)); // not an upsert
bulk.Find(Query.EQ("key", 2)).Upsert().UpdateOne(Update.Set("x", 2));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
RequestCount = 2,
UpsertsCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[] { new BsonDocument { { "key", 2 }, { "x", 2 } } };
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
// repeat the same operation with the current collection contents
var bulk2 = InitializeBulkOperation(_collection, ordered);
bulk2.Find(Query.EQ("key", 1)).UpdateOne(Update.Set("x", 1)); // not an upsert
bulk2.Find(Query.EQ("key", 2)).Upsert().UpdateOne(Update.Set("x", 2));
var result2 = bulk2.Execute();
var expectedResult2 = new ExpectedResult
{
MatchedCount = 1,
RequestCount = 2,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult2, result2);
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpsertUpdateOneOnlyAffectsOneMatchingDocument(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument("key", 1));
_collection.Insert(new BsonDocument("key", 1));
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(Query.EQ("key", 1)).Upsert().UpdateOne(Update.Set("x", 1));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
MatchedCount = 1,
ModifiedCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "key", 1 }, { "x", 1 } },
new BsonDocument { { "key", 1 } }
};
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpsertUpdateUpsertsAndDoesNotAffectNonUpsertsInTheSameOperation(bool ordered)
{
_collection.Drop();
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(Query.EQ("key", 1)).Update(Update.Set("x", 1)); // not an upsert
bulk.Find(Query.EQ("key", 2)).Upsert().Update(Update.Set("x", 2));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
RequestCount = 2,
UpsertsCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[] { new BsonDocument { { "key", 2 }, { "x", 2 } } };
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
// repeat the same batch with the current collection contents
var bulk2 = InitializeBulkOperation(_collection, ordered);
bulk2.Find(Query.EQ("key", 1)).Update(Update.Set("x", 1)); // not an upsert
bulk2.Find(Query.EQ("key", 2)).Upsert().Update(Update.Set("x", 2));
var result2 = bulk2.Execute();
var expectedResult2 = new ExpectedResult
{
MatchedCount = 1,
RequestCount = 2,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult2, result2);
_collection.FindAll().SetFields(Fields.Exclude("_id")).Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpsertWithMultipleMatchingDocuments(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument { { "_id", 1 }, { "x", 1 } });
_collection.Insert(new BsonDocument { { "_id", 2 }, { "x", 1 } });
var bulk = InitializeBulkOperation(_collection, ordered);
var query = Query.EQ("x", 1);
var update = Update.Set("x", 2);
bulk.Find(query).Upsert().Update(update);
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
MatchedCount = 2,
ModifiedCount = 2,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "_id", 1 }, { "x", 2 } },
new BsonDocument { { "_id", 2 }, { "x", 2 } }
};
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpsertWithNoMatchingDocument(bool ordered)
{
_collection.Drop();
// use non-ObjectIds to ensure functionality against < 2.6 servers
var id1 = 1;
var id2 = 2;
_collection.Insert(new BsonDocument { { "_id", id2 }, { "x", 2 } });
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Find(Query.EQ("_id", id1)).Upsert().Update(Update.Set("x", 1));
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
UpsertsCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "_id", id1 }, { "x", 1 } },
new BsonDocument { { "_id", id2 }, { "x", 2 } }
};
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestUpsertWithOneMatchingDocument(bool ordered)
{
_collection.Drop();
_collection.Insert(new BsonDocument { { "_id", 1 }, { "x", 1 } });
_collection.Insert(new BsonDocument { { "_id", 2 }, { "x", 2 } });
var bulk = InitializeBulkOperation(_collection, ordered);
var query = Query.EQ("_id", 1);
var update = Update.Set("x", 3);
bulk.Find(query).Upsert().Update(update);
var result = bulk.Execute();
var expectedResult = new ExpectedResult
{
MatchedCount = 1,
ModifiedCount = 1,
IsModifiedCountAvailable = _primary.Supports(FeatureId.WriteCommands)
};
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new BsonDocument[]
{
new BsonDocument { { "_id", 1 }, { "x", 3 } },
new BsonDocument { { "_id", 2 }, { "x", 2 } }
};
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestW0DoesNotReportErrors(bool ordered)
{
// use a request so we can read our own writes even with older servers
using (_server.RequestStart())
{
_collection.Drop();
var documents = new[]
{
new BsonDocument("_id", 1),
new BsonDocument("_id", 1)
};
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(documents[0]);
bulk.Insert(documents[1]);
var result = bulk.Execute(WriteConcern.Unacknowledged);
var expectedResult = new ExpectedResult { IsAcknowledged = false, RequestCount = 2 };
CheckExpectedResult(expectedResult, result);
var expectedDocuments = new[] { documents[0] };
_collection.FindAll().Should().BeEquivalentTo(expectedDocuments);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestW2AgainstStandalone(bool ordered)
{
if (_primary.InstanceType == MongoServerInstanceType.StandAlone)
{
_collection.Drop();
var documents = new[] { new BsonDocument("x", 1) };
var bulk = InitializeBulkOperation(_collection, ordered);
bulk.Insert(documents[0]);
if (_primary.Supports(FeatureId.WriteCommands))
{
Assert.Throws<MongoCommandException>(() => { bulk.Execute(WriteConcern.W2); });
Assert.Equal(0, _collection.Count());
}
else
{
var exception = Assert.Throws<MongoBulkWriteException<BsonDocument>>(() => { bulk.Execute(WriteConcern.W2); });
var result = exception.Result;
var expectedResult = new ExpectedResult { InsertedCount = 1, RequestCount = 1 };
CheckExpectedResult(expectedResult, result);
Assert.Equal(0, exception.UnprocessedRequests.Count);
Assert.Equal(0, exception.WriteErrors.Count);
var writeConcernError = exception.WriteConcernError;
Assert.NotNull(writeConcernError);
_collection.FindAll().Should().BeEquivalentTo(documents);
}
}
}
[SkippableFact]
public void TestWTimeoutPlusDuplicateKeyError()
{
RequireEnvironment.Check().EnvironmentVariable("EXPLICIT");
RequireServer.Check().Supports(Feature.FailPoints).ClusterType(ClusterType.ReplicaSet);
_collection.Drop();
var secondary = LegacyTestConfiguration.Server.Secondaries.First();
using (LegacyTestConfiguration.StopReplication(secondary))
{
var bulk = _collection.InitializeUnorderedBulkOperation();
bulk.Insert(new BsonDocument("_id", 1));
bulk.Insert(new BsonDocument("_id", 1));
var all = LegacyTestConfiguration.Server.Secondaries.Length + 1;
var exception = Assert.Throws<MongoBulkWriteException<BsonDocument>>(() => bulk.Execute(new WriteConcern(w: all, wTimeout: TimeSpan.FromMilliseconds(1))));
var result = exception.Result;
var expectedResult = new ExpectedResult { InsertedCount = 1, RequestCount = 2 };
CheckExpectedResult(expectedResult, result);
var writeErrors = exception.WriteErrors;
Assert.Equal(1, writeErrors.Count);
Assert.Equal(11000, writeErrors[0].Code);
Assert.Equal(1, writeErrors[0].Index);
var writeConcernError = exception.WriteConcernError;
Assert.Equal(64, writeConcernError.Code);
}
}
// private methods
private void CheckExpectedResult(ExpectedResult expectedResult, BulkWriteResult<BsonDocument> result)
{
Assert.Equal(expectedResult.IsAcknowledged ?? true, result.IsAcknowledged);
Assert.Equal(expectedResult.ProcessedRequestsCount ?? expectedResult.RequestCount ?? 1, result.ProcessedRequests.Count);
Assert.Equal(expectedResult.RequestCount ?? 1, result.RequestCount);
if (result.IsAcknowledged)
{
Assert.Equal(expectedResult.DeletedCount ?? 0, result.DeletedCount);
Assert.Equal(expectedResult.InsertedCount ?? 0, result.InsertedCount);
Assert.Equal(expectedResult.MatchedCount ?? 0, result.MatchedCount);
Assert.Equal(expectedResult.IsModifiedCountAvailable ?? true, result.IsModifiedCountAvailable);
if (result.IsModifiedCountAvailable)
{
Assert.Equal(expectedResult.ModifiedCount ?? 0, result.ModifiedCount);
}
else
{
Assert.Throws<NotSupportedException>(() => { var _ = result.ModifiedCount; });
}
Assert.Equal(expectedResult.UpsertsCount ?? 0, result.Upserts.Count);
}
else
{
Assert.Throws<NotSupportedException>(() => { var x = result.DeletedCount; });
Assert.Throws<NotSupportedException>(() => { var x = result.InsertedCount; });
Assert.Throws<NotSupportedException>(() => { var x = result.MatchedCount; });
Assert.Throws<NotSupportedException>(() => { var x = result.ModifiedCount; });
Assert.Throws<NotSupportedException>(() => { var x = result.Upserts; });
}
}
private BulkWriteOperation<T> InitializeBulkOperation<T>(MongoCollection<T> collection, bool ordered)
{
return ordered ? collection.InitializeOrderedBulkOperation() : collection.InitializeUnorderedBulkOperation();
}
// nested classes
private class ExpectedResult
{
// private fields
private int? _deletedCount;
private int? _insertedCount;
private bool? _isAcknowledged;
private int? _matchedCount;
private int? _modifiedCount;
private bool? _isModifiedCountAvailable;
private int? _processedRequestsCount;
private int? _requestCount;
private int? _upsertsCount;
// public properties
public int? DeletedCount
{
get { return _deletedCount; }
set { _deletedCount = value; }
}
public int? InsertedCount
{
get { return _insertedCount; }
set { _insertedCount = value; }
}
public bool? IsAcknowledged
{
get { return _isAcknowledged; }
set { _isAcknowledged = value; }
}
public bool? IsModifiedCountAvailable
{
get { return _isModifiedCountAvailable; }
set { _isModifiedCountAvailable = value; }
}
public int? MatchedCount
{
get { return _matchedCount; }
set { _matchedCount = value; }
}
public int? ModifiedCount
{
get { return _modifiedCount; }
set { _modifiedCount = value; }
}
public int? ProcessedRequestsCount
{
get { return _processedRequestsCount; }
set { _processedRequestsCount = value; }
}
public int? RequestCount
{
get { return _requestCount; }
set { _requestCount = value; }
}
public int? UpsertsCount
{
get { return _upsertsCount; }
set { _upsertsCount = value; }
}
}
}
}
| 38.752817 | 171 | 0.553335 | [
"Apache-2.0"
] | 591094733/mongo-csharp-driver | tests/MongoDB.Driver.Legacy.Tests/Operations/BulkWriteOperationTests.cs | 51,580 | C# |
using CrossoutLogView.GUI.Helpers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
namespace CrossoutLogView.GUI.Events
{
public delegate void SessionClickEventHandler(object sender, SessionClickEventArgs e);
public class SessionClickEventArgs : RoutedEventArgs
{
public SessionClickEventArgs(SessionTimes session, DateTime day) : base()
{
Session = session;
Day = day;
}
public SessionTimes Session { get; set; }
public DateTime Day { get; set; }
}
}
| 24.083333 | 90 | 0.681661 | [
"MIT"
] | ProphetLamb-Organistion/CrossoutLogViewer | CrossoutLogViewer.GUI/Events/SessionClickEvent.cs | 580 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace AckSharp
{
public abstract partial class EngineObject
{
private static Dictionary<IntPtr, EngineObject> registry = new Dictionary<IntPtr, EngineObject>();
public static T Get<T>(IntPtr ptr)
where T : EngineObject
{
if (ptr == IntPtr.Zero)
return null;
if (registry.ContainsKey(ptr))
{
return registry[ptr] as T;
}
else
{
var type = typeof(T).GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { typeof(IntPtr) },
null);
var obj = type.Invoke(new object[] { ptr }) as T;
registry.Add(ptr, obj);
return obj;
}
}
/// <summary>
/// Needed because old entity references would still be valid after level_load
/// </summary>
internal static void ClearEntityCache()
{
foreach (var obj in registry.ToArray())
{
var ent = obj.Value as Entity;
if (ent == null) continue;
registry.Remove(obj.Key);
}
}
readonly CLink link;
protected EngineObject(ObjectType type, bool userCreated, IntPtr ptr)
{
if (ptr == IntPtr.Zero)
throw new ArgumentException("Cannot create an object with an invalid pointer.");
this.link = new CLink(ptr);
Func<ObjectType, bool> isEntity = ent => ent == ObjectType.Entity || ent == ObjectType.EntityLayer || ent == ObjectType.EntityLocal;
if (isEntity(this.link.Type) && isEntity(type))
{
// All fine!
}
else
{
if (this.link.Type != type)
{
throw new ArgumentException("The provided pointer was of CLink type " + this.link.Type + " but the requested type is " + type);
}
}
if (IsUserCreated && registry.ContainsKey(ptr))
{
throw new InvalidOperationException("You are not allowed mark an EngineObject as user created object and initialize it with a already registered EngineObject pointer.");
}
this.IsUserCreated = userCreated;
this.InternalPointer = ptr;
if (IsUserCreated)
{
// Register this object so we get a reference equality.
registry.Add(ptr, this);
}
}
public IntPtr InternalPointer
{
get; protected set;
}
public bool IsUserCreated { get; private set; }
/// <summary>
/// Removes this object. Only allowed if the object is user created.
/// </summary>
/// <remarks>ptr_remove</remarks>
public void Remove()
{
CheckValid();
this.RemoveFromRegistry();
Native.NativeMethods.PtrRemove(this);
this.InternalPointer = IntPtr.Zero;
}
internal void RemoveFromRegistry()
{
registry.Remove(this.InternalPointer);
}
public static implicit operator IntPtr(EngineObject obj)
{
if (obj == null)
return IntPtr.Zero;
else
return obj.InternalPointer;
}
/// <summary>
/// Gets the CLink of this object.
/// </summary>
/// <returns></returns>
public CLink CLink
{
get { return this.link; }
}
protected ackvar GetVar(int offset)
{
CheckValid();
return new ackvar(Marshal.ReadInt32(InternalPointer, offset));
}
protected void SetVar(int offset, ackvar @var)
{
CheckValid();
Marshal.WriteInt32(InternalPointer, offset, @var.RawValue);
}
protected Vector GetVector(int offset)
{
CheckValid();
return new Vector(
GetVar(offset + 0),
GetVar(offset + 4),
GetVar(offset + 8));
}
protected void SetVector(int offset, Vector value)
{
CheckValid();
SetVar(offset + 0, value.X);
SetVar(offset + 4, value.Y);
SetVar(offset + 8, value.Z);
}
protected Angle GetAngle(int offset)
{
CheckValid();
return new Angle(
GetVar(offset + 0),
GetVar(offset + 4),
GetVar(offset + 8));
}
protected void SetAngle(int offset, Angle value)
{
CheckValid();
SetVar(offset + 0, value.Pan);
SetVar(offset + 4, value.Tilt);
SetVar(offset + 8, value.Roll);
}
protected Color GetColor(int offset)
{
CheckValid();
// Note: rgb constructor, bgr layout!
return new Color(
GetVar(offset + 8),
GetVar(offset + 4),
GetVar(offset + 0));
}
protected void SetColor(int offset, Color value)
{
CheckValid();
SetVar(offset + 0, value.B);
SetVar(offset + 4, value.G);
SetVar(offset + 8, value.R);
}
protected int GetInt(int offset)
{
CheckValid();
return Marshal.ReadInt32(InternalPointer + offset);
}
protected void SetInt(int offset, int @var)
{
CheckValid();
Marshal.WriteInt32(InternalPointer + offset, @var);
}
protected float GetFloat(int offset)
{
CheckValid();
return BitConverter.ToSingle(BitConverter.GetBytes(Marshal.ReadInt32(InternalPointer + offset)), 0);
}
protected void SetFloat(int offset, float @var)
{
CheckValid();
Marshal.WriteInt32(InternalPointer + offset, BitConverter.ToInt32(BitConverter.GetBytes(@var), 0));
}
protected void Set(int offset, EngineObject ent)
{
CheckValid();
IntPtr ptr = ent != null ? ent.InternalPointer : IntPtr.Zero;
Marshal.WriteIntPtr(InternalPointer + offset, ptr);
}
protected T Get<T>(int offset)
where T : EngineObject
{
CheckValid();
var dref = Marshal.ReadIntPtr(InternalPointer + offset);
if (dref != IntPtr.Zero)
return EngineObject.Get<T>(dref);
else
return null;
}
protected IntPtr GetPtr(int offset)
{
CheckValid();
return Marshal.ReadIntPtr(InternalPointer + offset);
}
protected void SetPtr(int offset, IntPtr ptr)
{
CheckValid();
Marshal.WriteIntPtr(InternalPointer + offset, ptr);
}
protected string GetString(int offset)
{
CheckValid();
return Marshal.PtrToStringAnsi(GetPtr(offset));
}
protected void SetString(int offset, NativeString str, string value)
{
CheckValid();
str.Update(value);
Marshal.WriteIntPtr(InternalPointer + offset, str.Pointer);
}
protected Delegate GetEvent(int offset, ref NativeEvent ne, Type type)
{
var ptr = GetPtr(offset);
if (ne.Pointer == ptr)
return ne.Delegate;
ne.Delegate = Marshal.GetDelegateForFunctionPointer(ptr, type);
return ne.Delegate;
}
protected void SetEvent(int offset, ref NativeEvent ne, Delegate ev)
{
if (ne.Delegate != ev)
{
ne.Delegate = ev;
ne.Pointer = Marshal.GetFunctionPointerForDelegate(ev);
}
SetPtr(offset, ne.Pointer);
}
//public static bool operator ==(EngineObject a, EngineObject b)
//{
// if ((object)a == null && (object)b == null) return true;
// if ((object)a == null || (object)b == null) return false;
// return a.Equals(b);
//}
//public static bool operator !=(EngineObject a, EngineObject b)
//{
// if ((object)a == null && (object)b == null) return true;
// if ((object)a == null || (object)b == null) return false;
// return !a.Equals(b);
//}
//public bool Equals(EngineObject other)
//{
// if (other == null) return false;
// return other.InternalPointer == this.InternalPointer;
//}
//public override bool Equals(object obj)
//{
// return this.Equals(obj as EngineObject);
//}
/// <summary>
/// Checks if the entity is valid.
/// </summary>
public void CheckValid()
{
if (!this.IsValid)
throw new InvalidOperationException("Cannot access an invalid entity.");
}
public bool IsValid { get { return this.InternalPointer != IntPtr.Zero; } }
public override int GetHashCode()
{
return this.InternalPointer.ToInt32();
}
public override string ToString()
{
return this.GetType().Name + "[" + this.InternalPointer + "]";
}
protected struct NativeEvent
{
public IntPtr Pointer;
public Delegate Delegate;
}
protected class NativeString
{
public IntPtr Pointer { get; private set; }
public int Length { get; private set; }
public NativeString()
{
this.Length = 0;
this.Pointer = IntPtr.Zero;
this.Update(new string('\0', 128));
}
~NativeString()
{
Marshal.FreeHGlobal(this.Pointer);
}
public void Update(string value)
{
if (value.Length >= this.Length)
{
// We don't have enough space for string + '\0'
if (this.Pointer != IntPtr.Zero) Marshal.FreeHGlobal(this.Pointer);
this.Length = value.Length + 1;
this.Pointer = Marshal.AllocHGlobal(this.Length);
}
var text = Encoding.ASCII.GetBytes(value).Concat(new byte[] { 0 }).ToArray();
memcpy(this.Pointer, text, text.Length);
}
[DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
private static extern IntPtr memcpy(IntPtr dest, byte[] source, int length);
}
}
}
| 24.875346 | 174 | 0.632294 | [
"MIT"
] | MasterQ32/AckNET | AckSharp/EngineObject.cs | 8,982 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNextGen.Network.V20171001.Outputs
{
[OutputType]
public sealed class RouteTableResponse
{
/// <summary>
/// Gets or sets whether to disable the routes learned by BGP on that route table. True means disable.
/// </summary>
public readonly bool? DisableBgpRoutePropagation;
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string? Etag;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// Resource location.
/// </summary>
public readonly string? Location;
/// <summary>
/// Resource name.
/// </summary>
public readonly string Name;
/// <summary>
/// The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
public readonly string? ProvisioningState;
/// <summary>
/// Collection of routes contained within a route table.
/// </summary>
public readonly ImmutableArray<Outputs.RouteResponse> Routes;
/// <summary>
/// A collection of references to subnets.
/// </summary>
public readonly ImmutableArray<Outputs.SubnetResponse> Subnets;
/// <summary>
/// Resource tags.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
[OutputConstructor]
private RouteTableResponse(
bool? disableBgpRoutePropagation,
string? etag,
string? id,
string? location,
string name,
string? provisioningState,
ImmutableArray<Outputs.RouteResponse> routes,
ImmutableArray<Outputs.SubnetResponse> subnets,
ImmutableDictionary<string, string>? tags,
string type)
{
DisableBgpRoutePropagation = disableBgpRoutePropagation;
Etag = etag;
Id = id;
Location = location;
Name = name;
ProvisioningState = provisioningState;
Routes = routes;
Subnets = subnets;
Tags = tags;
Type = type;
}
}
}
| 30.119565 | 110 | 0.579574 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20171001/Outputs/RouteTableResponse.cs | 2,771 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Channels
{
/// <summary>
/// Allocates a new receive buffer whose capacity is probably large enough to read all inbound data and small enough
/// not to waste its space.
/// </summary>
public interface IRecvByteBufAllocator
{
/// <summary>
/// Creates a new handle. The handle provides the actual operations and keeps the internal information which is
/// required for predicting an optimal buffer capacity.
/// </summary>
IRecvByteBufAllocatorHandle NewHandle();
}
} | 40.777778 | 124 | 0.677112 | [
"MIT"
] | 15000775075/DotNetty | src/DotNetty.Transport/Channels/IRecvByteBufAllocator.cs | 736 | C# |
#region BSD License
/*
* Use of this source code is governed by a BSD-style
* license or other governing licenses that can be found in the LICENSE.md file or at
* https://raw.githubusercontent.com/Krypton-Suite/Extended-Toolkit/master/LICENSE
*/
#endregion
using System;
using System.Runtime.InteropServices;
namespace Krypton.Toolkit.Suite.Extended.Utilities.System.Synthesis
{
[TypeLibType(16)]
internal struct WAVEFORMATEX
{
internal short wFormatTag;
internal short nChannels;
internal int nSamplesPerSec;
internal int nAvgBytesPerSec;
internal short nBlockAlign;
internal short wBitsPerSample;
internal short cbSize;
internal static WAVEFORMATEX Default
{
get
{
WAVEFORMATEX result = default(WAVEFORMATEX);
result.wFormatTag = 1;
result.nChannels = 1;
result.nSamplesPerSec = 22050;
result.nAvgBytesPerSec = 44100;
result.nBlockAlign = 2;
result.wBitsPerSample = 16;
result.cbSize = 0;
return result;
}
}
internal int Length => 18 + cbSize;
internal static WAVEFORMATEX ToWaveHeader(byte[] waveHeader)
{
GCHandle gCHandle = GCHandle.Alloc(waveHeader, GCHandleType.Pinned);
IntPtr ptr = gCHandle.AddrOfPinnedObject();
WAVEFORMATEX result = default(WAVEFORMATEX);
result.wFormatTag = Marshal.ReadInt16(ptr);
result.nChannels = Marshal.ReadInt16(ptr, 2);
result.nSamplesPerSec = Marshal.ReadInt32(ptr, 4);
result.nAvgBytesPerSec = Marshal.ReadInt32(ptr, 8);
result.nBlockAlign = Marshal.ReadInt16(ptr, 12);
result.wBitsPerSample = Marshal.ReadInt16(ptr, 14);
result.cbSize = Marshal.ReadInt16(ptr, 16);
if (result.cbSize != 0)
{
throw new InvalidOperationException();
}
gCHandle.Free();
return result;
}
internal static void AvgBytesPerSec(byte[] waveHeader, out int avgBytesPerSec, out int nBlockAlign)
{
GCHandle gCHandle = GCHandle.Alloc(waveHeader, GCHandleType.Pinned);
IntPtr ptr = gCHandle.AddrOfPinnedObject();
avgBytesPerSec = Marshal.ReadInt32(ptr, 8);
nBlockAlign = Marshal.ReadInt16(ptr, 12);
gCHandle.Free();
}
internal byte[] ToBytes()
{
GCHandle gCHandle = GCHandle.Alloc(this, GCHandleType.Pinned);
byte[] result = ToBytes(gCHandle.AddrOfPinnedObject());
gCHandle.Free();
return result;
}
internal static byte[] ToBytes(IntPtr waveHeader)
{
int num = Marshal.ReadInt16(waveHeader, 16);
byte[] array = new byte[18 + num];
Marshal.Copy(waveHeader, array, 0, 18 + num);
return array;
}
}
} | 32.5 | 107 | 0.589525 | [
"BSD-3-Clause"
] | Krypton-Suite/Extended-Toolk | Source/Krypton Toolkit/Shared/Krypton.Toolkit.Suite.Extended.Utilities/Classes/System/SAPI/Synthesis/Internal/WAVEFORMATEX.cs | 3,057 | C# |
using UnityEngine;
using System;
//http://albatrus.com/main/unity/5698
public class CameraFade : MonoBehaviour
{
private static CameraFade mInstance = null;
private static CameraFade instance
{
get
{
if (mInstance == null)
{
mInstance = GameObject.FindObjectOfType(typeof(CameraFade)) as CameraFade;
if (mInstance == null)
{
mInstance = new GameObject("CameraFade").AddComponent<CameraFade>();
}
}
return mInstance;
}
}
void Awake()
{
if (mInstance == null)
{
mInstance = this as CameraFade;
instance.init();
}
}
public GUIStyle m_BackgroundStyle = new GUIStyle(); // Style for background tiling
public Texture2D m_FadeTexture; // 1x1 pixel texture used for fading
public Color m_CurrentScreenOverlayColor = new Color(0, 0, 0, 0); // default starting color: black and fully transparrent
public Color m_TargetScreenOverlayColor = new Color(0, 0, 0, 0); // default target color: black and fully transparrent
public Color m_DeltaColor = new Color(0, 0, 0, 0); // the delta-color is basically the "speed / second" at which the current color should change
public int m_FadeGUIDepth = -1000; // make sure this texture is drawn on top of everything
public float m_FadeDelay = 0;
public Action m_OnFadeFinish = null;
// Initialize the texture, background-style and initial color:
public void init()
{
instance.m_FadeTexture = new Texture2D(1, 1);
instance.m_BackgroundStyle.normal.background = instance.m_FadeTexture;
}
// Draw the texture and perform the fade:
void OnGUI()
{
// If delay is over...
if (Time.time > instance.m_FadeDelay)
{
// If the current color of the screen is not equal to the desired color: keep fading!
if (instance.m_CurrentScreenOverlayColor != instance.m_TargetScreenOverlayColor)
{
// If the difference between the current alpha and the desired alpha is smaller than delta-alpha * deltaTime, then we're pretty much done fading:
if (Mathf.Abs(instance.m_CurrentScreenOverlayColor.a - instance.m_TargetScreenOverlayColor.a) < Mathf.Abs(instance.m_DeltaColor.a) * Time.deltaTime)
{
instance.m_CurrentScreenOverlayColor = instance.m_TargetScreenOverlayColor;
SetScreenOverlayColor(instance.m_CurrentScreenOverlayColor);
instance.m_DeltaColor = new Color(0, 0, 0, 0);
if (instance.m_OnFadeFinish != null)
instance.m_OnFadeFinish();
Die();
}
else
{
// Fade!
SetScreenOverlayColor(instance.m_CurrentScreenOverlayColor + instance.m_DeltaColor * Time.deltaTime);
}
}
}
// Only draw the texture when the alpha value is greater than 0:
if (m_CurrentScreenOverlayColor.a > 0)
{
GUI.depth = instance.m_FadeGUIDepth;
GUI.Label(new Rect(-10, -10, Screen.width + 10, Screen.height + 10), instance.m_FadeTexture, instance.m_BackgroundStyle);
}
}
/// <summary>
/// Sets the color of the screen overlay instantly. Useful to start a fade.
/// </summary>
/// <param name='newScreenOverlayColor'>
/// New screen overlay color.
/// </param>
private static void SetScreenOverlayColor(Color newScreenOverlayColor)
{
instance.m_CurrentScreenOverlayColor = newScreenOverlayColor;
instance.m_FadeTexture.SetPixel(0, 0, instance.m_CurrentScreenOverlayColor);
instance.m_FadeTexture.Apply();
}
/// <summary>
/// Starts the fade from color newScreenOverlayColor. If isFadeIn, start fully opaque, else start transparent.
/// </summary>
/// <param name='newScreenOverlayColor'>
/// Target screen overlay Color.
/// </param>
/// <param name='fadeDuration'>
/// Fade duration.
/// </param>
public static void StartAlphaFade(Color newScreenOverlayColor, bool isFadeIn, float fadeDuration)
{
if (fadeDuration <= 0.0f)
{
SetScreenOverlayColor(newScreenOverlayColor);
}
else
{
if (isFadeIn)
{
instance.m_TargetScreenOverlayColor = new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0);
SetScreenOverlayColor(newScreenOverlayColor);
}
else
{
instance.m_TargetScreenOverlayColor = newScreenOverlayColor;
SetScreenOverlayColor(new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0));
}
instance.m_DeltaColor = (instance.m_TargetScreenOverlayColor - instance.m_CurrentScreenOverlayColor) / fadeDuration;
}
}
/// <summary>
/// Starts the fade from color newScreenOverlayColor. If isFadeIn, start fully opaque, else start transparent, after a delay.
/// </summary>
/// <param name='newScreenOverlayColor'>
/// New screen overlay color.
/// </param>
/// <param name='fadeDuration'>
/// Fade duration.
/// </param>
/// <param name='fadeDelay'>
/// Fade delay.
/// </param>
public static void StartAlphaFade(Color newScreenOverlayColor, bool isFadeIn, float fadeDuration, float fadeDelay)
{
if (fadeDuration <= 0.0f)
{
SetScreenOverlayColor(newScreenOverlayColor);
}
else
{
instance.m_FadeDelay = Time.time + fadeDelay;
if (isFadeIn)
{
instance.m_TargetScreenOverlayColor = new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0);
SetScreenOverlayColor(newScreenOverlayColor);
}
else
{
instance.m_TargetScreenOverlayColor = newScreenOverlayColor;
SetScreenOverlayColor(new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0));
}
instance.m_DeltaColor = (instance.m_TargetScreenOverlayColor - instance.m_CurrentScreenOverlayColor) / fadeDuration;
}
}
/// <summary>
/// Starts the fade from color newScreenOverlayColor. If isFadeIn, start fully opaque, else start transparent, after a delay, with Action OnFadeFinish.
/// </summary>
/// <param name='newScreenOverlayColor'>
/// New screen overlay color.
/// </param>
/// <param name='fadeDuration'>
/// Fade duration.
/// </param>
/// <param name='fadeDelay'>
/// Fade delay.
/// </param>
/// <param name='OnFadeFinish'>
/// On fade finish, doWork().
/// </param>
public static void StartAlphaFade(Color newScreenOverlayColor, bool isFadeIn, float fadeDuration, float fadeDelay, Action OnFadeFinish)
{
if (fadeDuration <= 0.0f)
{
SetScreenOverlayColor(newScreenOverlayColor);
}
else
{
instance.m_OnFadeFinish = OnFadeFinish;
instance.m_FadeDelay = Time.time + fadeDelay;
if (isFadeIn)
{
instance.m_TargetScreenOverlayColor = new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0);
SetScreenOverlayColor(newScreenOverlayColor);
}
else
{
instance.m_TargetScreenOverlayColor = newScreenOverlayColor;
SetScreenOverlayColor(new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0));
}
instance.m_DeltaColor = (instance.m_TargetScreenOverlayColor - instance.m_CurrentScreenOverlayColor) / fadeDuration;
}
}
void Die()
{
mInstance = null;
Destroy(gameObject);
}
void OnApplicationQuit()
{
mInstance = null;
}
} | 38.635135 | 174 | 0.588784 | [
"MIT"
] | 0V/TwitterTimeLineShooter | Assets/Scripts/CameraFade.cs | 8,579 | C# |
version https://git-lfs.github.com/spec/v1
oid sha256:ed90e3d047b1000157a86321a109dfdbcd496d97330b19bbfe46a32cdfec7661
size 5256
| 32.25 | 75 | 0.883721 | [
"MIT"
] | bakiya-sefer/bakiya-sefer | Assets/Plugins/DarkTonic/MasterAudio/Scripts/Events/ButtonClicker.cs | 129 | C# |
namespace SyncIO.Transport.Encryption
{
using System;
public interface ISyncIOEncryption : IDisposable
{
byte[] Encrypt(byte[] data);
byte[] Decrypt(byte[] data);
}
} | 18.272727 | 52 | 0.626866 | [
"MPL-2.0"
] | versx/SyncIO | SyncIO/Transport/Encryption/ISyncIOEncryption.cs | 203 | C# |
using Bigtree.Algorithm.HiddenMarkovModel.MathUtils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bigtree.Algorithm.HiddenMarkovModel.MathHelpers
{
public class Gamma
{
/// <summary>
/// Natural logarithm of the gamma function.
/// </summary>
///
public static double Log(double x)
{
double p, q, w, z;
double[] A =
{
8.11614167470508450300E-4,
-5.95061904284301438324E-4,
7.93650340457716943945E-4,
-2.77777777730099687205E-3,
8.33333333333331927722E-2
};
double[] B =
{
-1.37825152569120859100E3,
-3.88016315134637840924E4,
-3.31612992738871184744E5,
-1.16237097492762307383E6,
-1.72173700820839662146E6,
-8.53555664245765465627E5
};
double[] C =
{
-3.51815701436523470549E2,
-1.70642106651881159223E4,
-2.20528590553854454839E5,
-1.13933444367982507207E6,
-2.53252307177582951285E6,
-2.01889141433532773231E6
};
if (x < -34.0)
{
q = -x;
w = Log(q);
p = System.Math.Floor(q);
if (p == q)
throw new OverflowException();
z = q - p;
if (z > 0.5)
{
p += 1.0;
z = p - q;
}
z = q * System.Math.Sin(System.Math.PI * z);
if (z == 0.0)
throw new OverflowException();
z = Constants.LogPI - System.Math.Log(z) - w;
return z;
}
if (x < 13.0)
{
z = 1.0;
while (x >= 3.0)
{
x -= 1.0;
z *= x;
}
while (x < 2.0)
{
if (x == 0.0)
throw new OverflowException();
z /= x;
x += 1.0;
}
if (z < 0.0) z = -z;
if (x == 2.0) return System.Math.Log(z);
x -= 2.0;
p = x * PolynomialHelper.Polevl(x, B, 5) / PolynomialHelper.P1evl(x, C, 6);
return (System.Math.Log(z) + p);
}
if (x > 2.556348e305)
throw new OverflowException();
q = (x - 0.5) * System.Math.Log(x) - x + 0.91893853320467274178;
if (x > 1.0e8) return (q);
p = 1.0 / (x * x);
if (x >= 1000.0)
{
q += ((7.9365079365079365079365e-4 * p
- 2.7777777777777777777778e-3) * p
+ 0.0833333333333333333333) / x;
}
else
{
q += PolynomialHelper.Polevl(p, A, 4) / x;
}
return q;
}
/// <summary>
/// Digamma function.
/// </summary>
///
public static double Digamma(double x)
{
double s = 0;
double w = 0;
double y = 0;
double z = 0;
double nz = 0;
bool negative = false;
if (x <= 0.0)
{
negative = true;
double q = x;
double p = (int)System.Math.Floor(q);
if (p == q)
throw new OverflowException("Function computation resulted in arithmetic overflow.");
nz = q - p;
if (nz != 0.5)
{
if (nz > 0.5)
{
p = p + 1.0;
nz = q - p;
}
nz = System.Math.PI / System.Math.Tan(System.Math.PI * nz);
}
else
{
nz = 0.0;
}
x = 1.0 - x;
}
if (x <= 10.0 & x == System.Math.Floor(x))
{
y = 0.0;
int n = (int)System.Math.Floor(x);
for (int i = 1; i <= n - 1; i++)
{
w = i;
y = y + 1.0 / w;
}
y = y - 0.57721566490153286061;
}
else
{
s = x;
w = 0.0;
while (s < 10.0)
{
w = w + 1.0 / s;
s = s + 1.0;
}
if (s < 1.0E17)
{
z = 1.0 / (s * s);
double polv = 8.33333333333333333333E-2;
polv = polv * z - 2.10927960927960927961E-2;
polv = polv * z + 7.57575757575757575758E-3;
polv = polv * z - 4.16666666666666666667E-3;
polv = polv * z + 3.96825396825396825397E-3;
polv = polv * z - 8.33333333333333333333E-3;
polv = polv * z + 8.33333333333333333333E-2;
y = z * polv;
}
else
{
y = 0.0;
}
y = System.Math.Log(s) - 0.5 / s - y - w;
}
if (negative == true)
{
y = y - nz;
}
return y;
}
/// <summary>
/// Trigamma function.
/// </summary>
///
/// <remarks>
/// This code has been adapted from the FORTRAN77 and subsequent
/// C code by B. E. Schneider and John Burkardt. The code had been
/// made public under the GNU LGPL license.
/// </remarks>
///
public static double Trigamma(double x)
{
double a = 0.0001;
double b = 5.0;
double b2 = 0.1666666667;
double b4 = -0.03333333333;
double b6 = 0.02380952381;
double b8 = -0.03333333333;
double value;
double y;
double z;
// Check the input.
if (x <= 0.0)
{
throw new ArgumentException("The input parameter x must be positive.", "x");
}
z = x;
// Use small value approximation if X <= A.
if (x <= a)
{
value = 1.0 / x / x;
return value;
}
// Increase argument to ( X + I ) >= B.
value = 0.0;
while (z < b)
{
value = value + 1.0 / z / z;
z = z + 1.0;
}
// Apply asymptotic formula if argument is B or greater.
y = 1.0 / z / z;
value = value + 0.5 *
y + (1.0
+ y * (b2
+ y * (b4
+ y * (b6
+ y * b8)))) / z;
return value;
}
}
}
| 27.12963 | 105 | 0.353174 | [
"Apache-2.0"
] | Oceania2018/Bigtree.Algorithm | Bigtree.Algorithm/HiddenMarkovModel/MathHelpers/Gamma.cs | 7,327 | C# |
using Newtonsoft.Json;
using System;
using stellar_dotnet_sdk.responses.effects;
using stellar_dotnet_sdk.responses.operations;
using stellar_dotnet_sdk.responses.page;
namespace stellar_dotnet_sdk.responses
{
public class TransactionResponse : Response, IPagingToken
{
[JsonProperty(PropertyName = "hash")] public string Hash { get; private set; }
[JsonProperty(PropertyName = "ledger")]
public long Ledger { get; private set; }
[JsonProperty(PropertyName = "created_at")]
public string CreatedAt { get; private set; }
[JsonProperty(PropertyName = "source_account")]
[JsonConverter(typeof(KeyPairTypeAdapter))]
public KeyPair SourceAccount { get; private set; }
[JsonProperty(PropertyName = "paging_token")]
public string PagingToken { get; private set; }
[JsonProperty(PropertyName = "source_account_sequence")]
public long SourceAccountSequence { get; private set; }
[JsonProperty(PropertyName = "fee_paid")]
public long FeePaid { get; private set; }
[JsonProperty(PropertyName = "operation_count")]
public int OperationCount { get; private set; }
[JsonProperty(PropertyName = "envelope_xdr")]
public string EnvelopeXdr { get; private set; }
[JsonProperty(PropertyName = "result_xdr")]
public string ResultXdr { get; private set; }
[JsonProperty(PropertyName = "result_meta_xdr")]
public string ResultMetaXdr { get; private set; }
[JsonProperty(PropertyName = "_links")]
public TransactionResponseLinks Links { get; private set; }
[JsonProperty(PropertyName = "memo_type")]
public string MemoType { get; private set; }
[JsonProperty(PropertyName = "memo")]
public string MemoValue { get; private set; }
public Memo Memo
{
get
{
switch (MemoType)
{
case "none":
return Memo.None();
case "id":
return Memo.Id(long.Parse(MemoValue));
case "hash":
return Memo.Hash(Convert.FromBase64String(MemoValue));
case "return":
return Memo.ReturnHash(Convert.FromBase64String(MemoValue));
default:
throw new ArgumentException(nameof(MemoType));
}
}
protected internal set
{
switch (value)
{
case MemoNone _:
MemoType = "none";
MemoValue = null;
return;
case MemoId id:
MemoType = "id";
MemoValue = id.IdValue.ToString();
return;
case MemoHash h:
MemoType = "hash";
MemoValue = Convert.ToBase64String(h.MemoBytes);
return;
case MemoReturnHash r:
MemoType = "return";
MemoValue = Convert.ToBase64String(r.MemoBytes);
return;
default:
throw new ArgumentException(nameof(value));
}
}
}
public TransactionResponse()
{
// Used by deserializer
}
public TransactionResponse(string hash, long ledger, string createdAt, KeyPair sourceAccount, string pagingToken, long sourceAccountSequence, long feePaid, int operationCount, string envelopeXdr, string resultXdr, string resultMetaXdr, Memo memo, TransactionResponseLinks links)
{
Hash = hash;
Ledger = ledger;
CreatedAt = createdAt;
SourceAccount = sourceAccount;
PagingToken = pagingToken;
SourceAccountSequence = sourceAccountSequence;
FeePaid = feePaid;
OperationCount = operationCount;
EnvelopeXdr = envelopeXdr;
ResultXdr = resultXdr;
ResultMetaXdr = resultMetaXdr;
Memo = memo;
Links = links;
}
///
/// Links connected to transaction.
///
public class TransactionResponseLinks
{
[JsonProperty(PropertyName = "account")]
public Link<AccountResponse> Account { get; private set; }
[JsonProperty(PropertyName = "effects")]
public Link<Page<EffectResponse>> Effects { get; private set; }
[JsonProperty(PropertyName = "ledger")]
public Link<LedgerResponse> Ledger { get; private set; }
[JsonProperty(PropertyName = "operations")]
public Link<Page<OperationResponse>> Operations { get; private set; }
[JsonProperty(PropertyName = "precedes")]
public Link<TransactionResponse> Precedes { get; private set; }
[JsonProperty(PropertyName = "self")]
public Link<TransactionResponse> Self { get; private set; }
[JsonProperty(PropertyName = "succeeds")]
public Link<TransactionResponse> Succeeds { get; private set; }
public TransactionResponseLinks(Link<AccountResponse> account, Link<Page<EffectResponse>> effects,
Link<LedgerResponse> ledger, Link<Page<OperationResponse>> operations, Link<TransactionResponse> self,
Link<TransactionResponse> precedes, Link<TransactionResponse> succeeds)
{
Account = account;
Effects = effects;
Ledger = ledger;
Operations = operations;
Self = self;
Precedes = precedes;
Succeeds = succeeds;
}
}
}
} | 37.459119 | 286 | 0.55591 | [
"Apache-2.0"
] | alphapoint/dotnet-stellar-sdk | stellar_dotnet_sdk_4.5.2/responses/TransactionResponse.cs | 5,958 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNextGen.DataBoxEdge.Latest.Outputs
{
[OutputType]
public sealed class ContactDetailsResponse
{
/// <summary>
/// The name of the company.
/// </summary>
public readonly string CompanyName;
/// <summary>
/// The contact person name.
/// </summary>
public readonly string ContactPerson;
/// <summary>
/// The email list.
/// </summary>
public readonly ImmutableArray<string> EmailList;
/// <summary>
/// The phone number.
/// </summary>
public readonly string Phone;
[OutputConstructor]
private ContactDetailsResponse(
string companyName,
string contactPerson,
ImmutableArray<string> emailList,
string phone)
{
CompanyName = companyName;
ContactPerson = contactPerson;
EmailList = emailList;
Phone = phone;
}
}
}
| 26.18 | 81 | 0.592819 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataBoxEdge/Latest/Outputs/ContactDetailsResponse.cs | 1,309 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Storage.Models;
namespace Azure.ResourceManager.Storage
{
/// <summary>
/// A Class representing a StorageAccount along with the instance operations that can be performed on it.
/// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="StorageAccountResource" />
/// from an instance of <see cref="ArmClient" /> using the GetStorageAccountResource method.
/// Otherwise you can get one from its parent resource <see cref="ResourceGroupResource" /> using the GetStorageAccount method.
/// </summary>
public partial class StorageAccountResource : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="StorageAccountResource"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string accountName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _storageAccountClientDiagnostics;
private readonly StorageAccountsRestOperations _storageAccountRestClient;
private readonly ClientDiagnostics _privateLinkResourcesClientDiagnostics;
private readonly PrivateLinkResourcesRestOperations _privateLinkResourcesRestClient;
private readonly StorageAccountData _data;
/// <summary> Initializes a new instance of the <see cref="StorageAccountResource"/> class for mocking. </summary>
protected StorageAccountResource()
{
}
/// <summary> Initializes a new instance of the <see cref = "StorageAccountResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal StorageAccountResource(ArmClient client, StorageAccountData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="StorageAccountResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal StorageAccountResource(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_storageAccountClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Storage", ResourceType.Namespace, Diagnostics);
TryGetApiVersion(ResourceType, out string storageAccountApiVersion);
_storageAccountRestClient = new StorageAccountsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, storageAccountApiVersion);
_privateLinkResourcesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Storage", ProviderConstants.DefaultProviderNamespace, Diagnostics);
_privateLinkResourcesRestClient = new PrivateLinkResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Storage/storageAccounts";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual StorageAccountData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Gets an object representing a ManagementPolicyResource along with the instance operations that can be performed on it in the StorageAccount. </summary>
/// <returns> Returns a <see cref="ManagementPolicyResource" /> object. </returns>
public virtual ManagementPolicyResource GetManagementPolicy()
{
return new ManagementPolicyResource(Client, new ResourceIdentifier(Id.ToString() + "/managementPolicies/default"));
}
/// <summary> Gets a collection of BlobInventoryPolicyResources in the StorageAccount. </summary>
/// <returns> An object representing collection of BlobInventoryPolicyResources and their operations over a BlobInventoryPolicyResource. </returns>
public virtual BlobInventoryPolicyCollection GetBlobInventoryPolicies()
{
return GetCachedClient(Client => new BlobInventoryPolicyCollection(Client, Id));
}
/// <summary>
/// Gets the blob inventory policy associated with the specified storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/inventoryPolicies/{blobInventoryPolicyName}
/// Operation Id: BlobInventoryPolicies_Get
/// </summary>
/// <param name="blobInventoryPolicyName"> The name of the storage account blob inventory policy. It should always be 'default'. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
[ForwardsClientCalls]
public virtual async Task<Response<BlobInventoryPolicyResource>> GetBlobInventoryPolicyAsync(BlobInventoryPolicyName blobInventoryPolicyName, CancellationToken cancellationToken = default)
{
return await GetBlobInventoryPolicies().GetAsync(blobInventoryPolicyName, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the blob inventory policy associated with the specified storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/inventoryPolicies/{blobInventoryPolicyName}
/// Operation Id: BlobInventoryPolicies_Get
/// </summary>
/// <param name="blobInventoryPolicyName"> The name of the storage account blob inventory policy. It should always be 'default'. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
[ForwardsClientCalls]
public virtual Response<BlobInventoryPolicyResource> GetBlobInventoryPolicy(BlobInventoryPolicyName blobInventoryPolicyName, CancellationToken cancellationToken = default)
{
return GetBlobInventoryPolicies().Get(blobInventoryPolicyName, cancellationToken);
}
/// <summary> Gets a collection of PrivateEndpointConnectionResources in the StorageAccount. </summary>
/// <returns> An object representing collection of PrivateEndpointConnectionResources and their operations over a PrivateEndpointConnectionResource. </returns>
public virtual PrivateEndpointConnectionCollection GetPrivateEndpointConnections()
{
return GetCachedClient(Client => new PrivateEndpointConnectionCollection(Client, Id));
}
/// <summary>
/// Gets the specified private endpoint connection associated with the storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}
/// Operation Id: PrivateEndpointConnections_Get
/// </summary>
/// <param name="privateEndpointConnectionName"> The name of the private endpoint connection associated with the Azure resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> is null. </exception>
[ForwardsClientCalls]
public virtual async Task<Response<PrivateEndpointConnectionResource>> GetPrivateEndpointConnectionAsync(string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
return await GetPrivateEndpointConnections().GetAsync(privateEndpointConnectionName, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified private endpoint connection associated with the storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}
/// Operation Id: PrivateEndpointConnections_Get
/// </summary>
/// <param name="privateEndpointConnectionName"> The name of the private endpoint connection associated with the Azure resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateEndpointConnectionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateEndpointConnectionName"/> is null. </exception>
[ForwardsClientCalls]
public virtual Response<PrivateEndpointConnectionResource> GetPrivateEndpointConnection(string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
return GetPrivateEndpointConnections().Get(privateEndpointConnectionName, cancellationToken);
}
/// <summary> Gets a collection of ObjectReplicationPolicyResources in the StorageAccount. </summary>
/// <returns> An object representing collection of ObjectReplicationPolicyResources and their operations over a ObjectReplicationPolicyResource. </returns>
public virtual ObjectReplicationPolicyCollection GetObjectReplicationPolicies()
{
return GetCachedClient(Client => new ObjectReplicationPolicyCollection(Client, Id));
}
/// <summary>
/// Get the object replication policy of the storage account by policy ID.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/objectReplicationPolicies/{objectReplicationPolicyId}
/// Operation Id: ObjectReplicationPolicies_Get
/// </summary>
/// <param name="objectReplicationPolicyId"> For the destination account, provide the value 'default'. Configure the policy on the destination account first. For the source account, provide the value of the policy ID that is returned when you download the policy that was defined on the destination account. The policy is downloaded as a JSON file. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="objectReplicationPolicyId"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="objectReplicationPolicyId"/> is null. </exception>
[ForwardsClientCalls]
public virtual async Task<Response<ObjectReplicationPolicyResource>> GetObjectReplicationPolicyAsync(string objectReplicationPolicyId, CancellationToken cancellationToken = default)
{
return await GetObjectReplicationPolicies().GetAsync(objectReplicationPolicyId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get the object replication policy of the storage account by policy ID.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/objectReplicationPolicies/{objectReplicationPolicyId}
/// Operation Id: ObjectReplicationPolicies_Get
/// </summary>
/// <param name="objectReplicationPolicyId"> For the destination account, provide the value 'default'. Configure the policy on the destination account first. For the source account, provide the value of the policy ID that is returned when you download the policy that was defined on the destination account. The policy is downloaded as a JSON file. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="objectReplicationPolicyId"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="objectReplicationPolicyId"/> is null. </exception>
[ForwardsClientCalls]
public virtual Response<ObjectReplicationPolicyResource> GetObjectReplicationPolicy(string objectReplicationPolicyId, CancellationToken cancellationToken = default)
{
return GetObjectReplicationPolicies().Get(objectReplicationPolicyId, cancellationToken);
}
/// <summary> Gets a collection of LocalUserResources in the StorageAccount. </summary>
/// <returns> An object representing collection of LocalUserResources and their operations over a LocalUserResource. </returns>
public virtual LocalUserCollection GetLocalUsers()
{
return GetCachedClient(Client => new LocalUserCollection(Client, Id));
}
/// <summary>
/// Get the local user of the storage account by username.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/localUsers/{username}
/// Operation Id: LocalUsers_Get
/// </summary>
/// <param name="username"> The name of local user. The username must contain lowercase letters and numbers only. It must be unique only within the storage account. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="username"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="username"/> is null. </exception>
[ForwardsClientCalls]
public virtual async Task<Response<LocalUserResource>> GetLocalUserAsync(string username, CancellationToken cancellationToken = default)
{
return await GetLocalUsers().GetAsync(username, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get the local user of the storage account by username.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/localUsers/{username}
/// Operation Id: LocalUsers_Get
/// </summary>
/// <param name="username"> The name of local user. The username must contain lowercase letters and numbers only. It must be unique only within the storage account. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="username"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="username"/> is null. </exception>
[ForwardsClientCalls]
public virtual Response<LocalUserResource> GetLocalUser(string username, CancellationToken cancellationToken = default)
{
return GetLocalUsers().Get(username, cancellationToken);
}
/// <summary> Gets a collection of EncryptionScopeResources in the StorageAccount. </summary>
/// <returns> An object representing collection of EncryptionScopeResources and their operations over a EncryptionScopeResource. </returns>
public virtual EncryptionScopeCollection GetEncryptionScopes()
{
return GetCachedClient(Client => new EncryptionScopeCollection(Client, Id));
}
/// <summary>
/// Returns the properties for the specified encryption scope.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes/{encryptionScopeName}
/// Operation Id: EncryptionScopes_Get
/// </summary>
/// <param name="encryptionScopeName"> The name of the encryption scope within the specified storage account. Encryption scope names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="encryptionScopeName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="encryptionScopeName"/> is null. </exception>
[ForwardsClientCalls]
public virtual async Task<Response<EncryptionScopeResource>> GetEncryptionScopeAsync(string encryptionScopeName, CancellationToken cancellationToken = default)
{
return await GetEncryptionScopes().GetAsync(encryptionScopeName, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns the properties for the specified encryption scope.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes/{encryptionScopeName}
/// Operation Id: EncryptionScopes_Get
/// </summary>
/// <param name="encryptionScopeName"> The name of the encryption scope within the specified storage account. Encryption scope names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="encryptionScopeName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="encryptionScopeName"/> is null. </exception>
[ForwardsClientCalls]
public virtual Response<EncryptionScopeResource> GetEncryptionScope(string encryptionScopeName, CancellationToken cancellationToken = default)
{
return GetEncryptionScopes().Get(encryptionScopeName, cancellationToken);
}
/// <summary> Gets an object representing a BlobServiceResource along with the instance operations that can be performed on it in the StorageAccount. </summary>
/// <returns> Returns a <see cref="BlobServiceResource" /> object. </returns>
public virtual BlobServiceResource GetBlobService()
{
return new BlobServiceResource(Client, new ResourceIdentifier(Id.ToString() + "/blobServices/default"));
}
/// <summary> Gets an object representing a FileServiceResource along with the instance operations that can be performed on it in the StorageAccount. </summary>
/// <returns> Returns a <see cref="FileServiceResource" /> object. </returns>
public virtual FileServiceResource GetFileService()
{
return new FileServiceResource(Client, new ResourceIdentifier(Id.ToString() + "/fileServices/default"));
}
/// <summary> Gets an object representing a QueueServiceResource along with the instance operations that can be performed on it in the StorageAccount. </summary>
/// <returns> Returns a <see cref="QueueServiceResource" /> object. </returns>
public virtual QueueServiceResource GetQueueService()
{
return new QueueServiceResource(Client, new ResourceIdentifier(Id.ToString() + "/queueServices/default"));
}
/// <summary> Gets an object representing a TableServiceResource along with the instance operations that can be performed on it in the StorageAccount. </summary>
/// <returns> Returns a <see cref="TableServiceResource" /> object. </returns>
public virtual TableServiceResource GetTableService()
{
return new TableServiceResource(Client, new ResourceIdentifier(Id.ToString() + "/tableServices/default"));
}
/// <summary>
/// Returns the properties for the specified storage account including but not limited to name, SKU name, location, and account status. The ListKeys operation should be used to retrieve storage keys.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_GetProperties
/// </summary>
/// <param name="expand"> May be used to expand the properties within account's properties. By default, data is not included when fetching properties. Currently we only support geoReplicationStats and blobRestoreStatus. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<StorageAccountResource>> GetAsync(StorageAccountExpand? expand = null, CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.Get");
scope.Start();
try
{
var response = await _storageAccountRestClient.GetPropertiesAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, expand, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new StorageAccountResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Returns the properties for the specified storage account including but not limited to name, SKU name, location, and account status. The ListKeys operation should be used to retrieve storage keys.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_GetProperties
/// </summary>
/// <param name="expand"> May be used to expand the properties within account's properties. By default, data is not included when fetching properties. Currently we only support geoReplicationStats and blobRestoreStatus. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<StorageAccountResource> Get(StorageAccountExpand? expand = null, CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.Get");
scope.Start();
try
{
var response = _storageAccountRestClient.GetProperties(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, expand, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new StorageAccountResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_Delete
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.Delete");
scope.Start();
try
{
var response = await _storageAccountRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new StorageArmOperation(response);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_Delete
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.Delete");
scope.Start();
try
{
var response = _storageAccountRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
var operation = new StorageArmOperation(response);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// The update operation can be used to update the SKU, encryption, access tier, or tags for a storage account. It can also be used to map the account to a custom domain. Only one custom domain is supported per storage account; the replacement/change of custom domain is not supported. In order to replace an old custom domain, the old value must be cleared/unregistered before a new value can be set. The update of multiple properties is supported. This call does not change the storage keys for the account. If you want to change the storage account keys, use the regenerate keys operation. The location and name of the storage account cannot be changed after creation.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_Update
/// </summary>
/// <param name="patch"> The parameters to provide for the updated account. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception>
public virtual async Task<Response<StorageAccountResource>> UpdateAsync(StorageAccountPatch patch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(patch, nameof(patch));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.Update");
scope.Start();
try
{
var response = await _storageAccountRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new StorageAccountResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// The update operation can be used to update the SKU, encryption, access tier, or tags for a storage account. It can also be used to map the account to a custom domain. Only one custom domain is supported per storage account; the replacement/change of custom domain is not supported. In order to replace an old custom domain, the old value must be cleared/unregistered before a new value can be set. The update of multiple properties is supported. This call does not change the storage keys for the account. If you want to change the storage account keys, use the regenerate keys operation. The location and name of the storage account cannot be changed after creation.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_Update
/// </summary>
/// <param name="patch"> The parameters to provide for the updated account. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception>
public virtual Response<StorageAccountResource> Update(StorageAccountPatch patch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(patch, nameof(patch));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.Update");
scope.Start();
try
{
var response = _storageAccountRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken);
return Response.FromValue(new StorageAccountResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Lists the access keys or Kerberos keys (if active directory enabled) for the specified storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/listKeys
/// Operation Id: StorageAccounts_ListKeys
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<StorageAccountListKeysResult>> GetKeysAsync(CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.GetKeys");
scope.Start();
try
{
var response = await _storageAccountRestClient.ListKeysAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Lists the access keys or Kerberos keys (if active directory enabled) for the specified storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/listKeys
/// Operation Id: StorageAccounts_ListKeys
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<StorageAccountListKeysResult> GetKeys(CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.GetKeys");
scope.Start();
try
{
var response = _storageAccountRestClient.ListKeys(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Regenerates one of the access keys or Kerberos keys for the specified storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/regenerateKey
/// Operation Id: StorageAccounts_RegenerateKey
/// </summary>
/// <param name="content"> Specifies name of the key which should be regenerated -- key1, key2, kerb1, kerb2. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
public virtual async Task<Response<StorageAccountListKeysResult>> RegenerateKeyAsync(StorageAccountRegenerateKeyContent content, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(content, nameof(content));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.RegenerateKey");
scope.Start();
try
{
var response = await _storageAccountRestClient.RegenerateKeyAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content, cancellationToken).ConfigureAwait(false);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Regenerates one of the access keys or Kerberos keys for the specified storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/regenerateKey
/// Operation Id: StorageAccounts_RegenerateKey
/// </summary>
/// <param name="content"> Specifies name of the key which should be regenerated -- key1, key2, kerb1, kerb2. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
public virtual Response<StorageAccountListKeysResult> RegenerateKey(StorageAccountRegenerateKeyContent content, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(content, nameof(content));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.RegenerateKey");
scope.Start();
try
{
var response = _storageAccountRestClient.RegenerateKey(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content, cancellationToken);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// List SAS credentials of a storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListAccountSas
/// Operation Id: StorageAccounts_ListAccountSas
/// </summary>
/// <param name="content"> The parameters to provide to list SAS credentials for the storage account. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
public virtual async Task<Response<ListAccountSasResponse>> GetAccountSasAsync(AccountSasContent content, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(content, nameof(content));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.GetAccountSas");
scope.Start();
try
{
var response = await _storageAccountRestClient.ListAccountSasAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content, cancellationToken).ConfigureAwait(false);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// List SAS credentials of a storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListAccountSas
/// Operation Id: StorageAccounts_ListAccountSas
/// </summary>
/// <param name="content"> The parameters to provide to list SAS credentials for the storage account. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
public virtual Response<ListAccountSasResponse> GetAccountSas(AccountSasContent content, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(content, nameof(content));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.GetAccountSas");
scope.Start();
try
{
var response = _storageAccountRestClient.ListAccountSas(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content, cancellationToken);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// List service SAS credentials of a specific resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListServiceSas
/// Operation Id: StorageAccounts_ListServiceSas
/// </summary>
/// <param name="content"> The parameters to provide to list service SAS credentials. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
public virtual async Task<Response<ListServiceSasResponse>> GetServiceSasAsync(ServiceSasContent content, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(content, nameof(content));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.GetServiceSas");
scope.Start();
try
{
var response = await _storageAccountRestClient.ListServiceSasAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content, cancellationToken).ConfigureAwait(false);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// List service SAS credentials of a specific resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListServiceSas
/// Operation Id: StorageAccounts_ListServiceSas
/// </summary>
/// <param name="content"> The parameters to provide to list service SAS credentials. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
public virtual Response<ListServiceSasResponse> GetServiceSas(ServiceSasContent content, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(content, nameof(content));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.GetServiceSas");
scope.Start();
try
{
var response = _storageAccountRestClient.ListServiceSas(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content, cancellationToken);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Failover request can be triggered for a storage account in case of availability issues. The failover occurs from the storage account's primary cluster to secondary cluster for RA-GRS accounts. The secondary cluster will become primary after failover.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/failover
/// Operation Id: StorageAccounts_Failover
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<ArmOperation> FailoverAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.Failover");
scope.Start();
try
{
var response = await _storageAccountRestClient.FailoverAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new StorageArmOperation(_storageAccountClientDiagnostics, Pipeline, _storageAccountRestClient.CreateFailoverRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Failover request can be triggered for a storage account in case of availability issues. The failover occurs from the storage account's primary cluster to secondary cluster for RA-GRS accounts. The secondary cluster will become primary after failover.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/failover
/// Operation Id: StorageAccounts_Failover
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation Failover(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.Failover");
scope.Start();
try
{
var response = _storageAccountRestClient.Failover(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
var operation = new StorageArmOperation(_storageAccountClientDiagnostics, Pipeline, _storageAccountRestClient.CreateFailoverRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Live Migration of storage account to enable Hns
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/hnsonmigration
/// Operation Id: StorageAccounts_HierarchicalNamespaceMigration
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="requestType"> Required. Hierarchical namespace migration type can either be a hierarchical namespace validation request 'HnsOnValidationRequest' or a hydration request 'HnsOnHydrationRequest'. The validation request will validate the migration whereas the hydration request will migrate the account. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="requestType"/> is null. </exception>
public virtual async Task<ArmOperation> HierarchicalNamespaceMigrationAsync(WaitUntil waitUntil, string requestType, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(requestType, nameof(requestType));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.HierarchicalNamespaceMigration");
scope.Start();
try
{
var response = await _storageAccountRestClient.HierarchicalNamespaceMigrationAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, requestType, cancellationToken).ConfigureAwait(false);
var operation = new StorageArmOperation(_storageAccountClientDiagnostics, Pipeline, _storageAccountRestClient.CreateHierarchicalNamespaceMigrationRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, requestType).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Live Migration of storage account to enable Hns
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/hnsonmigration
/// Operation Id: StorageAccounts_HierarchicalNamespaceMigration
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="requestType"> Required. Hierarchical namespace migration type can either be a hierarchical namespace validation request 'HnsOnValidationRequest' or a hydration request 'HnsOnHydrationRequest'. The validation request will validate the migration whereas the hydration request will migrate the account. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="requestType"/> is null. </exception>
public virtual ArmOperation HierarchicalNamespaceMigration(WaitUntil waitUntil, string requestType, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(requestType, nameof(requestType));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.HierarchicalNamespaceMigration");
scope.Start();
try
{
var response = _storageAccountRestClient.HierarchicalNamespaceMigration(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, requestType, cancellationToken);
var operation = new StorageArmOperation(_storageAccountClientDiagnostics, Pipeline, _storageAccountRestClient.CreateHierarchicalNamespaceMigrationRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, requestType).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Abort live Migration of storage account to enable Hns
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/aborthnsonmigration
/// Operation Id: StorageAccounts_AbortHierarchicalNamespaceMigration
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<ArmOperation> AbortHierarchicalNamespaceMigrationAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.AbortHierarchicalNamespaceMigration");
scope.Start();
try
{
var response = await _storageAccountRestClient.AbortHierarchicalNamespaceMigrationAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new StorageArmOperation(_storageAccountClientDiagnostics, Pipeline, _storageAccountRestClient.CreateAbortHierarchicalNamespaceMigrationRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Abort live Migration of storage account to enable Hns
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/aborthnsonmigration
/// Operation Id: StorageAccounts_AbortHierarchicalNamespaceMigration
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation AbortHierarchicalNamespaceMigration(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.AbortHierarchicalNamespaceMigration");
scope.Start();
try
{
var response = _storageAccountRestClient.AbortHierarchicalNamespaceMigration(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
var operation = new StorageArmOperation(_storageAccountClientDiagnostics, Pipeline, _storageAccountRestClient.CreateAbortHierarchicalNamespaceMigrationRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Restore blobs in the specified blob ranges
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/restoreBlobRanges
/// Operation Id: StorageAccounts_RestoreBlobRanges
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="content"> The parameters to provide for restore blob ranges. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
public virtual async Task<ArmOperation<BlobRestoreStatus>> RestoreBlobRangesAsync(WaitUntil waitUntil, BlobRestoreContent content, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(content, nameof(content));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.RestoreBlobRanges");
scope.Start();
try
{
var response = await _storageAccountRestClient.RestoreBlobRangesAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content, cancellationToken).ConfigureAwait(false);
var operation = new StorageArmOperation<BlobRestoreStatus>(new BlobRestoreStatusOperationSource(), _storageAccountClientDiagnostics, Pipeline, _storageAccountRestClient.CreateRestoreBlobRangesRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Restore blobs in the specified blob ranges
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/restoreBlobRanges
/// Operation Id: StorageAccounts_RestoreBlobRanges
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="content"> The parameters to provide for restore blob ranges. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception>
public virtual ArmOperation<BlobRestoreStatus> RestoreBlobRanges(WaitUntil waitUntil, BlobRestoreContent content, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(content, nameof(content));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.RestoreBlobRanges");
scope.Start();
try
{
var response = _storageAccountRestClient.RestoreBlobRanges(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content, cancellationToken);
var operation = new StorageArmOperation<BlobRestoreStatus>(new BlobRestoreStatusOperationSource(), _storageAccountClientDiagnostics, Pipeline, _storageAccountRestClient.CreateRestoreBlobRangesRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, content).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Revoke user delegation keys.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/revokeUserDelegationKeys
/// Operation Id: StorageAccounts_RevokeUserDelegationKeys
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response> RevokeUserDelegationKeysAsync(CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.RevokeUserDelegationKeys");
scope.Start();
try
{
var response = await _storageAccountRestClient.RevokeUserDelegationKeysAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Revoke user delegation keys.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/revokeUserDelegationKeys
/// Operation Id: StorageAccounts_RevokeUserDelegationKeys
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response RevokeUserDelegationKeys(CancellationToken cancellationToken = default)
{
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.RevokeUserDelegationKeys");
scope.Start();
try
{
var response = _storageAccountRestClient.RevokeUserDelegationKeys(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets the private link resources that need to be created for a storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/privateLinkResources
/// Operation Id: PrivateLinkResources_ListByStorageAccount
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="PrivateLinkResource" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<PrivateLinkResource> GetPrivateLinkResourcesAsync(CancellationToken cancellationToken = default)
{
async Task<Page<PrivateLinkResource>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _privateLinkResourcesClientDiagnostics.CreateScope("StorageAccountResource.GetPrivateLinkResources");
scope.Start();
try
{
var response = await _privateLinkResourcesRestClient.ListByStorageAccountAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
}
/// <summary>
/// Gets the private link resources that need to be created for a storage account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/privateLinkResources
/// Operation Id: PrivateLinkResources_ListByStorageAccount
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="PrivateLinkResource" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<PrivateLinkResource> GetPrivateLinkResources(CancellationToken cancellationToken = default)
{
Page<PrivateLinkResource> FirstPageFunc(int? pageSizeHint)
{
using var scope = _privateLinkResourcesClientDiagnostics.CreateScope("StorageAccountResource.GetPrivateLinkResources");
scope.Start();
try
{
var response = _privateLinkResourcesRestClient.ListByStorageAccount(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
}
/// <summary>
/// Add a tag to the current resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_GetProperties
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="value"> The value for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
public virtual async Task<Response<StorageAccountResource>> AddTagAsync(string key, string value, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
Argument.AssertNotNull(value, nameof(value));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.AddTag");
scope.Start();
try
{
var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.TagValues[key] = value;
await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _storageAccountRestClient.GetPropertiesAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, null, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new StorageAccountResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Add a tag to the current resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_GetProperties
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="value"> The value for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
public virtual Response<StorageAccountResource> AddTag(string key, string value, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
Argument.AssertNotNull(value, nameof(value));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.AddTag");
scope.Start();
try
{
var originalTags = GetTagResource().Get(cancellationToken);
originalTags.Value.Data.TagValues[key] = value;
GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _storageAccountRestClient.GetProperties(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, null, cancellationToken);
return Response.FromValue(new StorageAccountResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Replace the tags on the resource with the given set.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_GetProperties
/// </summary>
/// <param name="tags"> The set of tags to use as replacement. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
public virtual async Task<Response<StorageAccountResource>> SetTagsAsync(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tags, nameof(tags));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.SetTags");
scope.Start();
try
{
await GetTagResource().DeleteAsync(WaitUntil.Completed, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.TagValues.ReplaceWith(tags);
await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _storageAccountRestClient.GetPropertiesAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, null, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new StorageAccountResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Replace the tags on the resource with the given set.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_GetProperties
/// </summary>
/// <param name="tags"> The set of tags to use as replacement. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
public virtual Response<StorageAccountResource> SetTags(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tags, nameof(tags));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.SetTags");
scope.Start();
try
{
GetTagResource().Delete(WaitUntil.Completed, cancellationToken: cancellationToken);
var originalTags = GetTagResource().Get(cancellationToken);
originalTags.Value.Data.TagValues.ReplaceWith(tags);
GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _storageAccountRestClient.GetProperties(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, null, cancellationToken);
return Response.FromValue(new StorageAccountResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Removes a tag by key from the resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_GetProperties
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
public virtual async Task<Response<StorageAccountResource>> RemoveTagAsync(string key, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.RemoveTag");
scope.Start();
try
{
var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.TagValues.Remove(key);
await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _storageAccountRestClient.GetPropertiesAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, null, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new StorageAccountResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Removes a tag by key from the resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}
/// Operation Id: StorageAccounts_GetProperties
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
public virtual Response<StorageAccountResource> RemoveTag(string key, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
using var scope = _storageAccountClientDiagnostics.CreateScope("StorageAccountResource.RemoveTag");
scope.Start();
try
{
var originalTags = GetTagResource().Get(cancellationToken);
originalTags.Value.Data.TagValues.Remove(key);
GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _storageAccountRestClient.GetProperties(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, null, cancellationToken);
return Response.FromValue(new StorageAccountResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 66.19846 | 679 | 0.685512 | [
"MIT"
] | amar-sagare/azure-sdk-for-net | sdk/storage/Azure.ResourceManager.Storage/src/Generated/StorageAccountResource.cs | 77,386 | C# |
// -----------------------------------------------------------------------
// <copyright file="CSharpCodeGenerator.cs" company="sped.mobi">
// Copyright (c) 2019 Brad Marshall. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace System.CodeDom.CSharp
{
public class CSharpGenerator : CodeGeneratorBase
{
protected bool GeneratingForLoop { get; set; }
private void OpenBlock()
{
Output.WriteLine("{");
Indent++;
}
private void CloseBlock()
{
Indent--;
Output.WriteLine("}");
}
protected override void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e)
{
OutputIdentifier(e.ParameterName);
}
protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression e)
{
Output.Write("new ");
CodeExpressionCollection init = e.Initializers;
if (init.Count > 0)
{
OutputType(e.CreateType);
if (e.CreateType.ArrayRank == 0)
{
Output.Write("[]");
}
Output.WriteLine(" {");
Indent++;
OutputExpressionList(init, true);
Indent--;
Output.Write("}");
}
else
{
Output.Write(GetBaseTypeOutput(e.CreateType));
Output.Write("[");
if (e.SizeExpression != null)
{
GenerateExpression(e.SizeExpression);
}
else
{
Output.Write(e.Size);
}
Output.Write("]");
}
}
protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e)
{
GenerateExpression(e.TargetObject);
Output.Write("[");
bool first = true;
foreach (CodeExpression exp in e.Indices)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
GenerateExpression(exp);
}
Output.Write("]");
}
protected override void GenerateAssignStatement(CodeAssignStatement e)
{
GenerateExpression(e.Left);
Output.Write(" = ");
GenerateExpression(e.Right);
if (!GeneratingForLoop)
{
Output.WriteLine(";");
}
}
protected override void GenerateAttachEventStatement(CodeAttachEventStatement e)
{
GenerateEventReferenceExpression(e.Event);
Output.Write(" += ");
GenerateExpression(e.Listener);
Output.WriteLine(";");
}
protected override void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes)
{
Output.Write("]");
}
protected override void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes)
{
Output.Write("[");
}
protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e)
{
Output.Write("base");
}
protected override void GenerateCastExpression(CodeCastExpression e)
{
Output.Write("((");
OutputType(e.TargetType);
Output.Write(")(");
GenerateExpression(e.Expression);
Output.Write("))");
}
protected override void GenerateCompileUnitEnd(CodeCompileUnit e)
{
if (e.EndDirectives.Count > 0)
{
GenerateDirectives(e.EndDirectives);
}
}
protected override void GenerateCompileUnitStart(CodeCompileUnit e)
{
if (e.StartDirectives.Count > 0)
{
GenerateDirectives(e.StartDirectives);
}
WriteAutoGeneratedHeader();
if (MoveUsingsOutsideNamespace)
{
var importList = GetImportList(e);
foreach (string import in importList.Keys)
{
Output.Write("using ");
OutputIdentifier(import);
Output.WriteLine(";");
}
if (importList.Keys.Count > 0)
{
Output.WriteLine("");
}
}
if (e.AssemblyCustomAttributes.Count > 0)
{
GenerateAttributes(e.AssemblyCustomAttributes, "assembly: ");
Output.WriteLine("");
}
}
private void WriteAutoGeneratedHeader()
{
Output.WriteLine("//------------------------------------------------------------------------------");
Output.Write("// <");
Output.WriteLine(SR.AutoGen_Comment_Line1);
Output.Write("// ");
Output.WriteLine(SR.AutoGen_Comment_Line2);
Output.Write("// ");
Output.Write(SR.AutoGen_Comment_Line3);
Output.WriteLine(Environment.Version.ToString());
Output.WriteLine("//");
Output.Write("// ");
Output.WriteLine(SR.AutoGen_Comment_Line4);
Output.Write("// ");
Output.WriteLine(SR.AutoGen_Comment_Line5);
Output.Write("// </");
Output.WriteLine(SR.AutoGen_Comment_Line1);
Output.WriteLine("//------------------------------------------------------------------------------");
Output.WriteLine("");
}
protected override void GenerateCodeSwitchStatement(CodeSwitchStatement e)
{
Output.Write("switch(");
GenerateExpression(e.CheckExpression);
Output.WriteLine(")");
OpenBlock();
GenerateSwitchSections(e.Sections);
CloseBlock();
Output.WriteLine("}");
}
protected override void GenerateDefaultBreakSwitchSectionStatement(CodeDefaultBreakSwitchSectionStatement e)
{
Output.WriteLine("default:");
OpenBlock();
if (e.BodyStatements.Count > 0)
{
GenerateStatements(e.BodyStatements);
}
Output.WriteLine("break;");
CloseBlock();
}
protected override void GenerateDefaultReturnSwitchSectionStatement(CodeDefaultReturnSwitchSectionStatement e)
{
Output.WriteLine("default:");
OpenBlock();
if (e.BodyStatements.Count > 0)
{
GenerateStatements(e.BodyStatements);
}
GenerateMethodReturnStatement(e.ReturnStatement);
CloseBlock();
}
protected override void GenerateFallThroughSwitchSectionStatement(CodeFallThroughSwitchSectionStatement e)
{
GenerateSwitchSectionLabelExpression(e.Label);
Output.WriteLine();
}
protected override void GenerateReturnValueSwitchSectionStatement(CodeReturnValueSwitchSectionStatement e)
{
GenerateSwitchSectionLabelExpression(e.Label);
if (e.SingleLine)
{
GenerateMethodReturnStatement(e.ReturnStatement);
}
else
{
Output.WriteLine();
Output.WriteLine("{");
Indent++;
if (e.BodyStatements.Count > 0)
{
GenerateStatements(e.BodyStatements);
}
GenerateMethodReturnStatement(e.ReturnStatement);
Indent--;
Output.WriteLine("}");
}
}
protected override void GenerateSwitchSectionLabelExpression(CodeSwitchSectionLabelExpression e)
{
Output.Write("case ");
GenerateExpression(e.Expression);
Output.Write(": ");
}
protected override void GenerateBreakSwitchSectionStatement(CodeBreakSwitchSectionStatement e)
{
GenerateSwitchSectionLabelExpression(e.Label);
Output.WriteLine();
OpenBlock();
if (e.BodyStatements.Count > 0)
{
GenerateStatements(e.BodyStatements);
}
Output.WriteLine("break;");
CloseBlock();
}
protected override void GenerateConditionStatement(CodeConditionStatement e)
{
Output.Write("if (");
GenerateExpression(e.Condition);
Output.Write(")");
Output.WriteLine();
OpenBlock();
GenerateStatements(e.TrueStatements);
Indent--;
CodeStatementCollection falseStatemetns = e.FalseStatements;
if (falseStatemetns.Count > 0)
{
Output.Write("}");
if (Options.ElseOnClosing)
{
Output.Write(" ");
}
else
{
Output.WriteLine("");
}
Output.Write("else");
Output.WriteLine();
OpenBlock();
GenerateStatements(e.FalseStatements);
Indent--;
}
Output.WriteLine("}");
}
protected override void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c)
{
if (e.Comments.Count == 0)
{
Output.WriteLine();
}
GenerateAttributes(e.CustomAttributes);
OutputAccessibilityAndModifiers(e.Attributes);
Output.Write(e.Name);
Output.Write("(");
OutputParameters(e.Parameters);
Output.Write(')');
CodeExpressionCollection baseArgs = e.BaseConstructorArgs;
CodeExpressionCollection thisArgs = e.ChainedConstructorArgs;
if (baseArgs.Count > 0)
{
Indent++;
Output.Write(" : base(");
GenerateExpressionList(baseArgs, false);
Output.WriteLine(")");
Indent--;
}
if (thisArgs.Count > 0)
{
Indent++;
Output.Write(" : this(");
GenerateExpressionList(thisArgs, false);
Output.WriteLine(")");
Indent--;
}
if (thisArgs.Count == 0 && baseArgs.Count == 0)
{
Output.WriteLine();
}
OpenBlock();
GenerateStatements(e.Statements);
CloseBlock();
}
protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e)
{
Output.Write("new ");
OutputType(e.DelegateType);
Output.Write("(");
GenerateExpression(e.TargetObject);
Output.Write(".");
OutputIdentifier(e.MethodName);
Output.Write(")");
}
protected override void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
}
Output.Write("(");
OutputExpressionList(e.Parameters);
Output.Write(")");
}
protected override void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c)
{
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
Output.Write("public static ");
OutputType(e.ReturnType);
Output.Write(" Main()");
OpenBlock();
GenerateStatements(e.Statements);
Indent--;
Output.WriteLine("}");
}
protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c)
{
if (IsCurrentDelegate || IsCurrentEnum)
{
return;
}
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
if (e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
}
Output.Write("event ");
string name = e.Name;
if (e.PrivateImplementationType != null)
{
name = GetBaseTypeOutput(e.PrivateImplementationType) + "." + name;
}
OutputTypeNamePair(e.Type, name);
Output.WriteLine(";");
}
protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write(".");
}
OutputIdentifier(e.EventName);
}
protected override void GenerateExpressionStatement(CodeExpressionStatement e)
{
GenerateExpression(e.Expression);
if (!GeneratingForLoop)
{
Output.WriteLine(";");
}
}
protected override void GenerateField(CodeMemberField e)
{
if (IsCurrentDelegate || IsCurrentInterface)
{
return;
}
if (IsCurrentEnum)
{
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
OutputIdentifier(e.Name);
if (e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
Output.WriteLine(",");
}
else
{
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
OutputMemberAccessModifier(e.Attributes);
OutputVTableModifier(e.Attributes);
OutputFieldScopeModifier(e.Attributes);
OutputTypeNamePair(e.Type, e.Name);
if (e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
Output.WriteLine(";");
}
}
protected override void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write(".");
}
OutputIdentifier(e.FieldName);
}
protected override void GenerateGotoStatement(CodeGotoStatement e)
{
Output.Write("goto ");
Output.Write(e.Label);
Output.WriteLine(";");
}
protected override void GenerateIndexerExpression(CodeIndexerExpression e)
{
GenerateExpression(e.TargetObject);
Output.Write("[");
bool first = true;
foreach (CodeExpression exp in e.Indices)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
GenerateExpression(exp);
}
Output.Write("]");
}
protected override void GenerateIterationStatement(CodeIterationStatement e)
{
GeneratingForLoop = true;
Output.Write("for (");
GenerateStatement(e.InitStatement);
Output.Write("; ");
GenerateExpression(e.TestExpression);
Output.Write("; ");
GenerateStatement(e.IncrementStatement);
Output.Write(")");
Output.WriteLine("{");
GeneratingForLoop = false;
Indent++;
GenerateStatements(e.Statements);
CloseBlock();
}
protected override void GenerateLabeledStatement(CodeLabeledStatement e)
{
Indent--;
Output.Write(e.Label);
Output.WriteLine(":");
Indent++;
if (e.Statement != null)
{
GenerateStatement(e.Statement);
}
}
protected override void GenerateLinePragmaEnd(CodeLinePragma e)
{
Output.WriteLine();
Output.WriteLine("#line default");
Output.WriteLine("#line hidden");
}
protected override void GenerateLinePragmaStart(CodeLinePragma e)
{
Output.WriteLine("");
Output.Write("#line ");
Output.Write(e.LineNumber);
Output.Write(" \"");
Output.Write(e.FileName);
Output.Write("\"");
Output.WriteLine("");
}
protected override void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c)
{
if (!(IsCurrentClass || IsCurrentStruct || IsCurrentInterface))
{
return;
}
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
if (e.ReturnTypeCustomAttributes.Count > 0)
{
GenerateAttributes(e.ReturnTypeCustomAttributes, "return: ");
}
if (!IsCurrentInterface)
{
if (e.PrivateImplementationType == null)
{
OutputMemberAccessModifier(e.Attributes);
OutputVTableModifier(e.Attributes);
OutputMemberScopeModifier(e.Attributes);
}
}
else
{
OutputVTableModifier(e.Attributes);
}
OutputType(e.ReturnType);
Output.Write(" ");
if (e.PrivateImplementationType != null)
{
Output.Write(GetBaseTypeOutput(e.PrivateImplementationType));
Output.Write(".");
}
OutputIdentifier(e.Name);
OutputTypeParameters(e.TypeParameters);
Output.Write("(");
OutputParameters(e.Parameters);
Output.Write(")");
OutputTypeParameterConstraints(e.TypeParameters);
if (!IsCurrentInterface && (e.Attributes & MemberAttributes.ScopeMask) != MemberAttributes.Abstract)
{
Output.WriteLine();
OpenBlock();
GenerateStatements(e.Statements);
CloseBlock();
}
else
{
Output.WriteLine(";");
}
}
protected override void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e)
{
GenerateMethodReferenceExpression(e.Method);
Output.Write("(");
OutputExpressionList(e.Parameters);
Output.Write(")");
}
protected override void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e)
{
if (e.TargetObject != null)
{
if (e.TargetObject is CodeBinaryOperatorExpression)
{
Output.Write("(");
GenerateExpression(e.TargetObject);
Output.Write(")");
}
else
{
GenerateExpression(e.TargetObject);
}
Output.Write(".");
}
OutputIdentifier(e.MethodName);
if (e.TypeArguments.Count > 0)
{
Output.Write(GetTypeArgumentsOutput(e.TypeArguments));
}
}
protected override void GenerateMethodReturnStatement(CodeMethodReturnStatement e)
{
Output.Write("return");
if (e.Expression != null)
{
Output.Write(" ");
GenerateExpression(e.Expression);
}
Output.WriteLine(";");
}
protected override void GenerateNamespace(CodeNamespace e)
{
GenerateCommentStatements(e.Comments);
GenerateNamespaceStart(e);
if (!MoveUsingsOutsideNamespace)
{
GenerateNamespaceImports(e);
}
Output.WriteLine();
GenerateTypes(e);
GenerateNamespaceEnd(e);
}
protected override void GenerateNamespaceEnd(CodeNamespace e)
{
if (!string.IsNullOrEmpty(e.Name))
{
CloseBlock();
}
}
protected override void GenerateNamespaceImport(CodeNamespaceImport e)
{
Output.Write("using ");
OutputIdentifier(e.Namespace);
Output.WriteLine(";");
}
protected override void GenerateNamespaceStart(CodeNamespace e)
{
if (!string.IsNullOrEmpty(e.Name))
{
Output.Write("namespace ");
string[] names = e.Name.Split('.');
Debug.Assert(names.Length > 0);
OutputIdentifier(names[0]);
for (int i = 1; i < names.Length; i++)
{
Output.Write(".");
OutputIdentifier(names[i]);
}
Output.WriteLine();
OpenBlock();
}
}
protected override void GenerateObjectCreateExpression(CodeObjectCreateExpression e)
{
Output.Write("new ");
OutputType(e.CreateType);
Output.Write("(");
OutputExpressionList(e.Parameters);
Output.Write(")");
}
protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c)
{
if (Options.BlankLinesBetweenMembers)
{
Output.WriteLine();
}
GenerateAttributes(e.CustomAttributes);
if (!IsCurrentInterface)
{
OutputAccessibilityAndModifiers(e.Attributes);
}
OutputType(e.Type);
Output.Write(" ");
Output.Write(e.Name);
if (e.GetStatements.Count == 0)
{
if (e.HasGet && !e.HasSet)
{
Output.WriteLine(" { get; }");
}
else
{
if (e.GetStatements.Count == 0 && e.SetStatements.Count == 0)
{
Output.WriteLine(" { get; set; }");
}
}
}
else
{
Output.WriteLine();
OpenBlock();
Output.WriteLine("get");
OpenBlock();
GenerateStatements(e.GetStatements);
CloseBlock();
CloseBlock();
}
}
protected override void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e)
{
if (e.TargetObject != null)
{
GenerateExpression(e.TargetObject);
Output.Write(".");
}
OutputIdentifier(e.PropertyName);
}
protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
{
Output.Write("value");
}
protected override void GenerateRemoveEventStatement(CodeRemoveEventStatement e)
{
GenerateEventReferenceExpression(e.Event);
Output.Write(" -= ");
GenerateExpression(e.Listener);
Output.WriteLine(";");
}
protected override void GenerateSnippetExpression(CodeSnippetExpression e)
{
Output.Write(e.Value);
}
protected override void GenerateSnippetMember(CodeSnippetTypeMember e)
{
Output.Write(e.Text);
}
protected override void GenerateThisReferenceExpression(CodeThisReferenceExpression e)
{
Output.Write("this");
}
protected override void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e)
{
Output.Write("throw");
if (e.ToThrow != null)
{
Output.Write(" ");
GenerateExpression(e.ToThrow);
}
Output.WriteLine(";");
}
protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
{
Output.Write("try");
OpenBlock();
GenerateStatements(e.TryStatements);
CodeCatchClauseCollection catches = e.CatchClauses;
if (catches.Count > 0)
{
IEnumerator en = catches.GetEnumerator();
while (en.MoveNext())
{
Output.Write("}");
if (Options.ElseOnClosing)
{
Output.Write(" ");
}
else
{
Output.WriteLine("");
}
CodeCatchClause current = (CodeCatchClause)en.Current;
Output.Write("catch (");
OutputType(current.CatchExceptionType);
Output.Write(" ");
OutputIdentifier(current.LocalName);
Output.Write(")");
OpenBlock();
GenerateStatements(current.Statements);
CloseBlock();
}
}
CodeStatementCollection finallyStatements = e.FinallyStatements;
if (finallyStatements.Count > 0)
{
Output.Write("}");
if (Options.ElseOnClosing)
{
Output.Write(" ");
}
else
{
Output.WriteLine("");
}
Output.Write("finally");
OpenBlock();
GenerateStatements(finallyStatements);
CloseBlock();
}
Output.WriteLine("}");
}
protected override void GenerateTypeConstructor(CodeTypeConstructor e)
{
if (!(IsCurrentClass || IsCurrentStruct))
{
return;
}
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
Output.Write("static ");
Output.Write(CurrentTypeName);
Output.Write("()");
OpenBlock();
GenerateStatements(e.Statements);
CloseBlock();
Output.WriteLine("}");
}
protected override void GenerateTypeEnd(CodeTypeDeclaration e)
{
if (!IsCurrentDelegate)
{
CloseBlock();
}
}
protected override void GenerateTypeStart(CodeTypeDeclaration e)
{
if (e.CustomAttributes.Count > 0)
{
GenerateAttributes(e.CustomAttributes);
}
if (IsCurrentDelegate)
{
switch (e.TypeAttributes & TypeAttributes.VisibilityMask)
{
case TypeAttributes.Public:
Output.Write("public ");
break;
case TypeAttributes.NotPublic:
Output.Write("internal ");
break;
}
CodeTypeDelegate del = (CodeTypeDelegate)e;
Output.Write("delegate ");
OutputType(del.ReturnType);
Output.Write(" ");
OutputIdentifier(e.Name);
Output.Write("(");
OutputParameters(del.Parameters);
Output.WriteLine(");");
}
else
{
OutputTypeAttributes(e);
OutputIdentifier(e.Name);
OutputTypeParameters(e.TypeParameters);
bool first = true;
foreach (CodeTypeReference typeRef in e.BaseTypes)
{
if (first)
{
Output.Write(" : ");
first = false;
}
else
{
Output.Write(", ");
}
OutputType(typeRef);
}
OutputTypeParameterConstraints(e.TypeParameters);
Output.WriteLine();
OpenBlock();
}
}
protected override void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e)
{
OutputTypeNamePair(e.Type, e.Name);
if (e.InitExpression != null)
{
Output.Write(" = ");
GenerateExpression(e.InitExpression);
}
if (!GeneratingForLoop)
{
Output.WriteLine(";");
}
}
protected override void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e)
{
OutputIdentifier(e.VariableName);
}
/// <summary>Gets the type indicated by the specified <see cref="T:System.CodeDom.CodeTypeReference" />.</summary>
/// <param name="type">A <see cref="T:System.CodeDom.CodeTypeReference" /> that indicates the type to return. </param>
/// <returns>A text representation of the specified type for the language this code generator is designed to generate code in. For example, in Visual Basic, passing in type System.Int32 will return "Integer".</returns>
public override string GetTypeOutput(CodeTypeReference type)
{
string s = string.Empty;
CodeTypeReference baseTypeRef = type;
while (baseTypeRef.ArrayElementType != null)
{
baseTypeRef = baseTypeRef.ArrayElementType;
}
s += GetBaseTypeOutput(baseTypeRef);
while (type != null && type.ArrayRank > 0)
{
char[] results = new char[type.ArrayRank + 1];
results[0] = '[';
results[type.ArrayRank] = ']';
for (int i = 1; i < type.ArrayRank; i++)
{
results[i] = ',';
}
s += new string(results);
type = type.ArrayElementType;
}
return s;
}
protected override void OutputType(CodeTypeReference typeRef)
{
Output.Write(GetTypeOutput(typeRef));
}
protected override string QuoteSnippetString(string value)
{
return value;
}
private string GetBaseTypeOutput(CodeTypeReference typeRef)
{
string s = typeRef.BaseType;
if (s.Length == 0)
{
s = "void";
return s;
}
string lowerCaseString = s.ToLower(CultureInfo.InvariantCulture).Trim();
switch (lowerCaseString)
{
case "system.int16":
s = "short";
break;
case "system.int32":
s = "int";
break;
case "system.int64":
s = "long";
break;
case "system.string":
s = "string";
break;
case "system.object":
s = "object";
break;
case "system.boolean":
s = "bool";
break;
case "system.void":
s = "void";
break;
case "system.char":
s = "char";
break;
case "system.byte":
s = "byte";
break;
case "system.uint16":
s = "ushort";
break;
case "system.uint32":
s = "uint";
break;
case "system.uint64":
s = "ulong";
break;
case "system.sbyte":
s = "sbyte";
break;
case "system.single":
s = "float";
break;
case "system.double":
s = "double";
break;
case "system.decimal":
s = "decimal";
break;
default:
StringBuilder sb = new StringBuilder(s.Length + 10);
if ((typeRef.Options & CodeTypeReferenceOptions.GlobalReference) != 0)
{
sb.Append("global::");
}
string baseType = typeRef.BaseType;
int lastIndex = 0;
int currentTypeArgStart = 0;
for (int i = 0; i < baseType.Length; i++)
{
switch (baseType[i])
{
case '+':
case '.':
sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
sb.Append('.');
i++;
lastIndex = i;
break;
case '`':
sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
i++;
int numTypeArgs = 0;
while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <= '9')
{
numTypeArgs = numTypeArgs * 10 + (baseType[i] - '0');
i++;
}
GetTypeArgumentsOutput(typeRef.TypeArguments, currentTypeArgStart, numTypeArgs, sb);
currentTypeArgStart += numTypeArgs;
if (i < baseType.Length && (baseType[i] == '+' || baseType[i] == '.'))
{
sb.Append('.');
i++;
}
lastIndex = i;
break;
}
}
if (lastIndex < baseType.Length)
{
sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex)));
}
return sb.ToString();
}
return s;
}
protected virtual void OutputTypeParameters(CodeTypeParameterCollection typeParameters)
{
if (typeParameters.Count == 0)
{
return;
}
Output.Write('<');
bool first = true;
for (int i = 0; i < typeParameters.Count; i++)
{
if (first)
{
first = false;
}
else
{
Output.Write(", ");
}
if (typeParameters[i].CustomAttributes.Count > 0)
{
GenerateAttributes(typeParameters[i].CustomAttributes, null, true);
Output.Write(' ');
}
Output.Write(typeParameters[i].Name);
}
Output.Write('>');
}
private static SortedList GetImportList(CodeCompileUnit e)
{
SortedList importList = new SortedList(StringComparer.Ordinal);
foreach (CodeNamespace nspace in e.Namespaces)
{
if (!string.IsNullOrEmpty(nspace.Name))
{
nspace.UserData["GenerateImports"] = false;
foreach (CodeNamespaceImport import in nspace.Imports)
{
if (!importList.Contains(import.Namespace))
{
importList.Add(import.Namespace, import.Namespace);
}
}
}
}
return importList;
}
protected virtual void OutputTypeParameterConstraints(CodeTypeParameterCollection typeParameters)
{
if (typeParameters.Count == 0)
{
return;
}
for (int i = 0; i < typeParameters.Count; i++)
{
Output.WriteLine();
Indent++;
bool first = true;
if (typeParameters[i].Constraints.Count > 0)
{
foreach (CodeTypeReference typeRef in typeParameters[i].Constraints)
{
if (first)
{
Output.Write("where ");
Output.Write(typeParameters[i].Name);
Output.Write(" : ");
first = false;
}
else
{
Output.Write(", ");
}
OutputType(typeRef);
}
}
if (typeParameters[i].HasConstructorConstraint)
{
if (first)
{
Output.Write("where ");
Output.Write(typeParameters[i].Name);
Output.Write(" : new()");
}
else
{
Output.Write(", new ()");
}
}
Indent--;
}
}
private void OutputTypeAttributes(CodeTypeDeclaration e)
{
if ((e.Attributes & MemberAttributes.New) != 0)
{
Output.Write("new ");
}
TypeAttributes attributes = e.TypeAttributes;
switch (attributes & TypeAttributes.VisibilityMask)
{
case TypeAttributes.Public:
case TypeAttributes.NestedPublic:
Output.Write("public ");
break;
case TypeAttributes.NestedPrivate:
Output.Write("private ");
break;
case TypeAttributes.NestedFamily:
Output.Write("protected ");
break;
case TypeAttributes.NotPublic:
case TypeAttributes.NestedAssembly:
case TypeAttributes.NestedFamANDAssem:
Output.Write("internal ");
break;
case TypeAttributes.NestedFamORAssem:
Output.Write("protected internal ");
break;
}
if (e.IsStruct)
{
if (e.IsPartial)
{
Output.Write("partial ");
}
Output.Write("struct ");
}
else if (e.IsEnum)
{
Output.Write("enum ");
}
else if (e.IsInterface)
{
Output.Write("interface ");
}
else
{
switch (attributes & TypeAttributes.ClassSemanticsMask)
{
case TypeAttributes.Class:
if (IsStatic(e))
{
Output.Write("static ");
}
else
{
if ((attributes & TypeAttributes.Sealed) == TypeAttributes.Sealed)
{
Output.Write("sealed ");
}
if ((attributes & TypeAttributes.Abstract) == TypeAttributes.Abstract)
{
Output.Write("abstract ");
}
}
if (e.IsPartial)
{
Output.Write("partial ");
}
Output.Write("class ");
break;
case TypeAttributes.Interface:
if (e.IsPartial)
{
Output.Write("partial ");
}
Output.Write("interface ");
break;
}
}
}
private static bool IsStatic(CodeTypeDeclaration e)
{
var result = e.UserData["IsStatic"];
if (result != null && result is bool boolean)
{
return boolean;
}
return false;
}
private void OutputAccessibilityAndModifiers(MemberAttributes attributes)
{
OutputMemberAccessModifier(attributes);
OutputVTableModifier(attributes);
OutputMemberScopeModifier(attributes);
}
private void OutputVTableModifier(MemberAttributes attributes)
{
switch (attributes & MemberAttributes.VTableMask)
{
case MemberAttributes.New:
Output.Write("new ");
break;
}
}
private void GenerateExpressionList(CodeExpressionCollection expressions, bool newlineBetweenItems)
{
bool first = true;
IEnumerator en = expressions.GetEnumerator();
Indent++;
while (en.MoveNext())
{
if (first)
{
first = false;
}
else
{
if (newlineBetweenItems)
{
Output.WriteLine(',');
}
else
{
Output.Write(", ");
}
}
GenerateExpression((CodeExpression)en.Current);
}
Indent--;
}
}
//public class CSharpCodeGenerator : CodeGenerator, IDisposable
//{
// public CSharpCodeGeneratorOptions CSharpOptions;
// private bool generatingForLoop;
// protected override string NullToken => "null";
// public void Dispose()
// {
// }
// public void Flush()
// {
// Output.Flush();
// }
// public async Task FlushAsync()
// {
// await Output
// .FlushAsync()
// .ConfigureAwait(false);
// }
// public virtual void GenerateBreakSwitchSectionStatement(CodeBreakSwitchSectionStatement e)
// {
// GenerateSwitchSectionLabelExpression(e.Label);
// Output.WriteLine();
// Output.WriteLine("{");
// Indent++;
// if (e.BodyStatements.Count > 0)
// {
// GenerateStatements(e.BodyStatements);
// }
// Output.WriteLine("break;");
// Indent--;
// Output.WriteLine("}");
// }
// public void GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o)
// {
// SetOptions(o as CSharpCodeGeneratorOptions);
// ((ICodeGenerator)this).GenerateCodeFromCompileUnit(e, w, o);
// }
// public override void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options)
// {
// SetOptions(options as CSharpCodeGeneratorOptions);
// switch (member)
// {
// case CodeMemberEvent memberEvent:
// GenerateEvent(memberEvent, CurrentClass);
// break;
// case CodeEntryPointMethod entryPointMethod:
// GenerateEntryPointMethod(entryPointMethod, CurrentClass);
// break;
// case CodeConstructor constructor:
// GenerateConstructor(constructor, CurrentClass);
// break;
// case CodeMemberField memberField:
// GenerateField(memberField);
// break;
// case CodeTypeConstructor typeConstructor:
// GenerateTypeConstructor(typeConstructor);
// break;
// case CodeMemberMethod memberMethod:
// GenerateMethod(memberMethod, CurrentClass);
// break;
// case CodeMemberProperty memberProperty:
// GenerateProperty(memberProperty, CurrentClass);
// break;
// case CodeSnippetTypeMember snippetTypeMember:
// GenerateSnippetMember(snippetTypeMember);
// break;
// case CodeTypeDelegate typeDelegate:
// GenerateDelegate(typeDelegate);
// break;
// case CodeTypeDeclaration typeDeclaration:
// GenerateCodeFromType(typeDeclaration, writer, options);
// break;
// }
// }
// public virtual void GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o)
// {
// if (o is CSharpCodeGeneratorOptions oo)
// {
// SetOptions(oo);
// }
// ((ICodeGenerator)this).GenerateCodeFromNamespace(e, w, o);
// }
// public virtual void GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o)
// {
// if (o is CSharpCodeGeneratorOptions oo)
// {
// SetOptions(oo);
// }
// ((ICodeGenerator)this).GenerateCodeFromType(e, w, o);
// }
// public virtual void GenerateCodeSwitchStatement(CodeSwitchStatement e)
// {
// Output.Write("switch(");
// GenerateExpression(e.CheckExpression);
// Output.WriteLine(")");
// Output.WriteLine("{");
// Indent++;
// GenerateSwitchSections(e.Sections);
// Indent--;
// Output.WriteLine("}");
// }
// public virtual void GenerateDefaultBreakSwitchSectionStatement(CodeDefaultBreakSwitchSectionStatement e)
// {
// Output.WriteLine("default:");
// Output.WriteLine("{");
// Indent++;
// if (e.BodyStatements.Count > 0)
// {
// GenerateStatements(e.BodyStatements);
// }
// Output.WriteLine("break;");
// Indent--;
// Output.WriteLine("}");
// }
// public virtual void GenerateDefaultReturnSwitchSectionStatement(CodeDefaultReturnSwitchSectionStatement e)
// {
// Output.WriteLine("default:");
// Output.WriteLine("{");
// Indent++;
// if (e.BodyStatements.Count > 0)
// {
// GenerateStatements(e.BodyStatements);
// }
// GenerateMethodReturnStatement(e.ReturnStatement);
// Indent--;
// Output.WriteLine("}");
// }
// public virtual void GenerateFallThroughSwitchSectionStatement(CodeFallThroughSwitchSectionStatement e)
// {
// GenerateSwitchSectionLabelExpression(e.Label);
// Output.WriteLine();
// }
// public virtual void GenerateReturnValueSwitchSectionStatement(CodeReturnValueSwitchSectionStatement e)
// {
// GenerateSwitchSectionLabelExpression(e.Label);
// if (e.SingleLine)
// {
// GenerateMethodReturnStatement(e.ReturnStatement);
// }
// else
// {
// Output.WriteLine();
// Output.WriteLine("{");
// Indent++;
// if (e.BodyStatements.Count > 0)
// {
// GenerateStatements(e.BodyStatements);
// }
// GenerateMethodReturnStatement(e.ReturnStatement);
// Indent--;
// Output.WriteLine("}");
// }
// }
// public virtual void GenerateSwitchSectionLabelExpression(CodeSwitchSectionLabelExpression e)
// {
// Output.Write("case ");
// GenerateExpression(e.Expression);
// Output.Write(": ");
// }
// public virtual void GenerateSwitchSections(CodeSwitchSectionStatementCollection e)
// {
// foreach (var section in e)
// {
// switch (section)
// {
// case CodeReturnValueSwitchSectionStatement returnValueSection:
// GenerateReturnValueSwitchSectionStatement(returnValueSection);
// break;
// case CodeBreakSwitchSectionStatement breakSection:
// GenerateBreakSwitchSectionStatement(breakSection);
// break;
// case CodeFallThroughSwitchSectionStatement fallThroughSection:
// GenerateFallThroughSwitchSectionStatement(fallThroughSection);
// break;
// case CodeDefaultBreakSwitchSectionStatement defaultBreakSection:
// GenerateDefaultBreakSwitchSectionStatement(defaultBreakSection);
// break;
// case CodeDefaultReturnSwitchSectionStatement defaultReturnSection:
// GenerateDefaultReturnSwitchSectionStatement(defaultReturnSection);
// break;
// }
// }
// }
// protected void CloseBlock()
// {
// Indent--;
// Output.WriteLine("}");
// }
// protected override string CreateEscapedIdentifier(string value)
// {
// //if (IsKeyword(value) || IsPrefixTwoUnderscore(value))
// //{
// // return "@" + value;
// //}
// return value;
// }
// protected override string CreateValidIdentifier(string value)
// {
// if (IsPrefixTwoUnderscore(value))
// {
// value = "_" + value;
// }
// while (IsKeyword(value))
// {
// value = "_" + value;
// }
// return value;
// }
//protected override void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e)
//{
// OutputIdentifier(e.ParameterName);
//}
//protected override void GenerateArrayCreateExpression(CodeArrayCreateExpression e)
//{
// Output.Write("new ");
// CodeExpressionCollection init = e.Initializers;
// if (init.Count > 0)
// {
// OutputType(e.CreateType);
// if (e.CreateType.ArrayRank == 0)
// {
// Output.Write("[]");
// }
// Output.WriteLine(" {");
// Indent++;
// OutputExpressionList(init, true);
// Indent--;
// Output.Write("}");
// }
// else
// {
// Output.Write(GetBaseTypeOutput(e.CreateType));
// Output.Write("[");
// if (e.SizeExpression != null)
// {
// GenerateExpression(e.SizeExpression);
// }
// else
// {
// Output.Write(e.Size);
// }
// Output.Write("]");
// }
//}
//protected override void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e)
//{
// GenerateExpression(e.TargetObject);
// Output.Write("[");
// bool first = true;
// foreach (CodeExpression exp in e.Indices)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// Output.Write(", ");
// }
// GenerateExpression(exp);
// }
// Output.Write("]");
//}
//protected override void GenerateAssignStatement(CodeAssignStatement e)
//{
// GenerateExpression(e.Left);
// Output.Write(" = ");
// GenerateExpression(e.Right);
// if (!generatingForLoop)
// {
// Output.WriteLine(";");
// }
//}
//protected override void GenerateAttachEventStatement(CodeAttachEventStatement e)
//{
// GenerateEventReferenceExpression(e.Event);
// Output.Write(" += ");
// GenerateExpression(e.Listener);
// Output.WriteLine(";");
//}
//protected override void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes)
//{
// Output.Write("]");
//}
//protected override void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes)
//{
// Output.Write("[");
//}
//protected override void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e)
//{
// Output.Write("base");
//}
//protected override void GenerateCastExpression(CodeCastExpression e)
//{
// Output.Write("((");
// OutputType(e.TargetType);
// Output.Write(")(");
// GenerateExpression(e.Expression);
// Output.Write("))");
//}
// private void GenerateDocComment(CodeTypeMember member, CodeComment e)
// {
// switch (member)
// {
// case CodeConstructor codeConstructor:
// {
// GenerateConstructorComment(e, codeConstructor);
// break;
// }
// case CodeMemberMethod codeMemberMethod:
// {
// GenerateMethodComment(e, codeMemberMethod);
// break;
// }
// case CodeMemberProperty codeMemberProperty:
// {
// GeneratePropertyComment(e, codeMemberProperty);
// break;
// }
// case CodeTypeDeclaration codeTypeDeclaration:
// break;
// }
// }
// public virtual void GeneratePropertyComment(CodeComment comment, CodeMemberProperty property)
// {
// Output.WriteLine("/// <summary>");
// Output.Write("/// ");
// Output.WriteLine(comment.Text);
// Output.WriteLine("/// </summary>");
// }
// public virtual void GenerateConstructorComment(CodeComment comment, CodeConstructor codeConstructor)
// {
// Output.WriteLine("/// <summary>");
// Output.Write("/// ");
// Output.WriteLine(comment.Text);
// Output.WriteLine("/// </summary>");
// foreach (CodeParameterDeclarationExpression parameter in codeConstructor.Parameters)
// {
// Output.WriteLine($"/// <param name=\"{parameter.Name}\">the {parameter.Type}</param>");
// }
// }
// public virtual void GenerateMethodComment(CodeComment comment, CodeMemberMethod codeMemberMethod)
// {
// Output.WriteLine("/// <summary>");
// Output.Write("/// ");
// Output.WriteLine(comment.Text);
// Output.WriteLine("/// </summary>");
// foreach (CodeParameterDeclarationExpression parameter in codeMemberMethod.Parameters)
// {
// Output.WriteLine($"/// <param name=\"{parameter.Name}\">the {parameter.Type}</param>");
// }
// Output.WriteLine($"/// <returns>{codeMemberMethod.ReturnType}</returns>");
// }
// protected override void GenerateComment(CodeComment e)
// {
// Output.WriteLine();
// if (e.DocComment)
// {
// if (GetOption("MultilineDocComments", false))
// {
// if (CurrentClass != null)
// {
// if (CurrentMember != null)
// {
// if (CurrentMember is CodeMemberMethod method)
// {
// GenerateDocComment(method, e);
// }
// else if (CurrentMember is CodeConstructor constructor)
// {
// GenerateDocComment(constructor, e);
// }
// }
// }
// }
// else
// {
// Output.Write("/// <summary>");
// Output.Write(e.Text);
// Output.WriteLine("/// </summary>");
// }
// }
// else
// {
// Output.Write("// ");
// Output.WriteLine(e.Text);
// }
// }
// protected override void GenerateCommentStatement(CodeCommentStatement e)
// {
// if (e.Comment != null)
// {
// GenerateComment(e.Comment);
// }
// }
// protected override void GenerateCompileUnit(CodeCompileUnit e)
// {
// GenerateCompileUnitStart(e);
// GenerateNamespaces(e);
// GenerateCompileUnitEnd(e);
// }
// protected override void GenerateCompileUnitEnd(CodeCompileUnit e)
// {
// if (e.EndDirectives.Count > 0)
// {
// GenerateDirectives(e.EndDirectives);
// }
// }
// protected override void GenerateCompileUnitStart(CodeCompileUnit e)
// {
// if (e.StartDirectives.Count > 0)
// {
// GenerateDirectives(e.StartDirectives);
// }
// WriteAutoGeneratedHeader();
// if (GetOption("MoveUsingsOutsideNamespace", false))
// {
// var importList = GetImportList(e);
// foreach (string import in importList.Keys)
// {
// Output.Write("using ");
// OutputIdentifier(import);
// Output.WriteLine(";");
// }
// if (importList.Keys.Count > 0)
// {
// Output.WriteLine("");
// }
// }
// if (e.AssemblyCustomAttributes.Count > 0)
// {
// GenerateAttributes(e.AssemblyCustomAttributes, "assembly: ");
// Output.WriteLine("");
// }
// }
// protected override void GenerateConditionStatement(CodeConditionStatement e)
// {
// Output.Write("if (");
// GenerateExpression(e.Condition);
// Output.Write(")");
// Output.WriteLine();
// Output.WriteLine("{");
// Indent++;
// GenerateStatements(e.TrueStatements);
// Indent--;
// CodeStatementCollection falseStatemetns = e.FalseStatements;
// if (falseStatemetns.Count > 0)
// {
// Output.Write("}");
// if (Options.ElseOnClosing)
// {
// Output.Write(" ");
// }
// else
// {
// Output.WriteLine("");
// }
// Output.Write("else");
// Output.WriteLine();
// Output.WriteLine("{");
// Indent++;
// GenerateStatements(e.FalseStatements);
// Indent--;
// }
// Output.WriteLine("}");
// }
// protected override void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c)
// {
// if (e.Comments.Count > 0)
// {
// Output.WriteLine();
// }
// OutputAccessibilityAndModifiers(e.Attributes);
// Output.Write(e.Name);
// Output.Write("(");
// OutputParameters(e.Parameters);
// Output.Write(')');
// CodeExpressionCollection baseArgs = e.BaseConstructorArgs;
// CodeExpressionCollection thisArgs = e.ChainedConstructorArgs;
// if (baseArgs.Count > 0)
// {
// Indent++;
// Output.Write(" : base(");
// GenerateExpressionList(baseArgs, false);
// Output.WriteLine(")");
// Indent--;
// }
// if (thisArgs.Count > 0)
// {
// Indent++;
// Output.Write(" : this(");
// GenerateExpressionList(thisArgs, false);
// Output.WriteLine(")");
// Indent--;
// }
// if (thisArgs.Count == 0 && baseArgs.Count == 0)
// {
// Output.WriteLine();
// }
// OpenBlock();
// GenerateStatements(e.Statements);
// CloseBlock();
// }
// protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e)
// {
// Output.Write("new ");
// OutputType(e.DelegateType);
// Output.Write("(");
// GenerateExpression(e.TargetObject);
// Output.Write(".");
// OutputIdentifier(e.MethodName);
// Output.Write(")");
// }
// protected override void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e)
// {
// if (e.TargetObject != null)
// {
// GenerateExpression(e.TargetObject);
// }
// Output.Write("(");
// OutputExpressionList(e.Parameters);
// Output.Write(")");
// }
// protected override void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c)
// {
// if (e.CustomAttributes.Count > 0)
// {
// GenerateAttributes(e.CustomAttributes);
// }
// Output.Write("public static ");
// OutputType(e.ReturnType);
// Output.Write(" Main()");
// OutputStartingBrace();
// Indent++;
// GenerateStatements(e.Statements);
// Indent--;
// Output.WriteLine("}");
// }
// protected override void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c)
// {
// if (IsCurrentDelegate || IsCurrentEnum)
// {
// return;
// }
// if (e.CustomAttributes.Count > 0)
// {
// GenerateAttributes(e.CustomAttributes);
// }
// if (e.PrivateImplementationType == null)
// {
// OutputMemberAccessModifier(e.Attributes);
// }
// Output.Write("event ");
// string name = e.Name;
// if (e.PrivateImplementationType != null)
// {
// name = GetBaseTypeOutput(e.PrivateImplementationType) + "." + name;
// }
// OutputTypeNamePair(e.Type, name);
// Output.WriteLine(";");
// }
// protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e)
// {
// if (e.TargetObject != null)
// {
// GenerateExpression(e.TargetObject);
// Output.Write(".");
// }
// OutputIdentifier(e.EventName);
// }
// protected override void GenerateExpressionStatement(CodeExpressionStatement e)
// {
// GenerateExpression(e.Expression);
// if (!generatingForLoop)
// {
// Output.WriteLine(";");
// }
// }
// protected override void GenerateField(CodeMemberField e)
// {
// if (IsCurrentDelegate || IsCurrentInterface)
// {
// return;
// }
// if (IsCurrentEnum)
// {
// if (e.CustomAttributes.Count > 0)
// {
// GenerateAttributes(e.CustomAttributes);
// }
// OutputIdentifier(e.Name);
// if (e.InitExpression != null)
// {
// Output.Write(" = ");
// GenerateExpression(e.InitExpression);
// }
// Output.WriteLine(",");
// }
// else
// {
// if (e.CustomAttributes.Count > 0)
// {
// GenerateAttributes(e.CustomAttributes);
// }
// OutputMemberAccessModifier(e.Attributes);
// OutputVTableModifier(e.Attributes);
// OutputFieldScopeModifier(e.Attributes);
// OutputTypeNamePair(e.Type, e.Name);
// if (e.InitExpression != null)
// {
// Output.Write(" = ");
// GenerateExpression(e.InitExpression);
// }
// Output.WriteLine(";");
// }
// }
// protected override void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e)
// {
// if (e.TargetObject != null)
// {
// GenerateExpression(e.TargetObject);
// Output.Write(".");
// }
// OutputIdentifier(e.FieldName);
// }
// protected override void GenerateGotoStatement(CodeGotoStatement e)
// {
// Output.Write("goto ");
// Output.Write(e.Label);
// Output.WriteLine(";");
// }
// protected override void GenerateIndexerExpression(CodeIndexerExpression e)
// {
// GenerateExpression(e.TargetObject);
// Output.Write("[");
// bool first = true;
// foreach (CodeExpression exp in e.Indices)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// Output.Write(", ");
// }
// GenerateExpression(exp);
// }
// Output.Write("]");
// }
// protected override void GenerateIterationStatement(CodeIterationStatement e)
// {
// generatingForLoop = true;
// Output.Write("for (");
// GenerateStatement(e.InitStatement);
// Output.Write("; ");
// GenerateExpression(e.TestExpression);
// Output.Write("; ");
// GenerateStatement(e.IncrementStatement);
// Output.Write(")");
// Output.WriteLine("{");
// generatingForLoop = false;
// Indent++;
// GenerateStatements(e.Statements);
// CloseBlock();
// }
// protected override void GenerateLabeledStatement(CodeLabeledStatement e)
// {
// Indent--;
// Output.Write(e.Label);
// Output.WriteLine(":");
// Indent++;
// if (e.Statement != null)
// {
// GenerateStatement(e.Statement);
// }
// }
// protected override void GenerateLinePragmaEnd(CodeLinePragma e)
// {
// Output.WriteLine();
// Output.WriteLine("#line default");
// Output.WriteLine("#line hidden");
// }
// protected override void GenerateLinePragmaStart(CodeLinePragma e)
// {
// Output.WriteLine("");
// Output.Write("#line ");
// Output.Write(e.LineNumber);
// Output.Write(" \"");
// Output.Write(e.FileName);
// Output.Write("\"");
// Output.WriteLine("");
// }
// protected override void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c)
// {
// if (!(IsCurrentClass || IsCurrentStruct || IsCurrentInterface))
// {
// return;
// }
// if (e.CustomAttributes.Count > 0)
// {
// GenerateAttributes(e.CustomAttributes);
// }
// if (e.ReturnTypeCustomAttributes.Count > 0)
// {
// GenerateAttributes(e.ReturnTypeCustomAttributes, "return: ");
// }
// if (!IsCurrentInterface)
// {
// if (e.PrivateImplementationType == null)
// {
// OutputMemberAccessModifier(e.Attributes);
// OutputVTableModifier(e.Attributes);
// OutputMemberScopeModifier(e.Attributes);
// }
// }
// else
// {
// OutputVTableModifier(e.Attributes);
// }
// OutputType(e.ReturnType);
// Output.Write(" ");
// if (e.PrivateImplementationType != null)
// {
// Output.Write(GetBaseTypeOutput(e.PrivateImplementationType));
// Output.Write(".");
// }
// OutputIdentifier(e.Name);
// OutputTypeParameters(e.TypeParameters);
// Output.Write("(");
// OutputParameters(e.Parameters);
// Output.Write(")");
// OutputTypeParameterConstraints(e.TypeParameters);
// if (!IsCurrentInterface && (e.Attributes & MemberAttributes.ScopeMask) != MemberAttributes.Abstract)
// {
// OutputStartingBrace();
// Indent++;
// GenerateStatements(e.Statements);
// CloseBlock();
// }
// else
// {
// Output.WriteLine(";");
// }
// }
// protected override void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e)
// {
// GenerateMethodReferenceExpression(e.Method);
// Output.Write("(");
// OutputExpressionList(e.Parameters);
// Output.Write(")");
// }
// protected override void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e)
// {
// if (e.TargetObject != null)
// {
// if (e.TargetObject is CodeBinaryOperatorExpression)
// {
// Output.Write("(");
// GenerateExpression(e.TargetObject);
// Output.Write(")");
// }
// else
// {
// GenerateExpression(e.TargetObject);
// }
// Output.Write(".");
// }
// OutputIdentifier(e.MethodName);
// if (e.TypeArguments.Count > 0)
// {
// Output.Write(GetTypeArgumentsOutput(e.TypeArguments));
// }
// }
// protected override void GenerateMethodReturnStatement(CodeMethodReturnStatement e)
// {
// Output.Write("return");
// if (e.Expression != null)
// {
// Output.Write(" ");
// GenerateExpression(e.Expression);
// }
// Output.WriteLine(";");
// }
// protected override void GenerateNamespace(CodeNamespace e)
// {
// GenerateCommentStatements(e.Comments);
// GenerateNamespaceStart(e);
// if (!GetOption("MoveUsingsOutsideNamespace", false))
// {
// GenerateNamespaceImports(e);
// }
// Output.WriteLine("");
// GenerateTypes(e);
// GenerateNamespaceEnd(e);
// }
// protected override void GenerateNamespaceEnd(CodeNamespace e)
// {
// if (!string.IsNullOrEmpty(e.Name))
// {
// CloseBlock();
// }
// }
// protected override void GenerateNamespaceImport(CodeNamespaceImport e)
// {
// Output.Write("using ");
// OutputIdentifier(e.Namespace);
// Output.WriteLine(";");
// }
// protected override void GenerateNamespaceStart(CodeNamespace e)
// {
// if (!string.IsNullOrEmpty(e.Name))
// {
// Output.Write("namespace ");
// string[] names = e.Name.Split('.');
// Debug.Assert(names.Length > 0);
// OutputIdentifier(names[0]);
// for (int i = 1; i < names.Length; i++)
// {
// Output.Write(".");
// OutputIdentifier(names[i]);
// }
// OutputStartingBrace();
// Indent++;
// }
// }
// protected override void GenerateObjectCreateExpression(CodeObjectCreateExpression e)
// {
// Output.Write("new ");
// OutputType(e.CreateType);
// Output.Write("(");
// OutputExpressionList(e.Parameters);
// Output.Write(")");
// }
// protected override void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c)
// {
// if (GetOption("BlankLinesBetweenMembers", false))
// {
// Output.WriteLine();
// }
// if (!IsCurrentInterface)
// {
// OutputAccessibilityAndModifiers(e.Attributes);
// }
// OutputType(e.Type);
// Output.Write(" ");
// Output.Write(e.Name);
// if (e.GetStatements.Count == 0)
// {
// if (e.HasGet && !e.HasSet)
// {
// Output.WriteLine(" { get; }");
// }
// else
// {
// if (e.GetStatements.Count == 0 && e.SetStatements.Count == 0)
// {
// Output.WriteLine(" { get; set; }");
// }
// }
// }
// else
// {
// Output.WriteLine();
// OpenBlock();
// Output.WriteLine("get");
// OpenBlock();
// GenerateStatements(e.GetStatements);
// CloseBlock();
// CloseBlock();
// }
// }
// protected override void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e)
// {
// if (e.TargetObject != null)
// {
// GenerateExpression(e.TargetObject);
// Output.Write(".");
// }
// OutputIdentifier(e.PropertyName);
// }
// protected override void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e)
// {
// Output.Write("value");
// }
// protected override void GenerateRemoveEventStatement(CodeRemoveEventStatement e)
// {
// GenerateEventReferenceExpression(e.Event);
// Output.Write(" -= ");
// GenerateExpression(e.Listener);
// Output.WriteLine(";");
// }
// protected override void GenerateSnippetExpression(CodeSnippetExpression e)
// {
// Output.Write(e.Value);
// }
// protected override void GenerateSnippetMember(CodeSnippetTypeMember e)
// {
// Output.Write(e.Text);
// }
// protected override void GenerateThisReferenceExpression(CodeThisReferenceExpression e)
// {
// Output.Write("this");
// }
// protected override void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e)
// {
// Output.Write("throw");
// if (e.ToThrow != null)
// {
// Output.Write(" ");
// GenerateExpression(e.ToThrow);
// }
// Output.WriteLine(";");
// }
// protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
// {
// Output.Write("try");
// OutputStartingBrace();
// Indent++;
// GenerateStatements(e.TryStatements);
// Indent--;
// CodeCatchClauseCollection catches = e.CatchClauses;
// if (catches.Count > 0)
// {
// IEnumerator en = catches.GetEnumerator();
// while (en.MoveNext())
// {
// Output.Write("}");
// if (Options.ElseOnClosing)
// {
// Output.Write(" ");
// }
// else
// {
// Output.WriteLine("");
// }
// CodeCatchClause current = (CodeCatchClause)en.Current;
// Output.Write("catch (");
// OutputType(current.CatchExceptionType);
// Output.Write(" ");
// OutputIdentifier(current.LocalName);
// Output.Write(")");
// OutputStartingBrace();
// Indent++;
// GenerateStatements(current.Statements);
// Indent--;
// }
// }
// CodeStatementCollection finallyStatements = e.FinallyStatements;
// if (finallyStatements.Count > 0)
// {
// Output.Write("}");
// if (Options.ElseOnClosing)
// {
// Output.Write(" ");
// }
// else
// {
// Output.WriteLine("");
// }
// Output.Write("finally");
// OutputStartingBrace();
// Indent++;
// GenerateStatements(finallyStatements);
// Indent--;
// }
// Output.WriteLine("}");
// }
// protected override void GenerateTypeConstructor(CodeTypeConstructor e)
// {
// if (!(IsCurrentClass || IsCurrentStruct))
// {
// return;
// }
// if (e.CustomAttributes.Count > 0)
// {
// GenerateAttributes(e.CustomAttributes);
// }
// Output.Write("static ");
// Output.Write(CurrentTypeName);
// Output.Write("()");
// OutputStartingBrace();
// Indent++;
// GenerateStatements(e.Statements);
// Indent--;
// Output.WriteLine("}");
// }
// protected override void GenerateTypeEnd(CodeTypeDeclaration e)
// {
// if (!IsCurrentDelegate)
// {
// CloseBlock();
// }
// }
// protected override void GenerateTypeStart(CodeTypeDeclaration e)
// {
// if (e.CustomAttributes.Count > 0)
// {
// GenerateAttributes(e.CustomAttributes);
// }
// if (IsCurrentDelegate)
// {
// switch (e.TypeAttributes & TypeAttributes.VisibilityMask)
// {
// case TypeAttributes.Public:
// Output.Write("public ");
// break;
// case TypeAttributes.NotPublic:
// Output.Write("internal ");
// break;
// }
// CodeTypeDelegate del = (CodeTypeDelegate)e;
// Output.Write("delegate ");
// OutputType(del.ReturnType);
// Output.Write(" ");
// OutputIdentifier(e.Name);
// Output.Write("(");
// OutputParameters(del.Parameters);
// Output.WriteLine(");");
// }
// else
// {
// OutputTypeAttributes(e);
// OutputIdentifier(e.Name);
// OutputTypeParameters(e.TypeParameters);
// bool first = true;
// foreach (CodeTypeReference typeRef in e.BaseTypes)
// {
// if (first)
// {
// Output.Write(" : ");
// first = false;
// }
// else
// {
// Output.Write(", ");
// }
// OutputType(typeRef);
// }
// OutputTypeParameterConstraints(e.TypeParameters);
// OutputStartingBrace();
// Indent++;
// }
// }
// protected override void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e)
// {
// OutputTypeNamePair(e.Type, e.Name);
// if (e.InitExpression != null)
// {
// Output.Write(" = ");
// GenerateExpression(e.InitExpression);
// }
// if (!generatingForLoop)
// {
// Output.WriteLine(";");
// }
// }
// protected override void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e)
// {
// OutputIdentifier(e.VariableName);
// }
// protected override string GetTypeOutput(CodeTypeReference value)
// {
// string s = string.Empty;
// CodeTypeReference baseTypeRef = value;
// while (baseTypeRef.ArrayElementType != null)
// {
// baseTypeRef = baseTypeRef.ArrayElementType;
// }
// s += GetBaseTypeOutput(baseTypeRef);
// while (value != null && value.ArrayRank > 0)
// {
// char[] results = new char[value.ArrayRank + 1];
// results[0] = '[';
// results[value.ArrayRank] = ']';
// for (int i = 1; i < value.ArrayRank; i++)
// {
// results[i] = ',';
// }
// s += new string(results);
// value = value.ArrayElementType;
// }
// return s;
// }
// protected override bool IsValidIdentifier(string value)
// {
// if (IsKeyword(value))
// {
// return false;
// }
// return Regex.IsMatch(value, @"[A-Za-z_][A-Za-z0-9_]*");
// }
// protected void OpenBlock()
// {
// Output.WriteLine("{");
// Indent++;
// }
// protected override void OutputAttributeDeclarations(CodeAttributeDeclarationCollection attributes)
// {
// GenerateAttributes(attributes);
// }
// protected override void OutputFieldScopeModifier(MemberAttributes attributes)
// {
// OutputVTableModifier(attributes);
// switch (attributes & MemberAttributes.ScopeMask)
// {
// case MemberAttributes.Static:
// Output.Write("static ");
// break;
// case MemberAttributes.Const:
// Output.Write("const ");
// break;
// }
// }
// protected override void OutputIdentifier(string ident)
// {
// Output.Write(CreateEscapedIdentifier(ident));
// }
// protected override void OutputMemberAccessModifier(MemberAttributes attributes)
// {
// switch (attributes & MemberAttributes.AccessMask)
// {
// case MemberAttributes.Assembly:
// case MemberAttributes.FamilyAndAssembly:
// Output.Write("internal ");
// break;
// case MemberAttributes.Family:
// Output.Write("protected ");
// break;
// case MemberAttributes.FamilyOrAssembly:
// Output.Write("protected internal ");
// break;
// case MemberAttributes.Private:
// Output.Write("private ");
// break;
// case MemberAttributes.Public:
// Output.Write("public ");
// break;
// case MemberAttributes.Static:
// Output.Write("static ");
// break;
// }
// }
// protected override void OutputMemberScopeModifier(MemberAttributes attributes)
// {
// if ((attributes & MemberAttributes.VTableMask) == MemberAttributes.New)
// {
// Output.Write("new ");
// }
// switch (attributes & MemberAttributes.ScopeMask)
// {
// case MemberAttributes.Abstract:
// Output.Write("abstract ");
// break;
// case MemberAttributes.Final:
// Output.Write("sealed ");
// break;
// case MemberAttributes.Static:
// Output.Write("static ");
// break;
// case MemberAttributes.Override:
// Output.Write("override ");
// break;
// default:
// switch (attributes & MemberAttributes.AccessMask)
// {
// case MemberAttributes.Family:
// case MemberAttributes.Assembly:
// Output.Write("virtual ");
// return;
// default:
// return;
// }
// }
// }
// protected override void OutputType(CodeTypeReference typeRef)
// {
// Output.Write(GetTypeOutput(typeRef));
// }
// protected virtual void OutputTypeParameterConstraints(CodeTypeParameterCollection typeParameters)
// {
// if (typeParameters.Count == 0)
// {
// return;
// }
// for (int i = 0; i < typeParameters.Count; i++)
// {
// Output.WriteLine();
// Indent++;
// bool first = true;
// if (typeParameters[i].Constraints.Count > 0)
// {
// foreach (CodeTypeReference typeRef in typeParameters[i].Constraints)
// {
// if (first)
// {
// Output.Write("where ");
// Output.Write(typeParameters[i].Name);
// Output.Write(" : ");
// first = false;
// }
// else
// {
// Output.Write(", ");
// }
// OutputType(typeRef);
// }
// }
// if (typeParameters[i].HasConstructorConstraint)
// {
// if (first)
// {
// Output.Write("where ");
// Output.Write(typeParameters[i].Name);
// Output.Write(" : new()");
// }
// else
// {
// Output.Write(", new ()");
// }
// }
// Indent--;
// }
// }
// protected virtual void OutputTypeParameters(CodeTypeParameterCollection typeParameters)
// {
// if (typeParameters.Count == 0)
// {
// return;
// }
// Output.Write('<');
// bool first = true;
// for (int i = 0; i < typeParameters.Count; i++)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// Output.Write(", ");
// }
// if (typeParameters[i].CustomAttributes.Count > 0)
// {
// GenerateAttributes(typeParameters[i].CustomAttributes, null, true);
// Output.Write(' ');
// }
// Output.Write(typeParameters[i].Name);
// }
// Output.Write('>');
// }
// protected override string QuoteSnippetString(string value)
// {
// return '"' + value + '"';
// }
// protected override bool Supports(GeneratorSupport support)
// {
// return true;
// }
// protected virtual void WriteAutoGeneratedHeader()
// {
// Output.WriteLine("//------------------------------------------------------------------------------");
// Output.WriteLine("// <auto-generated>");
// Output.WriteLine("// This code was automatically generated by a tool. Do not make changes to");
// Output.WriteLine("// the code in this file. All chages are eventually overwritten.");
// Output.WriteLine("// </auto-generated>");
// Output.WriteLine("//------------------------------------------------------------------------------");
// Output.WriteLine();
// }
//private static SortedList GetImportList(CodeCompileUnit e)
//{
// SortedList importList = new SortedList(StringComparer.Ordinal);
// foreach (CodeNamespace nspace in e.Namespaces)
// {
// if (!string.IsNullOrEmpty(nspace.Name))
// {
// nspace.UserData["GenerateImports"] = false;
// foreach (CodeNamespaceImport import in nspace.Imports)
// {
// if (!importList.Contains(import.Namespace))
// {
// importList.Add(import.Namespace, import.Namespace);
// }
// }
// }
// }
// return importList;
//}
// private static bool IsKeyword(string value)
// {
// if (value == null)
// {
// throw new ArgumentNullException(nameof(value));
// }
// switch (value)
// {
// case "abstract":
// case "as":
// case "base":
// case "bool":
// case "break":
// case "byte":
// case "case":
// case "catch":
// case "char":
// case "checked":
// case "class":
// case "const":
// case "continue":
// case "decimal":
// case "default":
// case "delegate":
// case "do":
// case "double":
// case "else":
// case "enum":
// case "event":
// case "explicit":
// case "extern":
// case "false":
// case "finally":
// case "fixed":
// case "float":
// case "for":
// case "foreach":
// case "goto":
// case "if":
// case "implicit":
// case "in":
// case "int":
// case "interface":
// case "internal":
// case "is":
// case "lock":
// case "long":
// case "namespace":
// case "new":
// case "null":
// case "object":
// case "operator":
// case "out":
// case "override":
// case "params":
// case "private":
// case "protected":
// case "public":
// case "readonly":
// case "ref":
// case "return":
// case "sbyte":
// case "sealed":
// case "short":
// case "sizeof":
// case "stackalloc":
// case "static":
// case "string":
// case "struct":
// case "switch":
// case "this":
// case "throw":
// case "true":
// case "try":
// case "typeof":
// case "uint":
// case "ulong":
// case "unchecked":
// case "unsafe":
// case "ushort":
// case "using":
// case "var":
// case "virtual":
// case "void":
// case "volatile":
// case "while":
// return true;
// default: return false;
// }
// }
// private static bool IsPrefixTwoUnderscore(string value)
// {
// if (value.Length < 3 || value[0] != '_' || value[1] != '_')
// {
// return false;
// }
// return value[2] != '_';
// }
// private static bool IsStatic(CodeTypeDeclaration e)
// {
// var result = e.UserData["IsStatic"];
// if (result != null && result is bool boolean)
// {
// return boolean;
// }
// return false;
// }
// private void GenerateAttributes(CodeAttributeDeclarationCollection attributes, string prefix = null, bool inLine = false)
// {
// if (attributes.Count == 0)
// {
// return;
// }
// IEnumerator en = attributes.GetEnumerator();
// bool paramArray = false;
// while (en.MoveNext())
// {
// CodeAttributeDeclaration current = (CodeAttributeDeclaration)en.Current;
// if (current.Name.Equals("system.paramarrayattribute", StringComparison.OrdinalIgnoreCase))
// {
// paramArray = true;
// continue;
// }
// GenerateAttributeDeclarationsStart(attributes);
// if (prefix != null)
// {
// Output.Write(prefix);
// }
// if (current.AttributeType != null)
// {
// Output.Write(GetTypeOutput(current.AttributeType));
// }
// Output.Write("(");
// bool firstArg = true;
// foreach (CodeAttributeArgument arg in current.Arguments)
// {
// if (firstArg)
// {
// firstArg = false;
// }
// else
// {
// Output.Write(", ");
// }
// OutputAttributeArgument(arg);
// }
// Output.Write(")");
// GenerateAttributeDeclarationsEnd(attributes);
// if (inLine)
// {
// Output.Write(" ");
// }
// else
// {
// Output.WriteLine();
// }
// }
// if (paramArray)
// {
// if (prefix != null)
// {
// Output.Write(prefix);
// }
// Output.Write("params");
// if (inLine)
// {
// Output.Write(" ");
// }
// else
// {
// Output.WriteLine();
// }
// }
// }
// private void GenerateDelegate(CodeTypeDelegate e)
// {
// switch (e.TypeAttributes & TypeAttributes.VisibilityMask)
// {
// case TypeAttributes.Public:
// Output.Write("public ");
// break;
// case TypeAttributes.NotPublic:
// Output.Write("internal ");
// break;
// }
// CodeTypeDelegate del = e;
// Output.Write("delegate ");
// OutputType(del.ReturnType);
// Output.Write(" ");
// OutputIdentifier(e.Name);
// Output.Write("(");
// OutputParameters(del.Parameters);
// Output.WriteLine(");");
// }
// private void GenerateExpressionList(CodeExpressionCollection expressions, bool newlineBetweenItems)
// {
// bool first = true;
// IEnumerator en = expressions.GetEnumerator();
// Indent++;
// while (en.MoveNext())
// {
// if (first)
// {
// first = false;
// }
// else
// {
// if (newlineBetweenItems)
// {
// Output.WriteLine(',');
// }
// else
// {
// Output.Write(", ");
// }
// }
// GenerateExpression((CodeExpression)en.Current);
// }
// Indent--;
// }
// private string GetBaseTypeOutput(CodeTypeReference typeRef)
// {
// string s = typeRef.BaseType;
// if (s.Length == 0)
// {
// s = "void";
// return s;
// }
// string lowerCaseString = s.ToLower(CultureInfo.InvariantCulture).Trim();
// switch (lowerCaseString)
// {
// case "system.int16":
// s = "short";
// break;
// case "system.int32":
// s = "int";
// break;
// case "system.int64":
// s = "long";
// break;
// case "system.string":
// s = "string";
// break;
// case "system.object":
// s = "object";
// break;
// case "system.boolean":
// s = "bool";
// break;
// case "system.void":
// s = "void";
// break;
// case "system.char":
// s = "char";
// break;
// case "system.byte":
// s = "byte";
// break;
// case "system.uint16":
// s = "ushort";
// break;
// case "system.uint32":
// s = "uint";
// break;
// case "system.uint64":
// s = "ulong";
// break;
// case "system.sbyte":
// s = "sbyte";
// break;
// case "system.single":
// s = "float";
// break;
// case "system.double":
// s = "double";
// break;
// case "system.decimal":
// s = "decimal";
// break;
// default:
// StringBuilder sb = new StringBuilder(s.Length + 10);
// if ((typeRef.Options & CodeTypeReferenceOptions.GlobalReference) != 0)
// {
// sb.Append("global::");
// }
// string baseType = typeRef.BaseType;
// int lastIndex = 0;
// int currentTypeArgStart = 0;
// for (int i = 0; i < baseType.Length; i++)
// {
// switch (baseType[i])
// {
// case '+':
// case '.':
// sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
// sb.Append('.');
// i++;
// lastIndex = i;
// break;
// case '`':
// sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex, i - lastIndex)));
// i++;
// int numTypeArgs = 0;
// while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <= '9')
// {
// numTypeArgs = numTypeArgs * 10 + (baseType[i] - '0');
// i++;
// }
// GetTypeArgumentsOutput(typeRef.TypeArguments, currentTypeArgStart, numTypeArgs, sb);
// currentTypeArgStart += numTypeArgs;
// if (i < baseType.Length && (baseType[i] == '+' || baseType[i] == '.'))
// {
// sb.Append('.');
// i++;
// }
// lastIndex = i;
// break;
// }
// }
// if (lastIndex < baseType.Length)
// {
// sb.Append(CreateEscapedIdentifier(baseType.Substring(lastIndex)));
// }
// return sb.ToString();
// }
// return s;
// }
// private T GetOption<T>(string name, T defaultValue)
// {
// object o = Options[name];
// if (o != null && o is T option)
// {
// return option;
// }
// if (CSharpOptions != null && o is T oo)
// {
// return oo;
// }
// return defaultValue;
// }
// private string GetTypeArgumentsOutput(CodeTypeReferenceCollection typeArguments)
// {
// StringBuilder sb = new StringBuilder(128);
// GetTypeArgumentsOutput(typeArguments, 0, typeArguments.Count, sb);
// return sb.ToString();
// }
// private void GetTypeArgumentsOutput(CodeTypeReferenceCollection typeArguments, int start, int length, StringBuilder sb)
// {
// sb.Append('<');
// bool first = true;
// for (int i = start; i < start + length; i++)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// sb.Append(", ");
// }
// if (i < typeArguments.Count)
// {
// sb.Append(GetTypeOutput(typeArguments[i]));
// }
// }
// sb.Append('>');
// }
// private void OutputAccessibilityAndModifiers(MemberAttributes attributes)
// {
// OutputMemberAccessModifier(attributes);
// OutputVTableModifier(attributes);
// OutputMemberScopeModifier(attributes);
// }
// private void OutputStartingBrace()
// {
// if (Options.BracingStyle == "C")
// {
// Output.WriteLine("");
// Output.WriteLine("{");
// }
// else
// {
// Output.WriteLine(" {");
// }
// }
// private void OutputTabs()
// {
// for (int index = 0; index < Indent; ++index)
// {
// Output.Write(Options.IndentString);
// }
// }
// private void OutputTypeAttributes(CodeTypeDeclaration e)
// {
// if ((e.Attributes & MemberAttributes.New) != 0)
// {
// Output.Write("new ");
// }
// TypeAttributes attributes = e.TypeAttributes;
// switch (attributes & TypeAttributes.VisibilityMask)
// {
// case TypeAttributes.Public:
// case TypeAttributes.NestedPublic:
// Output.Write("public ");
// break;
// case TypeAttributes.NestedPrivate:
// Output.Write("private ");
// break;
// case TypeAttributes.NestedFamily:
// Output.Write("protected ");
// break;
// case TypeAttributes.NotPublic:
// case TypeAttributes.NestedAssembly:
// case TypeAttributes.NestedFamANDAssem:
// Output.Write("internal ");
// break;
// case TypeAttributes.NestedFamORAssem:
// Output.Write("protected internal ");
// break;
// }
// if (e.IsStruct)
// {
// if (e.IsPartial)
// {
// Output.Write("partial ");
// }
// Output.Write("struct ");
// }
// else if (e.IsEnum)
// {
// Output.Write("enum ");
// }
// else if (e.IsInterface)
// {
// Output.Write("interface ");
// }
// else
// {
// switch (attributes & TypeAttributes.ClassSemanticsMask)
// {
// case TypeAttributes.Class:
// if (IsStatic(e))
// {
// Output.Write("static ");
// }
// else
// {
// if ((attributes & TypeAttributes.Sealed) == TypeAttributes.Sealed)
// {
// Output.Write("sealed ");
// }
// if ((attributes & TypeAttributes.Abstract) == TypeAttributes.Abstract)
// {
// Output.Write("abstract ");
// }
// }
// if (e.IsPartial)
// {
// Output.Write("partial ");
// }
// Output.Write("class ");
// break;
// case TypeAttributes.Interface:
// if (e.IsPartial)
// {
// Output.Write("partial ");
// }
// Output.Write("interface ");
// break;
// }
// }
// }
// private void OutputVTableModifier(MemberAttributes attributes)
// {
// switch (attributes & MemberAttributes.VTableMask)
// {
// case MemberAttributes.New:
// Output.Write("new ");
// break;
// }
// }
// private void SetOptions(CSharpCodeGeneratorOptions generatorOptions)
// {
// CSharpOptions = generatorOptions;
// }
//}
}
| 31.94087 | 226 | 0.436341 | [
"MIT"
] | sped-mobi/System.CodeDom.Extensions | src/System.CodeDom.Extensions/CodeDom/CSharp/CSharpGenerator.cs | 110,198 | C# |
using Cofoundry.Core;
using Cofoundry.Domain;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cofoundry.Web.Internal
{
/// <summary>
/// Service for retreiving connection information about a client connected
/// to the application e.g. IPAddress and the UserAgent string.
/// </summary>
public class WebClientConnectionService : IClientConnectionService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public WebClientConnectionService(
IHttpContextAccessor httpContextAccessor
)
{
_httpContextAccessor = httpContextAccessor;
}
/// <summary>
/// Gets an object that represents the current client
/// connected to the application in the current request.
/// </summary>
public ClientConnectionInfo GetConnectionInfo()
{
var context = _httpContextAccessor.HttpContext;
var info = new ClientConnectionInfo();
if (context != null && context.Request != null)
{
info.IPAddress = context?.Connection?.RemoteIpAddress?.ToString();
info.UserAgent = context.Request?.Headers?.GetOrDefault("User-Agent");
}
return info;
}
}
}
| 29.456522 | 86 | 0.6369 | [
"MIT"
] | BearerPipelineTest/cofoundry | src/Cofoundry.Web/Framework/ClientConnection/WebClientConnectionService.cs | 1,357 | C# |
namespace LearningSystem.Models.ViewModels
{
public class CourseViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
}
| 17.1 | 43 | 0.608187 | [
"MIT"
] | ivajlotokiew/CSharp_ASP.NET_MVC | Learning_System/LearningSystem.Models/ViewModels/CourseViewModel.cs | 173 | C# |
using System;
using System.Collections.Generic;
#nullable disable
namespace EFCoreMySql.Models
{
public partial class Order
{
public Order()
{
OrderDetails = new HashSet<OrderDetail>();
}
public int OrderId { get; set; }
public int? CustomerId { get; set; }
public int? OrderStatus { get; set; }
public DateTime OrderDate { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
}
| 23.125 | 74 | 0.609009 | [
"MIT"
] | sinhdev/dotnet-core | EFCoreMySql/Models/Order.cs | 557 | C# |
using System;
using System.Threading.Tasks;
using Locust.Model;
using Locust.ServiceModel;
using Locust.ServiceModel.Babbage;
using Locust.Modules.Location.Model;
namespace Locust.Modules.Location.Strategies
{
public partial class CountryDeleteByIdStrategy : CountryDeleteByIdStrategyBase
{
protected void Init()
{
}
}
} | 22.333333 | 79 | 0.791045 | [
"MIT"
] | mansoor-omrani/Locust.NET | Modules/Locust.Modules.Location/Service/Country/DeleteById/Strategy.Customized.cs | 335 | C# |
namespace Binance.Net.Objects.Other
{
internal class BinanceExchangeApiWrapper<T>
{
public int Code { get; set; }
public string Message { get; set; } = string.Empty;
public string MessageDetail { get; set; } = string.Empty;
public T Data { get; set; } = default!;
public bool Success { get; set; }
}
}
| 25.5 | 65 | 0.59944 | [
"MIT"
] | CarlPrentice/Binance.Net | Binance.Net/Objects/Other/BinanceExchangeApiWrapper.cs | 359 | C# |
using System.Collections.Generic;
namespace ATF.Scripts.Helper
{
public static class DictionaryBasedIdGenerator
{
private static int _idCounter;
private static Dictionary<string, int> _ids;
public static int GetNewId(string displayName)
{
if (_ids == null)
{
_ids = new Dictionary<string, int>();
}
if (displayName == null)
{
return ++_idCounter;
}
if (_ids.ContainsKey(displayName))
{
return _ids[displayName];
}
_ids[displayName] = ++_idCounter;
return _ids[displayName];
}
}
}
| 23.3125 | 60 | 0.486595 | [
"MIT"
] | GoldenSylph/Unity3DAutoTestFramework | Assets/BedrinAssetPublishing/ATF/Scripts/Helper/DictionaryBasedIdGenerator.cs | 748 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ExtensionGrabber.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 38.777778 | 151 | 0.596944 | [
"MIT"
] | daveaperez/extensiongrabber | ExtensionGrabber/Properties/Settings.Designer.cs | 1,049 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501
{
using Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell;
/// <summary>Server backup properties</summary>
[System.ComponentModel.TypeConverter(typeof(ServerBackupTypeConverter))]
public partial class ServerBackup
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.ServerBackup"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackup" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackup DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new ServerBackup(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.ServerBackup"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackup" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackup DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new ServerBackup(content);
}
/// <summary>
/// Creates a new instance of <see cref="ServerBackup" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackup FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.ServerBackup"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal ServerBackup(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Property"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.ServerBackupPropertiesTypeConverter.ConvertFrom);
}
if (content.Contains("SystemData"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20.SystemDataTypeConverter.ConvertFrom);
}
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("Type"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString);
}
if (content.Contains("SystemDataCreatedBy"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedBy, global::System.Convert.ToString);
}
if (content.Contains("SystemDataCreatedAt"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("BackupType"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).BackupType = (string) content.GetValueForProperty("BackupType",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).BackupType, global::System.Convert.ToString);
}
if (content.Contains("CompletedTime"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).CompletedTime = (global::System.DateTime?) content.GetValueForProperty("CompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).CompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("Source"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).Source = (string) content.GetValueForProperty("Source",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).Source, global::System.Convert.ToString);
}
if (content.Contains("SystemDataCreatedByType"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedByType = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreatedByType?) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedByType, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreatedByType.CreateFrom);
}
if (content.Contains("SystemDataLastModifiedBy"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString);
}
if (content.Contains("SystemDataLastModifiedByType"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedByType = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreatedByType?) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedByType, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreatedByType.CreateFrom);
}
if (content.Contains("SystemDataLastModifiedAt"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.ServerBackup"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal ServerBackup(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Property"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.ServerBackupPropertiesTypeConverter.ConvertFrom);
}
if (content.Contains("SystemData"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20.SystemDataTypeConverter.ConvertFrom);
}
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("Type"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString);
}
if (content.Contains("SystemDataCreatedBy"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedBy, global::System.Convert.ToString);
}
if (content.Contains("SystemDataCreatedAt"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("BackupType"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).BackupType = (string) content.GetValueForProperty("BackupType",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).BackupType, global::System.Convert.ToString);
}
if (content.Contains("CompletedTime"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).CompletedTime = (global::System.DateTime?) content.GetValueForProperty("CompletedTime",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).CompletedTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("Source"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).Source = (string) content.GetValueForProperty("Source",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).Source, global::System.Convert.ToString);
}
if (content.Contains("SystemDataCreatedByType"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedByType = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreatedByType?) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataCreatedByType, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreatedByType.CreateFrom);
}
if (content.Contains("SystemDataLastModifiedBy"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString);
}
if (content.Contains("SystemDataLastModifiedByType"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedByType = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreatedByType?) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedByType, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreatedByType.CreateFrom);
}
if (content.Contains("SystemDataLastModifiedAt"))
{
((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20210501.IServerBackupInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Server backup properties
[System.ComponentModel.TypeConverter(typeof(ServerBackupTypeConverter))]
public partial interface IServerBackup
{
}
} | 83.227642 | 497 | 0.708655 | [
"MIT"
] | Agazoth/azure-powershell | src/MySql/generated/api/Models/Api20210501/ServerBackup.PowerShell.cs | 20,229 | C# |
using System.Collections;
using ComBlitz.ConstantData;
using UnityEngine;
namespace ComBlitz.Factories
{
public class FactoriesCreator : MonoBehaviour
{
[Header("Spawn Objects")] public Transform spawnTransform;
public GameObject unit;
public GameObject spawnEffect;
[Header("Spawn Stats")] public float waitBetweenSpawn = 5f;
public float waitBeteweenEffectAndSpawn = 0.1f;
[Header("Debug")] public bool spawnOnStart;
private Transform spawnerHolder;
private void Start()
{
if (spawnOnStart)
StartSpawn();
spawnerHolder = GameObject.FindGameObjectWithTag(TagManager.EnemyHolder).transform;
}
public void StartSpawn() => StartCoroutine(SpawnUnits());
private IEnumerator SpawnUnits()
{
while (true)
{
yield return new WaitForSeconds(waitBetweenSpawn);
Instantiate(spawnEffect, spawnTransform.position, spawnEffect.transform.rotation);
yield return new WaitForSeconds(waitBeteweenEffectAndSpawn);
GameObject unitInstance = Instantiate(unit, spawnTransform.position, unit.transform.rotation);
unitInstance.transform.SetParent(spawnerHolder.transform);
}
}
}
} | 29.977778 | 110 | 0.642698 | [
"MIT"
] | Rud156/ComBlitz | Assets/Scripts/Factories/FactoriesCreator.cs | 1,351 | C# |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kodestruct.Common.Section.Interfaces;
using Kodestruct.Common.Section.SectionTypes;
using Kodestruct.Steel.AISC.Interfaces;
using Kodestruct.Steel.AISC.SteelEntities;
using Kodestruct.Steel.AISC.SteelEntities.Materials;
namespace Kodestruct.Steel.AISC.AISC360v10.Connections
{
public class BeamCopeFactory
{
public IBeamCope GetCope(BeamCopeCase BeamCopeCase, double d, double b_f, double t_f, double t_w, double d_c, double c, double F_y, double F_u)
{
ISteelMaterial material = new SteelMaterial(F_y, F_u, SteelConstants.ModulusOfElasticity, SteelConstants.ShearModulus);
ISectionI section = new SectionI(null, d, b_f, t_f, t_w);
IBeamCope cope=null;
switch (BeamCopeCase)
{
case BeamCopeCase.Uncoped:
cope = new BeamUncoped(section, material);
break;
case BeamCopeCase.CopedTopFlange:
cope = new BeamCopeSingle(c, d_c, section, material);
break;
case BeamCopeCase.CopedBothFlanges:
cope = new BeamCopeDouble(c, d_c, section, material);
break;
}
return cope;
}
}
}
| 34.947368 | 151 | 0.679719 | [
"Apache-2.0"
] | Kodestruct/Kodestruct.Design | Kodestruct.Steel/AISC/AISC360v10/J_Connections/AffectedMembers/BeamCope/BeamCopeFactory.cs | 1,992 | C# |
#region BSD License
/*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE.md file or at
* https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.471/blob/master/LICENSE
*
*/
#endregion
using ComponentFactory.Krypton.Toolkit;
namespace KryptonExplorer.UX
{
public partial class MainWindow : KryptonForm
{
#region Variables
private KryptonManager _manager;
private KryptonPalette _palette;
#endregion
public MainWindow()
{
InitializeComponent();
}
}
} | 22.769231 | 90 | 0.670608 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.471 | Source/Krypton Toolkit Suite Extended/Applications/Krypton Explorer/UX/MainWindow.cs | 594 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OgreIdleState : IOgreState
{
private Ogre enemy;
public void Enter(Ogre enemy)
{
this.enemy = enemy;
enemy.armature.animation.timeScale = 1f;
}
public void Execute()
{
Idle();
if (enemy.Target == null)
{
enemy.ChangeState(new OgrePatrolState());
}
if (enemy.Target != null && enemy.canAttack)
{
enemy.ChangeState(new OgreMeleeState());
}
}
void Idle()
{
if (enemy.armature.animation.isCompleted)
{
enemy.armature.animation.FadeIn("idle", -1, -1);
}
}
public void Exit()
{
}
public void OnCollisionEnter2D(Collision2D other)
{
}
}
| 18.688889 | 60 | 0.545779 | [
"Apache-2.0"
] | MadGriffonGames/BiltyBlop | Assets/Scripts/Enemies&States/Ogre/OgreIdleState.cs | 843 | C# |
using LitJson;
using System;
namespace LitJson.Benchmarks
{
public class BenchmarkLitJson
{
[Benchmark]
public static void LitJsonReaderNumbers ()
{
for (int i = 0; i < Common.Iterations; i++) {
JsonReader reader = new JsonReader (Common.JsonNumbers);
while (reader.Read());
}
}
[Benchmark]
public static void LitJsonReaderStrings ()
{
for (int i = 0; i < Common.Iterations; i++) {
JsonReader reader = new JsonReader (Common.JsonStrings);
while (reader.Read());
}
}
[Benchmark]
public static void LitJsonReaderFirstProperty ()
{
for (int i = 0; i < Common.Iterations; i++) {
bool found = false;
JsonReader reader = new JsonReader (Common.JsonText);
while (reader.Read()) {
if (reader.Token == JsonToken.PropertyName &&
(string) reader.Value == "FirstProperty") {
found = true;
break;
}
}
if (! found)
Console.WriteLine ("FirstProperty not found!");
}
}
[Benchmark]
public static void LitJsonReaderLastProperty ()
{
for (int i = 0; i < Common.Iterations; i++) {
bool found = false;
JsonReader reader = new JsonReader (Common.JsonText);
while (reader.Read()) {
if (reader.Token == JsonToken.PropertyName &&
(string) reader.Value == "LastProperty") {
found = true;
break;
}
}
if (! found)
Console.WriteLine ("FirstProperty not found!");
}
}
}
}
| 26.77027 | 72 | 0.44422 | [
"Unlicense"
] | JEphron/UnityLitJson | benchmarks/BmLitJsonReader.cs | 1,981 | C# |
using System.Collections.Generic;
using DeconTools.Workflows.Backend.Results;
namespace DeconTools.Workflows.Backend.FileIO
{
public class TopDownTargetedResultFromTextImporter:TargetedResultFromTextImporter
{
#region Constructors
public TopDownTargetedResultFromTextImporter(string filename): base(filename){ }
#endregion
#region Public Methods
protected override TargetedResultDTO ConvertTextToDataObject(List<string> processedData)
{
TargetedResultDTO result = new TopDownTargetedResultDTO();
GetBasicResultDTOData(processedData, result);
return result;
}
#endregion
}
}
| 27.615385 | 97 | 0.685237 | [
"Apache-2.0"
] | PNNL-Comp-Mass-Spec/DeconTools | DeconTools.Workflows/DeconTools.Workflows/Backend/FileIO/TopDownTargetedResultFromTextImporter.cs | 720 | C# |
namespace AnnoSavegameViewer.Structures.Savegame.Generated {
using AnnoSavegameViewer.Serialization.Core;
public class HarborHandler {
#region Public Properties
[BinaryContent(Name = "SecurityFactor", NodeType = BinaryContentTypes.Attribute)]
public object SecurityFactor { get; set; }
#endregion Public Properties
}
} | 26.461538 | 85 | 0.764535 | [
"MIT"
] | Veraatversus/AnnoSavegameViewer | src/AnnoSavegameViewer/GeneratedA7s/Structures/Savegame2/Generated/Content/HarborHandler.cs | 344 | C# |
using System;
using System.Collections.Generic;
using AGO.Core.Model.Dictionary.Projects;
using AGO.Core.Attributes.Constraints;
using AGO.Core.Attributes.Mapping;
using AGO.Core.Attributes.Model;
using AGO.Core.Model.Security;
using Newtonsoft.Json;
namespace AGO.Core.Model.Projects
{
public class ProjectModel : CoreModel<Guid>, IProjectBoundModel
{
public const int PROJECT_CODE_SIZE = 32;
#region Persistent
[JsonProperty, UniqueProperty, NotLonger(PROJECT_CODE_SIZE), NotEmpty]
public virtual string ProjectCode { get; set; }
[NotLonger(64), JsonProperty, NotEmpty]
public virtual string Name { get; set; }
[NotLonger(512), JsonProperty]
public virtual new string Description { get; set; }
[JsonProperty, NotNull, Prefetched]
public virtual ProjectTypeModel Type { get; set; }
[ReadOnlyProperty, MetadataExclude]
public virtual Guid? TypeId { get; set; }
/// <summary>
/// Project is visible in projects list for all authenticated users
/// </summary>
[JsonProperty]
public virtual bool VisibleForAll { get; set; }
[JsonProperty]
public virtual ProjectStatus Status { get; set; }
[PersistentCollection(CascadeType = CascadeType.AllDeleteOrphan)]
public virtual ISet<ProjectStatusHistoryModel> StatusHistory { get { return statusHistory; } set { statusHistory = value; } }
private ISet<ProjectStatusHistoryModel> statusHistory = new HashSet<ProjectStatusHistoryModel>();
[PersistentCollection(CascadeType = CascadeType.AllDeleteOrphan)]
public virtual ISet<ProjectToTagModel> Tags { get { return tags; } set { tags = value; } }
private ISet<ProjectToTagModel> tags = new HashSet<ProjectToTagModel>();
[PersistentCollection(CascadeType = CascadeType.AllDeleteOrphan)]
public virtual ISet<ProjectMembershipModel> Members { get { return members; } set { members = value; } }
private ISet<ProjectMembershipModel> members = new HashSet<ProjectMembershipModel>();
#region Technical info
/// <summary>
/// Connection string to project database
/// </summary>
/// <remarks>May be empty, if project data stored in main db with projects and users.
/// Situation mostly for development and test.</remarks>
[MetadataExclude, NotLonger(512)]
public virtual string ConnectionString { get; set; }
#endregion
#endregion
#region Non-persistent
public override string ToString()
{
return Name.TrimSafe() ?? base.ToString();
}
#endregion
public virtual ProjectStatusHistoryModel ChangeStatus(ProjectStatus newStatus, UserModel changer)
{
return StatusChangeHelper.Change(this, newStatus, StatusHistory, changer);
}
}
} | 32.036585 | 127 | 0.751047 | [
"MIT"
] | olegsmetanin/apinet-server | AGO.Core/Model/Projects/ProjectModel.cs | 2,629 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace SemVer
{
/// <summary>
/// A semantic version.
/// </summary>
public class Version : IComparable<Version>, IEquatable<Version>
{
private readonly string _inputString;
private readonly int _major;
private readonly int _minor;
private readonly int _patch;
private readonly string _preRelease;
private readonly string _build;
/// <summary>
/// The major component of the version.
/// </summary>
public int Major { get { return _major; } }
/// <summary>
/// The minor component of the version.
/// </summary>
public int Minor { get { return _minor; } }
/// <summary>
/// The patch component of the version.
/// </summary>
public int Patch { get { return _patch; } }
/// <summary>
/// The pre-release string, or null for no pre-release version.
/// </summary>
public string PreRelease { get { return _preRelease; } }
/// <summary>
/// The build string, or null for no build version.
/// </summary>
public string Build { get {return _build; } }
private static Regex strictRegex = new Regex(@"^
\s*v?
(\d+) # major version
\.
(\d+) # minor version
\.
(\d+) # patch version
(\-([0-9A-Za-z\-\.]+))? # pre-release version
(\+([0-9A-Za-z\-\.]+))? # build metadata
\s*
$",
RegexOptions.IgnorePatternWhitespace);
private static Regex looseRegex = new Regex(@"^
[v=\s]*
(\d+) # major version
\.
(\d+) # minor version
\.
(\d+) # patch version
(\-?([0-9A-Za-z\-\.]+))? # pre-release version
(\+([0-9A-Za-z\-\.]+))? # build metadata
\s*
$",
RegexOptions.IgnorePatternWhitespace);
/// <summary>
/// Construct a new semantic version from a version string.
/// </summary>
/// <param name="input">The version string.</param>
/// <param name="loose">When true, be more forgiving of some invalid version specifications.</param>
/// <exception cref="System.ArgumentException">Thrown when the version string is invalid.</exception>
public Version(string input, bool loose=false)
{
_inputString = input;
var regex = loose ? looseRegex : strictRegex;
var match = regex.Match(input);
if (!match.Success)
{
throw new ArgumentException(String.Format("Invalid version string: {0}", input));
}
_major = Int32.Parse(match.Groups[1].Value);
_minor = Int32.Parse(match.Groups[2].Value);
_patch = Int32.Parse(match.Groups[3].Value);
if (match.Groups[4].Success)
{
var inputPreRelease = match.Groups[5].Value;
var cleanedPreRelease = PreReleaseVersion.Clean(inputPreRelease);
if (!loose && inputPreRelease != cleanedPreRelease)
{
throw new ArgumentException(String.Format(
"Invalid pre-release version: {0}", inputPreRelease));
}
_preRelease = cleanedPreRelease;
}
if (match.Groups[6].Success)
{
_build = match.Groups[7].Value;
}
}
/// <summary>
/// Construct a new semantic version from version components.
/// </summary>
/// <param name="major">The major component of the version.</param>
/// <param name="minor">The minor component of the version.</param>
/// <param name="patch">The patch component of the version.</param>
/// <param name="preRelease">The pre-release version string, or null for no pre-release version.</param>
/// <param name="build">The build version string, or null for no build version.</param>
public Version(int major, int minor, int patch,
string preRelease = null, string build = null)
{
_major = major;
_minor = minor;
_patch = patch;
_preRelease = preRelease;
_build = build;
}
/// <summary>
/// Returns this version without any pre-release or build version.
/// </summary>
/// <returns>The base version</returns>
public Version BaseVersion()
{
return new Version(Major, Minor, Patch);
}
/// <summary>
/// Returns the original input string the version was constructed from or
/// the cleaned version if the version was constructed from version components.
/// </summary>
/// <returns>The version string</returns>
public override string ToString()
{
return _inputString ?? Clean();
}
/// <summary>
/// Return a cleaned, normalised version string.
/// </summary>
/// <returns>The cleaned version string.</returns>
public string Clean()
{
var preReleaseString = PreRelease == null ? ""
: String.Format("-{0}", PreReleaseVersion.Clean(PreRelease));
var buildString = Build == null ? ""
: String.Format("+{0}", Build);
return String.Format("{0}.{1}.{2}{3}{4}",
Major, Minor, Patch, preReleaseString, buildString);
}
/// <summary>
/// Calculate a hash code for the version.
/// </summary>
public override int GetHashCode()
{
// The build version isn't included when calculating the hash,
// as two versions with equal properties except for the build
// are considered equal.
unchecked // Allow integer overflow with wrapping
{
int hash = 17;
hash = hash * 23 + Major.GetHashCode();
hash = hash * 23 + Minor.GetHashCode();
hash = hash * 23 + Patch.GetHashCode();
if (PreRelease != null)
{
hash = hash * 23 + PreRelease.GetHashCode();
}
return hash;
}
}
// Implement IEquatable<Version>
/// <summary>
/// Test whether two versions are semantically equivalent.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(Version other)
{
if (ReferenceEquals(other, null))
{
return false;
}
return CompareTo(other) == 0;
}
// Implement IComparable<Version>
public int CompareTo(Version other)
{
if (ReferenceEquals(other, null))
{
return 1;
}
foreach (var c in PartComparisons(other))
{
if (c != 0)
{
return c;
}
}
return PreReleaseVersion.Compare(this.PreRelease, other.PreRelease);
}
private IEnumerable<int> PartComparisons(Version other)
{
yield return Major.CompareTo(other.Major);
yield return Minor.CompareTo(other.Minor);
yield return Patch.CompareTo(other.Patch);
}
public override bool Equals(object other)
{
return Equals(other as Version);
}
public static bool operator ==(Version a, Version b)
{
if (ReferenceEquals(a, null))
{
return ReferenceEquals(b, null);
}
return a.Equals(b);
}
public static bool operator !=(Version a, Version b)
{
return !(a == b);
}
public static bool operator >(Version a, Version b)
{
if (ReferenceEquals(a, null))
{
return false;
}
return a.CompareTo(b) > 0;
}
public static bool operator >=(Version a, Version b)
{
if (ReferenceEquals(a, null))
{
return ReferenceEquals(b, null) ? true : false;
}
return a.CompareTo(b) >= 0;
}
public static bool operator <(Version a, Version b)
{
if (ReferenceEquals(a, null))
{
return ReferenceEquals(b, null) ? false : true;
}
return a.CompareTo(b) < 0;
}
public static bool operator <=(Version a, Version b)
{
if (ReferenceEquals(a, null))
{
return true;
}
return a.CompareTo(b) <= 0;
}
}
}
| 32.414035 | 112 | 0.497077 | [
"MIT"
] | TommasoPieroncini/semver.net | src/SemVer/Version.cs | 9,240 | C# |
/*
* Copyright (c) 2019 Robotic Eyes GmbH software
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace RoboticEyes.Rex.RexFileReader
{
/**
* Data block which allows to specify a 3D mesh
*/
public class RexDataMesh : RexDataBlock
{
private const byte SizeLod = 2;
private const byte SizeMaxLod = 2;
private const byte SizeNrOfVtxCoords = 4;
private const byte SizeNrOfNorCoords = 4;
private const byte SizeNrOfTexCoords = 4;
private const byte SizeNrOfVtxColors = 4;
private const byte SizeNrTriangles = 4;
private const byte SizeStartVtxCoords = 4;
private const byte SizeStartNorCoords = 4;
private const byte SizeStartTexCoords = 4;
private const byte SizeStartVtxColors = 4;
private const byte SizeStartTriangles = 4;
private const byte SizeMaterialId = 8;
private const byte SizeNameSize = 2;
private const byte SizeName = 74;
public ushort lod;
public ushort maxLod;
public List<Vector3> vertexCoordinates; //!< 3D coordinates of all vertices unit meters [#vtx:3]
public List<Vector3> normalVectors;
public List<Vector2> textureCoordinates; //!< 2D texture coordinates between 0 and 1 [#tex:2]
public List<Color> vertexColors; //!< color for each vertex
public int[] vertexTriangles; //!< vetex indices that define triangles [#triangles:3]
public ulong materialId; //!< materialId which refers to a MeshMaterialStandard block
public string name; //!< name of the mesh
#region WRITE
public RexDataMesh (string name, ushort lod, ushort maxLod,
List<Vector3> vertexCoordinates,
List<Vector3> normalVectors,
List<Vector2> textureCoordinates,
List<Color> vertexColors,
int[] vertexTriangles,
ulong materialId)
{
type = RexDataBlockType.Mesh;
this.name = name;
this.lod = lod;
this.maxLod = maxLod;
this.vertexCoordinates = vertexCoordinates;
this.normalVectors = normalVectors;
this.textureCoordinates = textureCoordinates;
this.vertexColors = vertexColors;
this.vertexTriangles = vertexTriangles;
this.materialId = materialId;
}
protected override byte[] GetBlockBytes ()
{
List<byte> data = new List<byte> ();
data.AddRange (BitConverter.GetBytes (lod) );
data.AddRange (BitConverter.GetBytes (maxLod) );
data.AddRange (BitConverter.GetBytes (vertexCoordinates.Count) );
data.AddRange (BitConverter.GetBytes (normalVectors.Count) );
data.AddRange (BitConverter.GetBytes (textureCoordinates.Count) );
data.AddRange (BitConverter.GetBytes (vertexColors.Count) );
data.AddRange (BitConverter.GetBytes (vertexTriangles.Length / 3) );
// calculate block positions in resulting block
byte[] nameBytes = Encoding.ASCII.GetBytes (name);
ushort nameLength = (ushort) nameBytes.Length;
int offset = DataBlockHeaderSize + (2 * sizeof (ushort) ) + (5 * sizeof (int) ) + (5 * sizeof (int) ) + sizeof (ulong) + sizeof (ushort) + SizeNameSize + SizeName;
data.AddRange (BitConverter.GetBytes (offset) );
offset += vertexCoordinates.Count * 3 * sizeof (float);
data.AddRange (BitConverter.GetBytes (offset) );
offset += normalVectors.Count * 3 * sizeof (float);
data.AddRange (BitConverter.GetBytes (offset) );
offset += textureCoordinates.Count * 2 * sizeof (float);
data.AddRange (BitConverter.GetBytes (offset) );
offset += vertexColors.Count * 3 * sizeof (float);
data.AddRange (BitConverter.GetBytes (offset) );
offset += vertexTriangles.Length * sizeof (uint);
// metadata
data.AddRange (BitConverter.GetBytes (materialId) );
data.AddRange (BitConverter.GetBytes (nameLength) );
data.AddRange (nameBytes);
for (int i = nameLength; i < SizeName; i++)
{
data.Add (0);
}
// add mesh data
data.AddRange (Utils.BytesFromVector3List (vertexCoordinates) );
data.AddRange (Utils.BytesFromVector3List (normalVectors) );
data.AddRange (Utils.BytesFromVector2List (textureCoordinates) );
data.AddRange (Utils.BytesFromColorList (vertexColors) );
foreach (var index in Utils.FlipTriangles (vertexTriangles) )
{
data.AddRange (BitConverter.GetBytes (index) );
}
return data.ToArray ();
}
#endregion
#region READ
public RexDataMesh (byte[] buffer, int offset) : base (buffer, ref offset)
{
lod = BitConverter.ToUInt16 (buffer, offset);
offset += SizeLod;
maxLod = BitConverter.ToUInt16 (buffer, offset);
offset += SizeMaxLod;
UInt32 nrVertices = BitConverter.ToUInt32 (buffer, offset);
offset += SizeNrOfVtxCoords;
UInt32 nrNormals = BitConverter.ToUInt32 (buffer, offset);
offset += SizeNrOfNorCoords;
UInt32 nrTextureCoords = BitConverter.ToUInt32 (buffer, offset);
offset += SizeNrOfTexCoords;
UInt32 nrVertexColors = BitConverter.ToUInt32 (buffer, offset);
offset += SizeNrOfVtxColors;
UInt32 nrTriangles = BitConverter.ToUInt32 (buffer, offset);
offset += SizeNrTriangles;
//startVtxCoords
offset += SizeStartVtxCoords;
//startNorCoords
offset += SizeStartNorCoords;
//startTexCoords
offset += SizeStartTexCoords;
//startVtxColors
offset += SizeStartVtxColors;
//startTriangles
offset += SizeStartTriangles;
materialId = BitConverter.ToUInt64 (buffer, offset);
offset += SizeMaterialId;
UInt16 sz = BitConverter.ToUInt16 (buffer, offset);
offset += SizeNameSize;
name = Encoding.ASCII.GetString (buffer, offset, sz);
offset += SizeName;
offset += FillVertexCoords (buffer, offset, (int) nrVertices);
offset += FillVertexNormals (buffer, offset, (int) nrNormals);
offset += FillTextureCoords (buffer, offset, (int) nrTextureCoords);
offset += FillVertexColors (buffer, offset, (int) nrVertexColors);
offset += FillVertexTriangles (buffer, offset, (int) nrTriangles);
}
private int FillVertexCoords (byte[] buffer, int offset, int nrVertices)
{
int sizeOfVerticesBlock = nrVertices * 3 * sizeof (float);
vertexCoordinates = Utils.Vector3ListFromArray (buffer, offset, sizeOfVerticesBlock);
return sizeOfVerticesBlock;
}
private int FillVertexNormals (byte[] buffer, int offset, int nrNormals)
{
int sizeOfNormalsBlock = nrNormals * 3 * sizeof (float);
normalVectors = Utils.Vector3ListFromArray (buffer, offset, sizeOfNormalsBlock);
return sizeOfNormalsBlock;
}
private int FillTextureCoords (byte[] buffer, int offset, int nrTextureCoords)
{
int sizeOfTextureCoordsBlock = nrTextureCoords * 2 * sizeof (float);
textureCoordinates = Utils.Vector2ListFromArray (buffer, offset, sizeOfTextureCoordsBlock);
return sizeOfTextureCoordsBlock;
}
private int FillVertexColors (byte[] buffer, int offset, int nrColors)
{
int sizeOfVertexColorsBlock = nrColors * 3 * sizeof (float);
vertexColors = Utils.ColorListFromArray (buffer, offset, sizeOfVertexColorsBlock);
return sizeOfVertexColorsBlock;
}
private int FillVertexTriangles (byte[] buffer, int offset, int nrTriangles)
{
int sizeOfTrianglessBlock = nrTriangles * 3 * sizeof (UInt32);
vertexTriangles = new int[nrTriangles * 3];
Buffer.BlockCopy (buffer, offset, vertexTriangles, 0, sizeOfTrianglessBlock);
return sizeOfTrianglessBlock;
}
#endregion
}
}
| 38.448276 | 175 | 0.606726 | [
"Apache-2.0"
] | alexanderzimmerman/upm-rex-rexfile-io | Assets/package/Runtime/RexFileReader/DataBlocks/RexDataMesh.cs | 8,922 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HashTableNamespace
{
/// <summary>
/// interface for hashfunction
/// </summary>
public interface IHashFunction
{
/// <summary>
/// make hash function
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
int HashFunction(string element);
}
}
| 21.045455 | 42 | 0.606911 | [
"Apache-2.0"
] | Vinogradov-Mikhail/University-part2 | 3_2/3_2/IHashFunction.cs | 465 | C# |
using System.Web.Mvc;
using EssentialTools.Models;
namespace EssentialTools.Controllers {
public class HomeController : Controller {
private IValueCalculator calc;
private Product[] products = {
new Product {Name = "Kayak", Category = "Watersports", Price = 275M},
new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95M},
new Product {Name = "Soccer ball", Category = "Soccer", Price = 19.50M},
new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M}
};
public HomeController(IValueCalculator calcParam, IValueCalculator calc2) {
calc = calcParam;
}
public ActionResult Index() {
ShoppingCart cart = new ShoppingCart(calc) { Products = products };
decimal totalValue = cart.CalculateProductTotal();
return View(totalValue);
}
}
}
| 32.206897 | 88 | 0.611349 | [
"MIT"
] | hwebz/pro-aspnet-mvc-5-fifth-edition | pro-asp.net-mvc-5/Chapter 06/EssentialTools/EssentialTools/Controllers/HomeController.cs | 936 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.