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 |
|---|---|---|---|---|---|---|---|---|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.Rds.Inputs
{
public sealed class OptionGroupOptionArgs : Pulumi.ResourceArgs
{
[Input("dbSecurityGroupMemberships")]
private InputList<string>? _dbSecurityGroupMemberships;
/// <summary>
/// A list of DB Security Groups for which the option is enabled.
/// </summary>
public InputList<string> DbSecurityGroupMemberships
{
get => _dbSecurityGroupMemberships ?? (_dbSecurityGroupMemberships = new InputList<string>());
set => _dbSecurityGroupMemberships = value;
}
/// <summary>
/// The Name of the Option (e.g., MEMCACHED).
/// </summary>
[Input("optionName", required: true)]
public Input<string> OptionName { get; set; } = null!;
[Input("optionSettings")]
private InputList<Inputs.OptionGroupOptionOptionSettingArgs>? _optionSettings;
/// <summary>
/// A list of option settings to apply.
/// </summary>
public InputList<Inputs.OptionGroupOptionOptionSettingArgs> OptionSettings
{
get => _optionSettings ?? (_optionSettings = new InputList<Inputs.OptionGroupOptionOptionSettingArgs>());
set => _optionSettings = value;
}
/// <summary>
/// The Port number when connecting to the Option (e.g., 11211).
/// </summary>
[Input("port")]
public Input<int>? Port { get; set; }
/// <summary>
/// The version of the option (e.g., 13.1.0.0).
/// </summary>
[Input("version")]
public Input<string>? Version { get; set; }
[Input("vpcSecurityGroupMemberships")]
private InputList<string>? _vpcSecurityGroupMemberships;
/// <summary>
/// A list of VPC Security Groups for which the option is enabled.
/// </summary>
public InputList<string> VpcSecurityGroupMemberships
{
get => _vpcSecurityGroupMemberships ?? (_vpcSecurityGroupMemberships = new InputList<string>());
set => _vpcSecurityGroupMemberships = value;
}
public OptionGroupOptionArgs()
{
}
}
}
| 33.864865 | 117 | 0.616919 | [
"ECL-2.0",
"Apache-2.0"
] | RafalSumislawski/pulumi-aws | sdk/dotnet/Rds/Inputs/OptionGroupOptionArgs.cs | 2,506 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VonMisesMaterial3D.cs" company="National Technical University of Athens">
// To be decided
// </copyright>
// <summary>
// Class for 3D Von Mises materials.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ISAAR.MSolve.PreProcessor.Materials
{
#region
using System;
using MSolve.PreProcessor.Interfaces;
using MSolve.Matrices.Interfaces;
using MSolve.Matrices;
#endregion
/// <summary>
/// Class for 3D Von Mises materials.
/// </summary>
/// <a href = "http://en.wikipedia.org/wiki/Von_Mises_yield_criterion">Wikipedia -Von Mises yield criterion</a>
public class VonMisesMaterial3D : IFiniteElementMaterial3D
{
/// <summary>
/// The Poisson ratio value of an incompressible solid.
/// </summary>
private const double PoissonRatioForIncompressibleSolid = 0.5;
/// <summary>
/// The total number of strains.
/// </summary>
private const int TotalStrains = 6;
/// <summary>
/// The total number of stresses.
/// </summary>
private const int TotalStresses = TotalStrains;
/// <summary>
/// An array needed for the formulation of the consistent constitutive matrix.
/// </summary>
private static readonly double[,] SupportiveMatrixForConsistentConstitutiveMatrix = new[,]
{
{
0, -1, -1, 0, 0, 0
}, {
-1, 0, -1, 0, 0, 0,
}, {
-1, -1, 0, 0, 0, 0
}, {
0, 0, 0, 0.5, 0, 0
},
{
0, 0, 0, 0, 0.5, 0
}, {
0, 0, 0, 0, 0, 0.5
}
};
/// <summary>
/// The constitutive matrix of the material while still in the elastic region.
/// </summary>
private readonly double[,] elasticConstitutiveMatrix;
/// <summary>
/// Hardening modulus for linear hardening.
/// </summary>
private readonly double hardeningRatio;
/// <summary>
/// The Poisson ratio.
/// </summary>
/// <remarks>
/// <a href = "http://en.wikipedia.org/wiki/Poisson%27s_ratio">Wikipedia - Poisson's Ratio</a>
/// </remarks>
private double poissonRatio;
/// <summary>
/// The shear modulus.
/// </summary>
/// <remarks>
/// <a href = "http://en.wikipedia.org/wiki/Shear_modulus">Wikipedia - Shear Modulus</a>
/// </remarks>
private readonly double shearModulus;
/// <summary>
/// The yields stress.
/// </summary>
/// <remarks>
/// <a href = "http://en.wikipedia.org/wiki/Yield_%28engineering%29">Yield (engineering)</a>
/// The yield strength or yield point of a material is defined in engineering and materials science as the stress at which a material begins to deform plastically.
/// </remarks>
private readonly double yieldStress;
/// <summary>
/// The young modulus.
/// </summary>
/// <remarks>
/// <a href = "http://en.wikipedia.org/wiki/Young%27s_modulus">Wikipedia - Young's Modulus</a>
/// </remarks>
private double youngModulus;
/// <summary>
/// The constitutive matrix of the material.
/// </summary>
private double[,] constitutiveMatrix;
/// <summary>
/// The array of incremental strains.
/// </summary>
/// <remarks>
/// <a href = "http://en.wikipedia.org/wiki/Deformation_%28engineering%29">Deformation (engineering)</a>
/// </remarks>
private double[] incrementalStrains = new double[6];
/// <summary>
/// Indicates whether this <see cref = "IFiniteElementMaterial" /> is modified.
/// </summary>
private bool modified;
/// <summary>
/// The current plastic strain.
/// </summary>
private double plasticStrain;
/// <summary>
/// The new plastic strain.
/// </summary>
private double plasticStrainNew;
/// <summary>
/// The array of stresses.
/// </summary>
private double[] stresses = new double[6];
/// <summary>
/// The array of new stresses.
/// </summary>
private double[] stressesNew = new double[6];
/// <summary>
/// Initializes a new instance of the <see cref = "VonMisesMaterial3D" /> class.
/// </summary>
/// <param name = "youngModulus">
/// The young modulus.
/// </param>
/// <param name = "poissonRatio">
/// The Poisson ratio.
/// </param>
/// <param name = "yieldStress">
/// The yield stress.
/// </param>
/// <param name = "hardeningRatio">
/// The hardening ratio.
/// </param>
/// <exception cref = "ArgumentException"> When Poisson ratio is equal to 0.5.</exception>
public VonMisesMaterial3D(double youngModulus, double poissonRatio, double yieldStress, double hardeningRatio)
{
this.youngModulus = youngModulus;
if (poissonRatio == PoissonRatioForIncompressibleSolid)
{
throw new ArgumentException(
"Poisson ratio cannot be" + PoissonRatioForIncompressibleSolid + "(incompressible solid)");
}
this.poissonRatio = poissonRatio;
this.yieldStress = yieldStress;
this.hardeningRatio = hardeningRatio;
this.shearModulus = this.YoungModulus / (2 * (1 + this.PoissonRatio));
double lamda = (youngModulus * poissonRatio) / ((1 + poissonRatio) * (1 - (2 * poissonRatio)));
double mi = youngModulus / (2 * (1 + poissonRatio));
double value1 = (2 * mi) + lamda;
this.elasticConstitutiveMatrix = new double[6, 6];
this.elasticConstitutiveMatrix[0, 0] = value1;
this.elasticConstitutiveMatrix[0, 1] = lamda;
this.elasticConstitutiveMatrix[0, 2] = lamda;
this.elasticConstitutiveMatrix[1, 0] = lamda;
this.elasticConstitutiveMatrix[1, 1] = value1;
this.elasticConstitutiveMatrix[1, 2] = lamda;
this.elasticConstitutiveMatrix[2, 0] = lamda;
this.elasticConstitutiveMatrix[2, 1] = lamda;
this.elasticConstitutiveMatrix[2, 2] = value1;
this.elasticConstitutiveMatrix[3, 3] = mi;
this.elasticConstitutiveMatrix[4, 4] = mi;
this.elasticConstitutiveMatrix[5, 5] = mi;
}
public double[] Coordinates { get; set; }
/// <summary>
/// Gets the constitutive matrix.
/// </summary>
/// <value>
/// The constitutive matrix.
/// </value>
public IMatrix2D<double> ConstitutiveMatrix
{
get
{
if (this.constitutiveMatrix == null)
{
this.UpdateMaterial(new double[6]);
}
return new Matrix2D<double>(this.constitutiveMatrix);
}
}
/// <summary>
/// Gets the ID of the material.
/// </summary>
/// <value>
/// The id.
/// </value>
public int ID
{
get
{
return 1;
}
}
/// <summary>
/// Gets the incremental strains of the finite element's material.
/// </summary>
/// <value>
/// The incremental strains.
/// </value>
/// <remarks>
/// <a href = "http://en.wikipedia.org/wiki/Deformation_%28engineering%29">Deformation (engineering)</a>
/// </remarks>
public double[] IncrementalStrains
{
get
{
return this.incrementalStrains;
}
}
/// <summary>
/// Gets a value indicating whether this <see cref = "IFiniteElementMaterial" /> is modified.
/// </summary>
/// <value>
/// <c>true</c> if modified; otherwise, <c>false</c>.
/// </value>
public bool Modified
{
get
{
return this.modified;
}
}
/// <summary>
/// Gets the plastic strain.
/// </summary>
/// <value>
/// The plastic strain.
/// </value>
public double PlasticStrain
{
get
{
return this.plasticStrain;
}
}
/// <summary>
/// Gets the Poisson ratio.
/// </summary>
/// <value>
/// The Poisson ratio.
/// </value>
/// <remarks>
/// <a href = "http://en.wikipedia.org/wiki/Poisson%27s_ratio">Wikipedia - Poisson's Ratio</a>
/// </remarks>
public double PoissonRatio
{
get
{
return this.poissonRatio;
}
set
{
this.poissonRatio = value;
}
}
/// <summary>
/// Gets the stresses of the finite element's material.
/// </summary>
/// <value>
/// The stresses.
/// </value>
/// <remarks>
/// <a href = "http://en.wikipedia.org/wiki/Stress_%28mechanics%29">Stress (mechanics)</a>
/// </remarks>
public double[] Stresses
{
get
{
return this.stressesNew;
}
}
/// <summary>
/// Gets the Young's Modulus.
/// </summary>
/// <value>
/// The young modulus.
/// </value>
/// <remarks>
/// <a href = "http://en.wikipedia.org/wiki/Young%27s_modulus">Wikipedia - Young's Modulus</a>
/// </remarks>
public double YoungModulus
{
get
{
return this.youngModulus;
}
set
{
this.youngModulus = value;
}
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public object Clone()
{
var strainsCopy = new double[incrementalStrains.Length];
Array.Copy(incrementalStrains, strainsCopy, incrementalStrains.Length);
var stressesCopy = new double[stresses.Length];
Array.Copy(stresses, stressesCopy, stresses.Length);
VonMisesMaterial3D m = new VonMisesMaterial3D(
this.youngModulus, this.poissonRatio, this.yieldStress, this.hardeningRatio)
{
modified = this.Modified,
plasticStrain = this.plasticStrain,
incrementalStrains = strainsCopy,
stresses = stressesCopy
};
return m;
}
/// <summary>
/// Resets the indicator of whether the material is modified.
/// </summary>
public void ResetModified()
{
this.modified = false;
}
/// <summary>
/// Clears the stresses of the element's material.
/// </summary>
public void ClearStresses()
{
Array.Clear(this.stresses, 0, 6);
Array.Clear(this.stressesNew, 0, 6);
}
public void ClearState()
{
modified = false;
Array.Clear(constitutiveMatrix, 0, constitutiveMatrix.Length);
Array.Clear(incrementalStrains, 0, incrementalStrains.Length);
Array.Clear(stresses, 0, stresses.Length);
Array.Clear(stressesNew, 0, stressesNew.Length);
plasticStrain = 0;
plasticStrainNew = 0;
}
/// <summary>
/// Saves the state of the element's material.
/// </summary>
public void SaveState()
{
this.plasticStrain = this.plasticStrainNew;
Array.Copy(this.stressesNew, this.stresses, 6);
//this.stresses = this.stressesNew.DeepClone();
}
/// <summary>
/// Updates the element's material with the provided incremental strains.
/// </summary>
/// <param name = "strainsIncrement">The incremental strains to use for the next step.</param>
public void UpdateMaterial(double[] strainsIncrement)
{
Array.Copy(strainsIncrement, this.incrementalStrains, 6);
//this.incrementalStrains = strainsIncrement.DeepClone();
this.CalculateNextStressStrainPoint();
}
/// <summary>
/// Builds the consistent tangential constitutive matrix.
/// </summary>
/// <param name = "value1"> This is a constant already calculated in the calling method. </param>
/// <remarks>
/// We need an additional constant here equal to: 2*G*G*deltaPlasticStrain*sqrt(3/J2elastic)
/// Since value1 is already calculated, the additional constant can be calculated through it:
/// value3 = 2 * G * value1;
/// </remarks>
private void BuildConsistentTangentialConstitutiveMatrix(double value1)
{
this.constitutiveMatrix = new double[TotalStresses, TotalStrains];
double invariantJ2New = this.GetDeviatorSecondStressInvariant(stressesNew);
double value2 = (3 * this.shearModulus * this.shearModulus) /
((this.hardeningRatio + (3 * this.shearModulus)) * invariantJ2New);
double value3 = 2 * this.shearModulus * value1;
double value4 = 0.5 / invariantJ2New;
var stressDeviator = this.GetStressDeviator(stressesNew);
for (int k1 = 0; k1 < TotalStresses; k1++)
{
for (int k2 = 0; k2 < TotalStresses; k2++)
{
this.constitutiveMatrix[k2, k1] = this.elasticConstitutiveMatrix[k2, k1] -
(value2 * stressDeviator[k2] * stressDeviator[k1]) -
(value3 *
(SupportiveMatrixForConsistentConstitutiveMatrix[k2, k1] -
(value4 * stressDeviator[k2] * stressDeviator[k1])));
}
}
}
/// <summary>
/// Builds the tangential constitutive matrix.
/// </summary>
private void BuildTangentialConstitutiveMatrix()
{
this.constitutiveMatrix = new double[TotalStresses, TotalStrains];
double invariantJ2New = this.GetDeviatorSecondStressInvariant(stressesNew);
double value2 = (3 * this.shearModulus * this.shearModulus) /
((this.hardeningRatio + (3 * this.shearModulus)) * invariantJ2New);
var stressDeviator = this.GetStressDeviator(stressesNew);
for (int k1 = 0; k1 < TotalStresses; k1++)
{
for (int k2 = 0; k2 < TotalStresses; k2++)
{
this.constitutiveMatrix[k2, k1] = this.elasticConstitutiveMatrix[k2, k1] -
(value2 * stressDeviator[k2] * stressDeviator[k1]);
}
}
}
/// <summary>
/// Calculates the next stress-strain point.
/// </summary>
/// <exception cref = "InvalidOperationException"> When the new plastic strain is less than the previous one.</exception>
private void CalculateNextStressStrainPoint()
{
var stressesElastic = new double[6];
for (int i = 0; i < 6; i++)
{
stressesElastic[i] = this.stresses[i];
for (int j = 0; j < 6; j++)
stressesElastic[i] += this.elasticConstitutiveMatrix[i, j] * this.incrementalStrains[j];
}
double invariantJ2Elastic = this.GetDeviatorSecondStressInvariant(stressesElastic);
double vonMisesStress = Math.Sqrt(3 * invariantJ2Elastic);
double vonMisesStressMinusYieldStress = vonMisesStress -
(this.yieldStress + (this.hardeningRatio * this.plasticStrain));
bool materialIsInElasticRegion = vonMisesStressMinusYieldStress <= 0;
if (materialIsInElasticRegion)
{
this.stressesNew = stressesElastic;
this.constitutiveMatrix = this.elasticConstitutiveMatrix;
this.plasticStrainNew = this.plasticStrain;
}
else
{
double deltaPlasticStrain = vonMisesStressMinusYieldStress /
((3 * this.shearModulus) + this.hardeningRatio);
this.plasticStrainNew = this.plasticStrain + deltaPlasticStrain;
// 2.0 and 1/2 cancel out
double value1 = this.shearModulus * deltaPlasticStrain * Math.Sqrt(3 / invariantJ2Elastic);
var stressDeviatorElastic = this.GetStressDeviator(stressesElastic);
for (int i = 0; i < 6; i++)
this.stressesNew[i] = stressesElastic[i] - (value1 * stressDeviatorElastic[i]);
//this.BuildConsistentTangentialConstitutiveMatrix(value1);
this.BuildTangentialConstitutiveMatrix();
}
if (Math.Abs(this.plasticStrainNew) < Math.Abs(this.plasticStrain))
{
throw new InvalidOperationException("Plastic strain cannot decrease.");
}
this.modified = this.plasticStrainNew != this.plasticStrain;
}
/// <summary>
/// Calculates and returns the first stress invariant (I1).
/// </summary>
/// <returns> The first stress invariant (I1).</returns>
public double GetFirstStressInvariant(double[] stresses)
{
return stresses[0] + stresses[1] + stresses[2];
}
/// <summary>
/// Calculates and returns the mean hydrostatic stress.
/// </summary>
/// <returns> The mean hydrostatic stress.</returns>
public double GetMeanStress(double[] stresses)
{
double i1 = this.GetFirstStressInvariant(stresses);
double mean = i1 / 3;
return mean;
}
/// <summary>
/// Calculates and returns the second stress invariant (I2).
/// </summary>
/// <returns> The second stress invariant (I2).</returns>
public double GetSecondStressInvariant(double[] stresses)
{
return (stresses[0] * stresses[1]) + (stresses[1] * stresses[2]) + (stresses[0] * stresses[2]) - Math.Pow(stresses[5], 2) -
Math.Pow(stresses[3], 2) - Math.Pow(stresses[4], 2);
}
/// <summary>
/// Calculates and returns the stress deviator tensor in vector form.
/// </summary>
/// <returns> The stress deviator tensor in vector form.</returns>
public double[] GetStressDeviator(double[] stresses)
{
var hydrostaticStress = this.GetMeanStress(stresses);
var stressDeviator = new double[]
{
stresses[0] - hydrostaticStress,
stresses[1] - hydrostaticStress,
stresses[2] - hydrostaticStress,
stresses[3],
stresses[4],
stresses[5]
};
return stressDeviator;
}
/// <summary>
/// Calculates and returns the third stress invariant (I3).
/// </summary>
/// <returns> The third stress invariant (I3). </returns>
public double GetThirdStressInvariant(double[] stresses)
{
return (stresses[0] * stresses[1] * stresses[2]) + (2 * stresses[5] * stresses[3] * stresses[4]) - (Math.Pow(stresses[5], 2) * stresses[2]) -
(Math.Pow(stresses[3], 2) * stresses[0]) - (Math.Pow(stresses[4], 2) * stresses[1]);
}
/// <summary>
/// Returns the first stress invariant of the stress deviator tensor (J1), which is zero.
/// </summary>
/// <returns> The first stress invariant of the stress deviator tensor (J1). </returns>
public double GetDeviatorFirstStressInvariant(double[] stresses)
{
return 0;
}
/// <summary>
/// Calculates and returns the second stress invariant of the stress deviator tensor (J2).
/// </summary>
/// <returns> The second stress invariant of the stress deviator tensor (J2). </returns>
public double GetDeviatorSecondStressInvariant(double[] stresses)
{
double i1 = this.GetFirstStressInvariant(stresses);
double i2 = this.GetSecondStressInvariant(stresses);
double j2 = (1 / 3d * Math.Pow(i1, 2)) - i2;
return j2;
}
/// <summary>
/// Calculates and returns the third stress invariant of the stress deviator tensor (J3).
/// </summary>
/// <returns> The third deviator stress invariant (J3). </returns>
public double GetDeviatorThirdStressInvariant(double[] stresses)
{
double i1 = this.GetFirstStressInvariant(stresses);
double i2 = this.GetSecondStressInvariant(stresses);
double i3 = this.GetThirdStressInvariant(stresses);
double j3 = (2 / 27 * Math.Pow(i1, 3)) - (1 / 3 * i1 * i2) + i3;
return j3;
}
}
} | 36.672668 | 173 | 0.519971 | [
"Apache-2.0"
] | Ambros21/MSolve | ISAAR.MSolve.PreProcessor/Materials/VonMisesMaterial3D.cs | 22,409 | C# |
using System;
using Unity.Entities;
namespace Reese.Utility
{
[Serializable]
public struct StickyFailed : IComponentData { }
}
| 15.111111 | 51 | 0.735294 | [
"MIT"
] | 0x6c23/ReeseUnityDemos | Packages/com.reese.utility/TransformExtensions/Sticky/StickyFailed.cs | 136 | C# |
using Neo.IO;
using System.IO;
namespace Neo.Ledger
{
public class StorageItem : ICloneable<StorageItem>, ISerializable
{
public byte[] Value;
public bool IsConstant;
public int Size => Value.GetVarSize() + sizeof(bool);
StorageItem ICloneable<StorageItem>.Clone()
{
return new StorageItem
{
Value = Value,
IsConstant = IsConstant
};
}
public void Deserialize(BinaryReader reader)
{
Value = reader.ReadVarBytes();
IsConstant = reader.ReadBoolean();
}
void ICloneable<StorageItem>.FromReplica(StorageItem replica)
{
Value = replica.Value;
IsConstant = replica.IsConstant;
}
public void Serialize(BinaryWriter writer)
{
writer.WriteVarBytes(Value);
writer.Write(IsConstant);
}
}
}
| 23.341463 | 69 | 0.549634 | [
"MIT"
] | Geo-Smart-Eco/geo | neo/Ledger/StorageItem.cs | 957 | C# |
/*<FILE_LICENSE>
* NFX (.NET Framework Extension) Unistack Library
* Copyright 2003-2018 Agnicore Inc. portions ITAdapter Corp. 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.
</FILE_LICENSE>*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace NFX.WinForms.Controls
{
/// <summary>
/// A ComboBox that allows to specify the color of the control.
/// Note that the ForeColor of the parent ComboBox only paints the drop-down list
/// but not the face color of the ComboBox itself.
/// </summary>
public class ComboBoxEx : ComboBox
{
public ComboBoxEx()
{
base.DrawMode = DrawMode.OwnerDrawFixed;
}
private Color m_HighlightColor = Color.Gray;
new public DrawMode DrawMode
{
get { return DrawMode.OwnerDrawFixed; }
set {}
}
[Browsable(true)]
public Color HighlightColor
{
get { return m_HighlightColor;}
set
{
m_HighlightColor = value;
Refresh();
}
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (e.Index < 0) return;
e.Graphics.FillRectangle(
(e.State & DrawItemState.Selected) == DrawItemState.Selected
? new SolidBrush(HighlightColor)
: new SolidBrush(this.BackColor),
e.Bounds);
e.Graphics.DrawString(Items[e.Index].ToString(), e.Font,
new SolidBrush(ForeColor),
new Point(e.Bounds.X, e.Bounds.Y));
e.DrawFocusRectangle();
base.OnDrawItem(e);
}
}
}
| 26.049383 | 83 | 0.656398 | [
"Apache-2.0"
] | agnicore/nfx | src/runtimes/netf/NFX.WinForms/Controls/ComboBoxEx.cs | 2,110 | C# |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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
namespace System.Web.Mvc
{
/// <summary>
/// MobileIndirectViewDirector
/// </summary>
public class MobileIndirectViewDirector : IndirectViewDirector
{
public MobileIndirectViewDirector()
: this(c => c.HttpContext.Request.Browser.IsMobileDevice) { }
public MobileIndirectViewDirector(Func<ControllerContext, bool> canIndirect)
: base(canIndirect)
{
ViewNameBuilder = (c, viewName) => "Mobile/" + viewName;
PartialViewNameBuilder = (c, partialViewName) => InsertTextAsParentOfLeaf(partialViewName, "Mobile");
}
private static string InsertTextAsParentOfLeaf(string text, string textToInsert)
{
var index = text.LastIndexOf('/');
return (index > -1 ? text.Substring(0, index) + "/" + textToInsert + text.Substring(index) : textToInsert + "/" + text);
}
}
} | 42.854167 | 133 | 0.706368 | [
"Apache-2.0",
"MIT"
] | Grimace1975/bclcontrib | Web/System.Web.MvcEx/Web/Mvc/MobileIndirectViewDirector.cs | 2,057 | C# |
using ChopShop2016.Commands.Drive;
using ChopShop2016.Commands.Intake;
using ChopShop2016.Commands.Shooter;
using WPILib.Commands;
namespace ChopShop2016.Commands.Autonomous
{
public class PositionTwoAuto : CommandGroup
{
public PositionTwoAuto()
{
AddSequential(new SetShooterSpeed(.9));
AddSequential(new MoveActuatorsDown(), 2);
AddSequential(new DriveDistance(.9, 70));
AddSequential(new RaiseRake());
AddSequential(new DriveDistance(.9, 50));
// AddSequential(new WaitCommand(1));
AddSequential(new TurnAngle(30));
// AddSequential(new DriveDistance(.7, 112));
AddSequential(new DriveDistance(.7, 10));
AddSequential(new MediumRangeShot());
// AddSequential(new ToggleDriveDirection());
}
}
}
| 33.384615 | 57 | 0.635945 | [
"MIT"
] | chopshop-166/frc-2016-cs | Commands/Autonomous/PositionTwoAuto.cs | 870 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace plilaServidor
{
class Persona
{
protected String Nombres;
protected String Apellido;
protected Sexo sexo;
protected int Edad;
private Persona puesto;
private List<string> historial;
public Persona(string nombres, string apellido, int edad)
{
Nombres = nombres;
Apellido = apellido;
this.Edad = edad;
}
public Persona(int numero)
{
puesto = new Persona(numero);
historial = new List<string>();
}
public string getNombre()
{
return Nombres;
}
public void setAlto(string nombre)
{
this.Nombres = nombre;
}
public string getApellido()
{
return Nombres;
}
public void setApellido(string apellido)
{
this.Apellido = apellido;
}
public Sexo getSexo()
{
return sexo;
}
public void setSexo(Sexo sexo)
{
this.sexo = sexo;
}
public int getEdad()
{
return Edad;
}
public void setEdad(int edad)
{
this.Edad = edad;
}
public override string ToString()
{
return sexo.ToString() + "Nombre " + Nombres + " Apellido " + Apellido + "" + Edad + sexo.ToString();
}
internal bool estaOcupado()
{
throw new NotImplementedException();
}
internal void getIndicePuesto()
{
throw new NotImplementedException();
}
}
enum Sexo
{
masculino, femenino
}
}
| 21.511905 | 113 | 0.494189 | [
"Apache-2.0"
] | danilo231/programacionIIItcd | examen3parcial/plilaServidor/plilaServidor/Persona.cs | 1,809 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Text;
using Elastic.Elasticsearch.Xunit.XunitPlumbing;
using Elastic.Transport;
using FluentAssertions;
using Nest;
namespace Tests.Reproduce
{
public class GithubIssue4013
{
[U]
public void CanDeserializeExtendedStats()
{
var json = @"{
""took"" : 1,
""timed_out"" : false,
""_shards"" : {
""total"" : 2,
""successful"" : 2,
""skipped"" : 0,
""failed"" : 0
},
""hits"" : {
""total"" : 1100,
""max_score"" : 0.0,
""hits"" : [ ]
},
""aggregations"": {
""extended_stats#1"": {
""count"": 3,
""min"": 1569521764937,
""max"": 1569526264937,
""avg"": 1569524464937,
""sum"": 4708573394811,
""min_as_string"": ""2019-09-26T18:16:04.937Z"",
""max_as_string"": ""2019-09-26T19:31:04.937Z"",
""avg_as_string"": ""2019-09-26T19:01:04.937Z"",
""sum_as_string"": ""2119-03-18T09:03:14.811Z"",
""sum_of_squares"": 7.390221138118668e+24,
""variance"": 3779929134421.3335,
""std_deviation"": 1944203.9847766317,
""std_deviation_bounds"": {
""upper"": 1569528353344.9695,
""lower"": 1569520576529.0305
},
""sum_of_squares_as_string"": ""292278994-08-17T07:12:55.807Z"",
""variance_as_string"": ""2089-10-12T04:18:54.421Z"",
""std_deviation_as_string"": ""1970-01-01T00:32:24.203Z"",
""std_deviation_bounds_as_string"": {
""upper"": ""2019-09-26T20:05:53.344Z"",
""lower"": ""2019-09-26T17:56:16.529Z""
}
}
}
}";
var bytes = Encoding.UTF8.GetBytes(json);
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings = new ConnectionSettings(pool, new InMemoryConnection(bytes));
var client = new ElasticClient(connectionSettings);
Action searchResponse = () => client.Search<object>(s => s.AllIndices());
searchResponse.Should().NotThrow();
var response = client.Search<object>(s => s.AllIndices());
var extendedStats = response.Aggregations.ExtendedStats("1");
extendedStats.Should().NotBeNull();
extendedStats.Count.Should().Be(3);
extendedStats.Min.Should().Be(1569521764937);
extendedStats.Max.Should().Be(1569526264937);
extendedStats.Average.Should().Be(1569524464937);
extendedStats.Sum.Should().Be(4708573394811);
extendedStats.SumOfSquares.Should().Be(7.390221138118668e+24);
extendedStats.Variance.Should().Be(3779929134421.3335);
extendedStats.StdDeviation.Should().Be(1944203.9847766317);
extendedStats.StdDeviationBounds.Should().NotBeNull();
extendedStats.StdDeviationBounds.Upper.Should().Be(1569528353344.9695);
extendedStats.StdDeviationBounds.Lower.Should().Be(1569520576529.0305);
}
}
}
| 35.134831 | 88 | 0.619444 | [
"Apache-2.0"
] | Jiasyuan/elasticsearch-net | tests/Tests.Reproduce/GitHubIssue4103.cs | 3,127 | C# |
// PsionicShieldBelt
using System.Collections.Generic;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.Sound;
[StaticConstructorOnStartup]
public class PsionicShieldBelt : Apparel
{
private const float MinDrawSize = 1.2f;
private const float MaxDrawSize = 1.55f;
private const float MaxDamagedJitterDist = 0.05f;
private const int JitterDurationTicks = 8;
private static readonly Material BubbleMat = MaterialPool.MatFrom("Other/ShieldBubble", ShaderDatabase.Transparent);
private readonly float ApparelScorePerEnergyMax = 0.25f;
private readonly float EnergyLossPerDamage = 0.033f;
private readonly float EnergyOnReset = 0.2f;
private readonly int KeepDisplayingTicks = 1000;
private readonly int StartingTicksToReset = 3200;
private float energy;
private Vector3 impactAngleVect;
private int lastAbsorbDamageTick = -9999;
private int lastKeepDisplayTick = -9999;
private int ticksToReset = -1;
private float EnergyMax => this.GetStatValue(StatDefOf.EnergyShieldEnergyMax);
private float EnergyGainPerTick => this.GetStatValue(StatDefOf.EnergyShieldRechargeRate) / 60f;
public float Energy => energy;
public ShieldState ShieldState
{
get
{
if (ticksToReset > 0)
{
return ShieldState.Resetting;
}
return ShieldState.Active;
}
}
private bool ShouldDisplay
{
get
{
var wearer = Wearer;
if (!wearer.Spawned || wearer.Dead || wearer.Downed)
{
return false;
}
if (wearer.InAggroMentalState)
{
return true;
}
if (wearer.Drafted)
{
return true;
}
if (wearer.Faction.HostileTo(Faction.OfPlayer) && !wearer.IsPrisoner)
{
return true;
}
if (Find.TickManager.TicksGame < lastKeepDisplayTick + KeepDisplayingTicks)
{
return true;
}
return false;
}
}
public override void ExposeData()
{
base.ExposeData();
Scribe_Values.Look(ref energy, "energy");
Scribe_Values.Look(ref ticksToReset, "ticksToReset", -1);
Scribe_Values.Look(ref lastKeepDisplayTick, "lastKeepDisplayTick");
}
public override IEnumerable<Gizmo> GetWornGizmos()
{
foreach (var gizmo in base.GetWornGizmos())
{
yield return gizmo;
}
if (Find.Selector.SingleSelectedThing == Wearer)
{
yield return new Gizmo_PsionicShieldStatus
{
shield = this
};
}
}
public override float GetSpecialApparelScoreOffset()
{
return EnergyMax * ApparelScorePerEnergyMax;
}
public override void Tick()
{
base.Tick();
if (Wearer == null)
{
energy = 0f;
}
else if (ShieldState == ShieldState.Resetting)
{
ticksToReset--;
if (ticksToReset <= 0)
{
Reset();
}
}
else if (ShieldState == ShieldState.Active)
{
energy += EnergyGainPerTick;
if (energy > EnergyMax)
{
energy = EnergyMax;
}
}
}
public override bool CheckPreAbsorbDamage(DamageInfo dinfo)
{
if (ShieldState != ShieldState.Active ||
(dinfo.Instigator == null || dinfo.Instigator.Position.AdjacentTo8WayOrInside(Wearer.Position)) &&
!dinfo.Def.isExplosive)
{
return false;
}
if (dinfo.Instigator is AttachableThing attachableThing && attachableThing.parent == Wearer)
{
return false;
}
energy -= dinfo.Amount * EnergyLossPerDamage;
if (dinfo.Def == DamageDefOf.EMP)
{
energy = -1f;
}
if (energy < 0f)
{
Break();
}
else
{
AbsorbedDamage(dinfo);
}
return true;
}
public void KeepDisplaying()
{
lastKeepDisplayTick = Find.TickManager.TicksGame;
}
private void AbsorbedDamage(DamageInfo dinfo)
{
SoundDefOf.EnergyShield_AbsorbDamage.PlayOneShot(new TargetInfo(Wearer.Position, Wearer.Map));
impactAngleVect = Vector3Utility.HorizontalVectorFromAngle(dinfo.Angle);
var loc = Wearer.TrueCenter() + (impactAngleVect.RotatedBy(180f) * 0.5f);
var num = Mathf.Min(10f, 2f + (dinfo.Amount / 10f));
FleckMaker.Static(loc, Wearer.Map, FleckDefOf.ExplosionFlash, num);
var num2 = (int) num;
for (var i = 0; i < num2; i++)
{
FleckMaker.ThrowDustPuff(loc, Wearer.Map, Rand.Range(0.8f, 1.2f));
}
lastAbsorbDamageTick = Find.TickManager.TicksGame;
KeepDisplaying();
}
private void Break()
{
SoundDefOf.EnergyShield_Broken.PlayOneShot(new TargetInfo(Wearer.Position, Wearer.Map));
FleckMaker.Static(Wearer.TrueCenter(), Wearer.Map, FleckDefOf.ExplosionFlash, 12f);
for (var i = 0; i < 6; i++)
{
var loc = Wearer.TrueCenter() +
(Vector3Utility.HorizontalVectorFromAngle(Rand.Range(0, 360)) * Rand.Range(0.3f, 0.6f));
FleckMaker.ThrowDustPuff(loc, Wearer.Map, Rand.Range(0.8f, 1.2f));
}
energy = 0f;
ticksToReset = StartingTicksToReset;
}
private void Reset()
{
if (Wearer.Spawned)
{
SoundDefOf.EnergyShield_Reset.PlayOneShot(new TargetInfo(Wearer.Position, Wearer.Map));
FleckMaker.ThrowLightningGlow(Wearer.TrueCenter(), Wearer.Map, 3f);
}
ticksToReset = -1;
energy = EnergyOnReset;
}
public override void DrawWornExtras()
{
if (ShieldState != ShieldState.Active || !ShouldDisplay)
{
return;
}
var num = Mathf.Lerp(MinDrawSize, MaxDrawSize, energy);
var vector = Wearer.Drawer.DrawPos;
vector.y = AltitudeLayer.MoteOverhead.AltitudeFor();
var num2 = Find.TickManager.TicksGame - lastAbsorbDamageTick;
if (num2 < JitterDurationTicks)
{
var num3 = (JitterDurationTicks - num2) / 8f * MaxDamagedJitterDist;
vector += impactAngleVect * num3;
num -= num3;
}
var angle = (float) Rand.Range(0, 360);
var s = new Vector3(num, 1f, num);
var matrix = default(Matrix4x4);
matrix.SetTRS(vector, Quaternion.AngleAxis(angle, Vector3.up), s);
Graphics.DrawMesh(MeshPool.plane10, matrix, BubbleMat, 0);
}
public override bool AllowVerbCast(Verb verb)
{
return true;
}
} | 26.906977 | 120 | 0.577355 | [
"MIT"
] | emipa606/MonstrousCompendium | Source/Illithid/PsionicShieldBelt.cs | 6,944 | C# |
using System.Threading;
using System.Threading.Tasks;
using Dynatrace.Net.Common.Extensions;
using Dynatrace.Net.Common.Models;
using Dynatrace.Net.Configuration.Services.Models;
using Flurl.Http;
// ReSharper disable once CheckNamespace
namespace Dynatrace.Net
{
public partial class DynatraceClient
{
private IFlurlRequest GetRequestNamingRulesUrl()
{
return GetBaseUrl()
.AppendPathSegment("config/v1/service/requestNaming");
}
public async Task<StubList> GetAllRequestNamingRulesAsync(CancellationToken cancellationToken = default)
{
var response = await GetRequestNamingRulesUrl()
.GetJsonWithErrorCheckingAsync<StubList>(cancellationToken)
.ConfigureAwait(false);
return response;
}
public async Task<RequestNaming> GetRequestNamingRuleAsync(string id, CancellationToken cancellationToken = default)
{
var response = await GetRequestNamingRulesUrl()
.AppendPathSegment(id)
.GetJsonWithErrorCheckingAsync<RequestNaming>(cancellationToken)
.ConfigureAwait(false);
return response;
}
public async Task<EntityShortRepresentation> CreateRequestNamingAsync(RequestNaming body = null, CancellationToken cancellationToken = default)
{
var response = await GetRequestNamingRulesUrl()
.PostJsonAsync(body, cancellationToken)
.ReceiveJsonWithErrorChecking<EntityShortRepresentation>()
.ConfigureAwait(false);
return response;
}
public async Task<bool> UpdateRequestNamingAsync(string id, RequestNaming body = null, CancellationToken cancellationToken = default)
{
var response = await GetRequestNamingRulesUrl()
.AppendPathSegment(id)
.PutJsonAsync(body, cancellationToken)
.ConfigureAwait(false);
return response.IsSuccessStatusCode;
}
public async Task<bool> DeleteRequestNamingAsync(string id, CancellationToken cancellationToken = default)
{
var response = await GetRequestNamingRulesUrl()
.AppendPathSegment(id)
.DeleteAsync(cancellationToken)
.ConfigureAwait(false);
return response.IsSuccessStatusCode;
}
}
}
| 30.753623 | 146 | 0.756362 | [
"MIT"
] | lvermeulen/Dynatrace.Net | src/Dynatrace.Net/Configuration/Services/RequestNaming/DynatraceClient.cs | 2,122 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ExoMerge.Documents;
namespace ExoMerge.UnitTests.Common
{
public static class LoggingDocumentAdapter
{
public static LoggingDocumentAdapter<TDocument, TNode> Create<TDocument, TNode>(IDocumentAdapter<TDocument, TNode> adapter)
{
return new LoggingDocumentAdapter<TDocument, TNode>(adapter);
}
}
public class LoggingDocumentAdapter<TDocument, TNode> : IDocumentAdapter<TDocument, TNode>, IDisposable
{
private readonly IDocumentAdapter<TDocument, TNode> adapter;
private readonly StringBuilder builder = new StringBuilder();
public LoggingDocumentAdapter(IDocumentAdapter<TDocument, TNode> adapter)
{
this.adapter = adapter;
}
public string Path { get; set; }
public Action<string> Before { get; set; }
public Action<string> After { get; set; }
private void Log(string format, params object[] args)
{
builder.AppendLine(args.Length == 0 ? format : string.Format(format, args));
}
private void FlushLog()
{
if (!string.IsNullOrEmpty(Path))
File.WriteAllText(Path, builder.ToString());
builder.Length = 0;
}
public void Dispose()
{
if (!string.IsNullOrEmpty(Path))
FlushLog();
}
public DocumentNodeType GetNodeType(TNode node)
{
Log("GetNodeType");
if (Before != null)
Before("GetNodeType");
var result = adapter.GetNodeType(node);
if (After != null)
After("GetNodeType");
return result;
}
public TNode GetParent(TNode node)
{
Log("GetParent");
if (Before != null)
Before("GetParent");
var result = adapter.GetParent(node);
if (After != null)
After("GetParent");
return result;
}
public TNode GetAncestor(TNode node, DocumentNodeType type)
{
Log("GetAncestor");
if (Before != null)
Before("GetAncestor");
var result = adapter.GetAncestor(node, type);
if (After != null)
After("GetAncestor");
return result;
}
public TNode GetNextSibling(TNode node)
{
Log("GetNextSibling");
if (Before != null)
Before("GetNextSibling");
var result = adapter.GetNextSibling(node);
if (After != null)
After("GetNextSibling");
return result;
}
public TNode GetPreviousSibling(TNode node)
{
Log("GetPreviousSibling");
if (Before != null)
Before("GetPreviousSibling");
var result = adapter.GetPreviousSibling(node);
if (After != null)
After("GetPreviousSibling");
return result;
}
public void Remove(TNode node)
{
Log("Remove");
if (Before != null)
Before("Remove");
adapter.Remove(node);
if (After != null)
After("Remove");
}
public IEnumerable<TNode> GetChildren(TDocument document)
{
Log("GetChildren");
if (Before != null)
Before("GetChildren");
var result = adapter.GetChildren(document).ToArray();
if (After != null)
After("GetChildren");
return result;
}
public bool IsComposite(TNode node)
{
Log("IsComposite");
if (Before != null)
Before("IsComposite");
var result = adapter.IsComposite(node);
if (After != null)
After("IsComposite");
return result;
}
public IEnumerable<TNode> GetChildren(TNode parent)
{
Log("GetChildren");
if (Before != null)
Before("GetChildren");
var result = adapter.GetChildren(parent);
if (After != null)
After("GetChildren");
return result;
}
public TNode GetFirstChild(TNode parent)
{
Log("GetFirstChild");
if (Before != null)
Before("GetFirstChild");
var result = adapter.GetFirstChild(parent);
if (After != null)
After("GetFirstChild");
return result;
}
public TNode GetLastChild(TNode parent)
{
Log("GetLastChild");
if (Before != null)
Before("GetLastChild");
var result = adapter.GetLastChild(parent);
if (After != null)
After("GetLastChild");
return result;
}
public TNode CreateTextRun(TDocument document, string text)
{
Log("CreateTextRun");
if (Before != null)
Before("CreateTextRun");
var result = adapter.CreateTextRun(document, text);
if (After != null)
After("CreateTextRun");
return result;
}
public string GetText(TNode node)
{
Log("GetText");
if (Before != null)
Before("GetText");
var result = adapter.GetText(node);
if (After != null)
After("GetText");
return result;
}
public void SetText(TNode node, string text)
{
Log("SetText");
if (Before != null)
Before("SetText");
adapter.SetText(node, text);
if (After != null)
After("SetText");
}
public bool IsNonVisibleMarker(TNode node)
{
Log("IsNonVisibleMarker");
if (Before != null)
Before("IsNonVisibleMarker");
var result = adapter.IsNonVisibleMarker(node);
if (After != null)
After("IsNonVisibleMarker");
return result;
}
public void InsertAfter(TNode newNode, TNode insertAfter)
{
Log("InsertAfter");
if (Before != null)
Before("InsertAfter");
adapter.InsertAfter(newNode, insertAfter);
if (After != null)
After("InsertAfter");
}
public void InsertBefore(TNode newNode, TNode insertBefore)
{
Log("InsertBefore");
if (Before != null)
Before("InsertBefore");
adapter.InsertBefore(newNode, insertBefore);
if (After != null)
After("InsertBefore");
}
public void AppendChild(TNode parent, TNode newChild)
{
Log("AppendChild");
if (Before != null)
Before("AppendChild");
adapter.AppendChild(parent, newChild);
if (After != null)
After("AppendChild");
}
public TNode Clone(TNode node, bool recursive)
{
Log("Clone");
if (Before != null)
Before("Clone");
var result = adapter.Clone(node, recursive);
if (After != null)
After("Clone");
return result;
}
}
}
| 22.305019 | 125 | 0.658993 | [
"MIT"
] | vc3/ExoMerge | ExoMerge.UnitTests/Common/LoggingDocumentAdapter.cs | 5,779 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Runtime.InteropServices;
[assembly: Guid("CA89ACD1-A1D5-43DE-890A-5FDF50BC1F93")]
namespace Microsoft.DiaSymReader.PortablePdb
{
[Guid("E4B18DEF-3B78-46AE-8F50-E67E421BDF70")]
[ComVisible(true)]
public class SymBinder : ISymUnmanagedBinder
{
[PreserveSig]
public int GetReaderForFile(
[MarshalAs(UnmanagedType.Interface)]object importer,
[MarshalAs(UnmanagedType.LPWStr)]string fileName,
[MarshalAs(UnmanagedType.LPWStr)]string searchPath,
[MarshalAs(UnmanagedType.Interface)]out ISymUnmanagedReader reader)
{
var pdbReader = new PortablePdbReader(File.OpenRead(fileName), importer);
reader = new SymReader(pdbReader);
return HResult.S_OK;
}
[PreserveSig]
public int GetReaderFromStream(
[MarshalAs(UnmanagedType.Interface)]object importer,
[MarshalAs(UnmanagedType.Interface)]object pstream,
[MarshalAs(UnmanagedType.Interface)]out ISymUnmanagedReader reader)
{
// TODO:
throw new NotImplementedException();
}
}
}
// regasm /codebase C:\R0\Binaries\Debug\Microsoft.DiaSymReader.PortablePdb.dll
// tlbexp C:\R0\Binaries\Debug\Microsoft.DiaSymReader.PortablePdb.dll | 38.538462 | 161 | 0.684631 | [
"Apache-2.0"
] | KashishArora/Roslyn | src/Debugging/Microsoft.DiaSymReader.PortablePdb/SymBinder.cs | 1,505 | C# |
//
// System.Runtime.InteropServices.ITypeLibExporterNotifySink.cs
//
// Author:
// Kevin Winchester (kwin@ns.sympatico.ca)
//
// (C) 2002 Kevin Winchester
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Reflection;
namespace System.Runtime.InteropServices {
#if NET_2_0
[ComVisible (true)]
#endif
[Guid("f1c3bf77-c3e4-11d3-88e7-00902754c43a")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ITypeLibExporterNotifySink {
void ReportEvent (ExporterEventKind eventKind, int eventCode, string eventMsg);
[return: MarshalAs(UnmanagedType.Interface)]
object ResolveRef (Assembly assembly);
}
}
| 37.042553 | 81 | 0.761631 | [
"MIT"
] | zlxy/Genesis-3D | Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/corlib/System.Runtime.InteropServices/ITypeLibExporterNotifySink.cs | 1,741 | C# |
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UI;
namespace JReact.JScreen.View
{
[RequireComponent(typeof(Toggle))]
public class J_UiView_FullScreen_Toggle : MonoBehaviour
{
// --------------- FIELDS AND PROPERTIES --------------- //
[BoxGroup("Setup", true, true, 0), SerializeField, AssetsOnly, Required] private J_ScreenResolutions _resolutions;
[BoxGroup("Setup", true, true, 0), SerializeField, Required] private Toggle _toggle;
[BoxGroup("Setup", true, true, 0), SerializeField] private bool _revertToggleValue;
// --------------- INITIALIZATION --------------- //
private void Awake()
{
InitThis();
SanityChecks();
}
private void InitThis()
{
if (_toggle == null) _toggle = GetComponent<Toggle>();
}
private void SanityChecks()
{
Assert.IsNotNull(_resolutions, $"{gameObject.name} requires a {nameof(_resolutions)}");
Assert.IsNotNull(_toggle, $"{gameObject.name} requires a {nameof(_toggle)}");
}
// --------------- COMMAND --------------- //
private void SetFullScreen(bool toggleValue)
{
if (_revertToggleValue) _resolutions.SetFullScreen(!toggleValue);
else _resolutions.SetFullScreen(toggleValue);
}
// --------------- LISTENER SETUP --------------- //
private void OnEnable()
{
_toggle.isOn = _revertToggleValue ? !_resolutions.IsFullScreen() : _resolutions.IsFullScreen();
_toggle.onValueChanged.AddListener(SetFullScreen);
}
private void OnDisable() { _toggle.onValueChanged.RemoveListener(SetFullScreen); }
}
}
| 35.254902 | 122 | 0.583426 | [
"MIT"
] | GiacomoMariani/JReac | Screen/Views/J_UiView_FullScreen_Toggle.cs | 1,798 | C# |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reactive.Disposables;
using Machine.Specifications;
namespace Dolittle.Specs.Logging.for_InternalLogger
{
public class when_beginning_scope : given.a_logger_with_two_writers
{
static string message;
static object[] arguments;
static IDisposable result;
Establish context = () =>
{
message = "Some message";
arguments = new object[] { "some arguments", 1 };
writer_one
.Setup(_ => _.BeginScope(Moq.It.IsAny<string>(), Moq.It.IsAny<object[]>()))
.Returns(Disposable.Empty);
writer_two
.Setup(_ => _.BeginScope(Moq.It.IsAny<string>(), Moq.It.IsAny<object[]>()))
.Returns(Disposable.Empty);
};
Because of = () => result = logger.BeginScope(message, arguments);
It should_begin_scope_in_writer_one = () =>
{
writer_one.Verify(_ => _.BeginScope(message, arguments), Moq.Times.Once());
writer_one.VerifyNoOtherCalls();
};
It should_forward_to_writer_two_with_level_debug_without_exception = () =>
{
writer_two.Verify(_ => _.BeginScope(message, arguments), Moq.Times.Once());
writer_two.VerifyNoOtherCalls();
};
It should_return_a_dispoable = () => result.ShouldNotBeNull();
Cleanup cleanup = () => result.Dispose();
}
} | 34.543478 | 101 | 0.611076 | [
"MIT"
] | dolittle-fundamentals/DotNET.Fundamentals | Specifications/Logging/for_InternalLogger/when_beginning_scope.cs | 1,589 | C# |
using UnityEngine.InputSystem.Layouts;
namespace UnityEngine.InputSystem.Composites
{
/// <summary>
/// A button with two additional modifiers. The button only triggers when
/// both modifiers are pressed.
/// </summary>
/// <remarks>
/// This composite can be used to require two other buttons to be held while
/// pressing the button that triggers the action. This is most commonly used
/// on keyboards to require two of the modifier keys (shift, ctrl, or alt)
/// to be held in combination with another key, e.g. "CTRL+SHIFT+1".
///
/// <example>
/// <code>
/// // Create a button action that triggers when CTRL+SHIFT+1
/// // is pressed on the keyboard.
/// var action = new InputAction(type: InputActionType.Button);
/// action.AddCompositeBinding("ButtonWithTwoModifiers")
/// .With("Modifier1", "<Keyboard>/leftCtrl")
/// .With("Modifier1", "<Keyboard>/rightCtrl")
/// .With("Modifier2", "<Keyboard>/leftShift")
/// .With("Modifier2", "<Keyboard>/rightShift")
/// .With("Button", "<Keyboard>/1")
/// </code>
/// </example>
///
/// Note that this is not restricted to the keyboard and will preserve
/// the full value of the button.
///
/// <example>
/// <code>
/// // Create a button action that requires the A and X button on the
/// // gamepad to be held and will then trigger from the gamepad's
/// // left trigger button.
/// var action = new InputAction(type: InputActionType.Button);
/// action.AddCompositeBinding("ButtonWithTwoModifiers")
/// .With("Modifier1", "<Gamepad>/buttonSouth")
/// .With("Modifier2", "<Gamepad>/buttonWest")
/// .With("Button", "<Gamepad>/leftTrigger");
/// </code>
/// </example>
/// </remarks>
/// <seealso cref="ButtonWithOneModifier"/>
[Scripting.Preserve]
public class ButtonWithTwoModifiers : InputBindingComposite<float>
{
/// <summary>
/// Binding for the first button that acts as a modifier, e.g. <c><Keyboard/leftCtrl</c>.
/// </summary>
/// <value>Part index to use with <see cref="InputBindingCompositeContext.ReadValue{T}(int)"/>.</value>
/// <remarks>
/// This property is automatically assigned by the input system.
/// </remarks>
// ReSharper disable once MemberCanBePrivate.Global
// ReSharper disable once FieldCanBeMadeReadOnly.Global
// ReSharper disable once UnassignedField.Global
[InputControl(layout = "Button")] public int modifier1;
/// <summary>
/// Binding for the second button that acts as a modifier, e.g. <c><Keyboard/leftCtrl</c>.
/// </summary>
/// <value>Part index to use with <see cref="InputBindingCompositeContext.ReadValue{T}(int)"/>.</value>
/// <remarks>
/// This property is automatically assigned by the input system.
/// </remarks>
// ReSharper disable once MemberCanBePrivate.Global
// ReSharper disable once FieldCanBeMadeReadOnly.Global
// ReSharper disable once UnassignedField.Global
[InputControl(layout = "Button")] public int modifier2;
/// <summary>
/// Binding for the button that is gated by the <see cref="modifier1"/> and <see cref="modifier2"/>.
/// The composite will assume the value of this button while both of the modifiers are pressed.
/// </summary>
/// <value>Part index to use with <see cref="InputBindingCompositeContext.ReadValue{T}(int)"/>.</value>
/// <remarks>
/// This property is automatically assigned by the input system.
/// </remarks>
// ReSharper disable once MemberCanBePrivate.Global
// ReSharper disable once FieldCanBeMadeReadOnly.Global
// ReSharper disable once UnassignedField.Global
[InputControl(layout = "Button")] public int button;
/// <summary>
/// Return the value of the <see cref="button"/> part while both <see cref="modifier1"/> and <see cref="modifier2"/>
/// are pressed. Otherwise return 0.
/// </summary>
/// <param name="context">Evaluation context passed in from the input system.</param>
/// <returns>The current value of the composite.</returns>
public override float ReadValue(ref InputBindingCompositeContext context)
{
if (context.ReadValueAsButton(modifier1) && context.ReadValueAsButton(modifier2))
return context.ReadValue<float>(button);
return default;
}
/// <summary>
/// Same as <see cref="ReadValue"/> in this case.
/// </summary>
/// <param name="context">Evaluation context passed in from the input system.</param>
/// <returns>A >0 value if the composite is currently actuated.</returns>
public override float EvaluateMagnitude(ref InputBindingCompositeContext context)
{
return ReadValue(ref context);
}
}
}
| 45.981982 | 124 | 0.626763 | [
"Apache-2.0"
] | kinten108101/ufssgp | TheLog/Library/PackageCache/com.unity.inputsystem@1.0.0-preview.3/InputSystem/Actions/Composites/ButtonWithTwoModifiers.cs | 5,104 | C# |
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using System.Collections.Generic;
#nullable disable
namespace T0002.Models
{
public partial class VStockCheckDiffSearch
{
public string Cticketcode { get; set; }
public string Ccheckname { get; set; }
public string Cerpcode { get; set; }
public string Cwareid { get; set; }
public string Cwarename { get; set; }
public string Cpositioncode { get; set; }
public string Cinvcode { get; set; }
public decimal Iquantity { get; set; }
public decimal? Onenum { get; set; }
public string Onedate { get; set; }
public string Onename { get; set; }
public decimal? Twonum { get; set; }
public string Twodate { get; set; }
public string Checktype { get; set; }
public string Twoname { get; set; }
public decimal? Onediff { get; set; }
public decimal? Twodiff { get; set; }
public string Dcheckdate { get; set; }
public int? Ptype { get; set; }
}
} | 36.870968 | 97 | 0.59755 | [
"MIT"
] | twoutlook/BlazorServerDbContextExample | BlazorServerEFCoreSample/T0002/Models/VStockCheckDiffSearch.cs | 1,145 | C# |
using System;
namespace Stankins.Interfaces
{
public interface IHistory : IMetadataRow
{
DateTimeOffset ModifiedDate { get; set; }
string ModifiedOwner { get; set; }
string ObjectName { get; set; }
string ObjectId { get; set; }
string Details { get; set; }
}
}
| 22.642857 | 49 | 0.602524 | [
"MIT"
] | Zeroshi/stankins | stankinsv2/solution/StankinsV2/Stankins.Interfaces/IHistory.cs | 319 | 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.
// Ported from https://github.com/adafruit/Adafruit_Python_BMP/blob/master/Adafruit_BMP/BMP085.py
// Formulas and code examples can also be found in the datasheet https://cdn-shop.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf
using System;
using System.Buffers.Binary;
using System.Device.I2c;
using System.Threading;
using Iot.Units;
namespace Iot.Device.Bmp180
{
public class Bmp180 : IDisposable
{
private I2cDevice _i2cDevice;
private readonly CalibrationData _calibrationData;
private Sampling _mode;
public const byte DefaultI2cAddress = 0x77;
public Bmp180(I2cDevice i2cDevice)
{
_i2cDevice = i2cDevice;
_calibrationData = new CalibrationData();
//Read the coefficients table
_calibrationData.ReadFromDevice(this);
SetSampling(Sampling.Standard);
}
/// <summary>
/// Sets sampling to the given value
/// </summary>
/// <param name="mode">Sampling Mode</param>
public void SetSampling(Sampling mode)
{
_mode = mode;
}
/// <summary>
/// Reads the temperature from the sensor
/// </summary>
/// <returns>
/// Temperature in degrees celsius
/// </returns>
public Temperature ReadTemperature()
{
return Temperature.FromCelsius((CalculateTrueTemperature() + 8) / 160.0);
}
/// <summary>
/// Reads the pressure from the sensor
/// </summary>
/// <returns>
/// Atmospheric pressure in Pa
/// </returns>
public double ReadPressure()
{
// Pressure Calculations
int B6 = CalculateTrueTemperature() - 4000;
int B62 = (B6 * B6) / 4096;
int X3 = (((short)_calibrationData.B2 * B62) + ((short)_calibrationData.AC2 * B6)) / 2048;
int B3 = ((((short)_calibrationData.AC1 * 4 + X3) << (short)Sampling.Standard) + 2) / 4;
int X1 = ((short)_calibrationData.AC3 * B6 ) / 8192;
int X2 = ((short)_calibrationData.B1 * B62) / 65536;
X3 = ((X1 + X2) + 2) / 4;
int B4 = _calibrationData.AC4 * (X3 + 32768) / 32768;
uint B7 = (uint)(ReadRawPressure() - B3) * (uint)(50000 >> (short)Sampling.Standard);
int p = (B7 < 0x80000000) ? (int)((B7 * 2) / B4) : (int)((B7 / B4) * 2);
X1 = (((p * p) / 65536 ) * 3038) / 65536;
return p + ( ((((p * p) / 65536 ) * 3038) / 65536) + ((-7357 * p) / 65536) + 3791) / 8;
}
/// <summary>
/// Calculates the altitude in meters from the specified sea-level pressure(in hPa).
/// </summary>
/// <param name="seaLevelPressure">
/// Sea-level pressure in hPa
/// </param>
/// <returns>
/// Height in meters from the sensor
/// </returns>
public double ReadAltitude(double seaLevelPressure = 101325.0)
{
return 44330.0 * (1.0 - Math.Pow(((double)ReadPressure() / seaLevelPressure), (1.0 / 5.255)));
}
/// <summary>
/// Calculates the pressure at sealevel when given a known altitude in meter
/// </summary>
/// <param name="altitude" >
/// altitude in meters
/// </param>
/// <returns>
/// Pressure in Pascals
/// </returns>
public double ReadSeaLevelPressure(double altitude = 0.0)
{
return (double)ReadPressure() / Math.Pow((1.0 - (altitude / 44333.0)), 5.255);
}
/// <summary>
/// Calculate true temperature
/// </summary>
/// <returns>
/// Coefficient B5
/// </returns>
private int CalculateTrueTemperature()
{
// Calculations below are taken straight from section 3.5 of the datasheet.
int X1 = (ReadRawTemperature() - _calibrationData.AC6) * _calibrationData.AC5 / 32768;
int X2 = _calibrationData.MC * (2048) / (X1 + _calibrationData.MD);
return X1 + X2;
}
/// <summary>
/// Reads raw temperatue from the sensor
/// </summary>
/// <returns>
/// Raw temperature
/// </returns>
private short ReadRawTemperature()
{
// Reads the raw (uncompensated) temperature from the sensor
Span<byte> command = stackalloc byte[] { (byte)Register.CONTROL, (byte)Register.READTEMPCMD };
_i2cDevice.Write(command);
// Wait 5ms, taken straight from section 3.3 of the datasheet.
Thread.Sleep(5);
return (short)Read16BitsFromRegisterBE((byte)Register.TEMPDATA);
}
/// <summary>
/// Reads raw pressure from the sensor
/// Taken from datasheet, Section 3.3.1
/// Standard - 8ms
/// UltraLowPower - 5ms
/// HighResolution - 14ms
/// UltraHighResolution - 26ms
/// </summary>
/// <returns>
/// Raw pressure
/// </returns>
private int ReadRawPressure()
{
// Reads the raw (uncompensated) pressure level from the sensor.
_i2cDevice.Write(new[] { (byte)Register.CONTROL, (byte)(Register.READPRESSURECMD + ((byte)Sampling.Standard << 6))});
if (_mode.Equals(Sampling.UltraLowPower))
{
Thread.Sleep(5);
}
else if (_mode.Equals(Sampling.HighResolution))
{
Thread.Sleep(14);
}
else if (_mode.Equals(Sampling.UltraHighResolution))
{
Thread.Sleep(26);
}
else
{
Thread.Sleep(8);
}
int msb = Read8BitsFromRegister((byte)Register.PRESSUREDATA);
int lsb = Read8BitsFromRegister((byte)Register.PRESSUREDATA + 1);
int xlsb = Read8BitsFromRegister((byte)Register.PRESSUREDATA + 2);
return ((msb << 16) + (lsb << 8) + xlsb) >> (8 - (byte)Sampling.Standard);
}
/// <summary>
/// Reads an 8 bit value from a register
/// </summary>
/// <param name="register">
/// Register to read from
/// </param>
/// <returns>
/// Value from register
/// </returns>
internal byte Read8BitsFromRegister(byte register)
{
_i2cDevice.WriteByte(register);
byte value = _i2cDevice.ReadByte();
return value;
}
/// <summary>
/// Reads a 16 bit value over I2C
/// </summary>
/// <param name="register">
/// Register to read from
/// </param>
/// <returns>
/// Value from register
/// </returns>
internal ushort Read16BitsFromRegister(byte register)
{
Span<byte> bytes = stackalloc byte[2];
_i2cDevice.WriteByte(register);
_i2cDevice.Read(bytes);
return BinaryPrimitives.ReadUInt16LittleEndian(bytes);
}
/// <summary>
/// Reads a 16 bit value over I2C
/// </summary>
/// <param name="register">
/// Register to read from
/// </param>
/// <returns>
/// Value (BigEndian) from register
/// </returns>
internal ushort Read16BitsFromRegisterBE(byte register)
{
Span<byte> bytes = stackalloc byte[2];
_i2cDevice.WriteByte(register);
_i2cDevice.Read(bytes);
return BinaryPrimitives.ReadUInt16BigEndian(bytes);
}
public void Dispose()
{
_i2cDevice?.Dispose();
_i2cDevice = null;
}
}
}
| 36.07173 | 130 | 0.504153 | [
"MIT"
] | IsharaPannila/iot | src/devices/Bmp180/Bmp180.cs | 8,551 | C# |
// den0bot (c) StanR 2021 - MIT License
using System.Collections.Generic;
using den0bot.Modules.Osu.Types.V1;
namespace den0bot.Modules.Osu.WebAPI.Requests.V1
{
public class GetRecentScores : IRequest<List<Score>, List<Score>>
{
public APIVersion API => APIVersion.V1;
public string Address => $"get_user_recent?limit={amount}&u={username}";
private readonly string username;
private readonly int amount;
public GetRecentScores(string username, int amount)
{
this.username = username;
this.amount = amount;
}
public List<Score> Process(List<Score> data) => data;
}
}
| 23.92 | 74 | 0.729097 | [
"MIT"
] | stanriders/den0bot | den0bot.Modules.Osu/WebAPI/Requests/V1/GetRecentScores.cs | 600 | C# |
using Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.Models;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Helpers;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Properties;
using Microsoft.Azure.Management.RecoveryServices.Backup.Models;
using CrrModel = Microsoft.Azure.Management.RecoveryServices.Backup.CrossRegionRestore.Models;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using AzureRestNS = Microsoft.Rest.Azure;
using CmdletModel = Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.Models;
namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets
{
public abstract class RSBackupVaultCmdletBase : RecoveryServicesBackupCmdletBase
{
/// <summary>
/// ARM ID of the Recovery Services Vault.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "ARM ID of the Recovery Services Vault.",
ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
public string VaultId { get; set; }
/// <summary>
/// Get the job PS model after fetching the job object from the service given the job ID.
/// </summary>
/// <param name="jobId">ID of the job to be fetched</param>
/// <returns></returns>
public CmdletModel.JobBase GetJobObject(string jobId, string vaultName = null, string resourceGroupName = null)
{
return JobConversions.GetPSJob(ServiceClientAdapter.GetJob(
jobId,
vaultName: vaultName,
resourceGroupName: resourceGroupName));
}
/// <summary>
/// Gets list of job PS models after fetching the job objects from the service given the list of job IDs.
/// </summary>
/// <param name="jobIds">List of IDs of jobs to be fetched</param>
/// <returns></returns>
public List<CmdletModel.JobBase> GetJobObject(IList<string> jobIds, string vaultName = null, string resourceGroupName = null)
{
List<CmdletModel.JobBase> result = new List<CmdletModel.JobBase>();
foreach (string jobId in jobIds)
{
result.Add(GetJobObject(
jobId,
vaultName: vaultName,
resourceGroupName: resourceGroupName));
}
return result;
}
/// <summary>
/// Get the job PS model after fetching the job object from the service given the job ID.
/// </summary>
/// <param name="jobId">ID of the job to be fetched</param>
/// <returns></returns>
public CmdletModel.JobBase GetCrrJobObject(string secondaryRegion, string vaultId, string jobId)
{
CrrModel.CrrJobRequest jobRequest = new CrrModel.CrrJobRequest();
jobRequest.JobName = jobId;
jobRequest.ResourceId = vaultId;
JobBase job = JobConversions.GetPSJobCrr(ServiceClientAdapter.GetCRRJobDetails(
secondaryRegion,
jobRequest));
return job;
}
/// <summary>
/// Based on the response from the service, handles the job created in the service appropriately.
/// </summary>
/// <param name="response">Response from service</param>
/// <param name="operationName">Name of the operation</param>
protected void HandleCreatedJob(
AzureRestNS.AzureOperationResponse response,
string operationName,
string vaultName = null,
string resourceGroupName = null)
{
WriteDebug(Resources.TrackingOperationStatusURLForCompletion +
response.Response.Headers.GetAzureAsyncOperationHeader());
var operationStatus = TrackingHelpers.GetOperationStatus(
response,
operationId => ServiceClientAdapter.GetProtectedItemOperationStatus(
operationId,
vaultName: vaultName,
resourceGroupName: resourceGroupName));
if (response != null && operationStatus != null)
{
WriteDebug(Resources.FinalOperationStatus + operationStatus.Status);
if (operationStatus.Properties != null)
{
var jobExtendedInfo =
(OperationStatusJobExtendedInfo)operationStatus.Properties;
if (jobExtendedInfo.JobId != null)
{
var jobStatusResponse =
(OperationStatusJobExtendedInfo)operationStatus.Properties;
WriteObject(GetJobObject(
jobStatusResponse.JobId,
vaultName: vaultName,
resourceGroupName: resourceGroupName));
}
}
if (operationStatus.Status == OperationStatusValues.Failed &&
operationStatus.Error != null)
{
var errorMessage = string.Format(
Resources.OperationFailed,
operationName,
operationStatus.Error.Code,
operationStatus.Error.Message);
throw new Exception(errorMessage);
}
}
}
protected void HandleCreatedJob(
AzureRestNS.AzureOperationResponse<ProtectedItemResource> response,
string operationName,
string vaultName = null,
string resourceGroupName = null)
{
WriteDebug(Resources.TrackingOperationStatusURLForCompletion +
response.Response.Headers.GetAzureAsyncOperationHeader());
var operationStatus = TrackingHelpers.GetOperationStatus(
response,
operationId => ServiceClientAdapter.GetProtectedItemOperationStatus(
operationId,
vaultName: vaultName,
resourceGroupName: resourceGroupName));
if (response != null && operationStatus != null)
{
WriteDebug(Resources.FinalOperationStatus + operationStatus.Status);
if (operationStatus.Properties != null)
{
var jobExtendedInfo =
(OperationStatusJobExtendedInfo)operationStatus.Properties;
if (jobExtendedInfo.JobId != null)
{
var jobStatusResponse =
(OperationStatusJobExtendedInfo)operationStatus.Properties;
WriteObject(GetJobObject(
jobStatusResponse.JobId,
vaultName: vaultName,
resourceGroupName: resourceGroupName));
}
}
if (operationStatus.Status == OperationStatusValues.Failed &&
operationStatus.Error != null)
{
var errorMessage = string.Format(
Resources.OperationFailed,
operationName,
operationStatus.Error.Code,
operationStatus.Error.Message);
throw new Exception(errorMessage);
}
}
}
}
}
| 43.497175 | 134 | 0.556306 | [
"MIT"
] | Agazoth/azure-powershell | src/RecoveryServices/RecoveryServices.Backup/RSBackupVaultCmdletBase.cs | 7,525 | C# |
using System;
using Dumper.Core;
namespace Legacy.Core.StaticData
{
public class SpellOfferStaticData : BaseStaticData
{
[CsvColumn("SpellIDs")]
private Int32[] m_spellIDs;
public Int32[] SpellIDs => m_spellIDs;
}
}
| 16.285714 | 51 | 0.736842 | [
"MIT"
] | Albeoris/MMXLegacy | Legacy.Core/Core/StaticData/SpellOfferStaticData.cs | 230 | C# |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
using Nohros.Logging;
namespace Nohros.Data.SqlServer
{
internal class UpdateStateQuery
{
const string kClassName = "Nohros.Data.SqlServer.UpdateStateQuery";
readonly MustLogger logger_ = MustLogger.ForCurrentProcess;
readonly SqlConnectionProvider sql_connection_provider_;
public UpdateStateQuery(SqlConnectionProvider sql_connection_provider) {
sql_connection_provider_ = sql_connection_provider;
logger_ = MustLogger.ForCurrentProcess;
SupressTransactions = true;
}
public bool Execute(string name, string table_name, object state) {
using (var scope =
new TransactionScope(SupressTransactions
? TransactionScopeOption.Suppress
: TransactionScopeOption.Required)) {
using (
SqlConnection conn = sql_connection_provider_.CreateConnection())
using (var builder = new CommandBuilder(conn)) {
IDbCommand cmd = builder
.SetText(@"
update " + table_name + @"
set state = @state" + @"
where state_name = @name")
.SetType(CommandType.Text)
.AddParameter("@name", name)
.AddParameterWithValue("@state", state)
.Build();
try {
conn.Open();
scope.Complete();
return cmd.ExecuteNonQuery() > 0;
} catch (SqlException e) {
throw new ProviderException(e);
}
}
}
}
public bool SupressTransactions { get; set; }
}
}
| 30.716981 | 77 | 0.628378 | [
"MIT"
] | nohros/must.data.sqlserver | src/sqlserver/UpdateStateQuery.cs | 1,630 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(Line))]
public class LineInspector : Editor
{
private void OnSceneGUI()
{
Line line = target as Line;
Transform handleTransform = line.transform;
Quaternion handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity;
Vector3 p0 = handleTransform.TransformPoint(line.p0);
Vector3 p1 = handleTransform.TransformPoint(line.p1);
EditorGUI.BeginChangeCheck();
p0 = Handles.DoPositionHandle(p0, handleRotation);
if (EditorGUI.EndChangeCheck()) {
line.p0 = handleTransform.InverseTransformPoint(p0);
}
EditorGUI.BeginChangeCheck();
p1 = Handles.DoPositionHandle(p1, handleRotation);
if (EditorGUI.EndChangeCheck()) {
line.p1 = handleTransform.InverseTransformPoint(p1);
}
Handles.color = Color.white;
Handles.DrawLine(p0, p1);
}
}
| 30.121212 | 128 | 0.717304 | [
"MIT"
] | CozyHome/cozyhome-n64platformer | n64platformer/Assets/Editor/LineInspector.cs | 994 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Akka.Actor;
using Akka.Streams.Kafka.Internal;
using Akka.Streams.Kafka.Stages.Consumers.Exceptions;
using Akka.Util.Internal;
using Confluent.Kafka;
namespace Akka.Streams.Kafka.Settings
{
public static class ConsumerSettings
{
internal const string ConfigPath = "akka.kafka.consumer";
}
/// <summary>
/// Consumer settings
/// </summary>
/// <typeparam name="TKey">Message key type</typeparam>
/// <typeparam name="TValue">Message value tyoe</typeparam>
public sealed class ConsumerSettings<TKey, TValue>
{
/// <summary>
/// Creates consumer settings
/// </summary>
/// <param name="system">Actor system for stage materialization</param>
/// <param name="keyDeserializer">Key deserializer</param>
/// <param name="valueDeserializer">Value deserializer</param>
/// <returns>Consumer settings</returns>
public static ConsumerSettings<TKey, TValue> Create(ActorSystem system, IDeserializer<TKey> keyDeserializer, IDeserializer<TValue> valueDeserializer)
{
var config = system.Settings.Config.GetConfig("akka.kafka.consumer");
return Create(config, keyDeserializer, valueDeserializer);
}
/// <summary>
/// Creates consumer settings
/// </summary>
/// <param name="config">Config to load properties from</param>
/// <param name="keyDeserializer">Key deserializer</param>
/// <param name="valueDeserializer">Value deserializer</param>
/// <returns>Consumer settings</returns>
/// <exception cref="ArgumentNullException">Thrown when kafka config for Akka.NET is not provided</exception>
public static ConsumerSettings<TKey, TValue> Create(Akka.Configuration.Config config, IDeserializer<TKey> keyDeserializer, IDeserializer<TValue> valueDeserializer)
{
var properties = config.GetConfig("kafka-clients").ParseKafkaClientsProperties();
if (config == null) throw new ArgumentNullException(nameof(config), "Kafka config for Akka.NET consumer was not provided");
return new ConsumerSettings<TKey, TValue>(
keyDeserializer: keyDeserializer,
valueDeserializer: valueDeserializer,
pollInterval: config.GetTimeSpan("poll-interval", TimeSpan.FromMilliseconds(50)),
pollTimeout: config.GetTimeSpan("poll-timeout", TimeSpan.FromMilliseconds(50)),
partitionHandlerWarning: config.GetTimeSpan("partition-handler-warning", TimeSpan.FromSeconds(5)),
commitTimeWarning: config.GetTimeSpan("commit-time-warning", TimeSpan.FromSeconds(1)),
commitTimeout: config.GetTimeSpan("commit-timeout", TimeSpan.FromSeconds(15)),
commitRefreshInterval: config.GetTimeSpan("commit-refresh-interval", Timeout.InfiniteTimeSpan, allowInfinite: true),
stopTimeout: config.GetTimeSpan("stop-timeout", TimeSpan.FromSeconds(30)),
positionTimeout: config.GetTimeSpan("position-timeout", TimeSpan.FromSeconds(5)),
waitClosePartition: config.GetTimeSpan("wait-close-partition", TimeSpan.FromSeconds(1)),
bufferSize: config.GetInt("buffer-size", 50),
metadataRequestTimeout: config.GetTimeSpan("metadata-request-timeout", TimeSpan.FromSeconds(5)),
drainingCheckInterval: config.GetTimeSpan("eos-draining-check-interval", TimeSpan.FromMilliseconds(30)),
dispatcherId: config.GetString("use-dispatcher", "akka.kafka.default-dispatcher"),
autoCreateTopicsEnabled: config.GetBoolean("allow.auto.create.topics", true),
properties: properties,
connectionCheckerSettings: ConnectionCheckerSettings.Create(config.GetConfig(ConnectionCheckerSettings.ConfigPath)));
}
/// <summary>
/// Gets property value by key
/// </summary>
public object this[string propertyKey] => this.Properties.GetValueOrDefault(propertyKey);
/// <summary>
/// Key deserializer
/// </summary>
public IDeserializer<TKey> KeyDeserializer { get; }
/// <summary>
/// Value deserializer
/// </summary>
public IDeserializer<TValue> ValueDeserializer { get; }
/// <summary>
/// Set the interval from one scheduled poll to the next.
/// </summary>
public TimeSpan PollInterval { get; }
/// <summary>
/// Set the maximum duration a poll to the Kafka broker is allowed to take.
/// </summary>
public TimeSpan PollTimeout { get; }
/// <summary>
/// When partition assigned events handling takes more then this timeout, the warning will be logged
/// </summary>
public TimeSpan PartitionHandlerWarning { get; }
/// <summary>
/// Time to wait for pending requests when a partition is closed.
/// </summary>
public TimeSpan WaitClosePartition { get; }
/// <summary>
/// When offset committing takes more then this timeout, the warning will be logged
/// </summary>
public TimeSpan CommitTimeWarning { get; }
/// <summary>
/// If offset commit requests are not completed within this timeout <see cref="CommitTimeoutException"/> will be thrown
/// </summary>
public TimeSpan CommitTimeout { get; }
/// <summary>
/// If set to a finite duration, the consumer will re-send the last committed offsets periodically for all assigned partitions.
/// Set it to TimeSpan.Zero to switch it off
/// </summary>
public TimeSpan CommitRefreshInterval { get; }
/// <summary>
/// Check interval for TransactionalProducer when finishing transaction before shutting down consumer
/// </summary>
public TimeSpan DrainingCheckInterval { get; }
/// <summary>
/// The stage will await outstanding offset commit requests before shutting down,
/// but if that takes longer than this timeout it will stop forcefully.
/// </summary>
public TimeSpan StopTimeout { get; }
/// <summary>
/// Limits the blocking on Kafka consumer position calls
/// </summary>
public TimeSpan PositionTimeout { get; }
public int BufferSize { get; }
/// <summary>
/// Fully qualified config path which holds the dispatcher configuration to be used by the consuming actor. Some blocking may occur.
/// </summary>
public string DispatcherId { get; }
/// <summary>
/// Allow automatic topic creation on the broker when subscribing to or assigning a topic.
/// </summary>
/// <remarks>
/// See more here: https://kafka.apache.org/documentation/#allow.auto.create.topics
/// Additionally, due to https://github.com/confluentinc/confluent-kafka-dotnet/issues/1366 ,
/// when set to `true` and topic is not created by Confluent driver, consuming error will be ignored
/// (like if no message to consume)
/// </remarks>
public bool AutoCreateTopicsEnabled { get; }
/// <summary>
/// Configuration properties
/// </summary>
public IImmutableDictionary<string, string> Properties { get; }
public TimeSpan MetadataRequestTimeout { get; }
public ConnectionCheckerSettings ConnectionCheckerSettings { get; }
public ConsumerSettings(
IDeserializer<TKey> keyDeserializer,
IDeserializer<TValue> valueDeserializer,
TimeSpan pollInterval,
TimeSpan pollTimeout,
TimeSpan commitTimeout,
TimeSpan commitRefreshInterval,
TimeSpan stopTimeout,
TimeSpan positionTimeout,
TimeSpan commitTimeWarning,
TimeSpan partitionHandlerWarning,
TimeSpan waitClosePartition,
TimeSpan metadataRequestTimeout,
TimeSpan drainingCheckInterval,
bool autoCreateTopicsEnabled,
int bufferSize, string dispatcherId,
IImmutableDictionary<string, string> properties,
ConnectionCheckerSettings connectionCheckerSettings)
{
KeyDeserializer = keyDeserializer;
ValueDeserializer = valueDeserializer;
PollInterval = pollInterval;
PollTimeout = pollTimeout;
PositionTimeout = positionTimeout;
StopTimeout = stopTimeout;
PartitionHandlerWarning = partitionHandlerWarning;
CommitTimeWarning = commitTimeWarning;
CommitTimeout = commitTimeout;
CommitRefreshInterval = commitRefreshInterval;
BufferSize = bufferSize;
DispatcherId = dispatcherId;
Properties = properties;
WaitClosePartition = waitClosePartition;
MetadataRequestTimeout = metadataRequestTimeout;
DrainingCheckInterval = drainingCheckInterval;
AutoCreateTopicsEnabled = autoCreateTopicsEnabled;
ConnectionCheckerSettings = connectionCheckerSettings;
}
public string GetProperty(string key) => Properties.GetValueOrDefault(key, null);
/// <summary>
/// Sets kafka server IPs
/// </summary>
public ConsumerSettings<TKey, TValue> WithBootstrapServers(string bootstrapServers) =>
Copy(properties: Properties.SetItem("bootstrap.servers", bootstrapServers));
/// <summary>
/// Sets client id to be used
/// </summary>
public ConsumerSettings<TKey, TValue> WithClientId(string clientId) =>
Copy(properties: Properties.SetItem("client.id", clientId));
/// <summary>
/// Sets consumer group Id
/// </summary>
public ConsumerSettings<TKey, TValue> WithGroupId(string groupId) =>
Copy(properties: Properties.SetItem("group.id", groupId));
/// <summary>
/// Sets property with given key to specified value
/// </summary>
public ConsumerSettings<TKey, TValue> WithProperty(string key, string value) =>
Copy(properties: Properties.SetItem(key, value));
public ConsumerSettings<TKey, TValue> WithProperties(IDictionary<string, string> properties)
{
var builder = ImmutableDictionary.CreateBuilder<string, string>();
builder.AddRange(Properties);
foreach (var kvp in properties)
{
builder.AddOrSet(kvp.Key, kvp.Value);
}
return Copy(properties: builder.ToImmutable());
}
/// <summary>
/// Set the interval from one scheduled poll to the next.
/// </summary>
public ConsumerSettings<TKey, TValue> WithPollInterval(TimeSpan pollInterval) => Copy(pollInterval: pollInterval);
/// <summary>
/// Set the maximum duration a poll to the Kafka broker is allowed to take.
/// </summary>
public ConsumerSettings<TKey, TValue> WithPollTimeout(TimeSpan pollTimeout) => Copy(pollTimeout: pollTimeout);
/// <summary>
/// If offset commit requests are not completed within this timeout <see cref="CommitTimeoutException"/> will be thrown
/// </summary>
public ConsumerSettings<TKey, TValue> WithCommitTimeout(TimeSpan commitTimeout) => Copy(commitTimeout: commitTimeout);
/// <summary>
/// If commits take longer than this time a warning is logged
/// </summary>
public ConsumerSettings<TKey, TValue> WithCommitTimeWarning(TimeSpan commitTimeWarning) => Copy(commitTimeWarning: commitTimeWarning);
/// <summary>
/// When partition assigned events handling takes more then this timeout, the warning will be logged
/// </summary>
public ConsumerSettings<TKey, TValue> WithPartitionHandlerWarning(TimeSpan partitionHandlerWarning) => Copy(partitionHandlerWarning: partitionHandlerWarning);
/// <summary>
/// Time to wait for pending requests when a partition is closed.
/// </summary>
public ConsumerSettings<TKey, TValue> WithWaitClosePartition(TimeSpan waitClosePartition) => Copy(waitClosePartition: waitClosePartition);
/// <summary>
/// Allows topic auto-creation when constumer is subscribing or assigning to the topic.
/// </summary>
/// <remarks>
/// When set, and still getting error from broker, consumer will assume that no message was produced yet
/// </remarks>
public ConsumerSettings<TKey, TValue> WithAutoCreateTopicsEnabled(bool autoCreateTopicsEnabled) => Copy(autoCreateTopicsEnabled: autoCreateTopicsEnabled);
/// <summary>
/// If set to a finite duration, the consumer will re-send the last committed offsets periodically for all assigned partitions.
/// Set it to TimeSpan.Zero to switch it off
/// </summary>
public ConsumerSettings<TKey, TValue> WithCommitRefreshInterval(TimeSpan commitRefreshInterval)
{
return Copy(commitRefreshInterval: commitRefreshInterval == TimeSpan.Zero ? Timeout.InfiniteTimeSpan : commitRefreshInterval);
}
/// <summary>
/// The stage will await outstanding offset commit requests before shutting down,
/// but if that takes longer than this timeout it will stop forcefully.
/// </summary>
public ConsumerSettings<TKey, TValue> WithStopTimeout(TimeSpan stopTimeout) => Copy(stopTimeout: stopTimeout);
/// <summary>
/// Limits the blocking on Kafka consumer position calls.
/// </summary>
public ConsumerSettings<TKey, TValue> WithPositionTimeout(TimeSpan positionTimeout) => Copy(positionTimeout: positionTimeout);
/// <summary>
/// Fully qualified config path which holds the dispatcher configuration to be used by the consuming actor. Some blocking may occur.
/// </summary>
public ConsumerSettings<TKey, TValue> WithDispatcher(string dispatcherId) => Copy(dispatcherId: dispatcherId);
/// <summary>
/// Check interval for TransactionalProducer when finishing transaction before shutting down consumer
/// </summary>
public ConsumerSettings<TKey, TValue> WithDrainingCheckInterval(TimeSpan drainingCheckInterval) => Copy(drainingCheckInterval: drainingCheckInterval);
/// <summary>
/// Sets key deserializer
/// </summary>
public ConsumerSettings<TKey, TValue> WithKeyDeserializer(IDeserializer<TKey> keyDeserializer) => Copy(keyDeserializer: keyDeserializer);
/// <summary>
/// Sets value deserializer
/// </summary>
public ConsumerSettings<TKey, TValue> WithValueDeserializer(IDeserializer<TValue> valueDeserializer) => Copy(valueDeserializer: valueDeserializer);
/// <summary>
/// Assigned consumer group Id, or null
/// </summary>
public string GroupId => Properties.ContainsKey("group.id") ? Properties["group.id"] : null;
private ConsumerSettings<TKey, TValue> Copy(
IDeserializer<TKey> keyDeserializer = null,
IDeserializer<TValue> valueDeserializer = null,
TimeSpan? pollInterval = null,
TimeSpan? pollTimeout = null,
TimeSpan? commitTimeout = null,
TimeSpan? partitionHandlerWarning = null,
TimeSpan? metadataRequestTimeout = null,
TimeSpan? drainingCheckInterval = null,
TimeSpan? commitTimeWarning = null,
TimeSpan? commitRefreshInterval = null,
TimeSpan? stopTimeout = null,
TimeSpan? positionTimeout = null,
TimeSpan? waitClosePartition = null,
bool? autoCreateTopicsEnabled = null,
int? bufferSize = null,
string dispatcherId = null,
IImmutableDictionary<string, string> properties = null,
ConnectionCheckerSettings connectionCheckerSettings = null) =>
new ConsumerSettings<TKey, TValue>(
keyDeserializer: keyDeserializer ?? this.KeyDeserializer,
valueDeserializer: valueDeserializer ?? this.ValueDeserializer,
pollInterval: pollInterval ?? this.PollInterval,
pollTimeout: pollTimeout ?? this.PollTimeout,
commitTimeout: commitTimeout ?? this.CommitTimeout,
partitionHandlerWarning: partitionHandlerWarning ?? this.PartitionHandlerWarning,
commitTimeWarning: commitTimeWarning ?? this.CommitTimeWarning,
commitRefreshInterval: commitRefreshInterval ?? this.CommitRefreshInterval,
stopTimeout: stopTimeout ?? this.StopTimeout,
waitClosePartition: waitClosePartition ?? this.WaitClosePartition,
positionTimeout: positionTimeout ?? this.PositionTimeout,
bufferSize: bufferSize ?? this.BufferSize,
metadataRequestTimeout: metadataRequestTimeout ?? this.MetadataRequestTimeout,
drainingCheckInterval: drainingCheckInterval ?? this.DrainingCheckInterval,
dispatcherId: dispatcherId ?? this.DispatcherId,
autoCreateTopicsEnabled: autoCreateTopicsEnabled ?? this.AutoCreateTopicsEnabled,
properties: properties ?? this.Properties,
connectionCheckerSettings: connectionCheckerSettings ?? this.ConnectionCheckerSettings);
/// <summary>
/// Creates new kafka consumer, using event handlers provided
/// </summary>
public Confluent.Kafka.IConsumer<TKey, TValue> CreateKafkaConsumer(Action<IConsumer<TKey, TValue>, Error> consumeErrorHandler = null,
Action<IConsumer<TKey, TValue>, List<TopicPartition>> partitionAssignedHandler = null,
Action<IConsumer<TKey, TValue>, List<TopicPartitionOffset>> partitionRevokedHandler = null,
Action<IConsumer<TKey, TValue>, string> statisticHandler = null)
{
return new Confluent.Kafka.ConsumerBuilder<TKey, TValue>(this.Properties)
.SetKeyDeserializer(this.KeyDeserializer)
.SetValueDeserializer(this.ValueDeserializer)
.SetErrorHandler((c, e) => consumeErrorHandler?.Invoke(c, e))
.SetPartitionsAssignedHandler((c, partitions) => partitionAssignedHandler?.Invoke(c, partitions))
.SetPartitionsRevokedHandler((c, partitions) => partitionRevokedHandler?.Invoke(c, partitions))
.SetStatisticsHandler((c, json) => statisticHandler?.Invoke(c, json))
.Build();
}
}
}
| 52.68956 | 171 | 0.646384 | [
"Apache-2.0"
] | Aaronontheweb/Akka.Streams.Kafka | src/Akka.Streams.Kafka/Settings/ConsumerSettings.cs | 19,179 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchoolClasses
{
abstract class People
{
// Fields
private string fullName;
private byte age;
private string gender;
// Constructors => protected in abstract classes
protected People() { }
protected People(string fullname, byte age, string gender)
{
this.Fullname = fullname;
this.Age = age;
this.Gender = gender;
}
// Properties => can be made protected in abstract classes
protected string Fullname { get; set; }
protected byte Age { get; set; }
protected string Gender { get; set; }
}
}
| 26.517241 | 66 | 0.605982 | [
"MIT"
] | zdzdz/Object-Oriented-Programming-Homeworks | 04. OOP-Principles-Part-I-HW/SchoolClasses/People.cs | 771 | C# |
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Hexapawn.Resources;
internal static class Resource
{
internal static class Streams
{
public static Stream Instructions => GetStream();
public static Stream Title => GetStream();
}
private static Stream GetStream([CallerMemberName] string name = null)
=> Assembly.GetExecutingAssembly().GetManifestResourceStream($"Hexapawn.Resources.{name}.txt");
} | 28.352941 | 103 | 0.732365 | [
"Unlicense"
] | AlaaSarhan/basic-computer-games | 46_Hexapawn/csharp/Resources/Resource.cs | 482 | C# |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissioßns and
// limitations under the License.
// The controller is not available for versions of Unity without the
// // GVR native integration.
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
using UnityEngine;
/// @cond
namespace Gvr.Internal {
/// Factory that provides a concrete implementation of IControllerProvider for the
/// current platform.
static class ControllerProviderFactory {
/// Provides a concrete implementation of IControllerProvider appropriate for the current
/// platform. This method never returns null. In the worst case, it might return a dummy
/// provider if the platform is not supported.
static internal IControllerProvider CreateControllerProvider(GvrController owner) {
#if UNITY_EDITOR || UNITY_STANDALONE
// Use the Controller Emulator.
return new EmulatorControllerProvider(owner.emulatorConnectionMode);
#elif UNITY_ANDROID
// Use the GVR C API.
return new AndroidNativeControllerProvider();
#else
// Platform not supported.
Debug.LogWarning("No controller support on this platform.");
return new DummyControllerProvider();
#endif // UNITY_EDITOR || UNITY_STANDALONE
}
}
}
/// @endcond
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
| 39.085106 | 93 | 0.744148 | [
"MIT"
] | CDJaramillo/DinoMuseumVR | Assets/GoogleVR/Scripts/Controller/Internal/ControllerProviderFactory.cs | 1,838 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace RearEndCollision
{
public abstract class MapGenerator
{
public const int MAX_ROWS = 60;
public const int MAX_COLS = 150;
public abstract char[,] GenerateMap();
}
}
| 18.785714 | 40 | 0.718631 | [
"MIT"
] | VProfirov/Telerik-Academy | Team Projects - old/team-tomato/theProject/MapGenerator/MapGenerator.cs | 263 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Axe.Windows.Core.Bases;
using Axe.Windows.Core.Enums;
using Axe.Windows.Rules.PropertyConditions;
using Axe.Windows.Rules.Resources;
using static Axe.Windows.Rules.PropertyConditions.ControlType;
using static Axe.Windows.Rules.PropertyConditions.Relationships;
namespace Axe.Windows.Rules.Library
{
[RuleInfo(ID = RuleId.ControlShouldSupportGridItemPattern)]
class ControlShouldSupportGridItemPattern : Rule
{
public ControlShouldSupportGridItemPattern()
{
this.Info.Description = Descriptions.ControlShouldSupportGridItemPattern;
this.Info.HowToFix = HowToFix.ControlShouldSupportGridItemPattern;
this.Info.Standard = A11yCriteriaId.AvailableActions;
}
public override EvaluationCode Evaluate(IA11yElement e)
{
if (e == null) throw new ArgumentNullException(nameof(e));
var condition = Patterns.GridItem | AnyChild(Patterns.GridItem);
return condition.Matches(e) ? EvaluationCode.Pass : EvaluationCode.Error;
}
protected override Condition CreateCondition()
{
return DataItem & Parent(Patterns.Grid);
}
} // class
} // namespace
| 38.189189 | 102 | 0.696391 | [
"MIT"
] | Bhaskers-Blu-Org2/axe-windows | src/Rules/Library/ControlShouldSupportGridItemPattern.cs | 1,377 | C# |
using Microsoft.AspNetCore.Components;
using PBCommon.Extensions;
using PBFrontend.UI.Authorization;
using System;
using System.Collections.Generic;
namespace PBFrontend.UI.Meta.Telemetry
{
public partial class TelemetryFrame : SessionChild
{
[Parameter]
public RenderFragment ChildContent { get; set; }
private readonly ICollection<Int64> renderTimes = new List<Int64>();
public Int64 AverageRenderTime => renderTimes.SafeAverage();
public void AddRenderTime(Int64 value)
{
renderTimes.Add(value);
InvokeAsync(StateHasChanged);
}
}
}
| 23.416667 | 70 | 0.772242 | [
"MIT"
] | PaulBraetz/PBAppRepository | PBFrontend/UI/Meta/Telemetry/TelemetryFrame.razor.cs | 564 | C# |
#region License
// Copyright (c) 2009, ClearCanvas Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ClearCanvas Inc. 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.
#endregion
using System.Collections.Generic;
using ClearCanvas.Common;
using ClearCanvas.Dicom;
using ClearCanvas.Dicom.Iod;
using ClearCanvas.ImageViewer.Annotations;
using ClearCanvas.ImageViewer.Annotations.Dicom;
using ClearCanvas.ImageViewer.StudyManagement;
namespace ClearCanvas.ImageViewer.AnnotationProviders.Dicom
{
[ExtensionOf(typeof(AnnotationItemProviderExtensionPoint))]
public class GeneralStudyAnnotationItemProvider : AnnotationItemProvider
{
private readonly List<IAnnotationItem> _annotationItems;
public GeneralStudyAnnotationItemProvider()
: base("AnnotationItemProviders.Dicom.GeneralStudy", new AnnotationResourceResolver(typeof(GeneralStudyAnnotationItemProvider).Assembly))
{
_annotationItems = new List<IAnnotationItem>();
AnnotationResourceResolver resolver = new AnnotationResourceResolver(this);
_annotationItems.Add
(
new DicomAnnotationItem<string>
(
"Dicom.GeneralStudy.AccessionNumber",
resolver,
delegate(Frame frame) { return frame.ParentImageSop.AccessionNumber; },
DicomDataFormatHelper.RawStringFormat
)
);
_annotationItems.Add
(
new DicomAnnotationItem<PersonName>
(
"Dicom.GeneralStudy.ReferringPhysiciansName",
resolver,
delegate(Frame frame) { return frame.ParentImageSop.ReferringPhysiciansName; },
DicomDataFormatHelper.PersonNameFormatter
)
);
_annotationItems.Add
(
new DicomAnnotationItem<string>
(
"Dicom.GeneralStudy.StudyDate",
resolver,
delegate(Frame frame) { return frame.ParentImageSop.StudyDate; },
DicomDataFormatHelper.DateFormat
)
);
_annotationItems.Add
(
new DicomAnnotationItem<string>
(
"Dicom.GeneralStudy.StudyTime",
resolver,
delegate(Frame frame) { return frame.ParentImageSop.StudyTime; },
DicomDataFormatHelper.TimeFormat
)
);
_annotationItems.Add
(
new DicomAnnotationItem<string>
(
"Dicom.GeneralStudy.StudyDescription",
resolver,
delegate(Frame frame) { return frame.ParentImageSop.StudyDescription; },
DicomDataFormatHelper.RawStringFormat
)
);
_annotationItems.Add
(
new DicomAnnotationItem<string>
(
"Dicom.GeneralStudy.StudyId",
resolver,
FrameDataRetrieverFactory.GetStringRetriever(DicomTags.StudyId),
DicomDataFormatHelper.RawStringFormat
)
);
}
public override IEnumerable<IAnnotationItem> GetAnnotationItems()
{
return _annotationItems;
}
}
}
| 33.952756 | 141 | 0.716605 | [
"Apache-2.0"
] | econmed/ImageServer20 | ImageViewer/AnnotationProviders/Dicom/GeneralStudyAnnotationItemProvider.cs | 4,314 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Old_Record_Store.Library
{
public interface IRecordStoreRepository : IDisposable
{
//Customer Methods
void AddCustomer(Customer customer);
//Prints out the list of customers, does not display ID.
void DisplayCustomers();
//Utilizes a field to look up a customer, iterates through customer list and checks if it is there
void SeachCustomer(string field);
//Location Methods
void DisplayOrderHistoryByCustomer(int customerID);
void DisplayOrderHistoryByLocation(int locationID);
void AddToOrder(int customerID, int locationID, List<int> recordID, List<int> amounts);
//Inventory
void DisplayLocations();
//OrderHistory
void DisplayRecords(int locationID);
void DisplayOrderDetails(int OrderID);
void DisplayOrderList();
void Save();
}
}
| 24.35 | 106 | 0.676591 | [
"MIT"
] | 1909-sep30-net/jose-project0 | Old-Record-Store/Old-Record-Store.Library/Interface/IRecordStoreRepository.cs | 976 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace CyberBullet {
namespace Editors {
public class CreateClimbPrefab : EditorWindow {
#region Variables
GenericEditor editor = new GenericEditor();
#endregion
#region Visuals
[MenuItem("Cyber Bullet/Climbing System/Generate ClimbPoint Prefab")]
private static void E_ClimbPrefab() {
EditorWindow window = EditorWindow.GetWindow (typeof(CreateClimbPrefab));//create an new windows
window.minSize = new Vector2(400,500);
window.Show ();
}
void OnEnable()
{
editor.InitTextures ();
}
void OnGUI()
{
editor.DrawBox ();
editor.DrawTitle ("GameDevRepo","Generate ClimbPoint Prefab");
editor.DrawHelpBox ("This will generate an empty prefab that will work with the climb system. The object name doesn't matter. Be sure to adjust the hands, feet, elbows, and knees to where you want them to be. Then best to make a prefab of this.");
Options ();
}
void Options()
{
GUILayout.BeginArea (new Rect (30, 200, Screen.width - 70, 30));
if (GUILayout.Button ("Generate ClimbPoint Prefab", GUILayout.Height (30)))
{
GeneratePrefab();
}
}
#endregion
#region Logic
void GeneratePrefab()
{
//Generate Object Hierarchy
GameObject climbPrefab = new GameObject ("ClimbPoint");
GameObject rootPosition = new GameObject("RootPosition");
rootPosition.transform.position = new Vector3(climbPrefab.transform.position.x, climbPrefab.transform.position.y-1.5f, climbPrefab.transform.position.z);
rootPosition.transform.parent = climbPrefab.transform;
GameObject hands = new GameObject("Hands");
GameObject feet = new GameObject("Feet");
hands.transform.position = new Vector3(climbPrefab.transform.position.x, climbPrefab.transform.position.y, climbPrefab.transform.position.z);
feet.transform.position = new Vector3(rootPosition.transform.position.x, rootPosition.transform.position.y+0.5f, rootPosition.transform.position.z);
hands.transform.parent = rootPosition.transform;
feet.transform.parent = rootPosition.transform;
GameObject lh = new GameObject("LeftHand");
GameObject rh = new GameObject("RightHand");
GameObject le = new GameObject("LeftElbow");
GameObject re = new GameObject("RightElbow");
lh.transform.position = new Vector3(hands.transform.position.x-0.25f, hands.transform.position.y, hands.transform.position.z);
rh.transform.position = new Vector3(hands.transform.position.x+0.25f, hands.transform.position.y, hands.transform.position.z);
le.transform.position = new Vector3(hands.transform.position.x-2.0f, hands.transform.position.y-0.5f, hands.transform.position.z-1.0f);
re.transform.position = new Vector3(hands.transform.position.x+2.0f, hands.transform.position.y-0.5f, hands.transform.position.z-1.0f);
GameObject lf = new GameObject("LeftFoot");
GameObject rf = new GameObject("RightFoot");
GameObject lk = new GameObject("LeftKnee");
GameObject rk = new GameObject("RightKnee");
lf.transform.position = new Vector3(feet.transform.position.x-0.25f, feet.transform.position.y, feet.transform.position.z);
rf.transform.position = new Vector3(feet.transform.position.x+0.25f, feet.transform.position.y, feet.transform.position.z);
lk.transform.position = new Vector3(feet.transform.position.x-0.25f, feet.transform.position.y, feet.transform.position.z+2.0f);
rk.transform.position = new Vector3(feet.transform.position.x+0.25f, feet.transform.position.y, feet.transform.position.z+2.0f);
lh.transform.parent = hands.transform;
rh.transform.parent = hands.transform;
le.transform.parent = hands.transform;
re.transform.parent = hands.transform;
lf.transform.parent = feet.transform;
rf.transform.parent = feet.transform;
lk.transform.parent = feet.transform;
rk.transform.parent = feet.transform;
//Add and populate script
rootPosition.AddComponent<Climbing.ClimbPoint>();
Climbing.ClimbPoint climbPoint = rootPosition.GetComponent<Climbing.ClimbPoint>();
List<Climbing.ClimbIKPositions> ik = new List<Climbing.ClimbIKPositions>();
Climbing.ClimbIKPositions ikLH = new Climbing.ClimbIKPositions();
ikLH.ikType = AvatarIKGoal.LeftHand;
ikLH.target = lh.transform;
ik.Add(ikLH);
Climbing.ClimbIKPositions ikRH = new Climbing.ClimbIKPositions();
ikRH.ikType = AvatarIKGoal.RightHand;
ikRH.target = rh.transform;
ik.Add(ikRH);
Climbing.ClimbIKPositions ikLF = new Climbing.ClimbIKPositions();
ikLF.ikType = AvatarIKGoal.LeftFoot;
ikLF.target = lf.transform;
ik.Add(ikLF);
Climbing.ClimbIKPositions ikRF = new Climbing.ClimbIKPositions();
ikRF.ikType = AvatarIKGoal.RightHand;
ikRF.target = rf.transform;
ik.Add(ikRF);
climbPoint.iks = ik.ToArray();
List<Climbing.ClimbHintIKPositions> hint = new List<Climbing.ClimbHintIKPositions>();
Climbing.ClimbHintIKPositions hintLE = new Climbing.ClimbHintIKPositions();
hintLE.hintType = AvatarIKHint.LeftElbow;
hintLE.target = le.transform;
hint.Add(hintLE);
Climbing.ClimbHintIKPositions hintRE = new Climbing.ClimbHintIKPositions();
hintRE.hintType = AvatarIKHint.RightElbow;
hintRE.target = re.transform;
hint.Add(hintRE);
Climbing.ClimbHintIKPositions hintLK = new Climbing.ClimbHintIKPositions();
hintLK.hintType = AvatarIKHint.LeftKnee;
hintLK.target = lk.transform;
hint.Add(hintLK);
Climbing.ClimbHintIKPositions hintRK = new Climbing.ClimbHintIKPositions();
hintRK.hintType = AvatarIKHint.RightKnee;
hintRK.target = rk.transform;
hint.Add(hintRK);
climbPoint.hints = hint.ToArray();
}
#endregion
}
}
} | 52.742188 | 251 | 0.628203 | [
"MIT"
] | pttb369/GameDevRepo | Scripts/Editor/CreateClimbPrefab.cs | 6,753 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/urlmon.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IInternetProtocolSink" /> struct.</summary>
public static unsafe class IInternetProtocolSinkTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IInternetProtocolSink" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IInternetProtocolSink).GUID, Is.EqualTo(IID_IInternetProtocolSink));
}
/// <summary>Validates that the <see cref="IInternetProtocolSink" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IInternetProtocolSink>(), Is.EqualTo(sizeof(IInternetProtocolSink)));
}
/// <summary>Validates that the <see cref="IInternetProtocolSink" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IInternetProtocolSink).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IInternetProtocolSink" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IInternetProtocolSink), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IInternetProtocolSink), Is.EqualTo(4));
}
}
}
}
| 38.076923 | 145 | 0.64697 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | tests/Interop/Windows/um/urlmon/IInternetProtocolSinkTests.cs | 1,982 | C# |
using System.Text;
namespace Togglr
{
public static class HtmlHelper
{
public static void WriteHtmlBegin(StringBuilder sb)
{
sb.AppendLine("<!doctype html><html>");
sb.AppendLine("<head><meta charset=\"utf-8\">");
sb.AppendLine("<link href=\"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.min.css\" rel=\"stylesheet\">");
sb.AppendLine("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/js/all.min.js\" integrity=\"sha256-iZGp5HAiwRmkbOKVYv5FUER4iXp5QbiEudkZOdwLrjw=\" crossorigin=\"anonymous\"></script>");
sb.AppendLine("</head><body>");
}
public static void WriteHtmlEnd(StringBuilder sb)
{
sb.AppendLine("</body></html>");
}
public static void WriteDocumentTitle(StringBuilder sb, string user)
{
sb.AppendLine("<section class=\"hero is-primary\"><div class=\"hero-body\">");
sb.AppendLine($"<div class=\"container\"><h1 class=\"title\">Arbeitszeit von {user}</h1></div>");
sb.AppendLine("</div>\n</section>");
}
}
} | 41.142857 | 220 | 0.59809 | [
"MIT"
] | kopfrechner/Togglr | Togglr/HtmlHelper.cs | 1,154 | C# |
using System;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Nez;
using Microsoft.Xna.Framework.Graphics;
using TinyAlgorithmVisualizer.Scenes;
namespace TinyAlgorithmVisualizer
{
public class MyGame : Core
{
protected override void Initialize()
{
base.Initialize();
Screen.SetSize(1280, 800);
DefaultSamplerState = SamplerState.AnisotropicClamp;
Scene = new BlankScene();
}
}
} | 24.6 | 64 | 0.668699 | [
"MIT"
] | yCatDev/BinaryTreeVisualizator | TinyAlgorithmVisualizer/TinyAlgorithmVisualizer/Game1.cs | 494 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace PaintCode
{
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args, null, "AppDelegate");
}
}
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
UIWindow window;
UINavigationController navCtrlr;
UITabBarController tabBarController;
UIViewController news, blue, glossy, lineart;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create a new window instance based on the screen size
window = new UIWindow (UIScreen.MainScreen.Bounds);
navCtrlr = new UINavigationController ();
navCtrlr.NavigationBar.Translucent = false;
blue = new BlueButtonViewController ();
glossy = new GlossyButtonViewController ();
lineart = new DrawingViewController ();
news = new NewsDialogViewController ();
// news.View.Frame = new System.Drawing.RectangleF (0
// , UIApplication.SharedApplication.StatusBarFrame.Height
// , UIScreen.MainScreen.ApplicationFrame.Width
// , UIScreen.MainScreen.ApplicationFrame.Height);
navCtrlr.PushViewController (news, false);
navCtrlr.TabBarItem = new UITabBarItem ("Calendar", UIImage.FromBundle ("Images/about.png"), 0);
blue.TabBarItem = new UITabBarItem ("Blue Button", UIImage.FromBundle ("Images/about.png"), 0);
glossy.TabBarItem = new UITabBarItem ("Glossy Button", UIImage.FromBundle ("Images/about.png"), 0);
lineart.TabBarItem = new UITabBarItem ("Line Art", UIImage.FromBundle ("Images/about.png"), 0);
tabBarController = new UITabBarController ();
tabBarController.ViewControllers = new UIViewController [] {
navCtrlr,
blue,
glossy,
lineart
};
window.RootViewController = tabBarController;
// make the window visible
window.MakeKeyAndVisible ();
return true;
}
}
}
| 28.101449 | 102 | 0.730273 | [
"MIT"
] | Art-Lav/ios-samples | PaintCode/PaintCodeDemo/AppDelegate.cs | 1,939 | C# |
namespace SwtorCaster.Core.Services.Settings
{
using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using Caliburn.Micro;
using Domain.Settings;
using Logging;
using Newtonsoft.Json;
public class SettingsService : ISettingsService
{
private static readonly string SwtorCaster = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SwtorCaster");
private static readonly string SettingsPath = Path.Combine(SwtorCaster, "settings.json");
private readonly ILoggerService loggerService;
private readonly IEventAggregator eventAggregator;
public AppSettings Settings { get; set; }
public SettingsService(ILoggerService loggerService, IEventAggregator eventAggregator)
{
this.loggerService = loggerService;
this.eventAggregator = eventAggregator;
Load();
}
private void SettingsOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
Save();
}
public void Save()
{
try
{
var settings = Settings;
var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
if (!Directory.Exists(SwtorCaster))
{
Directory.CreateDirectory(SwtorCaster);
}
File.WriteAllText(SettingsPath, json);
eventAggregator.PublishOnUIThread(settings);
}
catch (Exception e)
{
loggerService.Log(e.Message);
MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public void Load()
{
if (File.Exists(SettingsPath))
{
try
{
var json = File.ReadAllText(SettingsPath);
Settings = JsonConvert.DeserializeObject<AppSettings>(json);
}
catch (Exception e)
{
Settings = new AppSettings();
loggerService.Log(e.Message);
MessageBox.Show("Error reading saved settings, loading default settings.", "Settings", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
Settings = new AppSettings();
}
WireEvents();
}
private void WireEvents()
{
Settings.PropertyChanged -= SettingsOnPropertyChanged;
Settings.PropertyChanged += SettingsOnPropertyChanged;
}
}
} | 31.735632 | 156 | 0.566824 | [
"MIT"
] | pjmagee/SWTOR.Caster | src/SwtorCaster/Core/Services/Settings/SettingsService.cs | 2,761 | C# |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tenancy_config/rpc/room_call_billing_rates_svc.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.TenancyConfig.RPC {
/// <summary>Holder for reflection information generated from tenancy_config/rpc/room_call_billing_rates_svc.proto</summary>
public static partial class RoomCallBillingRatesSvcReflection {
#region Descriptor
/// <summary>File descriptor for tenancy_config/rpc/room_call_billing_rates_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static RoomCallBillingRatesSvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjR0ZW5hbmN5X2NvbmZpZy9ycGMvcm9vbV9jYWxsX2JpbGxpbmdfcmF0ZXNf",
"c3ZjLnByb3RvEh5ob2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZy5ycGMaG2dv",
"b2dsZS9wcm90b2J1Zi9lbXB0eS5wcm90bxosdGVuYW5jeV9jb25maWcvcm9v",
"bV9jYWxsX2JpbGxpbmdfcmF0ZXMucHJvdG8y1QEKF1Jvb21DYWxsQmlsbGlu",
"Z1JhdGVzU3ZjEk8KA0dldBIWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eRowLmhv",
"bG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLlJvb21DYWxsQmlsbGluZ1JhdGVz",
"EmkKA1NldBIwLmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLlJvb21DYWxs",
"QmlsbGluZ1JhdGVzGjAuaG9sbXMudHlwZXMudGVuYW5jeV9jb25maWcuUm9v",
"bUNhbGxCaWxsaW5nUmF0ZXNCM1oRdGVuYW5jeWNvbmZpZy9ycGOqAh1IT0xN",
"Uy5UeXBlcy5UZW5hbmN5Q29uZmlnLlJQQ2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::HOLMS.Types.TenancyConfig.RoomCallBillingRatesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null));
}
#endregion
}
}
#endregion Designer generated code
| 47.733333 | 184 | 0.772812 | [
"MIT"
] | PietroProperties/holms.platformclient.net | csharp/HOLMS.Platform/HOLMS.Platform/Types/out/RoomCallBillingRatesSvc.cs | 2,148 | C# |
namespace Byndyusoft.Dotnet.Core.Infrastructure.Logging.Serilog.Formatting
{
using System;
using System.Diagnostics.CodeAnalysis;
using global::Serilog.Formatting.Json;
[ExcludeFromCodeCoverage]
public class RenderedJsonFormatter : JsonFormatter
{
public RenderedJsonFormatter(string closingDelimiter = null, IFormatProvider formatProvider = null) :
base(closingDelimiter, true, formatProvider)
{
}
}
} | 31.2 | 109 | 0.717949 | [
"MIT"
] | Byndyusoft/Byndyusoft.Dotnet.Core.Infrastructure | src/Infrastructure/Logging.Serilog/Formatting/RenderedJsonFormatter.cs | 470 | C# |
namespace CommunityToolkit.Maui.Markup.Sample.Services;
public class SettingsService
{
public const int MinimumStoriesToFetch = 1;
public const int MaximumStoriesToFetch = 50;
readonly IPreferences preferences;
public SettingsService(IPreferences preferences) => this.preferences = preferences;
public int NumberOfTopStoriesToFetch
{
get => preferences.Get(nameof(NumberOfTopStoriesToFetch), 25, nameof(CommunityToolkit.Maui.Markup.Sample));
set => preferences.Set(nameof(NumberOfTopStoriesToFetch), Math.Clamp(value, MinimumStoriesToFetch, MaximumStoriesToFetch), nameof(CommunityToolkit.Maui.Markup.Sample));
}
} | 37.058824 | 170 | 0.814286 | [
"MIT"
] | ScriptBox99/Maui.Markup | samples/CommunityToolkit.Maui.Markup.Sample/Services/SettingsService.cs | 632 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Uxnet.ToolAdapter.Common
{
public interface IPdfUtility
{
void ConvertHtmlToPDF(String htmlFile, String pdfFile, double timeOutInMinute);
}
public interface IPdfUtility2 : IPdfUtility
{
void ConvertHtmlToPDF(String htmlFile, String pdfFile, double timeOutInMinute,String[] args);
}
}
| 22.315789 | 101 | 0.733491 | [
"MIT"
] | uxb2bralph/IFS-EIVO03 | Uxnet.ToolAdapter/Common/IPdfUtility.cs | 426 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FRONTIERGUI.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FRONTIERGUI.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 44.515625 | 178 | 0.59986 | [
"MIT"
] | gil-unx/FRONTIER-GATE-BOOST-PLUS | FRONTIERGUI/Properties/Resources.Designer.cs | 2,851 | C# |
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Palmmedia.ReportGenerator.Core.Logging;
using Palmmedia.ReportGenerator.Core.Properties;
namespace Palmmedia.ReportGenerator.Core.Parser.Preprocessing
{
/// <summary>
/// Preprocessor for Cobertura reports.
/// </summary>
internal class CoberturaReportPreprocessor
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(CoberturaReportPreprocessor));
/// <summary>
/// Executes the preprocessing of the report.
/// </summary>
/// <param name="report">The report.</param>
internal void Execute(XContainer report)
{
var modules = report.Descendants("package")
.ToArray();
if (modules.Length == 0)
{
if (report.Descendants("packages").Elements("class").Any())
{
Logger.Error(Resources.ErrorInvalidCoberturaReport);
// Fix malformed report files (See issues: #192, #209)
foreach (var packagesElement in report.Descendants("packages").ToArray())
{
packagesElement.Name = "classes";
var parent = packagesElement.Parent;
packagesElement.Remove();
parent.Add(new XElement("packages", new XElement("package", new XAttribute("name", "AutoGenerated"), packagesElement)));
}
}
}
var sources = report.Descendants("sources")
.Elements("source")
.Select(s => s.Value)
.Select(s => s.EndsWith(":") ? s + Path.DirectorySeparatorChar : s) // Issue: #115
.ToArray();
if (sources.Length == 0)
{
return;
}
var classes = report.Descendants("package")
.Elements("classes")
.Elements("class")
.ToArray();
if (sources.Length == 1)
{
foreach (var @class in classes)
{
var fileNameAttribute = @class.Attribute("filename");
if (fileNameAttribute.Value.StartsWith("http://") || fileNameAttribute.Value.StartsWith("https://"))
{
continue;
}
string sourcePath = sources[0]
.Replace('\\', Path.DirectorySeparatorChar)
.Replace('/', Path.DirectorySeparatorChar);
string fileName = fileNameAttribute.Value
.Replace('\\', Path.DirectorySeparatorChar)
.Replace('/', Path.DirectorySeparatorChar);
string path = Path.Combine(sourcePath, fileName);
fileNameAttribute.Value = path;
}
}
else
{
foreach (var @class in classes)
{
var fileNameAttribute = @class.Attribute("filename");
if (fileNameAttribute.Value.StartsWith("http://") || fileNameAttribute.Value.StartsWith("https://"))
{
continue;
}
foreach (var source in sources)
{
string sourcePath = source
.Replace('\\', Path.DirectorySeparatorChar)
.Replace('/', Path.DirectorySeparatorChar);
string fileName = fileNameAttribute.Value
.Replace('\\', Path.DirectorySeparatorChar)
.Replace('/', Path.DirectorySeparatorChar);
string path = Path.Combine(sourcePath, fileName);
if (File.Exists(path))
{
fileNameAttribute.Value = path;
break;
}
}
}
}
}
}
}
| 35.358333 | 144 | 0.469951 | [
"Apache-2.0"
] | 304NotModified/ReportGenerator | src/ReportGenerator.Core/Parser/Preprocessing/CoberturaReportPreprocessor.cs | 4,243 | C# |
// <copyright file="BingMainPageValidator.cs" company="Automate The Planet Ltd.">
// Copyright 2016 Automate The Planet Ltd.
// 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.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SingletonDesignPattern.Core;
namespace SingletonDesignPattern.Pages.BingMainPageSingletonDerived
{
public class BingMainPageValidator : BasePageValidator<BingMainPageElementMap>
{
public void ResultsCount(string expectedCount)
{
Assert.IsTrue(this.Map.ResultsCountDiv.Text.Contains(expectedCount), "The results DIV doesn't contains the specified text.");
}
}
} | 47.346154 | 137 | 0.757108 | [
"Apache-2.0"
] | alihassan5/TestAutomation | DesignPatternsInAutomatedTesting-Series/SingletonDesignPattern/Pages/BingMainPageSingletonDerived/BingMainPageValidator.cs | 1,233 | C# |
using System;
using System.Web;
namespace ExpressiveAnnotations.MvcWebSample.Misc
{
public class ValidationManager
{
private static readonly ValidationManager _instance = new ValidationManager();
private ValidationManager()
{
}
public static ValidationManager Instance
{
get { return _instance; }
}
public void Save(string type, HttpContextBase httpContext)
{
SetValueToCookie(type, httpContext);
}
public string Load(HttpContextBase httpContext)
{
var type = GetValueFromCookie(httpContext);
if (type != null)
return type;
type = "client";
SetValueToCookie(type, httpContext);
return type;
}
private string GetValueFromCookie(HttpContextBase httpContext)
{
var cookie = httpContext.Request.Cookies.Get("expressiv.mvcwebsample.validation");
return cookie != null ? cookie.Value : null;
}
private void SetValueToCookie(string type, HttpContextBase httpContext)
{
var cookie = new HttpCookie("expressiv.mvcwebsample.validation", type) {Expires = DateTime.Now.AddMonths(1)};
httpContext.Response.SetCookie(cookie);
}
}
}
| 28.875 | 122 | 0.58658 | [
"MIT"
] | StandBackBurrito/ExpressiveAnnotations | src/ExpressiveAnnotations.MvcWebSample/Misc/ValidationManager.cs | 1,388 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class EightDirectionMovement : MonoBehaviour
{
// speed in pixels per second the object travels at
public float speed = 200.0f;
[Range(0.0f, 0.3f)] public float smoothing = 0.05f;
private float horizontalInput = 0.0f;
private float verticalInput = 0.0f;
private Vector3 velocity = Vector3.zero;
private Rigidbody2D body;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
private void Update()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
Vector2 moveDirection = body.velocity;
if (moveDirection != Vector2.zero)
{
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
private void FixedUpdate()
{
float xMotion = speed * horizontalInput * Time.fixedDeltaTime;
float yMotion = speed * verticalInput * Time.fixedDeltaTime;
Vector3 targetVelocity = new Vector3(xMotion, yMotion, 0.0f);
body.velocity = Vector3.SmoothDamp(body.velocity, targetVelocity, ref velocity, smoothing);
}
}
| 27.591837 | 99 | 0.670858 | [
"MIT"
] | RichardMarks/UnityCodingDemo | Assets/Scripts/EightDirectionMovement.cs | 1,354 | C# |
using System.Windows.Input;
using Windows.UI.Xaml;
namespace NotepadRs4.Services.DragAndDrop
{
public class ListViewDropConfiguration : DropConfiguration
{
public static readonly DependencyProperty DragItemsStartingCommandProperty =
DependencyProperty.Register("DragItemsStartingCommand", typeof(ICommand), typeof(DropConfiguration), new PropertyMetadata(null));
public static readonly DependencyProperty DragItemsCompletedCommandProperty =
DependencyProperty.Register("DragItemsCompletedCommand", typeof(ICommand), typeof(DropConfiguration), new PropertyMetadata(null));
public ICommand DragItemsStartingCommand
{
get { return (ICommand)GetValue(DragItemsStartingCommandProperty); }
set { SetValue(DragItemsStartingCommandProperty, value); }
}
public ICommand DragItemsCompletedCommand
{
get { return (ICommand)GetValue(DragItemsCompletedCommandProperty); }
set { SetValue(DragItemsCompletedCommandProperty, value); }
}
}
}
| 39.5 | 143 | 0.707957 | [
"MIT"
] | MagicAndre1981/Notepad | NotepadRs4/NotepadRs4/Services/DragAndDrop/ListViewDropConfiguration.cs | 1,108 | C# |
namespace Sitecore.Feature.Media.Tests.Infrastructure
{
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using FluentAssertions;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.FakeDb;
using Sitecore.Feature.Media.Infrastructure.Models;
using Sitecore.Foundation.Testing.Attributes;
using Sitecore.Resources.Media;
using Xunit;
public class MediaBackgroundRenderingModelTests
{
[Theory]
[AutoDbData]
public void MediaType_ListOfTypes_ReturnFirstMediType(Db db, List<string> mimeTypes, MediaBackgroundRenderingModel model)
{
//Arrange
var id = ID.NewID;
db.Add(new DbItem("media", id)
{
{"Mime type", string.Join("/", mimeTypes) }
});
model.Media = db.GetItem(id).Paths.FullPath;
//Act
model.MediaType.Should().Be(mimeTypes.First());
}
[Theory]
[AutoDbData]
public void MediaFormat_ListOfTypes_ReturnLastMimeType(Db db, List<string> mimeTypes, MediaBackgroundRenderingModel model)
{
//Arrange
var id = ID.NewID;
db.Add(new DbItem("media", id)
{
{"Mime type", string.Join("/", mimeTypes) }
});
model.Media = db.GetItem(id).Paths.FullPath;
//Act
model.MediaFormat.Should().Be(mimeTypes.Last());
}
[Theory]
[AutoDbData]
public void MediaType_EmptyMedia_ReturnEmpty(MediaBackgroundRenderingModel model)
{
//Arrange
model.Media = null;
//Act
model.MediaType.Should().BeEmpty();
}
[Theory]
[AutoDbData]
public void MediaFormat_EmptyMedia_ReturnEmpty(MediaBackgroundRenderingModel model)
{
//Arrange
model.Media = null;
//Act
model.MediaFormat.Should().BeEmpty();
}
[Theory]
[AutoDbData]
public void CssClass_NoParallax_ReturnTypeAsClass(string cssClass, MediaBackgroundRenderingModel model)
{
//Arrange
model.Type = cssClass;
model.Parallax = "false";
//Act
model.CssClass.Should().Be(cssClass);
}
[Theory]
[AutoDbData]
public void CssClass_Parallax_ReturnTypeAndParallaxClass(string cssClass, MediaBackgroundRenderingModel model)
{
//Arrange
model.Type = cssClass;
model.Parallax = "true";
//Act
model.CssClass.Should().Be($"{cssClass} bg-parallax");
}
[Theory]
[AutoDbData]
public void IsMedia_NullType_ReturnFalse(MediaBackgroundRenderingModel model)
{
//Arrange
model.Type = null;
//Act
model.IsMedia.Should().BeFalse();
}
[Theory]
[AutoDbData]
public void IsMedia_WrongType_ReturnFalse(string type, MediaBackgroundRenderingModel model)
{
//Arrange
model.Type = type;
//Act
model.IsMedia.Should().BeFalse();
}
[Theory]
[AutoDbData]
public void IsMedia_CorrectType_ReturnTrue(MediaBackgroundRenderingModel model)
{
//Arrange
model.Type = "bg-media";
//Act
model.IsMedia.Should().BeTrue();
}
[Theory]
[AutoDbData]
public void IsMedia_NotSetMediaItem_EmptyBackgroundUrl(MediaBackgroundRenderingModel model)
{
//Arrange
model.Type = "bg-media";
model.Media = null;
//Act
model.MediaAttribute.Should().Be("style=background-image:url('');");
}
[Theory]
[AutoDbData]
public void IsMedia_MediaItemIsSet_EmptyBackgroundUrl(Db db, MediaBackgroundRenderingModel model)
{
//Arrange
model.Type = "bg-media";
var id = ID.NewID;
db.Add(new DbItem("media", id));
model.Media = db.GetItem(id).Paths.FullPath;
var mediaUrl = MediaManager.GetMediaUrl(db.GetItem(id));
//Act
model.MediaAttribute.Should().Be($"style=background-image:url('{mediaUrl}');");
}
}
}
| 25.019608 | 126 | 0.649687 | [
"Apache-2.0"
] | BIGANDYT/HabitatDemo | src/Feature/Media/Tests/Infrastructure/MediaBackgroundRenderingModelTests.cs | 3,830 | C# |
using System;
using System.Collections.Concurrent;
using RadPdf.Lite;
using RadPdf.Integration;
namespace RadPdfDemoNoService.CustomProviders
{
public class MemoryLiteStorageProvider : PdfLiteStorageProvider
{
private ConcurrentDictionary<string, byte[]> _storage;
public MemoryLiteStorageProvider() : base()
{
// This storage mechanism is for demonstration purposes and not recommended in production.
// It uses server memory as the storage location, which will require large amounts of memory.
_storage = new ConcurrentDictionary<string, byte[]>();
}
public override void DeleteData(PdfLiteSession session)
{
throw new NotImplementedException();
}
public override byte[] GetData(PdfLiteSession session, int subtype)
{
string key = CreateStorageKey(session, subtype);
byte[] data;
if (_storage.TryGetValue(key, out data))
{
return data;
}
return null;
}
public override void SetData(PdfLiteSession session, int subtype, byte[] value)
{
string key = CreateStorageKey(session, subtype);
_storage[key] = value;
}
private static string CreateStorageKey(PdfLiteSession session, int subtype)
{
return session.ID.ToString("N") + "-" + subtype.ToString();
}
}
}
| 28.980392 | 105 | 0.615697 | [
"MIT"
] | radpdf/samples | CS_NET6_No_Service/CustomProviders/MemoryLiteStorageProvider.cs | 1,480 | C# |
namespace SIL.Windows.Forms.WritingSystems
{
partial class DeleteInputSystemDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DeleteInputSystemDialog));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this._selectionTable = new System.Windows.Forms.TableLayoutPanel();
this._wsSelectionComboBox = new System.Windows.Forms.ComboBox();
this._helpButton = new System.Windows.Forms.Button();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this._cancelButton = new System.Windows.Forms.Button();
this._okButton = new System.Windows.Forms.Button();
this._radioTable = new System.Windows.Forms.TableLayoutPanel();
this._deleteRadioButton = new System.Windows.Forms.RadioButton();
this._mergeRadioButton = new System.Windows.Forms.RadioButton();
this.tableLayoutPanel1.SuspendLayout();
this._selectionTable.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
this._radioTable.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.AutoSize = true;
this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this._selectionTable, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel3, 0, 2);
this.tableLayoutPanel1.Controls.Add(this._radioTable, 0, 0);
this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 12);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 3;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.Size = new System.Drawing.Size(274, 125);
this.tableLayoutPanel1.TabIndex = 0;
//
// _selectionTable
//
this._selectionTable.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._selectionTable.AutoSize = true;
this._selectionTable.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._selectionTable.ColumnCount = 2;
this._selectionTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this._selectionTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this._selectionTable.Controls.Add(this._wsSelectionComboBox, 0, 0);
this._selectionTable.Controls.Add(this._helpButton, 1, 0);
this._selectionTable.Location = new System.Drawing.Point(3, 55);
this._selectionTable.Name = "_selectionTable";
this._selectionTable.RowCount = 1;
this._selectionTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this._selectionTable.Size = new System.Drawing.Size(268, 32);
this._selectionTable.TabIndex = 0;
//
// _wsSelectionComboBox
//
this._wsSelectionComboBox.FormattingEnabled = true;
this._wsSelectionComboBox.Location = new System.Drawing.Point(3, 3);
this._wsSelectionComboBox.Name = "_wsSelectionComboBox";
this._wsSelectionComboBox.Size = new System.Drawing.Size(230, 21);
this._wsSelectionComboBox.TabIndex = 2;
//
// _helpButton
//
this._helpButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._helpButton.Image = ((System.Drawing.Image)(resources.GetObject("_helpButton.Image")));
this._helpButton.Location = new System.Drawing.Point(239, 3);
this._helpButton.Name = "_helpButton";
this._helpButton.Size = new System.Drawing.Size(26, 26);
this._helpButton.TabIndex = 3;
this._helpButton.UseVisualStyleBackColor = true;
//
// tableLayoutPanel3
//
this.tableLayoutPanel3.AutoSize = true;
this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel3.ColumnCount = 2;
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel3.Controls.Add(this._cancelButton, 1, 0);
this.tableLayoutPanel3.Controls.Add(this._okButton, 0, 0);
this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 93);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 1;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel3.Size = new System.Drawing.Size(268, 29);
this.tableLayoutPanel3.TabIndex = 1;
//
// _cancelButton
//
this._cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this._cancelButton.Location = new System.Drawing.Point(190, 3);
this._cancelButton.Name = "_cancelButton";
this._cancelButton.Size = new System.Drawing.Size(75, 23);
this._cancelButton.TabIndex = 0;
this._cancelButton.Text = "Cancel";
this._cancelButton.UseVisualStyleBackColor = true;
//
// _okButton
//
this._okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this._okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this._okButton.Location = new System.Drawing.Point(109, 3);
this._okButton.Name = "_okButton";
this._okButton.Size = new System.Drawing.Size(75, 23);
this._okButton.TabIndex = 1;
this._okButton.Text = "&Delete";
this._okButton.UseVisualStyleBackColor = true;
//
// _radioTable
//
this._radioTable.AutoSize = true;
this._radioTable.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._radioTable.ColumnCount = 1;
this._radioTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this._radioTable.Controls.Add(this._deleteRadioButton, 0, 0);
this._radioTable.Controls.Add(this._mergeRadioButton, 0, 1);
this._radioTable.Location = new System.Drawing.Point(3, 3);
this._radioTable.Name = "_radioTable";
this._radioTable.RowCount = 2;
this._radioTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._radioTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
this._radioTable.Size = new System.Drawing.Size(159, 46);
this._radioTable.TabIndex = 2;
//
// _deleteRadioButton
//
this._deleteRadioButton.AutoSize = true;
this._deleteRadioButton.Location = new System.Drawing.Point(3, 3);
this._deleteRadioButton.Name = "_deleteRadioButton";
this._deleteRadioButton.Size = new System.Drawing.Size(153, 17);
this._deleteRadioButton.TabIndex = 0;
this._deleteRadioButton.TabStop = true;
this._deleteRadioButton.Text = "Delete all data stored in {0}";
this._deleteRadioButton.UseVisualStyleBackColor = true;
//
// _mergeRadioButton
//
this._mergeRadioButton.AutoSize = true;
this._mergeRadioButton.Location = new System.Drawing.Point(3, 26);
this._mergeRadioButton.Name = "_mergeRadioButton";
this._mergeRadioButton.Size = new System.Drawing.Size(134, 17);
this._mergeRadioButton.TabIndex = 1;
this._mergeRadioButton.TabStop = true;
this._mergeRadioButton.Text = "Merge all {0} data with:";
this._mergeRadioButton.UseVisualStyleBackColor = true;
//
// DeleteInputSystemDialog
//
this.AcceptButton = this._okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.CancelButton = this._cancelButton;
this.ClientSize = new System.Drawing.Size(357, 160);
this.ControlBox = false;
this.Controls.Add(this.tableLayoutPanel1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DeleteInputSystemDialog";
this.Text = "Delete Input System";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this._selectionTable.ResumeLayout(false);
this.tableLayoutPanel3.ResumeLayout(false);
this._radioTable.ResumeLayout(false);
this._radioTable.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TableLayoutPanel _selectionTable;
private System.Windows.Forms.ComboBox _wsSelectionComboBox;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.Button _cancelButton;
private System.Windows.Forms.Button _okButton;
private System.Windows.Forms.TableLayoutPanel _radioTable;
private System.Windows.Forms.RadioButton _deleteRadioButton;
private System.Windows.Forms.RadioButton _mergeRadioButton;
private System.Windows.Forms.Button _helpButton;
}
} | 46.591743 | 152 | 0.758492 | [
"MIT"
] | ArmorBearer/libpalaso | SIL.Windows.Forms.WritingSystems/DeleteInputSystemDialog.Designer.cs | 10,159 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Turmerik.Collections.Helpers;
using Turmerik.Core.Collections;
namespace Turmerik.Collections.Components
{
public abstract class ListBuilderBase<TOut, TIn>
{
protected readonly List<TOut> List;
protected ListBuilderBase()
{
this.List = new List<TOut>();
}
public TOut Add(TIn inVal)
{
TOut outVal = this.GetOutVal(inVal);
this.List.Add(outVal);
return outVal;
}
public TOut[] AddRange(params TIn[] inValsArr)
{
TOut[] retArr = inValsArr.SelToArr(inVal => this.GetOutVal(inVal));
this.List.AddRange(retArr);
return retArr;
}
public int Clear()
{
int retVal = this.List.Count;
this.List.Clear();
return retVal;
}
public List<TOut> ToList()
{
List<TOut> retList = this.List.ToList();
return retList;
}
public TOut[] ToArray()
{
TOut[] retArr = this.List.ToArray();
return retArr;
}
public ReadOnlyCollection<TOut> ToRdnlColl()
{
ReadOnlyCollection<TOut> retColl = this.List.ToRdnlColl();
return retColl;
}
protected abstract TOut GetOutVal(TIn inVal);
}
public class ListBuilder<TVal> : ListBuilderBase<TVal, TVal>
{
protected override TVal GetOutVal(TVal inVal)
{
return inVal;
}
}
public class ListBuilder<TOut, TIn> : ListBuilderBase<TOut, TIn>
{
private readonly Func<TIn, TOut> outValFactory;
public ListBuilder(Func<TIn, TOut> outValFactory)
{
this.outValFactory = outValFactory ?? throw new ArgumentNullException(nameof(outValFactory));
}
protected override TOut GetOutVal(TIn inVal)
{
TOut outVal = this.outValFactory(inVal);
return outVal;
}
}
public class ListBuilder<TOut, T1, T2> : ListBuilderBase<TOut, Tuple<T1, T2>>
{
private readonly Func<T1, T2, TOut> outValFactory;
public ListBuilder(Func<T1, T2, TOut> outValFactory)
{
this.outValFactory = outValFactory ?? throw new ArgumentNullException(nameof(outValFactory));
}
public TOut Add(T1 item1, T2 item2)
{
Tuple<T1, T2> inVal = new Tuple<T1, T2>(
item1,
item2);
TOut retVal = this.Add(inVal);
return retVal;
}
protected override TOut GetOutVal(Tuple<T1, T2> inVal)
{
TOut outVal = this.outValFactory(
inVal.Item1,
inVal.Item2);
return outVal;
}
}
public class ListBuilder<TOut, T1, T2, T3> : ListBuilderBase<TOut, Tuple<T1, T2, T3>>
{
private readonly Func<T1, T2, T3, TOut> outValFactory;
public ListBuilder(Func<T1, T2, T3, TOut> outValFactory)
{
this.outValFactory = outValFactory ?? throw new ArgumentNullException(nameof(outValFactory));
}
public TOut Add(T1 item1, T2 item2, T3 item3)
{
Tuple<T1, T2, T3> inVal = new Tuple<T1, T2, T3>(
item1,
item2,
item3);
TOut retVal = this.Add(inVal);
return retVal;
}
protected override TOut GetOutVal(Tuple<T1, T2, T3> inVal)
{
TOut outVal = this.outValFactory(
inVal.Item1,
inVal.Item2,
inVal.Item3);
return outVal;
}
}
public class ListBuilder<TOut, T1, T2, T3, T4> : ListBuilderBase<TOut, Tuple<T1, T2, T3, T4>>
{
private readonly Func<T1, T2, T3, T4, TOut> outValFactory;
public ListBuilder(Func<T1, T2, T3, T4, TOut> outValFactory)
{
this.outValFactory = outValFactory ?? throw new ArgumentNullException(nameof(outValFactory));
}
public TOut Add(
T1 item1,
T2 item2,
T3 item3,
T4 item4)
{
Tuple<T1, T2, T3, T4> inVal = new Tuple<T1, T2, T3, T4>(
item1,
item2,
item3,
item4);
TOut retVal = this.Add(inVal);
return retVal;
}
protected override TOut GetOutVal(Tuple<T1, T2, T3, T4> inVal)
{
TOut outVal = this.outValFactory(
inVal.Item1,
inVal.Item2,
inVal.Item3,
inVal.Item4);
return outVal;
}
}
public class ListBuilder<TOut, T1, T2, T3, T4, T5> : ListBuilderBase<TOut, Tuple<T1, T2, T3, T4, T5>>
{
private readonly Func<T1, T2, T3, T4, T5, TOut> outValFactory;
public ListBuilder(Func<T1, T2, T3, T4, T5, TOut> outValFactory)
{
this.outValFactory = outValFactory ?? throw new ArgumentNullException(nameof(outValFactory));
}
public TOut Add(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
Tuple<T1, T2, T3, T4, T5> inVal = new Tuple<T1, T2, T3, T4, T5>(
item1,
item2,
item3,
item4,
item5);
TOut retVal = this.Add(inVal);
return retVal;
}
protected override TOut GetOutVal(Tuple<T1, T2, T3, T4, T5> inVal)
{
TOut outVal = this.outValFactory(
inVal.Item1,
inVal.Item2,
inVal.Item3,
inVal.Item4,
inVal.Item5);
return outVal;
}
}
public class ListBuilder<TOut, T1, T2, T3, T4, T5, T6> : ListBuilderBase<TOut, Tuple<T1, T2, T3, T4, T5, T6>>
{
private readonly Func<T1, T2, T3, T4, T5, T6, TOut> outValFactory;
public ListBuilder(Func<T1, T2, T3, T4, T5, T6, TOut> outValFactory)
{
this.outValFactory = outValFactory ?? throw new ArgumentNullException(nameof(outValFactory));
}
public TOut Add(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
Tuple<T1, T2, T3, T4, T5, T6> inVal = new Tuple<T1, T2, T3, T4, T5, T6>(
item1,
item2,
item3,
item4,
item5,
item6);
TOut retVal = this.Add(inVal);
return retVal;
}
protected override TOut GetOutVal(Tuple<T1, T2, T3, T4, T5, T6> inVal)
{
TOut outVal = this.outValFactory(
inVal.Item1,
inVal.Item2,
inVal.Item3,
inVal.Item4,
inVal.Item5,
inVal.Item6);
return outVal;
}
}
public class ListBuilder<TOut, T1, T2, T3, T4, T5, T6, T7> : ListBuilderBase<TOut, Tuple<T1, T2, T3, T4, T5, T6, T7>>
{
private readonly Func<T1, T2, T3, T4, T5, T6, T7, TOut> outValFactory;
public ListBuilder(Func<T1, T2, T3, T4, T5, T6, T7, TOut> outValFactory)
{
this.outValFactory = outValFactory ?? throw new ArgumentNullException(nameof(outValFactory));
}
public TOut Add(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
Tuple<T1, T2, T3, T4, T5, T6, T7> inVal = new Tuple<T1, T2, T3, T4, T5, T6, T7>(
item1,
item2,
item3,
item4,
item5,
item6,
item7);
TOut retVal = this.Add(inVal);
return retVal;
}
protected override TOut GetOutVal(Tuple<T1, T2, T3, T4, T5, T6, T7> inVal)
{
TOut outVal = this.outValFactory(
inVal.Item1,
inVal.Item2,
inVal.Item3,
inVal.Item4,
inVal.Item5,
inVal.Item6,
inVal.Item7);
return outVal;
}
}
public class ListBuilder<TOut, T1, T2, T3, T4, T5, T6, T7, TRest> : ListBuilderBase<TOut, Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>>
{
private readonly Func<T1, T2, T3, T4, T5, T6, T7, TRest, TOut> outValFactory;
public ListBuilder(Func<T1, T2, T3, T4, T5, T6, T7, TRest, TOut> outValFactory)
{
this.outValFactory = outValFactory ?? throw new ArgumentNullException(nameof(outValFactory));
}
public TOut Add(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
{
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> inVal = new Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>(
item1,
item2,
item3,
item4,
item5,
item6,
item7,
rest);
TOut retVal = this.Add(inVal);
return retVal;
}
protected override TOut GetOutVal(Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> inVal)
{
TOut outVal = this.outValFactory(
inVal.Item1,
inVal.Item2,
inVal.Item3,
inVal.Item4,
inVal.Item5,
inVal.Item6,
inVal.Item7,
inVal.Rest);
return outVal;
}
}
}
| 28.591716 | 135 | 0.508796 | [
"MIT"
] | dantincu/turmerik | dotnet/Turmerik.Collections/Components/ListBuilder.cs | 9,666 | C# |
#pragma checksum "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\Shared\Error.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "583387379a597938339285f5a623245873b0a91c"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared_Error), @"mvc.1.0.view", @"/Views/Shared/Error.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Shared/Error.cshtml", typeof(AspNetCore.Views_Shared_Error))]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#line 1 "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\_ViewImports.cshtml"
using MyAnimeWorld.Models;
#line default
#line hidden
#line 2 "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\_ViewImports.cshtml"
using MyAnimeWorld.App.Models;
#line default
#line hidden
#line 3 "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\_ViewImports.cshtml"
using MyAnimeWorld.Common.Main.ViewModels;
#line default
#line hidden
#line 4 "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\_ViewImports.cshtml"
using MyAnimeWorld.Common.Utilities.Constants;
#line default
#line hidden
#line 5 "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\_ViewImports.cshtml"
using MyAnimeWorld.Common.Main.BindingModels;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"583387379a597938339285f5a623245873b0a91c", @"/Views/Shared/Error.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"59425f4569f9df14d12dfd947a78081273c19cb6", @"/Views/_ViewImports.cshtml")]
public class Views_Shared_Error : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<ErrorViewModel>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#line 2 "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\Shared\Error.cshtml"
ViewData["Title"] = "Error";
#line default
#line hidden
BeginContext(64, 120, true);
WriteLiteral("\r\n<h1 class=\"text-danger\">Error.</h1>\r\n<h2 class=\"text-danger\">An error occurred while processing your request.</h2>\r\n\r\n");
EndContext();
#line 9 "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\Shared\Error.cshtml"
if (Model.ShowRequestId)
{
#line default
#line hidden
BeginContext(214, 52, true);
WriteLiteral(" <p>\r\n <strong>Request ID:</strong> <code>");
EndContext();
BeginContext(267, 15, false);
#line 12 "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\Shared\Error.cshtml"
Write(Model.RequestId);
#line default
#line hidden
EndContext();
BeginContext(282, 19, true);
WriteLiteral("</code>\r\n </p>\r\n");
EndContext();
#line 14 "C:\Users\KIRO\source\repos\MyAnimeWorld\MyAnimeWorld.App\Views\Shared\Error.cshtml"
}
#line default
#line hidden
BeginContext(304, 562, true);
WriteLiteral(@"
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application.
</p>
");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ErrorViewModel> Html { get; private set; }
}
}
#pragma warning restore 1591
| 47.140187 | 381 | 0.73751 | [
"MIT"
] | kirrcho/Project | MyAnimeWorld.App/obj/Debug/netcoreapp2.1/Razor/Views/Shared/Error.g.cshtml.cs | 5,044 | C# |
using System;
namespace nyom.queuebuilder
{
public interface IEnfileirarMensagens
{
bool EnfileirarMensagensPush(Guid id);
}
} | 15.666667 | 41 | 0.737589 | [
"MIT"
] | AlessandroSilveira/nyom | nyom/nyom.queuebuilder/IEnfileirarMensagens.cs | 143 | C# |
namespace PS.Learning.Utils.EnvironmentEditor
{
partial class SizeSelectorForm
{
/// <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.okBtn = new System.Windows.Forms.Button();
this.cancelBtn = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.rowsNumUD = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.colsNumUD = new System.Windows.Forms.NumericUpDown();
this.label4 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.rowsNumUD)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.colsNumUD)).BeginInit();
this.SuspendLayout();
//
// okBtn
//
this.okBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.okBtn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.okBtn.Location = new System.Drawing.Point(14, 53);
this.okBtn.Name = "okBtn";
this.okBtn.Size = new System.Drawing.Size(87, 27);
this.okBtn.TabIndex = 3;
this.okBtn.Text = "&OK";
this.okBtn.UseVisualStyleBackColor = true;
this.okBtn.Click += new System.EventHandler(this.OkBtnClick);
//
// cancelBtn
//
this.cancelBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelBtn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cancelBtn.Location = new System.Drawing.Point(152, 53);
this.cancelBtn.Name = "cancelBtn";
this.cancelBtn.Size = new System.Drawing.Size(87, 27);
this.cancelBtn.TabIndex = 4;
this.cancelBtn.Text = "&Cancel";
this.cancelBtn.UseVisualStyleBackColor = true;
this.cancelBtn.Click += new System.EventHandler(this.CancelBtnClick);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(14, 10);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(0, 17);
this.label1.TabIndex = 1;
//
// rowsNumUD
//
this.rowsNumUD.Location = new System.Drawing.Point(77, 14);
this.rowsNumUD.Name = "rowsNumUD";
this.rowsNumUD.Size = new System.Drawing.Size(48, 23);
this.rowsNumUD.TabIndex = 0;
this.rowsNumUD.Value = new decimal(new int[] {
3,
0,
0,
0});
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(14, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(45, 17);
this.label2.TabIndex = 3;
this.label2.Text = "Rows:";
//
// colsNumUD
//
this.colsNumUD.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.colsNumUD.Location = new System.Drawing.Point(191, 14);
this.colsNumUD.Name = "colsNumUD";
this.colsNumUD.Size = new System.Drawing.Size(48, 23);
this.colsNumUD.TabIndex = 1;
this.colsNumUD.Value = new decimal(new int[] {
3,
0,
0,
0});
//
// label4
//
this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(148, 16);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(37, 17);
this.label4.TabIndex = 3;
this.label4.Text = "Cols:";
//
// SizeSelectorForm
//
this.AcceptButton = this.okBtn;
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.CancelButton = this.cancelBtn;
this.ClientSize = new System.Drawing.Size(253, 93);
this.ControlBox = false;
this.Controls.Add(this.label4);
this.Controls.Add(this.colsNumUD);
this.Controls.Add(this.label2);
this.Controls.Add(this.rowsNumUD);
this.Controls.Add(this.label1);
this.Controls.Add(this.cancelBtn);
this.Controls.Add(this.okBtn);
this.Font = new System.Drawing.Font("Candara", 8.830189F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.Black;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "SizeSelectorForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Select Size";
((System.ComponentModel.ISupportInitialize)(this.rowsNumUD)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.colsNumUD)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button okBtn;
private System.Windows.Forms.Button cancelBtn;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown rowsNumUD;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.NumericUpDown colsNumUD;
private System.Windows.Forms.Label label4;
}
} | 44.811321 | 160 | 0.581614 | [
"MIT"
] | pedrodbs/SocioEmotionalIMRL | PS.Learning/Utils/EnvironmentEditor/SizeSelectorForm.Designer.cs | 7,127 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Temp
{
class MergeSortAlgorithm
{
static void Main()
{
int[] numbers = { 1, -1, 2, -2, 3, -3, 4, -4, 5, -5 };
int[] temp = new int[numbers.Length];
System.Console.WriteLine("Before sorting: {0}", string.Join(" ", numbers));
MergeSort(numbers, temp, 0, numbers.Length - 1);
System.Console.WriteLine("After sorting: {0}", string.Join(" ", numbers));
}
static void MergeSort(int[] array, int[] tmp, int start, int end)
{
// Array with 1 element
if (start >= end) return;
// Define a middle of the array
int middle = start + (end - start) / 2;
MergeSort(array, tmp, start, middle);
MergeSort(array, tmp, middle + 1, end);
CompareAndSort(array, tmp, start, middle, end);
}
static void CompareAndSort(int[] array, int[] tmp, int start, int middle, int end)
{
int left_tmp = start, left_arr = start, middle_arr = middle + 1;
while (left_arr <= middle && middle_arr <= end)
{
if (array[left_arr] > array[middle_arr])
{
tmp[left_tmp++] = array[middle_arr++];
}
else
{
tmp[left_tmp++] = array[left_arr++];
}
}
while (left_arr <= middle)
tmp[left_tmp++] = array[left_arr++];
while (middle_arr <= end)
tmp[left_tmp++] = array[middle_arr++];
for (int i = start; i <= end; i++)
array[i] = tmp[i];
}
}
}
| 28.515625 | 90 | 0.484932 | [
"MIT"
] | LuGeorgiev/CSharpSelfLearning | NumberSystems/Temp/Temp.cs | 1,827 | C# |
#pragma checksum "..\..\..\..\Views\BrowserView.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "1A9764E57BD2372BB342E6F668160072"
//------------------------------------------------------------------------------
// <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 MahApps.Metro.Controls;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace WpfApplication1.Views {
/// <summary>
/// BrowserView
/// </summary>
public partial class BrowserView : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
#line 12 "..\..\..\..\Views\BrowserView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TextBlock debug;
#line default
#line hidden
#line 13 "..\..\..\..\Views\BrowserView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TabControl Tabs;
#line default
#line hidden
#line 15 "..\..\..\..\Views\BrowserView.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.WebBrowser browser;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/WpfApplication1;component/views/browserview.xaml", System.UriKind.Relative);
#line 1 "..\..\..\..\Views\BrowserView.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.debug = ((System.Windows.Controls.TextBlock)(target));
return;
case 2:
this.Tabs = ((System.Windows.Controls.TabControl)(target));
return;
case 3:
this.browser = ((System.Windows.Controls.WebBrowser)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 38.8125 | 141 | 0.641592 | [
"MIT"
] | Nymini/Vlive-Streamers | Vlive Stream Machine 3/obj/x64/Debug/Views/BrowserView.g.i.cs | 4,349 | C# |
using Microsoft.EntityFrameworkCore;
using TodoList.Infrastructure.EntityFramework.Entities;
namespace TodoList.Infrastructure.EntityFramework.Contexts
{
public class TodoListDbContext : DbContext
{
public TodoListDbContext(DbContextOptions<TodoListDbContext> options): base(options)
{ }
public DbSet<TodoItemEntity> Items { get; set; }
public DbSet<ToDoListEntity> Lists { get; set; }
public DbSet<UserEntity> Users { get; set; }
}
}
| 30.625 | 92 | 0.718367 | [
"MIT"
] | anton-matsyshyn/easy-peasy-todo-list | src/TodoList.Infrastructure/EntityFramework/Contexts/TodoListDbContext.cs | 492 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Hout.Models.Device;
using Newtonsoft.Json;
namespace Hout.Models.Db
{
public partial class Client
{
private readonly TableColumnInfo[] _deviceColumns =
{
new TableColumnInfo("Id", DbType.Text, false, true),
new TableColumnInfo("Name", DbType.Text, false),
new TableColumnInfo("Type", DbType.Text, false),
new TableColumnInfo("PropertiesJson", DbType.Text)
};
private async Task CreateDeviceTable()
{
if (!await CheckTableExists("Devices"))
{
var createTableSql =
$"CREATE TABLE Devices({string.Join(", ", _deviceColumns.Select(c => c.GetCreateColumnTxt()))});";
_conn.Execute(createTableSql);
}
}
public async Task AddOrUpdate(BaseDevice device)
{
var script = GetInsertScript("Devices", _deviceColumns);
await _conn.ExecuteAsync(script, new
{
Id = device.GetId(),
Name = device.Name,
Type = device.GetType().AssemblyQualifiedName,
PropertiesJson = JsonConvert.SerializeObject(device.Properties, JsonSerializerSettings)
});
}
public async Task Remove(BaseDevice device)
{
var script = $@"DELETE FROM Devices WHERE Id = @Id";
await _conn.ExecuteAsync(script, new {Id = device.Id});
}
public async Task<IEnumerable<BaseDevice>> GetDevices()
{
var recs = await _conn.QueryAsync("SELECT * FROM Devices");
return recs.Select(GetDeviceFromRec);
}
private BaseDevice GetDeviceFromRec(dynamic rec)
{
var type = Type.GetType(rec.Type);
var device = (BaseDevice) Activator.CreateInstance(type);
device.Name = rec.Name;
device.Properties = JsonConvert.DeserializeObject<PropertyCollection>(rec.PropertiesJson);
device.Id = rec.Id;
return device;
}
}
}
| 33.938462 | 118 | 0.587035 | [
"MIT"
] | Inrego/Hout | Hout.Models/Db/Client.Devices.cs | 2,208 | 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("DeRange")]
[assembly: AssemblyDescription("DEsktop aRANGEr")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bright Silence Ltd")]
[assembly: AssemblyProduct("DeRange")]
[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("741737c2-f3b6-497c-9e18-c138a414368c")]
// 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("0.2.2.0")]
[assembly: AssemblyFileVersion("0.2.2.0")]
| 39.333333 | 85 | 0.725282 | [
"Apache-2.0"
] | bright-tools/DeRange | DeRange/Properties/AssemblyInfo.cs | 1,419 | C# |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.Diagnostics;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace HtmlAgilityPack
{
/// <summary>
/// Represents an HTML navigator on an HTML document seen as a data store.
/// </summary>
public class HtmlNodeNavigator : XPathNavigator, IXPathNavigable
{
private HtmlDocument _doc = new HtmlDocument();
private HtmlNode _currentnode;
private int _attindex;
private HtmlNameTable _nametable = new HtmlNameTable();
internal bool Trace = false;
internal HtmlNodeNavigator()
{
Reset();
}
private void Reset()
{
InternalTrace(null);
_currentnode = _doc.DocumentNode;
_attindex = -1;
}
[Conditional("TRACE")]
internal void InternalTrace(object Value)
{
if (!Trace)
{
return;
}
string name = null;
StackFrame sf = new StackFrame(1, true);
name = sf.GetMethod().Name;
string nodename;
if (_currentnode == null)
{
nodename = "(null)";
}
else
{
nodename = _currentnode.Name;
}
string nodevalue;
if (_currentnode == null)
{
nodevalue = "(null)";
}
else
{
switch(_currentnode.NodeType)
{
case HtmlNodeType.Comment:
nodevalue = ((HtmlCommentNode)_currentnode).Comment;
break;
case HtmlNodeType.Document:
nodevalue = "";
break;
case HtmlNodeType.Text:
nodevalue = ((HtmlTextNode)_currentnode).Text;
break;
default:
nodevalue = _currentnode.CloneNode(false).OuterHtml;
break;
}
}
System.Diagnostics.Trace.WriteLine("oid=" + GetHashCode()
+ ",n=" + nodename
+ ",a=" + _attindex + ","
+ ",v=" + nodevalue + ","
+ Value, "N!"+ name);
}
internal HtmlNodeNavigator(HtmlDocument doc, HtmlNode currentNode)
{
if (currentNode == null)
{
throw new ArgumentNullException("currentNode");
}
if (currentNode.OwnerDocument != doc)
{
throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild);
}
InternalTrace(null);
_doc = doc;
Reset();
_currentnode = currentNode;
}
private HtmlNodeNavigator(HtmlNodeNavigator nav)
{
if (nav == null)
{
throw new ArgumentNullException("nav");
}
InternalTrace(null);
_doc = nav._doc;
_currentnode = nav._currentnode;
_attindex = nav._attindex;
_nametable = nav._nametable; // REVIEW: should we do this?
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
public HtmlNodeNavigator(Stream stream)
{
_doc.Load(stream);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(stream, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding)
{
_doc.Load(stream, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML data into the document.</param>
public HtmlNodeNavigator(TextReader reader)
{
_doc.Load(reader);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
public HtmlNodeNavigator(string path)
{
_doc.Load(path);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(path, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(string path, Encoding encoding)
{
_doc.Load(path, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
/// <summary>
/// Gets the name of the current HTML node without the namespace prefix.
/// </summary>
public override string LocalName
{
get
{
if (_attindex != -1)
{
InternalTrace("att>" + _currentnode.Attributes[_attindex].Name);
return _nametable.GetOrAdd(_currentnode.Attributes[_attindex].Name);
}
else
{
InternalTrace("node>" + _currentnode.Name);
return _nametable.GetOrAdd(_currentnode.Name);
}
}
}
/// <summary>
/// Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string NamespaceURI
{
get
{
InternalTrace(">");
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the qualified name of the current node.
/// </summary>
public override string Name
{
get
{
InternalTrace(">" + _currentnode.Name);
return _nametable.GetOrAdd(_currentnode.Name);
}
}
/// <summary>
/// Gets the prefix associated with the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string Prefix
{
get
{
InternalTrace(null);
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the type of the current node.
/// </summary>
public override XPathNodeType NodeType
{
get
{
switch(_currentnode.NodeType)
{
case HtmlNodeType.Comment:
InternalTrace(">" + XPathNodeType.Comment);
return XPathNodeType.Comment;
case HtmlNodeType.Document:
InternalTrace(">" + XPathNodeType.Root);
return XPathNodeType.Root;
case HtmlNodeType.Text:
InternalTrace(">" + XPathNodeType.Text);
return XPathNodeType.Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
InternalTrace(">" + XPathNodeType.Attribute);
return XPathNodeType.Attribute;
}
InternalTrace(">" + XPathNodeType.Element);
return XPathNodeType.Element;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the text value of the current node.
/// </summary>
public override string Value
{
get
{
InternalTrace("nt=" + _currentnode.NodeType);
switch(_currentnode.NodeType)
{
case HtmlNodeType.Comment:
InternalTrace(">" + ((HtmlCommentNode)_currentnode).Comment);
return ((HtmlCommentNode)_currentnode).Comment;
case HtmlNodeType.Document:
InternalTrace(">");
return "";
case HtmlNodeType.Text:
InternalTrace(">" + ((HtmlTextNode)_currentnode).Text);
return ((HtmlTextNode)_currentnode).Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
InternalTrace(">" + _currentnode.Attributes[_attindex].Value);
return _currentnode.Attributes[_attindex].Value;
}
return _currentnode.InnerText;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the base URI for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string BaseURI
{
get
{
InternalTrace(">");
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the xml:lang scope for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string XmlLang
{
get
{
InternalTrace(null);
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets a value indicating whether the current node is an empty element.
/// </summary>
public override bool IsEmptyElement
{
get
{
InternalTrace(">" + !HasChildren);
// REVIEW: is this ok?
return !HasChildren;
}
}
/// <summary>
/// Gets the XmlNameTable associated with this implementation.
/// </summary>
public override XmlNameTable NameTable
{
get
{
InternalTrace(null);
return _nametable;
}
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasAttributes
{
get
{
InternalTrace(">" + (_currentnode.Attributes.Count>0));
return (_currentnode.Attributes.Count>0);
}
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasChildren
{
get
{
InternalTrace(">" + (_currentnode.ChildNodes.Count>0));
return (_currentnode.ChildNodes.Count>0);
}
}
/// <summary>
/// Moves to the next sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the next sibling node, false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToNext()
{
if (_currentnode.NextSibling == null)
{
InternalTrace(">false");
return false;
}
InternalTrace("_c=" + _currentnode.CloneNode(false).OuterHtml);
InternalTrace("_n=" + _currentnode.NextSibling.CloneNode(false).OuterHtml);
_currentnode = _currentnode.NextSibling;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the previous sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the previous sibling node, false if there is no previous sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToPrevious()
{
if (_currentnode.PreviousSibling == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.PreviousSibling;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the first sibling node, false if there is no first sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToFirst()
{
if (_currentnode.ParentNode == null)
{
InternalTrace(">false");
return false;
}
if (_currentnode.ParentNode.FirstChild == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ParentNode.FirstChild;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first child of the current node.
/// </summary>
/// <returns>true if there is a first child node, otherwise false.</returns>
public override bool MoveToFirstChild()
{
if (!_currentnode.HasChildNodes)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ChildNodes[0];
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the parent of the current node.
/// </summary>
/// <returns>true if there is a parent node, otherwise false.</returns>
public override bool MoveToParent()
{
if (_currentnode.ParentNode == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ParentNode;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the root node to which the current node belongs.
/// </summary>
public override void MoveToRoot()
{
_currentnode = _doc.DocumentNode;
InternalTrace(null);
}
/// <summary>
/// Moves to the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator positioned on the node that you want to move to.</param>
/// <returns>true if successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveTo(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
InternalTrace(">false (nav is not an HtmlNodeNavigator)");
return false;
}
InternalTrace("moveto oid=" + nav.GetHashCode()
+ ", n:" + nav._currentnode.Name
+ ", a:" + nav._attindex);
if (nav._doc == _doc)
{
_currentnode = nav._currentnode;
_attindex = nav._attindex;
InternalTrace(">true");
return true;
}
// we don't know how to handle that
InternalTrace(">false (???)");
return false;
}
/// <summary>
/// Moves to the node that has an attribute of type ID whose value matches the specified string.
/// </summary>
/// <param name="id">A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.</param>
/// <returns>true if the move was successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToId(string id)
{
InternalTrace("id=" + id);
HtmlNode node = _doc.GetElementbyId(id);
if (node == null)
{
InternalTrace(">false");
return false;
}
_currentnode = node;
InternalTrace(">true");
return true;
}
/// <summary>
/// Determines whether the current HtmlNavigator is at the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator that you want to compare against.</param>
/// <returns>true if the two navigators have the same position, otherwise, false.</returns>
public override bool IsSamePosition(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
InternalTrace(">false");
return false;
}
InternalTrace(">" + (nav._currentnode == _currentnode));
return (nav._currentnode == _currentnode);
}
/// <summary>
/// Creates a new HtmlNavigator positioned at the same node as this HtmlNavigator.
/// </summary>
/// <returns>A new HtmlNavigator object positioned at the same node as the original HtmlNavigator.</returns>
public override XPathNavigator Clone()
{
InternalTrace(null);
return new HtmlNodeNavigator(this);
}
/// <summary>
/// Gets the value of the HTML attribute with the specified LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>The value of the specified HTML attribute. String.Empty or null if a matching attribute is not found or if the navigator is not positioned on an element node.</returns>
public override string GetAttribute(string localName, string namespaceURI)
{
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
HtmlAttribute att = _currentnode.Attributes[localName];
if (att == null)
{
InternalTrace(">null");
return null;
}
InternalTrace(">" + att.Value);
return att.Value;
}
/// <summary>
/// Moves to the HTML attribute with matching LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>true if the HTML attribute is found, otherwise, false. If false, the position of the navigator does not change.</returns>
public override bool MoveToAttribute(string localName, string namespaceURI)
{
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
int index = _currentnode.Attributes.GetAttributeIndex(localName);
if (index == -1)
{
InternalTrace(">false");
return false;
}
_attindex = index;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first HTML attribute.
/// </summary>
/// <returns>true if the navigator is successful moving to the first HTML attribute, otherwise, false.</returns>
public override bool MoveToFirstAttribute()
{
if (!HasAttributes)
{
InternalTrace(">false");
return false;
}
_attindex = 0;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the next HTML attribute.
/// </summary>
/// <returns></returns>
public override bool MoveToNextAttribute()
{
InternalTrace(null);
if (_attindex>=(_currentnode.Attributes.Count-1))
{
InternalTrace(">false");
return false;
}
_attindex++;
InternalTrace(">true");
return true;
}
/// <summary>
/// Returns the value of the namespace node corresponding to the specified local name.
/// Always returns string.Empty for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns string.Empty for the HtmlNavigator implementation.</returns>
public override string GetNamespace(string name)
{
InternalTrace("name=" + name);
return string.Empty;
}
/// <summary>
/// Moves the XPathNavigator to the namespace node with the specified local name.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNamespace(string name)
{
InternalTrace("name=" + name);
return false;
}
/// <summary>
/// Moves the XPathNavigator to the first namespace node of the current element.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
InternalTrace(null);
return false;
}
/// <summary>
/// Moves the XPathNavigator to the next namespace node.
/// Always returns falsefor the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
InternalTrace(null);
return false;
}
/// <summary>
/// Gets the current HTML node.
/// </summary>
public HtmlNode CurrentNode
{
get
{
return _currentnode;
}
}
/// <summary>
/// Gets the current HTML document.
/// </summary>
public HtmlDocument CurrentDocument
{
get
{
return _doc;
}
}
}
}
| 29.259115 | 249 | 0.678474 | [
"MIT"
] | shana/bugzz | 3rdparty/HtmlAgilityPack/HtmlNodeNavigator.cs | 22,471 | C# |
using System;
namespace entr1.Models
{
public class Funcionario
{
public int IdFuncionario { get; set; }
public string Nome { get; set; }
public string Email { get; set; }
public string Departamento { get; set; }
public DateTime? DataNascimento { get; set; }
public string TelefonePrimario { get; set; }
public string TelefoneSecundario { get; set; }
public string Login { get; set; }
public string Senha { get; set; }
public bool AcessoAoIClips { get; set; }
public bool AtivoNaAgencia { get; set; }
}
} | 21.482759 | 54 | 0.58748 | [
"MIT"
] | jonataspiazzi/Aula | genesis/exercicios/entr1/Models/Funcionario.cs | 623 | C# |
using System;
using UnityEngine;
// Token: 0x02000039 RID: 57
public class FollowPlayer : MonoBehaviour
{
// Token: 0x06000428 RID: 1064 RVA: 0x00021AA0 File Offset: 0x0001FCA0
private void LateUpdate()
{
Camera mainCamera = Utils.GetMainCamera();
if (Player.m_localPlayer == null || mainCamera == null)
{
return;
}
Vector3 vector = Vector3.zero;
if (this.m_follow == FollowPlayer.Type.Camera || GameCamera.InFreeFly())
{
vector = mainCamera.transform.position;
}
else
{
vector = Player.m_localPlayer.transform.position;
}
if (this.m_lockYPos)
{
vector.y = base.transform.position.y;
}
if (vector.y > this.m_maxYPos)
{
vector.y = this.m_maxYPos;
}
base.transform.position = vector;
}
// Token: 0x04000428 RID: 1064
public FollowPlayer.Type m_follow = FollowPlayer.Type.Camera;
// Token: 0x04000429 RID: 1065
public bool m_lockYPos;
// Token: 0x0400042A RID: 1066
public bool m_followCameraInFreefly;
// Token: 0x0400042B RID: 1067
public float m_maxYPos = 1000000f;
// Token: 0x02000139 RID: 313
public enum Type
{
// Token: 0x0400105D RID: 4189
Player,
// Token: 0x0400105E RID: 4190
Camera
}
}
| 21.035714 | 74 | 0.697793 | [
"Apache-2.0"
] | ingvard/valheim-jserver | materials/sources/assembly_valheim/FollowPlayer.cs | 1,180 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lm.ErrorsNotification.Service.Dal
{
[Serializable]
public class CachedItem<T>
{
public virtual T Item { get; set; }
public virtual DateTime InsertedDate { get; set; }
public CachedItem(){
InsertedDate = DateTime.Now;
}
public CachedItem(T items){
this.InsertedDate = DateTime.Now;
this.Item = items;
}
}
}
| 22.909091 | 58 | 0.609127 | [
"MIT"
] | EdutechSRL/Adevico | 3-Business/4-Services/ErrorNotifications/lm.ErrorsNotification.Service/Dal/CachedItem.cs | 506 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Contains Call Center statistics reporting settings.
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:18810""}]")]
public class GroupCallCenterGetInstanceStatisticsReportingResponse16 : BroadWorksConnector.Ocip.Models.C.OCIDataResponse
{
private bool _generateDailyReport;
[XmlElement(ElementName = "generateDailyReport", IsNullable = false, Namespace = "")]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:18810")]
public bool GenerateDailyReport
{
get => _generateDailyReport;
set
{
GenerateDailyReportSpecified = true;
_generateDailyReport = value;
}
}
[XmlIgnore]
protected bool GenerateDailyReportSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterStatisticsCollectionPeriodMinutes _collectionPeriodMinutes;
[XmlElement(ElementName = "collectionPeriodMinutes", IsNullable = false, Namespace = "")]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:18810")]
public BroadWorksConnector.Ocip.Models.CallCenterStatisticsCollectionPeriodMinutes CollectionPeriodMinutes
{
get => _collectionPeriodMinutes;
set
{
CollectionPeriodMinutesSpecified = true;
_collectionPeriodMinutes = value;
}
}
[XmlIgnore]
protected bool CollectionPeriodMinutesSpecified { get; set; }
private string _reportingEmailAddress1;
[XmlElement(ElementName = "reportingEmailAddress1", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:18810")]
[MinLength(1)]
[MaxLength(80)]
public string ReportingEmailAddress1
{
get => _reportingEmailAddress1;
set
{
ReportingEmailAddress1Specified = true;
_reportingEmailAddress1 = value;
}
}
[XmlIgnore]
protected bool ReportingEmailAddress1Specified { get; set; }
private string _reportingEmailAddress2;
[XmlElement(ElementName = "reportingEmailAddress2", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:18810")]
[MinLength(1)]
[MaxLength(80)]
public string ReportingEmailAddress2
{
get => _reportingEmailAddress2;
set
{
ReportingEmailAddress2Specified = true;
_reportingEmailAddress2 = value;
}
}
[XmlIgnore]
protected bool ReportingEmailAddress2Specified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterStatisticsSource _statisticsSource;
[XmlElement(ElementName = "statisticsSource", IsNullable = false, Namespace = "")]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:18810")]
public BroadWorksConnector.Ocip.Models.CallCenterStatisticsSource StatisticsSource
{
get => _statisticsSource;
set
{
StatisticsSourceSpecified = true;
_statisticsSource = value;
}
}
[XmlIgnore]
protected bool StatisticsSourceSpecified { get; set; }
}
}
| 33.178571 | 131 | 0.63267 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/GroupCallCenterGetInstanceStatisticsReportingResponse16.cs | 3,716 | C# |
#region MIT
// /*The MIT License (MIT)
//
// Copyright 2016 lizs lizs4ever@163.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// * */
#endregion
using System;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedParameter.Local
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
namespace socket4net.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage
/// </summary>
/// <example><code>
/// [CanBeNull] public object Test() { return null; }
/// public void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Property | AttributeTargets.Delegate |
AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class CanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>
/// </summary>
/// <example><code>
/// [NotNull] public object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Property | AttributeTargets.Delegate |
AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class NotNullAttribute : Attribute { }
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form
/// </summary>
/// <example><code>
/// [StringFormatMethod("message")]
/// public void ShowError(string message, params object[] args) { /* do something */ }
/// public void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method,
AllowMultiple = false, Inherited = true)]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute(string formatParameterName)
{
FormatParameterName = formatParameterName;
}
public string FormatParameterName { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>
/// </summary>
/// <example><code>
/// public void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <see cref="System.ComponentModel.INotifyPropertyChanged"/> interface
/// and this method is used to notify that some property value changed
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example><code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// private string _name;
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() => Property)</c></item>
/// <item><c>NotifyChanged((VM x) => x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute() { }
public NotifyPropertyChangedInvocatorAttribute(string parameterName)
{
ParameterName = parameterName;
}
public string ParameterName { get; private set; }
}
/// <summary>
/// Describes dependency between method input and output
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same)
/// for method output means that the methos doesn't return normally.<br/>
/// <c>canbenull</c> annotation is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row,
/// or use single attribute with rows separated by semicolon.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null, and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) { }
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that marked element should be localized or not
/// </summary>
/// <example><code>
/// [LocalizationRequiredAttribute(true)]
/// public class Foo {
/// private string str = "my string"; // Warning: Localizable string
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true) { }
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example><code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
/// class UsesNoEquality {
/// public void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Interface | AttributeTargets.Class |
AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute { }
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example><code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute { }
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent { }
/// </code></example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull] public Type BaseType { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly
/// (e.g. via reflection, in external library), so this symbol
/// will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public UsedImplicitlyAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; private set; }
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper
/// to not mark symbols marked with such attributes as unused
/// (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public MeansImplicitUseAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type</summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly
/// when marked with <see cref="MeansImplicitUseAttribute"/>
/// or <see cref="UsedImplicitlyAttribute"/>
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used
/// </summary>
[MeansImplicitUse]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute() { }
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
[NotNull] public string Comment { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled
/// when the invoked method is on stack. If the parameter is a delegate,
/// indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated
/// while the method is executed
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = true)]
public sealed class InstantHandleAttribute : Attribute { }
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>
/// </summary>
/// <example><code>
/// [Pure] private int Multiply(int x, int y) { return x * y; }
/// public void Foo() {
/// const int a = 2, b = 2;
/// Multiply(a, b); // Waring: Return value of pure method is not used
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public sealed class PureAttribute : Attribute { }
/// <summary>
/// Indicates that a parameter is a path to a file or a folder
/// within a web project. Path can be relative or absolute,
/// starting from web root (~)
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute() { }
public PathReferenceAttribute([PathReference] string basePath)
{
BasePath = basePath;
}
[NotNull] public string BasePath { get; private set; }
}
// ASP.NET MVC attributes
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute(string format) { }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute() { }
public AspMvcActionAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : PathReferenceAttribute
{
public AspMvcAreaAttribute() { }
public AspMvcAreaAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that
/// the parameter is an MVC controller. If applied to a method,
/// the MVC controller name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute() { }
public AspMvcControllerAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(String, Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that
/// the parameter is an MVC partial view. If applied to a method,
/// the MVC partial view name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. Allows disabling all inspections
/// for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSupressViewErrorAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name
/// </summary>
/// <example><code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute { }
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Field, Inherited = true)]
public sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute() { }
public HtmlElementAttributesAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Field |
AttributeTargets.Property, Inherited = true)]
public sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
// Razor attributes
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, Inherited = true)]
public sealed class RazorSectionAttribute : Attribute { }
} | 39.137931 | 103 | 0.702483 | [
"MIT"
] | lizs/Socket4Net | Core/Properties/Annotations.cs | 24,972 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace CRM.Interface
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Teamrraprogram operations.
/// </summary>
public partial class Teamrraprogram : IServiceOperations<DynamicsClient>, ITeamrraprogram
{
/// <summary>
/// Initializes a new instance of the Teamrraprogram class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Teamrraprogram(DynamicsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DynamicsClient
/// </summary>
public DynamicsClient Client { get; private set; }
/// <summary>
/// Get team_rra_program from teams
/// </summary>
/// <param name='ownerid'>
/// key: ownerid of team
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMrraProgramCollection>> GetWithHttpMessagesAsync(string ownerid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (ownerid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ownerid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("ownerid", ownerid);
tracingParameters.Add("top", top);
tracingParameters.Add("skip", skip);
tracingParameters.Add("search", search);
tracingParameters.Add("filter", filter);
tracingParameters.Add("count", count);
tracingParameters.Add("orderby", orderby);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "teams({ownerid})/team_rra_program").ToString();
_url = _url.Replace("{ownerid}", System.Uri.EscapeDataString(ownerid));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (skip != null)
{
_queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"'))));
}
if (search != null)
{
_queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (count != null)
{
_queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
}
if (orderby != null)
{
_queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby))));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMrraProgramCollection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMrraProgramCollection>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get team_rra_program from teams
/// </summary>
/// <param name='ownerid'>
/// key: ownerid of team
/// </param>
/// <param name='rraProgramid'>
/// key: rra_programid of rra_program
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMrraProgram>> ProgramByKeyWithHttpMessagesAsync(string ownerid, string rraProgramid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (ownerid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ownerid");
}
if (rraProgramid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "rraProgramid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("ownerid", ownerid);
tracingParameters.Add("rraProgramid", rraProgramid);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ProgramByKey", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "teams({ownerid})/team_rra_program({rra_programid})").ToString();
_url = _url.Replace("{ownerid}", System.Uri.EscapeDataString(ownerid));
_url = _url.Replace("{rra_programid}", System.Uri.EscapeDataString(rraProgramid));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMrraProgram>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMrraProgram>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 43.857143 | 543 | 0.558231 | [
"MIT"
] | msehudi/cms-accelerator | OData.OpenAPI/odata2openapi/Client/Teamrraprogram.cs | 18,727 | C# |
#region Using directives
using Blazorise.Utilities;
using Microsoft.AspNetCore.Components;
#endregion
namespace Blazorise
{
/// <summary>
/// Base class for components that are containers for other components.
/// </summary>
public abstract class BaseContainerComponent : BaseComponent
{
#region Members
private IFluentColumn columnSize;
#endregion
#region Methods
/// <inheritdoc/>
protected override void BuildClasses( ClassBuilder builder )
{
if ( ColumnSize != null )
builder.Append( ColumnSize.Class( ClassProvider ) );
base.BuildClasses( builder );
}
#endregion
#region Properties
/// <summary>
/// Defines the column sizes.
/// </summary>
[Parameter]
public IFluentColumn ColumnSize
{
get => columnSize;
set
{
columnSize = value;
DirtyClasses();
}
}
/// <summary>
/// Specifies the content to be rendered inside this <see cref="BaseContainerComponent"/>.
/// </summary>
[Parameter] public RenderFragment ChildContent { get; set; }
#endregion
}
}
| 22.561404 | 98 | 0.55832 | [
"MIT"
] | CPlusPlus17/Blazorise | Source/Blazorise/Base/BaseContainerComponent.razor.cs | 1,288 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Synapse.Models
{
/// <summary>
/// Defines values for NodeSize.
/// </summary>
public static class NodeSize
{
public const string None = "None";
public const string Small = "Small";
public const string Medium = "Medium";
public const string Large = "Large";
public const string XLarge = "XLarge";
public const string XXLarge = "XXLarge";
}
}
| 29.814815 | 74 | 0.669565 | [
"MIT"
] | AWESOME-S-MINDSET/azure-sdk-for-net | sdk/synapse/Microsoft.Azure.Management.Synapse/src/Generated/Models/NodeSize.cs | 805 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Spark.CSharp.Configuration;
using Microsoft.Spark.CSharp.Network;
using NUnit.Framework;
namespace AdapterTest
{
/// <summary>
/// Validates SaeaSocketWrapper by creating a ISocketWrapper server to
/// simulate interactions between CSharpRDD and CSharpWorker
/// </summary>
[TestFixture]
public class SocketWrapperTest
{
private void SocketTest(ISocketWrapper serverSocket)
{
serverSocket.Listen();
if (serverSocket is RioSocketWrapper)
{
// Do nothing for second listen operation.
Assert.DoesNotThrow(() => serverSocket.Listen(int.MaxValue));
}
var port = ((IPEndPoint)serverSocket.LocalEndPoint).Port;
var clientMsg = "Hello Message from client";
var clientMsgBytes = Encoding.UTF8.GetBytes(clientMsg);
Task.Run(() =>
{
var bytes = new byte[1024];
using (var socket = serverSocket.Accept())
{
using (var s = socket.GetStream())
{
// Receive data
var bytesRec = s.Read(bytes, 0, bytes.Length);
// send echo message.
s.Write(bytes, 0, bytesRec);
s.Flush();
// Receive one byte
var oneByte = s.ReadByte();
// Send echo one byte
byte[] oneBytes = { (byte)oneByte };
s.Write(oneBytes, 0, oneBytes.Length);
Thread.SpinWait(0);
// Keep sending to ensure no memory leak
var longBytes = Encoding.UTF8.GetBytes(new string('x', 8192));
for (int i = 0; i < 1000; i++)
{
s.Write(longBytes, 0, longBytes.Length);
}
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
s.Write(msg, 0, msg.Length);
// Receive echo byte.
s.ReadByte();
}
}
});
var clientSock = SocketFactory.CreateSocket();
// Valid invalid operation
Assert.Throws<InvalidOperationException>(() => clientSock.GetStream());
Assert.Throws<InvalidOperationException>(() => clientSock.Receive());
Assert.Throws<InvalidOperationException>(() => clientSock.Send(null));
Assert.Throws<SocketException>(() => clientSock.Connect(IPAddress.Any, 1024));
clientSock.Connect(IPAddress.Loopback, port);
// Valid invalid operation
var byteBuf = ByteBufPool.Default.Allocate();
Assert.Throws<ArgumentException>(() => clientSock.Send(byteBuf));
byteBuf.Release();
Assert.Throws<SocketException>(() => clientSock.Listen());
if (clientSock is RioSocketWrapper)
{
Assert.Throws<InvalidOperationException>(() => clientSock.Accept());
}
using (var s = clientSock.GetStream())
{
// Send message
s.Write(clientMsgBytes, 0, clientMsgBytes.Length);
// Receive echo message
var bytes = new byte[1024];
var bytesRec = s.Read(bytes, 0, bytes.Length);
Assert.AreEqual(clientMsgBytes.Length, bytesRec);
var recvStr = Encoding.UTF8.GetString(bytes, 0, bytesRec);
Assert.AreEqual(clientMsg, recvStr);
// Send one byte
byte[] oneBytes = { 1 };
s.Write(oneBytes, 0, oneBytes.Length);
// Receive echo message
var oneByte = s.ReadByte();
Assert.AreEqual((byte)1, oneByte);
// Keep receiving to ensure no memory leak.
while (true)
{
bytesRec = s.Read(bytes, 0, bytes.Length);
recvStr = Encoding.UTF8.GetString(bytes, 0, bytesRec);
if (recvStr.IndexOf("<EOF>", StringComparison.OrdinalIgnoreCase) > -1)
{
break;
}
}
// send echo bytes
s.Write(oneBytes, 0, oneBytes.Length);
}
clientSock.Close();
// Verify invalid operation
Assert.Throws<ObjectDisposedException>(() => clientSock.Receive());
serverSocket.Close();
}
[Test]
public void TestSaeaSocket()
{
// Set Socket wrapper to Saea
Environment.SetEnvironmentVariable(ConfigurationService.CSharpSocketTypeEnvName, "Saea");
SocketFactory.SocketWrapperType = SocketWrapperType.None;
var serverSocket = SocketFactory.CreateSocket();
Assert.IsTrue(serverSocket is SaeaSocketWrapper);
SocketTest(serverSocket);
// Reset socket wrapper type
Environment.SetEnvironmentVariable(ConfigurationService.CSharpSocketTypeEnvName, string.Empty);
SocketFactory.SocketWrapperType = SocketWrapperType.None;
}
[Test]
public void TestRioSocket()
{
if (!SocketFactory.IsRioSockSupported())
{
Assert.Ignore("Omitting due to missing Riosock.dll. It might caused by no VC++ build tool or running on an OS that not supports Windows RIO socket.");
}
// Set Socket wrapper to Rio
Environment.SetEnvironmentVariable(ConfigurationService.CSharpSocketTypeEnvName, "Rio");
SocketFactory.SocketWrapperType = SocketWrapperType.None;
RioSocketWrapper.rioRqGrowthFactor = 1;
var serverSocket = SocketFactory.CreateSocket();
Assert.IsTrue(serverSocket is RioSocketWrapper);
SocketTest(serverSocket);
// Reset socket wrapper type
Environment.SetEnvironmentVariable(ConfigurationService.CSharpSocketTypeEnvName, string.Empty);
SocketFactory.SocketWrapperType = SocketWrapperType.None;
RioNative.UnloadRio();
}
[Test]
public void TestUseThreadPoolForRioNative()
{
if (!SocketFactory.IsRioSockSupported())
{
Assert.Ignore("Omitting due to missing Riosock.dll. It might caused by no VC++ build tool or running on an OS that not supports Windows RIO socket.");
}
RioNative.SetUseThreadPool(true);
RioNative.EnsureRioLoaded();
Assert.AreEqual(Environment.ProcessorCount, RioNative.GetWorkThreadNumber());
RioNative.UnloadRio();
RioNative.SetUseThreadPool(false);
}
[Test]
public void TestUseSingleThreadForRioNative()
{
if (!SocketFactory.IsRioSockSupported())
{
Assert.Ignore("Omitting due to missing Riosock.dll. It might caused by no VC++ build tool or running on an OS that not supports Windows RIO socket.");
}
RioNative.SetUseThreadPool(false);
RioNative.EnsureRioLoaded();
Assert.AreEqual(1, RioNative.GetWorkThreadNumber());
RioNative.UnloadRio();
}
}
} | 38.642157 | 166 | 0.549283 | [
"MIT"
] | qintao1976/Mobius | csharp/AdapterTest/SocketWrapperTest.cs | 7,885 | C# |
#region Using Directives
using System;
using System.Collections.Generic;
using StackExchange.NET.Helpers;
using StackExchange.NET.Interfaces;
using StackExchange.NET.Models;
#endregion
namespace StackExchange.NET.Clients
{
public partial class StackExchangeClient : IQuestions
{
/// <summary>
/// StackExchangeClient used to perform operations on APIs.
/// </summary>
public IQuestions Questions => this;
BaseResponse<Question> IQuestions.GetAllQuestions(QuestionFilters filters)
{
var url = ApiUrlBuilder
.Initialize(_apiKey)
.ForClient(ClientType.Questions)
.WithFilter(filters)
.GetApiUrl();
var response = _httpClient.GetAsync(url).Result.ReadAsJsonAsync<Data<Question>>().ValidateApiResponse();
return response;
}
BaseResponse<Question> IQuestions.GetQuestionsByIds(List<string> ids, QuestionFilters filters)
{
var url = ApiUrlBuilder.Initialize(_apiKey)
.ForClient(ClientType.Questions)
.WithFilter(filters)
.WithIds(ids)
.GetApiUrl();
var response = _httpClient.GetAsync(url).Result.ReadAsJsonAsync<Data<Question>>().ValidateApiResponse();
return response;
}
BaseResponse<Answer> IQuestions.GetAnswersByQuestionIds(List<string> ids, QuestionFilters filters)
{
var url = ApiUrlBuilder.Initialize(_apiKey)
.ForClient(ClientType.Questions)
.WithFilter(filters)
.WithIds(ids)
.GetApiUrl();
var response = _httpClient.GetAsync(url).Result.ReadAsJsonAsync<Data<Answer>>().ValidateApiResponse();
return response;
}
BaseResponse<Comment> IQuestions.GetCommentsByQuestionIds(List<string> ids, QuestionFilters filters)
{
var url = ApiUrlBuilder.Initialize(_apiKey)
.ForClient(ClientType.Questions)
.WithFilter(filters)
.WithIds(ids)
.GetApiUrl();
var response = _httpClient.GetAsync(url).Result.ReadAsJsonAsync<Data<Comment>>().ValidateApiResponse();
return response;
}
BaseResponse<Question> IQuestions.GetLinkedQuestions(List<string> ids, QuestionFilters filters)
{
var url = ApiUrlBuilder.Initialize(_apiKey)
.ForClient(ClientType.Questions)
.WithFilter(filters)
.WithIds(ids,"linked")
.GetApiUrl();
var response = _httpClient.GetAsync(url).Result.ReadAsJsonAsync<Data<Question>>().ValidateApiResponse();
return response;
}
BaseResponse<Question> IQuestions.GetRelatedQuestions(List<string> ids, QuestionFilters filters)
{
var url = ApiUrlBuilder.Initialize(_apiKey)
.ForClient(ClientType.Questions)
.WithFilter(filters)
.WithIds(ids,"related")
.GetApiUrl();
var response = _httpClient.GetAsync(url).Result.ReadAsJsonAsync<Data<Question>>().ValidateApiResponse();
return response;
}
BaseResponse<Question> IQuestions.GetTimeLine(List<string> ids, QuestionFilters filters)
{
throw new NotImplementedException();
}
BaseResponse<Question> IQuestions.GetFeaturedQuestions(QuestionFilters filters)
{
var url = ApiUrlBuilder
.Initialize(_apiKey)
.ForClient(ClientType.Questions,"featured")
.WithFilter(filters)
.GetApiUrl();
var response = _httpClient.GetAsync(url).Result.ReadAsJsonAsync<Data<Question>>().ValidateApiResponse();
return response;
}
BaseResponse<Question> IQuestions.GetQuestionsWithNoAnswers(QuestionFilters filters)
{
var url = ApiUrlBuilder
.Initialize(_apiKey)
.ForClient(ClientType.Questions,"no-answers")
.WithFilter(filters)
.GetApiUrl();
var response = _httpClient.GetAsync(url).Result.ReadAsJsonAsync<Data<Question>>().ValidateApiResponse();
return response;
}
BaseResponse<Question> IQuestions.GetUnansweredQuestions(QuestionFilters filters)
{
var url = ApiUrlBuilder
.Initialize(_apiKey)
.ForClient(ClientType.Questions,"unanswered")
.WithFilter(filters)
.GetApiUrl();
var response = _httpClient.GetAsync(url).Result.ReadAsJsonAsync<Data<Question>>().ValidateApiResponse();
return response;
}
}
}
| 31.693548 | 107 | 0.746565 | [
"MIT"
] | gethari/FluentExchange | StackExchange.NET/StackExchange.NET/Clients/QuestionsClient.cs | 3,932 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Linq;
using PCExpert.DomainFramework;
using PCExpert.DomainFramework.Exceptions;
using PCExpert.DomainFramework.Utils;
namespace PCExpert.Core.Domain
{
public class PCConfiguration : Entity
{
#region Constructors
public PCConfiguration()
{
ContainedComponents = new List<PCComponent>();
Status = PCConfigurationStatus.Personal;
}
#endregion
#region Properties
public string Name { get; private set; }
public string PublicName { get; private set; }
public PCConfigurationStatus Status { get; private set; }
private IList<PCComponent> ContainedComponents { get; set; }
/// <summary>
/// Components, included in this configuration
/// </summary>
public IReadOnlyCollection<PCComponent> Components
{
get { return new ReadOnlyCollection<PCComponent>(ContainedComponents); }
}
#endregion
#region Methods
/// <summary>
/// Calculates sum price of all included components
/// </summary>
public decimal CalculatePrice()
{
return ContainedComponents.Sum(x => x.AveragePrice);
}
/// <summary>
/// Sets new name for configuration
/// </summary>
public PCConfiguration WithName(string name)
{
Name = name;
if (Status == PCConfigurationStatus.Published)
PublicName = name;
return this;
}
/// <summary>
/// Adds component to configuration
/// </summary>
public PCConfiguration WithComponent(PCComponent component)
{
Argument.NotNull(component);
if (ContainedComponents.Any(x => x.SameIdentityAs(component)))
throw new DuplicateElementException("Component already added");
ContainedComponents.Add(component);
return this;
}
/// <summary>
/// Changes status of the configuration
/// </summary>
public void MoveToStatus(PCConfigurationStatus newStatus)
{
Argument.ValidEnumItem(newStatus);
Status = newStatus;
switch (newStatus)
{
case PCConfigurationStatus.Published:
PublicName = Name;
break;
case PCConfigurationStatus.Personal:
PublicName = null;
break;
}
}
[ContractInvariantMethod]
private void NameInvariant()
{
Contract.Invariant(
(Status == PCConfigurationStatus.Personal && PublicName == null) ||
(Status == PCConfigurationStatus.Published && PublicName == Name) ||
(Status == PCConfigurationStatus.Undefined));
}
#endregion
}
} | 22.545455 | 75 | 0.704435 | [
"MIT"
] | RegiSV2/PCExpertDDD | src/PCExpert.Core.Domain/PCConfiguration.cs | 2,482 | C# |
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Sombra.Core.Enums;
using Sombra.Messaging.Infrastructure;
using Sombra.Messaging.Requests.Story;
using Sombra.Messaging.Responses.Story;
using Sombra.StoryService.DAL;
namespace Sombra.StoryService
{
public class ApproveStoryRequestHandler : AsyncCrudRequestHandler<ApproveStoryRequest, ApproveStoryResponse>
{
private readonly StoryContext _context;
public ApproveStoryRequestHandler(StoryContext context)
{
_context = context;
}
public override async Task<ApproveStoryResponse> Handle(ApproveStoryRequest message)
{
var story = await _context.Stories.FirstOrDefaultAsync(b => b.StoryKey.Equals(message.StoryKey));
if (story != null)
{
if (story.IsApproved)
return Error(ErrorType.AlreadyActive);
story.IsApproved = true;
return await _context.TrySaveChangesAsync<ApproveStoryResponse>();
}
return Error(ErrorType.NotFound);
}
}
} | 31.083333 | 112 | 0.671135 | [
"MIT"
] | JelleKerkstra/Sombra | Sombra.StoryService/ApproveStoryRequestHandler.cs | 1,121 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Linq;
using System.Diagnostics;
namespace System.Runtime.Serialization
{
/// <SecurityNote>
/// Critical - Class holds static instances used in serializer.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// Safe - All get-only properties marked safe since they only need to be protected for write.
/// </SecurityNote>
internal static class Globals
{
/// <SecurityNote>
/// Review - changes to const could affect code generation logic; any changes should be reviewed.
/// </SecurityNote>
internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
[SecurityCritical]
private static XmlQualifiedName s_idQualifiedName;
internal static XmlQualifiedName IdQualifiedName
{
[SecuritySafeCritical]
get
{
if (s_idQualifiedName == null)
s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace);
return s_idQualifiedName;
}
}
[SecurityCritical]
private static XmlQualifiedName s_refQualifiedName;
internal static XmlQualifiedName RefQualifiedName
{
[SecuritySafeCritical]
get
{
if (s_refQualifiedName == null)
s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace);
return s_refQualifiedName;
}
}
[SecurityCritical]
private static Type s_typeOfObject;
internal static Type TypeOfObject
{
[SecuritySafeCritical]
get
{
if (s_typeOfObject == null)
s_typeOfObject = typeof(object);
return s_typeOfObject;
}
}
[SecurityCritical]
private static Type s_typeOfValueType;
internal static Type TypeOfValueType
{
[SecuritySafeCritical]
get
{
if (s_typeOfValueType == null)
s_typeOfValueType = typeof(ValueType);
return s_typeOfValueType;
}
}
[SecurityCritical]
private static Type s_typeOfArray;
internal static Type TypeOfArray
{
[SecuritySafeCritical]
get
{
if (s_typeOfArray == null)
s_typeOfArray = typeof(Array);
return s_typeOfArray;
}
}
[SecurityCritical]
private static Type s_typeOfException;
internal static Type TypeOfException
{
[SecuritySafeCritical]
get
{
if (s_typeOfException == null)
s_typeOfException = typeof(Exception);
return s_typeOfException;
}
}
[SecurityCritical]
private static Type s_typeOfString;
internal static Type TypeOfString
{
[SecuritySafeCritical]
get
{
if (s_typeOfString == null)
s_typeOfString = typeof(string);
return s_typeOfString;
}
}
[SecurityCritical]
private static Type s_typeOfInt;
internal static Type TypeOfInt
{
[SecuritySafeCritical]
get
{
if (s_typeOfInt == null)
s_typeOfInt = typeof(int);
return s_typeOfInt;
}
}
[SecurityCritical]
private static Type s_typeOfULong;
internal static Type TypeOfULong
{
[SecuritySafeCritical]
get
{
if (s_typeOfULong == null)
s_typeOfULong = typeof(ulong);
return s_typeOfULong;
}
}
[SecurityCritical]
private static Type s_typeOfVoid;
internal static Type TypeOfVoid
{
[SecuritySafeCritical]
get
{
if (s_typeOfVoid == null)
s_typeOfVoid = typeof(void);
return s_typeOfVoid;
}
}
[SecurityCritical]
private static Type s_typeOfByteArray;
internal static Type TypeOfByteArray
{
[SecuritySafeCritical]
get
{
if (s_typeOfByteArray == null)
s_typeOfByteArray = typeof(byte[]);
return s_typeOfByteArray;
}
}
[SecurityCritical]
private static Type s_typeOfTimeSpan;
internal static Type TypeOfTimeSpan
{
[SecuritySafeCritical]
get
{
if (s_typeOfTimeSpan == null)
s_typeOfTimeSpan = typeof(TimeSpan);
return s_typeOfTimeSpan;
}
}
[SecurityCritical]
private static Type s_typeOfGuid;
internal static Type TypeOfGuid
{
[SecuritySafeCritical]
get
{
if (s_typeOfGuid == null)
s_typeOfGuid = typeof(Guid);
return s_typeOfGuid;
}
}
[SecurityCritical]
private static Type s_typeOfDateTimeOffset;
internal static Type TypeOfDateTimeOffset
{
[SecuritySafeCritical]
get
{
if (s_typeOfDateTimeOffset == null)
s_typeOfDateTimeOffset = typeof(DateTimeOffset);
return s_typeOfDateTimeOffset;
}
}
[SecurityCritical]
private static Type s_typeOfDateTimeOffsetAdapter;
internal static Type TypeOfDateTimeOffsetAdapter
{
[SecuritySafeCritical]
get
{
if (s_typeOfDateTimeOffsetAdapter == null)
s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter);
return s_typeOfDateTimeOffsetAdapter;
}
}
[SecurityCritical]
private static Type s_typeOfUri;
internal static Type TypeOfUri
{
[SecuritySafeCritical]
get
{
if (s_typeOfUri == null)
s_typeOfUri = typeof(Uri);
return s_typeOfUri;
}
}
[SecurityCritical]
private static Type s_typeOfTypeEnumerable;
internal static Type TypeOfTypeEnumerable
{
[SecuritySafeCritical]
get
{
if (s_typeOfTypeEnumerable == null)
s_typeOfTypeEnumerable = typeof(IEnumerable<Type>);
return s_typeOfTypeEnumerable;
}
}
[SecurityCritical]
private static Type s_typeOfStreamingContext;
internal static Type TypeOfStreamingContext
{
[SecuritySafeCritical]
get
{
if (s_typeOfStreamingContext == null)
s_typeOfStreamingContext = typeof(StreamingContext);
return s_typeOfStreamingContext;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatClassWriterDelegate;
internal static Type TypeOfXmlFormatClassWriterDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatClassWriterDelegate == null)
s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate);
return s_typeOfXmlFormatClassWriterDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatCollectionWriterDelegate;
internal static Type TypeOfXmlFormatCollectionWriterDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatCollectionWriterDelegate == null)
s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate);
return s_typeOfXmlFormatCollectionWriterDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatClassReaderDelegate;
internal static Type TypeOfXmlFormatClassReaderDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatClassReaderDelegate == null)
s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate);
return s_typeOfXmlFormatClassReaderDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatCollectionReaderDelegate;
internal static Type TypeOfXmlFormatCollectionReaderDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatCollectionReaderDelegate == null)
s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate);
return s_typeOfXmlFormatCollectionReaderDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfXmlFormatGetOnlyCollectionReaderDelegate;
internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null)
s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate);
return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate;
}
}
[SecurityCritical]
private static Type s_typeOfKnownTypeAttribute;
internal static Type TypeOfKnownTypeAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfKnownTypeAttribute == null)
s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute);
return s_typeOfKnownTypeAttribute;
}
}
/// <SecurityNote>
/// Critical - attribute type used in security decision
/// </SecurityNote>
[SecurityCritical]
private static Type s_typeOfDataContractAttribute;
internal static Type TypeOfDataContractAttribute
{
/// <SecurityNote>
/// Critical - accesses critical field for attribute type
/// Safe - controls inputs and logic
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (s_typeOfDataContractAttribute == null)
s_typeOfDataContractAttribute = typeof(DataContractAttribute);
return s_typeOfDataContractAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfDataMemberAttribute;
internal static Type TypeOfDataMemberAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfDataMemberAttribute == null)
s_typeOfDataMemberAttribute = typeof(DataMemberAttribute);
return s_typeOfDataMemberAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfEnumMemberAttribute;
internal static Type TypeOfEnumMemberAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfEnumMemberAttribute == null)
s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute);
return s_typeOfEnumMemberAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfCollectionDataContractAttribute;
internal static Type TypeOfCollectionDataContractAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfCollectionDataContractAttribute == null)
s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute);
return s_typeOfCollectionDataContractAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfObjectArray;
internal static Type TypeOfObjectArray
{
[SecuritySafeCritical]
get
{
if (s_typeOfObjectArray == null)
s_typeOfObjectArray = typeof(object[]);
return s_typeOfObjectArray;
}
}
[SecurityCritical]
private static Type s_typeOfOnSerializingAttribute;
internal static Type TypeOfOnSerializingAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfOnSerializingAttribute == null)
s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute);
return s_typeOfOnSerializingAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfOnSerializedAttribute;
internal static Type TypeOfOnSerializedAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfOnSerializedAttribute == null)
s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute);
return s_typeOfOnSerializedAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfOnDeserializingAttribute;
internal static Type TypeOfOnDeserializingAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfOnDeserializingAttribute == null)
s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute);
return s_typeOfOnDeserializingAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfOnDeserializedAttribute;
internal static Type TypeOfOnDeserializedAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfOnDeserializedAttribute == null)
s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute);
return s_typeOfOnDeserializedAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfFlagsAttribute;
internal static Type TypeOfFlagsAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfFlagsAttribute == null)
s_typeOfFlagsAttribute = typeof(FlagsAttribute);
return s_typeOfFlagsAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfIXmlSerializable;
internal static Type TypeOfIXmlSerializable
{
[SecuritySafeCritical]
get
{
if (s_typeOfIXmlSerializable == null)
s_typeOfIXmlSerializable = typeof(IXmlSerializable);
return s_typeOfIXmlSerializable;
}
}
[SecurityCritical]
private static Type s_typeOfXmlSchemaProviderAttribute;
internal static Type TypeOfXmlSchemaProviderAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlSchemaProviderAttribute == null)
s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute);
return s_typeOfXmlSchemaProviderAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfXmlRootAttribute;
internal static Type TypeOfXmlRootAttribute
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlRootAttribute == null)
s_typeOfXmlRootAttribute = typeof(XmlRootAttribute);
return s_typeOfXmlRootAttribute;
}
}
[SecurityCritical]
private static Type s_typeOfXmlQualifiedName;
internal static Type TypeOfXmlQualifiedName
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlQualifiedName == null)
s_typeOfXmlQualifiedName = typeof(XmlQualifiedName);
return s_typeOfXmlQualifiedName;
}
}
[SecurityCritical]
private static Type s_typeOfISerializableDataNode;
internal static Type TypeOfISerializableDataNode
{
[SecuritySafeCritical]
get
{
if (s_typeOfISerializableDataNode == null)
s_typeOfISerializableDataNode = typeof(ISerializableDataNode);
return s_typeOfISerializableDataNode;
}
}
[SecurityCritical]
private static Type s_typeOfClassDataNode;
internal static Type TypeOfClassDataNode
{
[SecuritySafeCritical]
get
{
if (s_typeOfClassDataNode == null)
s_typeOfClassDataNode = typeof(ClassDataNode);
return s_typeOfClassDataNode;
}
}
[SecurityCritical]
private static Type s_typeOfCollectionDataNode;
internal static Type TypeOfCollectionDataNode
{
[SecuritySafeCritical]
get
{
if (s_typeOfCollectionDataNode == null)
s_typeOfCollectionDataNode = typeof(CollectionDataNode);
return s_typeOfCollectionDataNode;
}
}
#if NET_NATIVE
[SecurityCritical]
private static Type s_typeOfSafeSerializationManager;
private static bool s_typeOfSafeSerializationManagerSet;
internal static Type TypeOfSafeSerializationManager
{
[SecuritySafeCritical]
get
{
if (!s_typeOfSafeSerializationManagerSet)
{
s_typeOfSafeSerializationManager = TypeOfInt.GetTypeInfo().Assembly.GetType("System.Runtime.Serialization.SafeSerializationManager");
s_typeOfSafeSerializationManagerSet = true;
}
return s_typeOfSafeSerializationManager;
}
}
#endif
[SecurityCritical]
private static Type s_typeOfNullable;
internal static Type TypeOfNullable
{
[SecuritySafeCritical]
get
{
if (s_typeOfNullable == null)
s_typeOfNullable = typeof(Nullable<>);
return s_typeOfNullable;
}
}
[SecurityCritical]
private static Type s_typeOfIDictionaryGeneric;
internal static Type TypeOfIDictionaryGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfIDictionaryGeneric == null)
s_typeOfIDictionaryGeneric = typeof(IDictionary<,>);
return s_typeOfIDictionaryGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfIDictionary;
internal static Type TypeOfIDictionary
{
[SecuritySafeCritical]
get
{
if (s_typeOfIDictionary == null)
s_typeOfIDictionary = typeof(IDictionary);
return s_typeOfIDictionary;
}
}
[SecurityCritical]
private static Type s_typeOfIListGeneric;
internal static Type TypeOfIListGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfIListGeneric == null)
s_typeOfIListGeneric = typeof(IList<>);
return s_typeOfIListGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfIList;
internal static Type TypeOfIList
{
[SecuritySafeCritical]
get
{
if (s_typeOfIList == null)
s_typeOfIList = typeof(IList);
return s_typeOfIList;
}
}
[SecurityCritical]
private static Type s_typeOfICollectionGeneric;
internal static Type TypeOfICollectionGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfICollectionGeneric == null)
s_typeOfICollectionGeneric = typeof(ICollection<>);
return s_typeOfICollectionGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfICollection;
internal static Type TypeOfICollection
{
[SecuritySafeCritical]
get
{
if (s_typeOfICollection == null)
s_typeOfICollection = typeof(ICollection);
return s_typeOfICollection;
}
}
[SecurityCritical]
private static Type s_typeOfIEnumerableGeneric;
internal static Type TypeOfIEnumerableGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfIEnumerableGeneric == null)
s_typeOfIEnumerableGeneric = typeof(IEnumerable<>);
return s_typeOfIEnumerableGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfIEnumerable;
internal static Type TypeOfIEnumerable
{
[SecuritySafeCritical]
get
{
if (s_typeOfIEnumerable == null)
s_typeOfIEnumerable = typeof(IEnumerable);
return s_typeOfIEnumerable;
}
}
[SecurityCritical]
private static Type s_typeOfIEnumeratorGeneric;
internal static Type TypeOfIEnumeratorGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfIEnumeratorGeneric == null)
s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>);
return s_typeOfIEnumeratorGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfIEnumerator;
internal static Type TypeOfIEnumerator
{
[SecuritySafeCritical]
get
{
if (s_typeOfIEnumerator == null)
s_typeOfIEnumerator = typeof(IEnumerator);
return s_typeOfIEnumerator;
}
}
[SecurityCritical]
private static Type s_typeOfKeyValuePair;
internal static Type TypeOfKeyValuePair
{
[SecuritySafeCritical]
get
{
if (s_typeOfKeyValuePair == null)
s_typeOfKeyValuePair = typeof(KeyValuePair<,>);
return s_typeOfKeyValuePair;
}
}
[SecurityCritical]
private static Type s_typeOfKeyValuePairAdapter;
internal static Type TypeOfKeyValuePairAdapter
{
[SecuritySafeCritical]
get
{
if (s_typeOfKeyValuePairAdapter == null)
s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>);
return s_typeOfKeyValuePairAdapter;
}
}
[SecurityCritical]
private static Type s_typeOfKeyValue;
internal static Type TypeOfKeyValue
{
[SecuritySafeCritical]
get
{
if (s_typeOfKeyValue == null)
s_typeOfKeyValue = typeof(KeyValue<,>);
return s_typeOfKeyValue;
}
}
[SecurityCritical]
private static Type s_typeOfIDictionaryEnumerator;
internal static Type TypeOfIDictionaryEnumerator
{
[SecuritySafeCritical]
get
{
if (s_typeOfIDictionaryEnumerator == null)
s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator);
return s_typeOfIDictionaryEnumerator;
}
}
[SecurityCritical]
private static Type s_typeOfDictionaryEnumerator;
internal static Type TypeOfDictionaryEnumerator
{
[SecuritySafeCritical]
get
{
if (s_typeOfDictionaryEnumerator == null)
s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator);
return s_typeOfDictionaryEnumerator;
}
}
[SecurityCritical]
private static Type s_typeOfGenericDictionaryEnumerator;
internal static Type TypeOfGenericDictionaryEnumerator
{
[SecuritySafeCritical]
get
{
if (s_typeOfGenericDictionaryEnumerator == null)
s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>);
return s_typeOfGenericDictionaryEnumerator;
}
}
[SecurityCritical]
private static Type s_typeOfDictionaryGeneric;
internal static Type TypeOfDictionaryGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfDictionaryGeneric == null)
s_typeOfDictionaryGeneric = typeof(Dictionary<,>);
return s_typeOfDictionaryGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfHashtable;
internal static Type TypeOfHashtable
{
[SecuritySafeCritical]
get
{
if (s_typeOfHashtable == null)
s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject);
return s_typeOfHashtable;
}
}
[SecurityCritical]
private static Type s_typeOfListGeneric;
internal static Type TypeOfListGeneric
{
[SecuritySafeCritical]
get
{
if (s_typeOfListGeneric == null)
s_typeOfListGeneric = typeof(List<>);
return s_typeOfListGeneric;
}
}
[SecurityCritical]
private static Type s_typeOfXmlElement;
internal static Type TypeOfXmlElement
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlElement == null)
s_typeOfXmlElement = typeof(XmlElement);
return s_typeOfXmlElement;
}
}
[SecurityCritical]
private static Type s_typeOfXmlNodeArray;
internal static Type TypeOfXmlNodeArray
{
[SecuritySafeCritical]
get
{
if (s_typeOfXmlNodeArray == null)
s_typeOfXmlNodeArray = typeof(XmlNode[]);
return s_typeOfXmlNodeArray;
}
}
private static bool s_shouldGetDBNullType = true;
[SecurityCritical]
private static Type s_typeOfDBNull;
internal static Type TypeOfDBNull
{
[SecuritySafeCritical]
get
{
if (s_typeOfDBNull == null && s_shouldGetDBNullType)
{
s_typeOfDBNull = Type.GetType("System.DBNull, System.Data.Common, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", false);
s_shouldGetDBNullType = false;
}
return s_typeOfDBNull;
}
}
[SecurityCritical]
private static object s_valueOfDBNull;
internal static object ValueOfDBNull
{
[SecuritySafeCritical]
get
{
if (s_valueOfDBNull == null && TypeOfDBNull != null)
{
var fieldInfo = TypeOfDBNull.GetField("Value");
if (fieldInfo != null)
s_valueOfDBNull = fieldInfo.GetValue(null);
}
return s_valueOfDBNull;
}
}
[SecurityCritical]
private static Uri s_dataContractXsdBaseNamespaceUri;
internal static Uri DataContractXsdBaseNamespaceUri
{
[SecuritySafeCritical]
get
{
if (s_dataContractXsdBaseNamespaceUri == null)
s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace);
return s_dataContractXsdBaseNamespaceUri;
}
}
#region Contract compliance for System.Type
private static bool TypeSequenceEqual(Type[] seq1, Type[] seq2)
{
if (seq1 == null || seq2 == null || seq1.Length != seq2.Length)
return false;
for (int i = 0; i < seq1.Length; i++)
{
if (!seq1[i].Equals(seq2[i]) && !seq1[i].IsAssignableFrom(seq2[i]))
return false;
}
return true;
}
private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] parameterTypes, string methodName)
{
if (methodBases == null || string.IsNullOrEmpty(methodName))
return null;
var matchedMethods = methodBases.Where(method => method.Name.Equals(methodName));
matchedMethods = matchedMethods.Where(method => TypeSequenceEqual(method.GetParameters().Select(param => param.ParameterType).ToArray(), parameterTypes));
return matchedMethods.FirstOrDefault();
}
internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes)
{
var constructorInfos = type.GetConstructors(bindingFlags);
var constructorInfo = FilterMethodBases(constructorInfos.Cast<MethodBase>().ToArray(), parameterTypes, ".ctor");
return constructorInfo != null ? (ConstructorInfo)constructorInfo : null;
}
internal static MethodInfo GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes)
{
var methodInfos = type.GetMethods(bindingFlags);
var methodInfo = FilterMethodBases(methodInfos.Cast<MethodBase>().ToArray(), parameterTypes, methodName);
return methodInfo != null ? (MethodInfo)methodInfo : null;
}
#endregion
private static Type s_typeOfScriptObject;
private static Func<object, string> s_serializeFunc;
private static Func<string, object> s_deserializeFunc;
internal static ClassDataContract CreateScriptObjectClassDataContract()
{
Debug.Assert(s_typeOfScriptObject != null);
return new ClassDataContract(s_typeOfScriptObject);
}
internal static bool TypeOfScriptObject_IsAssignableFrom(Type type)
{
return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type);
}
internal static void SetScriptObjectJsonSerializer(Type typeOfScriptObject, Func<object, string> serializeFunc, Func<string, object> deserializeFunc)
{
Globals.s_typeOfScriptObject = typeOfScriptObject;
Globals.s_serializeFunc = serializeFunc;
Globals.s_deserializeFunc = deserializeFunc;
}
internal static string ScriptObjectJsonSerialize(object obj)
{
Debug.Assert(s_serializeFunc != null);
return Globals.s_serializeFunc(obj);
}
internal static object ScriptObjectJsonDeserialize(string json)
{
Debug.Assert(s_deserializeFunc != null);
return Globals.s_deserializeFunc(json);
}
internal static bool IsDBNullValue(object o)
{
return o != null && ValueOfDBNull != null && ValueOfDBNull.Equals(o);
}
public const bool DefaultIsRequired = false;
public const bool DefaultEmitDefaultValue = true;
public const int DefaultOrder = 0;
public const bool DefaultIsReference = false;
// The value string.Empty aids comparisons (can do simple length checks
// instead of string comparison method calls in IL.)
public readonly static string NewObjectId = string.Empty;
public const string NullObjectId = null;
public const string SimpleSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*$";
public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$";
public const string Space = " ";
public const string XsiPrefix = "i";
public const string XsdPrefix = "x";
public const string SerPrefix = "z";
public const string SerPrefixForSchema = "ser";
public const string ElementPrefix = "q";
public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/";
public const string DataContractXmlNamespace = DataContractXsdBaseNamespace + "System.Xml";
public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema";
public const string XsiNilLocalName = "nil";
public const string XsiTypeLocalName = "type";
public const string TnsPrefix = "tns";
public const string OccursUnbounded = "unbounded";
public const string AnyTypeLocalName = "anyType";
public const string StringLocalName = "string";
public const string IntLocalName = "int";
public const string True = "true";
public const string False = "false";
public const string ArrayPrefix = "ArrayOf";
public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
public const string XmlnsPrefix = "xmlns";
public const string SchemaLocalName = "schema";
public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
public const string DefaultClrNamespace = "GeneratedNamespace";
public const string DefaultTypeName = "GeneratedType";
public const string DefaultGeneratedMember = "GeneratedMember";
public const string DefaultFieldSuffix = "Field";
public const string DefaultPropertySuffix = "Property";
public const string DefaultMemberSuffix = "Member";
public const string NameProperty = "Name";
public const string NamespaceProperty = "Namespace";
public const string OrderProperty = "Order";
public const string IsReferenceProperty = "IsReference";
public const string IsRequiredProperty = "IsRequired";
public const string EmitDefaultValueProperty = "EmitDefaultValue";
public const string ClrNamespaceProperty = "ClrNamespace";
public const string ItemNameProperty = "ItemName";
public const string KeyNameProperty = "KeyName";
public const string ValueNameProperty = "ValueName";
public const string SerializationInfoPropertyName = "SerializationInfo";
public const string SerializationInfoFieldName = "info";
public const string NodeArrayPropertyName = "Nodes";
public const string NodeArrayFieldName = "nodesField";
public const string ExportSchemaMethod = "ExportSchema";
public const string IsAnyProperty = "IsAny";
public const string ContextFieldName = "context";
public const string GetObjectDataMethodName = "GetObjectData";
public const string GetEnumeratorMethodName = "GetEnumerator";
public const string MoveNextMethodName = "MoveNext";
public const string AddValueMethodName = "AddValue";
public const string CurrentPropertyName = "Current";
public const string ValueProperty = "Value";
public const string EnumeratorFieldName = "enumerator";
public const string SerializationEntryFieldName = "entry";
public const string ExtensionDataSetMethod = "set_ExtensionData";
public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData";
public const string ExtensionDataObjectPropertyName = "ExtensionData";
public const string ExtensionDataObjectFieldName = "extensionDataField";
public const string AddMethodName = "Add";
public const string GetCurrentMethodName = "get_Current";
// NOTE: These values are used in schema below. If you modify any value, please make the same change in the schema.
public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/";
public const string ClrTypeLocalName = "Type";
public const string ClrAssemblyLocalName = "Assembly";
public const string IsValueTypeLocalName = "IsValueType";
public const string EnumerationValueLocalName = "EnumerationValue";
public const string SurrogateDataLocalName = "Surrogate";
public const string GenericTypeLocalName = "GenericType";
public const string GenericParameterLocalName = "GenericParameter";
public const string GenericNameAttribute = "Name";
public const string GenericNamespaceAttribute = "Namespace";
public const string GenericParameterNestedLevelAttribute = "NestedLevel";
public const string IsDictionaryLocalName = "IsDictionary";
public const string ActualTypeLocalName = "ActualType";
public const string ActualTypeNameAttribute = "Name";
public const string ActualTypeNamespaceAttribute = "Namespace";
public const string DefaultValueLocalName = "DefaultValue";
public const string EmitDefaultValueAttribute = "EmitDefaultValue";
public const string IdLocalName = "Id";
public const string RefLocalName = "Ref";
public const string ArraySizeLocalName = "Size";
public const string KeyLocalName = "Key";
public const string ValueLocalName = "Value";
public const string MscorlibAssemblyName = "0";
public const string ParseMethodName = "Parse";
public const string SafeSerializationManagerName = "SafeSerializationManager";
public const string SafeSerializationManagerNamespace = "http://schemas.datacontract.org/2004/07/System.Runtime.Serialization";
public const string ISerializableFactoryTypeLocalName = "FactoryType";
}
}
| 36.045045 | 463 | 0.594326 | [
"MIT"
] | hgGeorg/corefx | src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs | 40,010 | C# |
//------------------------------------------------------------------------------
// <copyright file="DataColumnChangeEventHandler.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">amirhmy</owner>
// <owner current="true" primary="false">markash</owner>
// <owner current="false" primary="false">jasonzhu</owner>
//------------------------------------------------------------------------------
namespace System.Data {
using System;
// Represents the method that will handle the the <see cref='System.Data.DataTable.ColumnChanging'/> event.</para>
public delegate void DataColumnChangeEventHandler(object sender, DataColumnChangeEventArgs e);
}
| 50.125 | 118 | 0.546135 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/fx/src/data/System/Data/DataColumnChangeEventHandler.cs | 802 | C# |
using System;
namespace CustomDependancyInjectionFramework.Contracts
{
public interface IModule
{
void Configure();
Type GetMapping(Type currentInterface, object attribute);
object GetInstance(Type type);
void SetInstance(Type implementation, object instance);
}
}
| 19.625 | 65 | 0.697452 | [
"MIT"
] | NaskoVasilev/CSharp-OOP-Advanced | Dependancy Injection/DependancyInjection/CustomDependancyInjectionFramework/Contracts/IModule.cs | 316 | C# |
namespace CatMash.Domain.StoredProceduresParameters
{
public interface ISelectOneCatParameters : IBaseStoredProcedureParameters
{
}
} | 24.333333 | 77 | 0.794521 | [
"MIT"
] | isis08/CatMash-Ddd-For-Paas | CatMash.Domain/StoredProceduresParameters/ISelectOneCatParameters.cs | 148 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
/// <summary>
/// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services.
/// </summary>
internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService
{
internal static readonly TraceLog Log = new TraceLog(2048, "EnC");
private readonly Workspace _workspace;
private readonly IActiveStatementTrackingService _trackingService;
private readonly IActiveStatementProvider _activeStatementProvider;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly IDebuggeeModuleMetadataProvider _debugeeModuleMetadataProvider;
private readonly EditAndContinueDiagnosticUpdateSource _emitDiagnosticsUpdateSource;
private readonly EditSessionTelemetry _editSessionTelemetry;
private readonly DebuggingSessionTelemetry _debuggingSessionTelemetry;
private readonly ICompilationOutputsProviderService _compilationOutputsProvider;
private readonly Action<DebuggingSessionTelemetry.Data> _reportTelemetry;
/// <summary>
/// A document id is added whenever a diagnostic is reported while in run mode.
/// These diagnostics are cleared as soon as we enter break mode or the debugging session terminates.
/// </summary>
private readonly HashSet<DocumentId> _documentsWithReportedDiagnosticsDuringRunMode;
private readonly object _documentsWithReportedDiagnosticsDuringRunModeGuard = new object();
private DebuggingSession? _debuggingSession;
private EditSession? _editSession;
private PendingSolutionUpdate? _pendingUpdate;
internal EditAndContinueWorkspaceService(
Workspace workspace,
IActiveStatementTrackingService activeStatementTrackingService,
ICompilationOutputsProviderService compilationOutputsProvider,
IDiagnosticAnalyzerService diagnosticService,
EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource,
IActiveStatementProvider activeStatementProvider,
IDebuggeeModuleMetadataProvider debugeeModuleMetadataProvider,
Action<DebuggingSessionTelemetry.Data>? reportTelemetry = null)
{
_workspace = workspace;
_diagnosticService = diagnosticService;
_emitDiagnosticsUpdateSource = diagnosticUpdateSource;
_activeStatementProvider = activeStatementProvider;
_debugeeModuleMetadataProvider = debugeeModuleMetadataProvider;
_trackingService = activeStatementTrackingService;
_debuggingSessionTelemetry = new DebuggingSessionTelemetry();
_editSessionTelemetry = new EditSessionTelemetry();
_documentsWithReportedDiagnosticsDuringRunMode = new HashSet<DocumentId>();
_compilationOutputsProvider = compilationOutputsProvider;
_reportTelemetry = reportTelemetry ?? ReportTelemetry;
}
// test only:
internal DebuggingSession? Test_GetDebuggingSession() => _debuggingSession;
internal EditSession? Test_GetEditSession() => _editSession;
internal PendingSolutionUpdate? Test_GetPendingSolutionUpdate() => _pendingUpdate;
public bool IsDebuggingSessionInProgress
=> _debuggingSession != null;
public void OnSourceFileUpdated(DocumentId documentId)
{
var debuggingSession = _debuggingSession;
if (debuggingSession != null)
{
// fire and forget
_ = Task.Run(() => debuggingSession.LastCommittedSolution.OnSourceFileUpdatedAsync(documentId, debuggingSession.CancellationToken));
}
}
/// <summary>
/// Invoked whenever a module instance is loaded to a process being debugged.
/// </summary>
public void OnManagedModuleInstanceLoaded(Guid mvid)
=> _editSession?.ModuleInstanceLoadedOrUnloaded(mvid);
/// <summary>
/// Invoked whenever a module instance is unloaded from a process being debugged.
/// </summary>
public void OnManagedModuleInstanceUnloaded(Guid mvid)
=> _editSession?.ModuleInstanceLoadedOrUnloaded(mvid);
public void StartDebuggingSession()
{
var previousSession = Interlocked.CompareExchange(ref _debuggingSession, new DebuggingSession(_workspace, _debugeeModuleMetadataProvider, _activeStatementProvider, _compilationOutputsProvider), null);
Contract.ThrowIfFalse(previousSession == null, "New debugging session can't be started until the existing one has ended.");
}
public void StartEditSession()
{
var debuggingSession = _debuggingSession;
Contract.ThrowIfNull(debuggingSession, "Edit session can only be started during debugging session");
var newSession = new EditSession(debuggingSession, _editSessionTelemetry);
var previousSession = Interlocked.CompareExchange(ref _editSession, newSession, null);
Contract.ThrowIfFalse(previousSession == null, "New edit session can't be started until the existing one has ended.");
_trackingService.StartTracking(newSession);
// clear diagnostics reported during run mode:
ClearReportedRunModeDiagnostics();
}
public void EndEditSession()
{
// first, publish null session:
var session = Interlocked.Exchange(ref _editSession, null);
Contract.ThrowIfNull(session, "Edit session has not started.");
// then cancel all ongoing work bound to the session:
session.Cancel();
// then clear all reported rude edits:
_diagnosticService.Reanalyze(_workspace, documentIds: session.GetDocumentsWithReportedDiagnostics());
_trackingService.EndTracking();
_debuggingSessionTelemetry.LogEditSession(_editSessionTelemetry.GetDataAndClear());
session.Dispose();
}
public void EndDebuggingSession()
{
var debuggingSession = Interlocked.Exchange(ref _debuggingSession, null);
Contract.ThrowIfNull(debuggingSession, "Debugging session has not started.");
// cancel all ongoing work bound to the session:
debuggingSession.Cancel();
_reportTelemetry(_debuggingSessionTelemetry.GetDataAndClear());
// clear emit/apply diagnostics reported previously:
_emitDiagnosticsUpdateSource.ClearDiagnostics();
// clear diagnostics reported during run mode:
ClearReportedRunModeDiagnostics();
debuggingSession.Dispose();
}
internal static bool SupportsEditAndContinue(Project project)
=> project.LanguageServices.GetService<IEditAndContinueAnalyzer>() != null;
internal static bool IsDesignTimeOnlyDocument(Document document)
=> document.Services.GetService<DocumentPropertiesService>()?.DesignTimeOnly == true;
public async Task<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
{
try
{
var debuggingSession = _debuggingSession;
if (debuggingSession == null)
{
return ImmutableArray<Diagnostic>.Empty;
}
// Not a C# or VB project.
var project = document.Project;
if (!SupportsEditAndContinue(project))
{
return ImmutableArray<Diagnostic>.Empty;
}
// Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only)
if (IsDesignTimeOnlyDocument(document) || !document.SupportsSyntaxTree)
{
return ImmutableArray<Diagnostic>.Empty;
}
// Do not analyze documents (and report diagnostics) of projects that have not been built.
// Allow user to make any changes in these documents, they won't be applied within the current debugging session.
// Do not report the file read error - it might be an intermittent issue. The error will be reported when the
// change is attempted to be applied.
var (mvid, _) = await debuggingSession.GetProjectModuleIdAsync(project.Id, cancellationToken).ConfigureAwait(false);
if (mvid == Guid.Empty)
{
return ImmutableArray<Diagnostic>.Empty;
}
var (oldDocument, oldDocumentState) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(document.Id, cancellationToken).ConfigureAwait(false);
if (oldDocumentState == CommittedSolution.DocumentState.OutOfSync ||
oldDocumentState == CommittedSolution.DocumentState.Indeterminate ||
oldDocumentState == CommittedSolution.DocumentState.DesignTimeOnly)
{
// Do not report diagnostics for existing out-of-sync documents or design-time-only documents.
return ImmutableArray<Diagnostic>.Empty;
}
// The document has not changed while the application is running since the last changes were committed:
var editSession = _editSession;
if (editSession == null)
{
if (document == oldDocument)
{
return ImmutableArray<Diagnostic>.Empty;
}
// Any changes made in loaded, built projects outside of edit session are rude edits (the application is running):
var newSyntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(newSyntaxTree);
var changedSpans = await GetChangedSpansAsync(oldDocument, newSyntaxTree, cancellationToken).ConfigureAwait(false);
return GetRunModeDocumentDiagnostics(document, newSyntaxTree, changedSpans);
}
var analysis = await editSession.GetDocumentAnalysis(oldDocument, document).GetValueAsync(cancellationToken).ConfigureAwait(false);
if (analysis.HasChanges)
{
// Once we detected a change in a document let the debugger know that the corresponding loaded module
// is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying
// the change blocks the UI when the user "continues".
debuggingSession.PrepareModuleForUpdate(mvid);
// Check if EnC is allowed for all loaded modules corresponding to the project.
var moduleDiagnostics = editSession.GetModuleDiagnostics(mvid, project.Name);
if (!moduleDiagnostics.IsEmpty)
{
// track the document, so that we can refresh or clean diagnostics at the end of edit session:
editSession.TrackDocumentWithReportedDiagnostics(document.Id);
var newSyntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(newSyntaxTree);
var changedSpans = await GetChangedSpansAsync(oldDocument, newSyntaxTree, cancellationToken).ConfigureAwait(false);
var diagnosticsBuilder = ArrayBuilder<Diagnostic>.GetInstance();
foreach (var span in changedSpans)
{
var location = Location.Create(newSyntaxTree, span);
foreach (var diagnostic in moduleDiagnostics)
{
diagnosticsBuilder.Add(diagnostic.ToDiagnostic(location));
}
}
return diagnosticsBuilder.ToImmutableAndFree();
}
}
if (analysis.RudeEditErrors.IsEmpty)
{
return ImmutableArray<Diagnostic>.Empty;
}
editSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors);
// track the document, so that we can refresh or clean diagnostics at the end of edit session:
editSession.TrackDocumentWithReportedDiagnostics(document.Id);
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree);
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
return ImmutableArray<Diagnostic>.Empty;
}
}
private static async Task<IEnumerable<TextSpan>> GetChangedSpansAsync(Document? oldDocument, SyntaxTree newSyntaxTree, CancellationToken cancellationToken)
{
if (oldDocument != null)
{
var oldSyntaxTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(oldSyntaxTree);
return GetSpansInNewDocument(await GetDocumentTextChangesAsync(oldSyntaxTree, newSyntaxTree, cancellationToken).ConfigureAwait(false));
}
var newRoot = await newSyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
return SpecializedCollections.SingletonEnumerable(newRoot.FullSpan);
}
private ImmutableArray<Diagnostic> GetRunModeDocumentDiagnostics(Document newDocument, SyntaxTree newSyntaxTree, IEnumerable<TextSpan> changedSpans)
{
if (!changedSpans.Any())
{
return ImmutableArray<Diagnostic>.Empty;
}
lock (_documentsWithReportedDiagnosticsDuringRunModeGuard)
{
_documentsWithReportedDiagnosticsDuringRunMode.Add(newDocument.Id);
}
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ChangesNotAppliedWhileRunning);
var args = new[] { newDocument.Project.Name };
return changedSpans.SelectAsArray(span => Diagnostic.Create(descriptor, Location.Create(newSyntaxTree, span), args));
}
// internal for testing
internal static async Task<IList<TextChange>> GetDocumentTextChangesAsync(SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree, CancellationToken cancellationToken)
{
var list = newSyntaxTree.GetChanges(oldSyntaxTree);
if (list.Count != 0)
{
return list;
}
var oldText = await oldSyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
var newText = await newSyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (oldText.ContentEquals(newText))
{
return Array.Empty<TextChange>();
}
var roList = newText.GetTextChanges(oldText);
if (roList.Count != 0)
{
return roList.ToArray();
}
return Array.Empty<TextChange>();
}
// internal for testing
internal static IEnumerable<TextSpan> GetSpansInNewDocument(IEnumerable<TextChange> changes)
{
int oldPosition = 0;
int newPosition = 0;
foreach (var change in changes)
{
if (change.Span.Start < oldPosition)
{
Debug.Fail("Text changes not ordered");
yield break;
}
if (change.Span.Length == 0 && change.NewText.Length == 0)
{
continue;
}
// skip unchanged text:
newPosition += change.Span.Start - oldPosition;
yield return new TextSpan(newPosition, change.NewText.Length);
// apply change:
oldPosition = change.Span.End;
newPosition += change.NewText.Length;
}
}
private void ClearReportedRunModeDiagnostics()
{
// clear diagnostics reported during run mode:
ImmutableArray<DocumentId> documentsToReanalyze;
lock (_documentsWithReportedDiagnosticsDuringRunModeGuard)
{
documentsToReanalyze = _documentsWithReportedDiagnosticsDuringRunMode.ToImmutableArray();
_documentsWithReportedDiagnosticsDuringRunMode.Clear();
}
// clear all reported run mode diagnostics:
_diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze);
}
/// <summary>
/// Determine whether the updates made to projects containing the specified file (or all projects that are built,
/// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply
/// them on "continue".
/// </summary>
/// <returns>
/// Returns <see cref="SolutionUpdateStatus.Blocked"/> if there are rude edits or other errors
/// that block the application of the updates. Might return <see cref="SolutionUpdateStatus.Ready"/> even if there are
/// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until
/// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts,
/// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether
/// the update is valid or not.
/// </returns>
public Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken)
{
// GetStatusAsync is called outside of edit session when the debugger is determining
// whether a source file checksum matches the one in PDB.
// The debugger expects no changes in this case.
var editSession = _editSession;
if (editSession == null)
{
return Task.FromResult(false);
}
return editSession.HasChangesAsync(_workspace.CurrentSolution, sourceFilePath, cancellationToken);
}
public async Task<(SolutionUpdateStatus Summary, ImmutableArray<Deltas> Deltas)> EmitSolutionUpdateAsync(CancellationToken cancellationToken)
{
var editSession = _editSession;
if (editSession == null)
{
return (SolutionUpdateStatus.None, ImmutableArray<Deltas>.Empty);
}
var solution = _workspace.CurrentSolution;
var solutionUpdate = await editSession.EmitSolutionUpdateAsync(solution, cancellationToken).ConfigureAwait(false);
if (solutionUpdate.Summary == SolutionUpdateStatus.Ready)
{
var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate(
solution,
solutionUpdate.EmitBaselines,
solutionUpdate.Deltas,
solutionUpdate.ModuleReaders));
// commit/discard was not called:
Contract.ThrowIfFalse(previousPendingUpdate == null);
}
// clear emit/apply diagnostics reported previously:
_emitDiagnosticsUpdateSource.ClearDiagnostics();
// report emit/apply diagnostics:
foreach (var (projectId, diagnostics) in solutionUpdate.Diagnostics)
{
_emitDiagnosticsUpdateSource.ReportDiagnostics(solution, projectId, diagnostics);
}
// Note that we may return empty deltas if all updates have been deferred.
// The debugger will still call commit or discard on the update batch.
return (solutionUpdate.Summary, solutionUpdate.Deltas);
}
public void CommitSolutionUpdate()
{
var editSession = _editSession;
Contract.ThrowIfNull(editSession);
var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null);
Contract.ThrowIfNull(pendingUpdate);
editSession.DebuggingSession.CommitSolutionUpdate(pendingUpdate);
editSession.ChangesApplied();
}
public void DiscardSolutionUpdate()
{
Contract.ThrowIfNull(_editSession);
var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null);
Contract.ThrowIfNull(pendingUpdate);
foreach (var moduleReader in pendingUpdate.ModuleReaders)
{
moduleReader.Dispose();
}
}
public async Task<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken)
{
try
{
// It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so.
// We return null since there the concept of active statement only makes sense during break mode.
var editSession = _editSession;
if (editSession == null)
{
return null;
}
// TODO: Avoid enumerating active statements for unchanged documents.
// We would need to add a document path parameter to be able to find the document we need to check for changes.
// https://github.com/dotnet/roslyn/issues/24324
var baseActiveStatements = await editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement))
{
return null;
}
var (oldPrimaryDocument, _) = await editSession.DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(baseActiveStatement.PrimaryDocumentId, cancellationToken).ConfigureAwait(false);
if (oldPrimaryDocument == null)
{
// Can't determine position of an active statement if the document is out-of-sync with loaded module debug information.
return null;
}
var primaryDocument = _workspace.CurrentSolution.GetDocument(baseActiveStatement.PrimaryDocumentId);
if (primaryDocument == null)
{
// The document has been deleted.
return null;
}
var documentAnalysis = await editSession.GetDocumentAnalysis(oldPrimaryDocument, primaryDocument).GetValueAsync(cancellationToken).ConfigureAwait(false);
var currentActiveStatements = documentAnalysis.ActiveStatements;
if (currentActiveStatements.IsDefault)
{
// The document has syntax errors.
return null;
}
return currentActiveStatements[baseActiveStatement.PrimaryDocumentOrdinal].Span;
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
return null;
}
}
/// <summary>
/// Called by the debugger to determine whether an active statement is in an exception region,
/// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes.
/// If the debugger determines we can remap active statements, the application of changes proceeds.
/// </summary>
/// <returns>
/// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement
/// or the exception regions can't be determined.
/// </returns>
public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken)
{
try
{
var editSession = _editSession;
if (editSession == null)
{
return null;
}
// This method is only called when the EnC is about to apply changes, at which point all active statements and
// their exception regions will be needed. Hence it's not neccessary to scope this query down to just the instruction
// the debugger is interested at this point while not calculating the others.
var baseActiveStatements = await editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement))
{
return null;
}
var baseExceptionRegions = (await editSession.GetBaseActiveExceptionRegionsAsync(cancellationToken).ConfigureAwait(false))[baseActiveStatement.Ordinal];
// If the document is out-of-sync the exception regions can't be determined.
return baseExceptionRegions.Spans.IsDefault ? (bool?)null : baseExceptionRegions.IsActiveStatementCovered;
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
return null;
}
}
public void ReportApplyChangesException(string message)
{
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError);
_emitDiagnosticsUpdateSource.ReportDiagnostics(
_workspace.CurrentSolution,
projectId: null,
new[] { Diagnostic.Create(descriptor, Location.None, new[] { message }) });
}
private static void ReportTelemetry(DebuggingSessionTelemetry.Data data)
{
// report telemetry (fire and forget):
_ = Task.Run(() => LogDebuggingSessionTelemetry(data, Logger.Log, LogAggregator.GetNextId));
}
// internal for testing
internal static void LogDebuggingSessionTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId)
{
const string SessionId = nameof(SessionId);
const string EditSessionId = nameof(EditSessionId);
var debugSessionId = getNextId();
log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map =>
{
map[SessionId] = debugSessionId;
map["SessionCount"] = debugSessionData.EditSessionData.Length;
map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount;
}));
foreach (var editSessionData in debugSessionData.EditSessionData)
{
var editSessionId = getNextId();
log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map =>
{
map[SessionId] = debugSessionId;
map[EditSessionId] = editSessionId;
map["HadCompilationErrors"] = editSessionData.HadCompilationErrors;
map["HadRudeEdits"] = editSessionData.HadRudeEdits;
map["HadValidChanges"] = editSessionData.HadValidChanges;
map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges;
map["RudeEditsCount"] = editSessionData.RudeEdits.Length;
map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length;
}));
foreach (var errorId in editSessionData.EmitErrorIds)
{
log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map =>
{
map[SessionId] = debugSessionId;
map[EditSessionId] = editSessionId;
map["ErrorId"] = errorId;
}));
}
foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits)
{
log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map =>
{
map[SessionId] = debugSessionId;
map[EditSessionId] = editSessionId;
map["RudeEditKind"] = editKind;
map["RudeEditSyntaxKind"] = syntaxKind;
map["RudeEditBlocking"] = editSessionData.HadRudeEdits;
}));
}
}
}
}
}
| 47.215839 | 212 | 0.633111 | [
"Apache-2.0"
] | Saibamen/roslyn | src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceService.cs | 30,409 | C# |
using System;
using System.Threading.Tasks;
using Infrastructure.SwaggerSchema.Dropdowns;
using Infrastructure.SwaggerSchema.Dropdowns.Providers;
namespace HightechAngular.Shop.Features.Index
{
public class SaleListDropdownProvider: IDropdownProvider<SaleListItem>
{
private readonly IServiceProvider _serviceProvider;
public SaleListDropdownProvider(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public Task<Dropdowns> GetDropdownOptionsAsync()
{
return _serviceProvider.DropdownsFor<SaleListItem>();
}
}
} | 28.681818 | 74 | 0.727417 | [
"MIT"
] | AlexProkhor/DotNext-Moscow-2020 | Modules/HightechAngular.Shop/Features/Index/SaleListDropdownProvider.cs | 633 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BXJG.WeChat.Payment;
using DemoMVC.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DemoMVC.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MiniProgramPaymentController : ControllerBase
{
private readonly BXJG.WeChat.Payment.WeChatPaymentService weChatPaymentService;
public MiniProgramPaymentController(WeChatPaymentService weChatPaymentService)
{
this.weChatPaymentService = weChatPaymentService;
}
public async Task<BXJG.WeChat.Payment.WeChatPaymentUnifyOrderResultForMiniProgram> PaymentAsync(PaymentInput intput)
{
//做一堆业务判断
//金额 订单 优惠 ... 你的业务
var order = weChatPaymentService.Create("商品描述", "本地订单号", 3.5m);
order.product_id = "aaa";
//继续配置微信需要的消息参数
var rt = await weChatPaymentService.PayAsync(order, base.HttpContext.RequestAborted);
//你的业务再判断
return rt.CreateMiniProgramResult();
}
}
} | 32.628571 | 124 | 0.687391 | [
"MIT"
] | bxjg1987/abpGeneralModules | src/DemoMVC/Controllers/MiniProgramPaymentController.cs | 1,236 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WOTK {
/// <summary>
/// Every shape supported by the overlay.
/// </summary>
public enum Shapes {
Rectangle,
Arc,
Bezier,
ClosedCurve,
Curve,
Ellipse,
Icon,
Image,
GraphicPath,
Pie,
Polygon,
String
}
/// <summary>
/// An Overlay object creates a FormOverlay window and draws shapes over it. You need to specify a <see cref="WPMTK.Process"/> object in the constructor.
/// </summary>
public class Overlay {
private FormOverlay formOverlay;
internal bool isLocked;
internal WPMTK.Process process;
/// <summary>
/// In case you want to edit the form manually, you can do it here.
/// </summary>
public FormOverlay FormOverlay {
get => !isLocked ? formOverlay : throw new InvalidOperationException("Overlay is locked from modification.");
set { if (!isLocked) formOverlay = value; else throw new InvalidOperationException("Overlay is locked from modification."); }
}
/// <summary>
/// Draw a new overlay above the specified Process's main window.
/// </summary>
/// <param name="process"></param>
public Overlay(WPMTK.Process process)
{
this.process = process;
FormOverlay = new FormOverlay(process, true);
}
/// <summary>
/// Draw a new overlay above the specified Process's main window.
/// </summary>
/// <param name="process"></param>
/// <param name="isBorderless">You can specify false to keep your overlay window from drawing borderless. (Useful for testing)</param>
public Overlay(WPMTK.Process process, bool isBorderless)
{
this.process = process;
FormOverlay = new FormOverlay(process, isBorderless);
}
/// <summary>
/// After creating the overlay, you need to specify whether it's visible or not.
/// </summary>
/// <param name="visible"></param>
public void IsOverlayShown(bool visible) {
if (visible) {
FormOverlay.Show();
} else {
FormOverlay.Hide();
}
}
/// <summary>
/// Draws a shape onto the overlay.
/// </summary>
/// <param name="shape">Shape from <see cref="Shapes"/> to define the type of supported shape.</param>
/// <param name="shape_struct">Shape struct from <see cref="System.Drawing"/> to define the attributes of the shape. Must match the specified <see cref="Shapes"/> shape.</param>
public void AddShape(Shapes shape, object shape_struct) {
if (!isLocked) {
switch (shape) {
case Shapes.Rectangle:
if (shape_struct is RectangleF) {
FormOverlay.AddRectangle((RectangleF)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.Arc:
if (shape_struct is Arc) {
FormOverlay.AddArc((Arc)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.Bezier:
if (shape_struct is PointF) {
FormOverlay.AddBezier((PointF)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.ClosedCurve:
if (shape_struct is ClosedCurve) {
FormOverlay.AddClosedCurve((ClosedCurve)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.Curve:
if (shape_struct is Curve) {
FormOverlay.AddCurve((Curve)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.Ellipse:
if (shape_struct is RectangleF) {
FormOverlay.AddEllipse((RectangleF)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.Icon:
if (shape_struct is IconStruct) {
FormOverlay.AddIcon((IconStruct)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.Image:
if (shape_struct is ImageStruct) {
FormOverlay.AddImage((ImageStruct)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.GraphicPath:
if (shape_struct is GraphicsPath) {
FormOverlay.AddGraphicsPaths((GraphicsPath)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.Pie:
if (shape_struct is Pie) {
FormOverlay.AddPie((Pie)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.Polygon:
if (shape_struct is Polygon) {
FormOverlay.AddPolygon((Polygon)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
case Shapes.String:
if (shape_struct is StringStruct) {
FormOverlay.AddString((StringStruct)shape_struct);
} else {
throw new InvalidOperationException("structData object does not match the required object.");
}
break;
}
formOverlay.RefreshForm();
} else {
throw new InvalidOperationException("Overlay is locked from modification.");
}
}
}
}
| 44.039548 | 185 | 0.494933 | [
"MIT"
] | VenHayz/WPMTK | OverlayLib/Overlay.cs | 7,797 | C# |
#region License
//
// MIT License
//
// CoiniumServ - Crypto Currency Mining Pool Server Software
// Copyright (C) 2013 - 2017, CoiniumServ Project
// Hüseyin Uslu, shalafiraistlin at gmail dot com
// https://github.com/bonesoul/CoiniumServ
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#endregion
using System;
using CoiniumServ.Configuration;
namespace CoiniumServ.Payments.Config
{
public interface IPaymentConfig:IConfig
{
bool Enabled { get; }
/// <summary>
/// interval in seconds that payment-processor will be running.
/// </summary>
Int32 Interval { get; }
/// <summary>
/// interval in seconds that payment-processor's block checks will be running.
/// </summary>
Int32 CheckInterval { get; }
/// <summary>
/// minimum amount of coins before a miner is eligable for getting a payment.
/// </summary>
double Minimum { get; }
void Disable();
}
}
| 37.157895 | 86 | 0.669027 | [
"MIT"
] | MyCryptoCoins/CoiniumServ | src/CoiniumServ/Payments/Config/IPaymentConfig.cs | 2,121 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Scorpio.AspNetCore.TagHelpers.Card
{
/// <summary>
///
/// </summary>
[HtmlTargetElement("img", ParentTag = "card")]
public class CardImageTagHelper : TagHelper
{
/// <summary>
///
/// </summary>
public CardImagePosition Position { get; set; }
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="output"></param>
/// <returns></returns>
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "img";
output.AddClass($"card-img{Position.ToClassName()}");
return base.ProcessAsync(context, output);
}
}
}
| 26.34375 | 91 | 0.562278 | [
"MIT"
] | project-scorpio/Scorpio | src/aspnetcore/src/Scorpio.AspNetCore.UI.Bootstrap/Scorpio/AspNetCore/TagHelpers/Card/CardImageTagHelper.cs | 845 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeDataSet
{
public void Example()
{
#region Usage
string json = @"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}";
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
DataTable dataTable = dataSet.Tables["Table1"];
Console.WriteLine(dataTable.Rows.Count);
// 2
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["id"] + " - " + row["item"]);
}
// 0 - item 0
// 1 - item 1
#endregion
}
}
} | 19.909091 | 69 | 0.530822 | [
"MIT"
] | Chimpaneez/LiveSplit | LiveSplit/Libs/JSON.Net/Source/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDataSet.cs | 878 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Mammothcode.AdminService")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Mammothcode.AdminService")]
[assembly: System.Reflection.AssemblyTitleAttribute("Mammothcode.AdminService")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// 由 MSBuild WriteCodeFragment 类生成。
| 38.25 | 82 | 0.643791 | [
"Apache-2.0"
] | 1152250070/juzen | Mammothcode.BeiQin/Mammothcode.AdminService/obj/Release/netstandard2.0/Mammothcode.AdminService.AssemblyInfo.cs | 1,034 | C# |
using System;
using System.Composition;
namespace Multiformats.Hash.Algorithms
{
[Export(typeof(IMultihashAlgorithm))]
[MultihashAlgorithmExport(HashType.ID, "id", 32)]
public class ID : MultihashAlgorithm
{
public ID()
: base(HashType.ID, "id", 32)
{
}
public override byte[] ComputeHash(byte[] data, int length = -1)
{
if (length >= 0 && length != data.Length)
throw new Exception($"The length of the identity hash ({length}) must be equal to the length of the data ({data.Length})");
return data;
}
}
}
| 26.208333 | 139 | 0.581876 | [
"MIT"
] | DalavanCloud/cs-multihash | src/Multiformats.Hash/Algorithms/ID.cs | 629 | C# |
#region License
/*
MIT License
Copyright(c) 2020 Petteri Kautonen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using VPKSoft.Utils;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;
using MakeANuGet.DialogForms;
using MakeANuGet.HelperClasses;
using VPKSoft.ScintillaLexers;
using static MakeANuGet.HelperClasses.XmlUtilities;
namespace MakeANuGet
{
/// <summary>
/// The main form for the MakeANuGet software.
/// </summary>
public partial class FormMain : Form
{
/// <summary>
/// The main form for the software.
/// </summary>
public FormMain()
{
InitializeComponent();
// ReSharper disable once CommentTypo
// create the settings folder if it doesn't already exists (%LOCALAPPDATA%\MakeANuGet)..
var settingsPath = Paths.MakeAppSettingsFolder();
// load the NuGet API key..
vnml = new VPKNml();
settingsFile = Path.Combine(settingsPath, "settings.vnml");
vmmlPath = Path.Combine(settingsPath, "defaults.vnml");
vnml.Load(settingsFile);
ApiKey = vnml["api", "key", ""].ToString();
// ReSharper disable once StringLiteralTypo
TestApiKey = vnml["apitest", "key", ""].ToString();
GitHubPackagesApiKey = vnml["apiGitHubPackages", "key", ""].ToString();
GitHubPackagesUserName = vnml["apiGitHubPackages", "userName", ""].ToString();
CertificatePassword = vnml["certificate", "password", ""].ToString();
CertificateFile = vnml["certificate", "file", ""].ToString();
CertificateTimeStampServer = vnml["certificate", "timeStampServer", ""].ToString();
signPackage = bool.Parse(vnml["certificate", "use", false].ToString());
// set the API key to the text box..
btApiKey.Tag = cbTestNuGet.Checked ? TestApiKey : ApiKey;
btApiKey.Text = bool.Parse(pnToggleApiKeyVisible.Tag.ToString())
? btApiKey.Tag.ToString()
: new string('•', btApiKey.Tag.ToString().Length);
// display the test menu in a debug session..
mnuTest.Visible = Debugger.IsAttached;
if (Debugger.IsAttached)
{
var initialDirectory = Path.GetFullPath(Path.Combine(Paths.AppInstallDir, "..", "..", "..", "VPKSoft.MakeANugetTest"));
odCSProj.InitialDirectory = initialDirectory;
var testPath = Path.GetFullPath(Path.Combine(Paths.AppInstallDir, "..", "..", "..", "VPKSoft.MakeANugetTest", "NugetIcons"));
odIconFile.InitialDirectory = testPath;
}
ScintillaLexers.CreateLexer(scintillaNuspecContents,
LexerEnumerations.LexerType.Xml);
// this is suitable for XML files..
scintillaNuspecContents.TabWidth = 2;
scintillaNuspecContents.UseTabs = false;
SetStepZero();
}
#region PrivateFields
// use the self developed "not a markup language"..
private readonly VPKNml vnml;
// the settings file name (to store the API key only)..
private readonly string settingsFile;
// the C# project file (*.cs) to make the NuGet from..
private string csprojFile;
// the .nuspec file for the NuGet package generation..
private string nuspecFile;
// the .nuspec file is a XML document..
private XDocument nuspec;
// a binary path for the release folder of your library..
private string binaryPath;
// an assembly name for your library..
private string assemblyName;
// the assembly which from which to NuGet package is to be created..
private Assembly assemblyNuget;
// your nuget.org API key
internal static string ApiKey;
// ReSharper disable twice CommentTypo
// your apiint.nugettest.org API key
internal static string TestApiKey;
// your API key for the GitHub packages..
internal static string GitHubPackagesApiKey;
// your user name for the GitHub packages..
internal static string GitHubPackagesUserName;
// a path to the common settings .vnml file..
// ReSharper disable once IdentifierTypo
private readonly string vmmlPath;
// a password for a certificate file to sign the nuget package..
internal static string CertificatePassword;
// an URL for the certificate time stamp server..
internal static string CertificateTimeStampServer;
// the certificate file to be used for signing the nuget package..
internal static string CertificateFile;
// a value indicating whether to sign the nuget package with a certificate
private bool signPackage;
#endregion
#region ValidityChecks
/// <summary>
/// Blinks a text box's background color to indicate a missing or an invalid value.
/// </summary>
/// <param name="textBox">The text box of which background to blink in case of an error.</param>
/// <param name="blinkText">The erroneous value (text) for blinking.</param>
/// <returns>True if the value was invalid; otherwise false.</returns>
private bool BlinkTextBox(TextBox textBox, string blinkText)
{
return BlinkTextBox(textBox, () => textBox.Text == blinkText || textBox.Text.Trim() == string.Empty);
}
/// <summary>
/// Blinks a text box's background color to indicate a missing or an invalid value.
/// </summary>
/// <param name="textBox">The text box of which background to blink in case of an error.</param>
/// <param name="condition">A function to validate the value.</param>
/// <returns>True if the value was invalid; otherwise false.</returns>
private bool BlinkTextBox(TextBox textBox, Func<bool> condition)
{
// test the condition and in case of true blink to indicate an error..
if (condition())
{
// a value of 3 seconds should be enough..
for (int i = 0; i < 10; i++)
{
// the logic with remainder..
textBox.BackColor = (i % 2) == 0 ? Color.Red : SystemColors.Window;
// non-asynchronous blinking - sorry..
Application.DoEvents();
// sleep for 300 milliseconds..
Thread.Sleep(300);
}
return true;
}
else
{
// indicate a valid value..
return false;
}
}
/// <summary>
/// Validate the input values on the form and indicate erroneous fields.
/// </summary>
/// <returns>True if the data was valid; otherwise false.</returns>
private bool ValidateStepTwo()
{
// The text "constants" are the "empty" values for a NuGet package..
return
!(BlinkTextBox(tbTags, "Tag1 Tag2") ||
// Removed as deprecated: BlinkTextBox(tbLicenseUrl, "http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE") ||
BlinkTextBox(tbLicenseFile, (() => tbLicenseFile.Tag == null)) ||
BlinkTextBox(tbProjectURL, "http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE") ||
BlinkTextBox(tbReleaseNotes, "Summary of changes made in this release of the package.") ||
BlinkTextBox(tbCopyright, "Copyright " + DateTime.Now.Year));
}
/// <summary>
/// Clear all data if another project is loaded.
/// </summary>
private void SetStepZero()
{
SetGuiEnabled(false);
}
/// <summary>
/// Sets the GUI enabled or disabled.
/// </summary>
/// <param name="enabled">if set to <c>true</c> the GUI is enabled.</param>
private void SetGuiEnabled(bool enabled)
{
if (!enabled)
{
csprojFile = null;
nuspecFile = null;
nuspec = null;
assemblyNuget = null;
binaryPath = null;
assemblyName = null;
cbForceNuspec.Checked = false;
cbTestNuGet.Checked = false;
tbTags.Text = string.Empty;
tbTags.Text = string.Empty;
tbLicenseFile.Text = string.Empty;
tbLicenseFileTarget.Text = string.Empty;
tbProjectURL.Text = string.Empty;
tbIcon.Text = string.Empty;
tbIconTarget.Text = string.Empty;
tbReleaseNotes.Text = string.Empty;
tbCopyright.Text = string.Empty;
tbDescription.Text = string.Empty;
cbRequireLicenseAcceptance.Checked = false;
tbIconURL.Text = string.Empty;
tbLicenseUrl.Text = string.Empty;
scintillaNuspecContents.Text = string.Empty;
tbLicenseFile.Tag = null;
tbIcon.Tag = null;
dgvFiles.Rows.Clear();
}
btSaveFileChanges.Enabled = enabled;
btUndoFileChanges.Enabled = enabled;
mnuFillWithDefaults.Enabled = enabled;
mnuSaveChanges.Enabled = enabled;
cbForceNuspec.Enabled = enabled;
cbTestNuGet.Enabled = enabled;
lbTags.Enabled = enabled;
tbTags.Enabled = enabled;
lbLicenseFileOrType.Enabled = enabled;
tbLicenseFile.Enabled = enabled;
tbLicenseFileTarget.Enabled = enabled;
btLicenseFile.Enabled = enabled;
btSelectLicenseByType.Enabled = enabled;
btAddLicenseByType.Enabled = enabled;
lbProjectURL.Enabled = enabled;
tbProjectURL.Enabled = enabled;
lbIcon.Enabled = enabled;
tbIcon.Enabled = enabled;
tbIconTarget.Enabled = enabled;
btIconFile.Enabled = enabled;
lbReleaseNotes.Enabled = enabled;
tbReleaseNotes.Enabled = enabled;
lbCopyright.Enabled = enabled;
tbCopyright.Enabled = enabled;
lbDescription.Enabled = enabled;
tbDescription.Enabled = enabled;
lbRequireLicenseAcceptance.Enabled = enabled;
cbRequireLicenseAcceptance.Enabled = enabled;
lbIconURL.Enabled = enabled;
tbIconURL.Enabled = enabled;
btClearIconUrl.Enabled = enabled;
lbLicenseUrl.Enabled = enabled;
tbLicenseUrl.Enabled = enabled;
btClearLicenseUrl.Enabled = enabled;
scintillaNuspecContents.Enabled = enabled;
btSaveXMLChanges.Enabled = enabled;
lbFiles.Enabled = enabled;
dgvFiles.Enabled = enabled;
}
#endregion
#region Settings
// ReSharper disable once CommentTypo
/// <summary>
/// Gets or sets the assembly copyright value. For the getter the copyright is first tried to be gotten from the actual assembly
/// and if not found then the value is defaulted to a saved setting if any. The setter saves a default value to a file called
/// "%LOCALAPPDATA%\MakeANuGet\defaults.vnml".
/// </summary>
private string AssemblyCopyright
{
get
{
// get the basic attributes for the assembly..
var obj = assemblyNuget.GetCustomAttributes(false);
// loop through the attributes..
foreach (var o in obj)
{
// if a AssemblyCopyrightAttribute exists..
if (o is AssemblyCopyrightAttribute assemblyCopyrightAttribute)
{
// return it as a string..
return assemblyCopyrightAttribute.Copyright;
}
}
// fall back to the saved default value and..
VPKNml vnmlDefaults = new VPKNml();
vnmlDefaults.Load(vmmlPath);
// ..return it..
return vnmlDefaults["defaults", "copyright", ""].ToString();
}
set
{
// save the default value to the defaults.vnml file..
VPKNml vnmlDefaults = new VPKNml();
vnmlDefaults.Load(vmmlPath);
vnmlDefaults["defaults", "copyright"] = value;
vnmlDefaults.Save(vmmlPath);
}
}
/// <summary>
/// Gets or sets a default value for the "requireLicenseAcceptance" in the .nuspec file.
/// </summary>
private bool AssemblyMustAcceptLicense
{
get
{
// return the value..
VPKNml vnmlDefaults = new VPKNml();
vnmlDefaults.Load(vmmlPath);
return bool.Parse(vnmlDefaults["defaults", "requireLicenseAcceptance", "True"].ToString());
}
set
{
// save the value..
VPKNml vnmlDefaults = new VPKNml();
vnmlDefaults.Load(vmmlPath);
vnmlDefaults["defaults", "requireLicenseAcceptance"] = value.ToString();
vnmlDefaults.Save(vmmlPath);
}
}
/// <summary>
/// Gets or set a default value for the "iconUrl" in the .nuspec file.
/// </summary>
private string AssemblyIconUrl
{
get
{
// return the value..
VPKNml vnmlDefaults = new VPKNml();
vnmlDefaults.Load(vmmlPath);
return vnmlDefaults["defaults", "iconUrl", ""].ToString();
}
set
{
// save the value..
VPKNml vnmlDefaults = new VPKNml();
vnmlDefaults.Load(vmmlPath);
vnmlDefaults["defaults", "iconUrl"] = value;
vnmlDefaults.Save(vmmlPath);
}
}
#endregion
#region XmlData
/// <summary>
/// Displays the relevant contents of the .nuspec file.
/// </summary>
private void DisplayXmlData()
{
if (nuspec != null)
{
var metadataElement = nuspec.Root?.Element("metadata");
tbTags.Text = metadataElement?.Element("tags")?.Value;
tbLicenseUrl.Text = metadataElement?.Element("licenseUrl")?.Value;
tbProjectURL.Text = metadataElement?.Element("projectUrl")?.Value;
tbIconURL.Text = metadataElement?.Element("iconUrl")?.Value;
tbReleaseNotes.Text = metadataElement?.Element("releaseNotes")?.Value;
tbCopyright.Text = metadataElement?.Element("copyright")?.Value;
tbDescription.Text = metadataElement?.Element("description")?.Value;
tbIcon.Text = metadataElement?.Element("icon")?.Value;
var iconFileElement = GetFileElementSourceAndTarget(nuspec, tbIcon.Text);
tbIcon.Tag = iconFileElement.source;
tbIconTarget.Text = iconFileElement.target;
var boolString = metadataElement?.Element("requireLicenseAcceptance")?.Value;
cbRequireLicenseAcceptance.Checked = boolString != null && bool.Parse(boolString);
tbDescription.Text = metadataElement?.Element("description")?.Value;
var licenseElement = metadataElement?.Element("license"); // the license is bit more complicated..
var licenseType = licenseElement?.Attribute("type")?.Value;
if (licenseType != null)
{
// the "expression" license may contain many SPDX licenses listed by the Linux Foundation (https://spdx.org/licenses/)..
if (licenseType == "expression")
{
// construct a list of SPDX licenses..
List<SPDXLicense> licenses = new List<SPDXLicense>();
// the licenses are combined with a text " OR " or " AND ", so split them..
string[] licenseIds = licenseElement.Value.Split(new[] { " OR ", " AND " }, StringSplitOptions.RemoveEmptyEntries);
// get a licenses for each occurrence..
foreach (string licenseId in licenseIds)
{
// ..and add them to the list..
licenses.Add(FormDialogQuerySPDXLicense.SPDXLicenseCollection.GetLicenseByIdentifier(licenseId));
}
// set the text..
tbLicenseFile.Text = SPDXLicenseCollection.ConstructLicenseString(licenses);
// save the licenses to the text box's Tag property..
tbLicenseFile.Tag = licenses;
}
// a license may also be an embedded file within the NuGet..
else if (licenseType == "file")
{
// the file name is without a path..
tbLicenseFile.Text = licenseElement.Value;
// the files node in the .nuspec file must contain a relative path the license file
// so do try to get it..
var fileElement = GetFileElementSourceAndTarget(nuspec, licenseElement.Value);
tbLicenseFile.Tag = fileElement.source;
tbLicenseFileTarget.Text = fileElement.target;
}
}
DisplayFileElements();
}
}
/// <summary>
/// Saves the data on the form to the .nuspec file.
/// </summary>
private void SaveXmlData()
{
// save the .nuspec..
nuspec?.Save(nuspecFile);
}
/// <summary>
/// Displays the file elements defined in the .nuspec file.
/// </summary>
private void DisplayFileElements()
{
dgvFiles.Rows.Clear();
if (nuspec != null)
{
var dataEntries = GetFileElementData(nuspec);
foreach (var dataEntry in dataEntries)
{
var rowIndex = dgvFiles.Rows.Add();
dgvFiles.Rows[rowIndex].Cells[colFile.Index].Value = dataEntry.SrcAttribute;
dgvFiles.Rows[rowIndex].Cells[colTarget.Index].Value = dataEntry.TargetAttribute;
dgvFiles.Rows[rowIndex].Cells[colExcludePattern.Index].Value = dataEntry.ExcludeAttribute;
dgvFiles.Rows[rowIndex].Cells[colCopyToOutput.Index].Value = false;
dgvFiles.Rows[rowIndex].Cells[colFlatten.Index].Value = false;
dgvFiles.Rows[rowIndex].Cells[colUseContentElement.Index].Value = false;
}
var contentFilesEntries = GetContentFileElementData(nuspec);
foreach (var contentFilesEntry in contentFilesEntries)
{
var rowIndex = dgvFiles.Rows.Add();
dgvFiles.Rows[rowIndex].Cells[colFile.Index].Value = contentFilesEntry.IncludeAttribute;
dgvFiles.Rows[rowIndex].Cells[colExcludePattern.Index].Value = contentFilesEntry.ExcludeAttribute;
dgvFiles.Rows[rowIndex].Cells[colBuildAction.Index].Value = contentFilesEntry.BuildActionAttribute;
dgvFiles.Rows[rowIndex].Cells[colCopyToOutput.Index].Value = contentFilesEntry.CopyToOutputAttribute;
dgvFiles.Rows[rowIndex].Cells[colFlatten.Index].Value = contentFilesEntry.FlattenAttribute;
dgvFiles.Rows[rowIndex].Cells[colUseContentElement.Index].Value = true;
}
}
}
/// <summary>
/// Updates the files defined in the file <see cref="DataGridView"/>.
/// </summary>
private void UpdateFiles()
{
bool ValueToBool(object value)
{
if (value == null)
{
return false;
}
if (value is bool boolValue)
{
return boolValue;
}
return false;
}
List<NuspecFileContentElement> contentElements = new List<NuspecFileContentElement>();
List<NuspecFileElement> fileElements = new List<NuspecFileElement>();
foreach (DataGridViewRow row in dgvFiles.Rows)
{
if (row.Cells[colUseContentElement.Index].Value is bool &&
(bool) row.Cells[colUseContentElement.Index].Value)
{
contentElements.Add(new NuspecFileContentElement
{
IncludeAttribute = (string) row.Cells[colFile.Index].Value,
ExcludeAttribute = (string) row.Cells[colExcludePattern.Index].Value,
BuildActionAttribute = (string) row.Cells[colBuildAction.Index].Value,
CopyToOutputAttribute = ValueToBool(row.Cells[colCopyToOutput.Index].Value),
FlattenAttribute = ValueToBool(row.Cells[colFlatten.Index].Value),
}
);
}
else
{
fileElements.Add(new NuspecFileElement
{
SrcAttribute = (string) row.Cells[colFile.Index].Value,
TargetAttribute = (string) row.Cells[colTarget.Index].Value,
ExcludeAttribute = (string) row.Cells[colExcludePattern.Index].Value,
});
}
}
UpdateContentFilesAndFiles(nuspec, contentElements, fileElements);
DisplayXmlData();
}
#endregion
#region NuGetProcess
// gets the path to the generated .nupkg file..
private string GetNugetFile()
{
var csprojPath = Path.GetDirectoryName(csprojFile);
if (csprojPath == null)
{
return string.Empty;
}
// enumerate the files in the directory where the .csproj file resides..
string[] nugPackages = Directory.GetFiles(csprojPath, "*.nupkg");
// initialize a list of FileInfo class instances..
List<FileInfo> nugPackagesInfo = new List<FileInfo>();
// loop through the gotten files and get their information..
foreach (string nupkg in nugPackages)
{
nugPackagesInfo.Add(new FileInfo(nupkg));
}
// sort the files with their last write times..
nugPackagesInfo = nugPackagesInfo.OrderBy(f => f.LastWriteTime).ToList();
// pick the newest file..
return Path.GetFileName(nugPackagesInfo.Last().Name);
}
// a user wishes to push the NuGet package to nuget.org (https://www.nuget.org)..
private void btPushNugetPackage_Click(object sender, EventArgs e)
{
string np = GetNugetFile();
// push the NuGet package to nuget.org (https://int.nugettest.org) (NOTE: For testing!)..
RunSpecNuGet(cbTestNuGet.Checked
? $" push {np} {btApiKey.Tag} -Source https://apiint.nugettest.org/v3/index.json"
: $" push {np} {btApiKey.Tag} -Source https://api.nuget.org/v3/index.json");
}
/// <summary>
/// Updates the contained nuget.exe.
/// </summary>
private void UpdateNugetExe()
{
string processPath = Path.Combine(Paths.AppInstallDir, "nuget.exe");
if (!File.Exists(processPath))
{
return;
}
// the output from the nuget.exe is piped to the lower black text box..
tbProcessOutput.AppendText("> " + processPath + " update - self" + Environment.NewLine);
// create a process..
Process process = new Process
{
StartInfo =
{
FileName = processPath,
Arguments = "update -self",
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = Paths.AppInstallDir,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
// give it the process file name..
// give the process it's arguments..
// no shell execution..
// no exclusive window..
// set the working directory to the same as the .csproj file location..
// redirect the process output(s)..
// subscribe to the process events with anonymous event handlers..
process.OutputDataReceived += (sender, e) =>
{
// append new line endings to the each output string..
if (!String.IsNullOrEmpty(e.Data))
{
// invocation is required (another process)..
Invoke(new MethodInvoker(delegate { tbProcessOutput.AppendText(e.Data + Environment.NewLine); }));
}
};
process.ErrorDataReceived += (sender, e) =>
{
// append new line endings to the each output string..
if (!String.IsNullOrEmpty(e.Data))
{
// invocation is required (another process)..
Invoke(new MethodInvoker(delegate { tbProcessOutput.AppendText(e.Data + Environment.NewLine); }));
}
};
// start the process after "hefty" initialization..
process.Start();
// asynchronously read the standard output of the spawned process.
// This raises OutputDataReceived events for each line of output.
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// wait for the process to exit while "pumping" the software to be "responsive"..
while (!process.HasExited)
{
Application.DoEvents();
Thread.Sleep(100);
}
Application.DoEvents();
// empty line to the output..
tbProcessOutput.AppendText(Environment.NewLine);
using (process)
{
// dispose of the process..
}
}
/// <summary>
/// Signs the nuget package with a code signing certificate.
/// </summary>
private void SignPackage()
{
var csprojPath = Path.GetDirectoryName(csprojFile);
if (!signPackage || csprojPath == null)
{
return;
}
string processPath = Path.Combine(Paths.AppInstallDir, "nuget.exe");
var package = GetNugetFile();
// the output from the nuget.exe is piped to the lower black text box..
// ReSharper disable once StringLiteralTypo
tbProcessOutput.AppendText("> " + processPath + $" sign \"{package}\" -CertificatePath \"{CertificateFile}\" -Timestamper {CertificateTimeStampServer} -CertificatePassword \"{new string('•', CertificatePassword.Length)}\" " + Environment.NewLine);
// create a process..
Process process = new Process
{
StartInfo =
{
FileName = processPath,
Arguments =
$"sign \"{package}\" -CertificatePath \"{CertificateFile}\" -Timestamper {CertificateTimeStampServer} -CertificatePassword \"{CertificatePassword}\"",
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = csprojPath,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
// give it the process file name..
// give the process it's arguments..
// no shell execution..
// no exclusive window..
// set the working directory to the same as the .csproj file location..
// redirect the process output(s)..
// subscribe to the process events with anonymous event handlers..
process.OutputDataReceived += (sender, e) =>
{
// append new line endings to the each output string..
if (!String.IsNullOrEmpty(e.Data))
{
// invocation is required (another process)..
Invoke(new MethodInvoker(delegate { tbProcessOutput.AppendText(e.Data + Environment.NewLine); }));
}
};
process.ErrorDataReceived += (sender, e) =>
{
// append new line endings to the each output string..
if (!String.IsNullOrEmpty(e.Data))
{
// invocation is required (another process)..
Invoke(new MethodInvoker(delegate { tbProcessOutput.AppendText(e.Data + Environment.NewLine); }));
}
};
// start the process after "hefty" initialization..
process.Start();
// asynchronously read the standard output of the spawned process.
// This raises OutputDataReceived events for each line of output.
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// wait for the process to exit while "pumping" the software to be "responsive"..
while (!process.HasExited)
{
Application.DoEvents();
Thread.Sleep(100);
}
Application.DoEvents();
// empty line to the output..
tbProcessOutput.AppendText(Environment.NewLine);
using (process)
{
// dispose of the process..
}
}
/// <summary>
/// Tries to push a generated NuGet package to nuget.org (https://www.nuget.org).
/// </summary>
/// <param name="parameters">Parameters for the nuget.exe.</param>
/// <returns>True if the package was pushed successfully; otherwise false.</returns>
private bool RunSpecNuGet(string parameters)
{
// a flag indicating if the push was successful..
bool returnValue = false;
var csprojPath = Path.GetDirectoryName(csprojFile);
// first check there is everything in place..
if (!string.IsNullOrEmpty(csprojFile) && csprojPath != null)
{
// assume success..
returnValue = true;
// ..\..\nuget\nuget.exe spec ConfLib.csproj - Force
string processPath = Path.Combine(Paths.AppInstallDir, "nuget.exe");
// the output from the nuget.exe is piped to the lower black text box..
var commandEcho = "> " + processPath + parameters + Environment.NewLine;
// hide the API key in case of a screen shot, etc..
commandEcho = commandEcho.Replace(btApiKey.Tag.ToString(), new string('•', btApiKey.Tag.ToString().Length));
tbProcessOutput.AppendText(commandEcho);
// create a process..
Process process = new Process
{
StartInfo =
{
FileName = processPath,
Arguments = parameters,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = csprojPath,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
// give it the process file name..
// give the process it's arguments..
// no shell execution..
// no exclusive window..
// set the working directory to the same as the .csproj file location..
// redirect the process output(s)..
// subscribe to the process events with anonymous event handlers..
process.OutputDataReceived += (sender, e) =>
{
// append new line endings to the each output string..
if (!string.IsNullOrEmpty(e.Data))
{
// invocation is required (another process)..
Invoke(new MethodInvoker(delegate { tbProcessOutput.AppendText(e.Data + Environment.NewLine); }));
}
};
process.ErrorDataReceived += (sender, e) =>
{
// append new line endings to the each output string..
if (!String.IsNullOrEmpty(e.Data))
{
// invocation is required (another process)..
Invoke(new MethodInvoker(delegate { tbProcessOutput.AppendText(e.Data + Environment.NewLine); }));
}
};
// start the process after "hefty" initialization..
process.Start();
// asynchronously read the standard output of the spawned process.
// This raises OutputDataReceived events for each line of output.
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// wait for the process to exit while "pumping" the software to be "responsive"..
while (!process.HasExited)
{
Application.DoEvents();
Thread.Sleep(100);
}
Application.DoEvents();
// reload the .nuspec file..
if (File.Exists(nuspecFile))
{
nuspec = XDocument.Load(nuspecFile);
// display the contents of the .nuspec file..
DisplayXmlData();
btGenerateNugetPackage.Enabled = true; // and enabled the next step..;
SetGuiEnabled(true);
// fill empty fields with defaults..
tbCopyright.Text = tbCopyright.Text == string.Empty ? AssemblyCopyright : tbCopyright.Text;
cbRequireLicenseAcceptance.Checked = AssemblyMustAcceptLicense;
tbIconURL.Text = tbIconURL.Text == string.Empty ? AssemblyIconUrl : tbIconURL.Text;
}
// check the process exit code and show an error dialog if the exit code is not 0..
if (process.ExitCode != 0)
{
returnValue = false; // indicate failure..
MessageBox.Show($@"Process exited with an error: {process.ExitCode}.", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
// empty line to the output..
tbProcessOutput.AppendText(Environment.NewLine);
// scroll the process output to the end..
tbProcessOutput.SelectionStart = tbProcessOutput.Text.Length;
tbProcessOutput.ScrollToCaret();
using (process)
{
// dispose of the process..
}
}
return returnValue; // return the result (true == success)..
}
#endregion
#region InternalEvents
// a user wishes to open a project (.cs) to generate a NuGet package..
private void mnuOpenProject_Click(object sender, EventArgs e)
{
// display an open file dialog for the .csproj file..
if (odCSProj.ShowDialog() == DialogResult.OK)
{
// display the main tab..
tcMain.SelectedTab = tabMain;
// clear the data..
SetStepZero();
// save the file name..
csprojFile = odCSProj.FileName;
// set the form's title..
Text = $@"Make a NuGet - [{csprojFile}]";
// get a file name for the .nuspec file..
nuspecFile = Path.ChangeExtension(csprojFile, ".nuspec");
// load the .csproj file..
if (csprojFile != null)
{
// create a XDocument class instance..
var csproj = XDocument.Load(csprojFile);
XNamespace xNamespace = "http://schemas.microsoft.com/developer/msbuild/2003";
// set the initial directory for the
odAnyFile.InitialDirectory = Path.GetDirectoryName(csprojFile);
var propertyGroups = csproj.Root?.Elements(xNamespace + "PropertyGroup");
// get the assembly name and the binary path from the .csproj file for the NuGet generation..
if (propertyGroups != null)
{
foreach (XElement element in propertyGroups)
{
var propertyGroupElements = element.Elements(xNamespace + "AssemblyName");
if (assemblyName == null)
{
foreach (var propertyGroupElement in propertyGroupElements)
{
if (assemblyName == null)
{
assemblyName = propertyGroupElement.Value;
}
}
}
if (binaryPath == null)
{
//foreach (var conditionAttribute in conditionAttributes)
var conditionAttribute = element.Attribute("Condition");
{
if (conditionAttribute?.Value.Trim(' ') ==
" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ".Trim(' '))
{
binaryPath = element.Element(xNamespace + "OutputPath")?.Value;
}
}
}
if (assemblyName != null && binaryPath != null)
{
break;
}
}
}
var csprojPath = Path.GetDirectoryName(csprojFile);
// combine the assembly DLL name..
if (binaryPath == null || csprojPath == null)
{
return;
}
binaryPath = Path.Combine(csprojPath, binaryPath, assemblyName + ".dll");
// load the assembly to get data from it..
try
{
assemblyNuget = Assembly.LoadFile(binaryPath);
}
catch (Exception ex)
{
MessageBox.Show($@"Failed to load assembly {binaryPath} with exception '{ex.Message}'.", @"Error",
MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
SetStepZero();
return;
}
// if the .nuspec already exists, then load it..
if (File.Exists(nuspecFile))
{
if (nuspecFile != null)
{
nuspec = XDocument.Load(nuspecFile);
}
SetGuiEnabled(true);
btGenerateNugetPackage.Enabled = true; // and enabled the next step..
DisplayXmlData(); // display the loaded data..
}
// enable the NuGet generation button..
btGenerateNuget.Enabled = true;
}
}
}
// a user decided to close the form, so save some setting which
// are presumed to be constant for the developer..
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
vnml["api", "key"] = ApiKey; // the NuGet API key..
// ReSharper disable once StringLiteralTypo
vnml["apitest", "key"] = TestApiKey; // the test NuGet API key..
// the certificate settings..
vnml["certificate", "password"] = CertificatePassword;
vnml["certificate", "file"] = CertificateFile;
vnml["certificate", "timeStampServer"] = CertificateTimeStampServer;
vnml["certificate", "use"] = signPackage;
vnml["apiGitHubPackages", "key"] = GitHubPackagesApiKey;
vnml["apiGitHubPackages", "userName"] = GitHubPackagesUserName;
vnml.Save(settingsFile);
// the assembly copyright..
AssemblyCopyright = tbCopyright.Text;
// the need for a "consumer" to accept the license..
AssemblyMustAcceptLicense = cbRequireLicenseAcceptance.Checked;
// an icon URL for the NuGet..
AssemblyIconUrl = tbIconURL.Text;
}
// a user wished to generate a .nuspec file..
private void btGenerateNuget_Click(object sender, EventArgs e)
{
// ..so do try to generate it..
RunSpecNuGet(" spec " + "\"" + csprojFile + "\"" + (cbForceNuspec.Checked ? " -Force" : string.Empty));
}
// a user wished to generate a NuGet package..
private void btGenerateNugetPackage_Click(object sender, EventArgs e)
{
// validate first..
// TODO::add extra validation..
if (ValidateStepTwo())
{
// save the .nuspec contents..
SaveXmlData();
// generate a NuGet package..
if (RunSpecNuGet(" pack -Prop Configuration=Release"))
{
// if successful, enable the push NuGet button..
btPushNugetPackage.Enabled = true;
// sign the package if set..
SignPackage();
}
}
}
// a user wishes to fill the "common" fields with default values..
private void mnuFillWithDefaults_Click(object sender, EventArgs e)
{
tbCopyright.Text = AssemblyCopyright;
tbIconURL.Text = AssemblyIconUrl;
cbRequireLicenseAcceptance.Checked = AssemblyMustAcceptLicense;
}
// a user wishes to select a license..
private void btSelectLicenseByType_Click(object sender, EventArgs e)
{
SPDXLicense license;
// show the SPDX license dialog..
if ((license = FormDialogQuerySPDXLicense.Execute()) != null)
{
// create a list of SPDXLicense class instances..
List<SPDXLicense> licenses = new List<SPDXLicense>(new[] { license });
// set the selected license to the Tag property of the text box..
tbLicenseFile.Tag = licenses;
// set the text for the text box to match the license list..
tbLicenseFile.Text = SPDXLicenseCollection.ConstructLicenseString(licenses);
// set the target to nothing..
tbLicenseFileTarget.Text = string.Empty;
}
SetLicenseElementSpdx(nuspec, tbLicenseFile.Tag);
}
// a user wishes to add to an existing license (https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60)..
private void btAddLicenseByType_Click(object sender, EventArgs e)
{
SPDXLicense license;
// show the SPDX license dialog..
if ((license = FormDialogQuerySPDXLicense.Execute()) != null)
{
// if the license list is already stored in the Tag value, then add to it..
if (tbLicenseFile.Tag != null && tbLicenseFile.Tag.GetType() == typeof(List<SPDXLicense>))
{
// get a list of SPDXLicense class instances..
List<SPDXLicense> licenses = (List<SPDXLicense>)tbLicenseFile.Tag;
// add the license to the list..
licenses.Add(license);
// set the Tag property of the text box..
tbLicenseFile.Tag = licenses;
// set the text for the text box to match the license list..
tbLicenseFile.Text = SPDXLicenseCollection.ConstructLicenseString(licenses);
// set the target to nothing..
tbLicenseFileTarget.Text = string.Empty;
}
// create a new instance of List<SPDXLicense> and add the selected license to it..
else
{
// create a list of SPDXLicense class instances..
List<SPDXLicense> licenses = new List<SPDXLicense>(new[] { license });
// set the Tag value..
tbLicenseFile.Tag = licenses;
// set the text for the text box to match the license list..
tbLicenseFile.Text = SPDXLicenseCollection.ConstructLicenseString(licenses);
// set the target to nothing..
tbLicenseFileTarget.Text = string.Empty;
}
}
SetLicenseElementSpdx(nuspec, tbLicenseFile.Tag);
}
// a user wishes to use a file for a license..
private void btLicenseFile_Click(object sender, EventArgs e)
{
if (sender.Equals(btLicenseFile))
{
if (odAnyFile.ShowDialog() == DialogResult.OK)
{
SetLicenseElementFile(nuspec, odAnyFile.FileName, tbLicenseFileTarget.Text, nuspecFile);
string relativePath =
RelativePath.GetRelativePath(odAnyFile.FileName, nuspecFile);
tbLicenseFile.Tag = relativePath;
tbLicenseFile.Text = Path.GetFileName(odAnyFile.FileName);
tbLicenseFileTarget.Text = string.Empty;
}
}
else if (sender.Equals(btIconFile) || sender.Equals(tbIconTarget))
{
if (odIconFile.ShowDialog() == DialogResult.OK)
{
SetIconElementFile(nuspec, odIconFile.FileName, tbIconTarget.Text, nuspecFile);
string relativePath =
RelativePath.GetRelativePath(odIconFile.FileName, nuspecFile);
tbIcon.Tag = relativePath;
tbIcon.Text = Path.GetFileName(odIconFile.FileName);
tbIconTarget.Text = string.Empty;
}
}
}
// clear a one of the deprecated boxes..
private void btClearDeprecatedText_Click(object sender, EventArgs e)
{
if (sender.Equals(btClearLicenseUrl))
{
tbLicenseUrl.Text = string.Empty;
}
else if (sender.Equals(btClearIconUrl))
{
tbIconURL.Text = string.Empty;
}
}
// a user wishes to check for updates for the current nuget.exe..
private void mnuUpdateNuGetEXE_Click(object sender, EventArgs e)
{
UpdateNugetExe();
}
// a user wishes to enter the NuGet API keys..
private void mnuEnterAPIKeys_Click(object sender, EventArgs e)
{
FormDialogApiKeys.Execute(ref ApiKey, ref TestApiKey, ref GitHubPackagesApiKey, ref GitHubPackagesUserName);
}
// a user toggles the test NuGet check box..
private void cbTestNuGet_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkBox = (CheckBox)sender;
btApiKey.Tag = checkBox.Checked ? TestApiKey : ApiKey;
btApiKey.Text = bool.Parse(pnToggleApiKeyVisible.Tag.ToString())
? btApiKey.Tag.ToString()
: new string('•', btApiKey.Tag.ToString().Length);
// ReSharper disable once StringLiteralTypo
btPushNugetPackage.Text = checkBox.Checked ? "Push NuGet package to the int.nugettest.org" : "Push NuGet package to the nuget.org";
}
// show to user the about dialog..
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
// ReSharper disable once ObjectCreationAsStatement
new VPKSoft.About.FormAbout(this, "MIT", "https://github.com/VPKSoft/MageANuGet/blob/master/LICENSE");
}
// shows the detail dialog for the code signing certificate settings..
private void MnuCertificateSettings_Click(object sender, EventArgs e)
{
new FormDialogCertificate().ShowDialog(ref CertificatePassword, ref CertificateTimeStampServer,
ref CertificateFile);
}
// the user wishes to change, add or update the certificate settings..
private void CbUseCodeSigningCertificate_CheckedChanged(object sender, EventArgs e)
{
var checkBox = (CheckBox) sender;
if (checkBox.Checked)
{
if (CertificatePassword == string.Empty || CertificateFile == string.Empty ||
CertificateTimeStampServer == string.Empty)
{
new FormDialogCertificate().ShowDialog(ref CertificatePassword, ref CertificateTimeStampServer,
ref CertificateFile);
if (CertificatePassword == string.Empty || CertificateFile == string.Empty ||
CertificateTimeStampServer == string.Empty)
{
checkBox.Checked = false;
}
}
}
signPackage = checkBox.Checked;
}
private void mnuTest_Click(object sender, EventArgs e)
{
if (odIconFile.ShowDialog() == DialogResult.OK)
{
var iconFile = odIconFile.FileName;
MessageBox.Show(RelativePath.GetRelativePath(iconFile, nuspecFile));
}
}
private void tcMain_Selected(object sender, TabControlEventArgs e)
{
if (nuspecFile != null && e.TabPage.Equals(tabNuspec))
{
scintillaNuspecContents.Text = nuspec.ToString();
}
}
private void tcMain_Click(object sender, EventArgs e)
{
var tabControl = (TabControl) sender;
if (nuspec != null && tabControl.SelectedTab.Equals(tabNuspec))
{
scintillaNuspecContents.Text = @"<?xml version=""1.0""?>" + Environment.NewLine + nuspec;
}
}
private void mnuSaveChanges_Click(object sender, EventArgs e)
{
SaveXmlData();
}
private void tbSimpleElement_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox) sender;
SetSimpleElement(nuspec, textBox.Tag.ToString(), textBox.Text);
}
private void lbCopyright_Click(object sender, EventArgs e)
{
tbCopyright.SelectedText = "©";
}
private void cbRequireLicenseAcceptance_CheckedChanged(object sender, EventArgs e)
{
var checkBox = (CheckBox) sender;
SetSimpleElement(nuspec, checkBox.Tag.ToString(), checkBox.Checked.ToString().ToLower());
}
private void pnToggleApiKeyVisible_Click(object sender, EventArgs e)
{
var panel = (Panel) sender;
var enabled = !bool.Parse(panel.Tag.ToString());
panel.Tag = enabled.ToString();
panel.BackgroundImage =
enabled ? Properties.Resources.eye_password_visible : Properties.Resources.eye_password_hidden;
btApiKey.Text = enabled
? btApiKey.Tag.ToString()
: new string('•', btApiKey.Tag.ToString().Length);
}
private void btSaveXMLChanges_Click(object sender, EventArgs e)
{
if (nuspec != null)
{
try
{
nuspec = XDocument.Parse(scintillaNuspecContents.Text);
SaveXmlData();
}
catch (Exception ex)
{
MessageBox.Show($@"XML parsing error: {ex.Message}.", @"Error", MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
}
private void dgvFiles_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var dataGridView = (DataGridView)sender;
if (dataGridView.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
if (odAnyFile.ShowDialog() == DialogResult.OK)
{
var relativePath = RelativePath.GetRelativePath(odAnyFile.FileName, nuspecFile);
dataGridView.Rows[e.RowIndex].Cells[colFile.Index].Value = relativePath;
}
}
}
private void dgvFiles_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
var dataGridView = (DataGridView) sender;
if (dataGridView.Rows[e.RowIndex].Cells[colUseContentElement.Index].Value is bool isContentElementRow)
{
if (!isContentElementRow)
{
if (e.ColumnIndex == colBuildAction.Index ||
e.ColumnIndex == colCopyToOutput.Index ||
e.ColumnIndex == colFlatten.Index)
{
e.Cancel = true;
}
}
else
{
if (e.ColumnIndex == colTarget.Index)
{
e.Cancel = true;
}
}
}
}
private void btUndoFileChanges_Click(object sender, EventArgs e)
{
DisplayFileElements();
}
private void btSaveFileChanges_Click(object sender, EventArgs e)
{
UpdateFiles();
SaveXmlData();
}
private void HelpLink_Click(object sender, EventArgs e)
{
var label = (Label) sender;
try
{
Process.Start(label.Tag.ToString());
}
catch
{
// ignored..
}
}
#endregion
private void mnuBatchEnumeratePackages_Click(object sender, EventArgs e)
{
if (fbdFolder.ShowDialog() == DialogResult.OK)
{
var files = FileEnumerator.RecurseFiles(fbdFolder.SelectedPath, "*.nupkg");
var nugetConfigFile = FileEnumerator
.RecurseFiles(fbdFolder.SelectedPath, "*.config*").FirstOrDefault(f => f.FileName == "nuget.config");
files = files.Where(f => f.PathFull.IndexOf("debug", StringComparison.InvariantCultureIgnoreCase) == -1);
string nugetConfigFileName = nugetConfigFile?.FileNameWithPath;
if (!File.Exists(nugetConfigFileName))
{
if (odNugetConfig.ShowDialog() == DialogResult.OK)
{
nugetConfigFileName = odNugetConfig.FileName;
}
}
FormDialogRoamSolution.ShowDialog(this, files, nugetConfigFileName);
}
}
private void mnuSignMsi_Click(object sender, EventArgs e)
{
if (odMsi.ShowDialog() == DialogResult.OK)
{
var description = FormDialogQueryDescription.ShowDialog();
if (description == null)
{
return;
}
// make a secure string password..
using var password = new SecureString();
foreach (var c in CertificatePassword)
{
password.AppendChar(c);
}
// open the certificate to get the thumbprint for it..
using var cert = new X509Certificate2(File.ReadAllBytes(CertificateFile), password);
// run the signtool utility..
FormDialogCommandShell.ExecuteCommand(this, Paths.AppInstallDir, Paths.AppInstallDir, "signtool.exe",
new CommandArgument("sign"),
new CommandArgument("/f", CertificateFile, true) {QuoteValue = true},
new CommandArgument("/d", description) {QuoteValue = true},
new CommandArgument("/p", CertificatePassword, true) {QuoteValue = true},
new CommandArgument("/v"),
new CommandArgument("/sha1", cert.Thumbprint),
new CommandArgument("/t", CertificateTimeStampServer),
new CommandArgument(null, odMsi.FileName));
}
}
}
}
| 41.440621 | 260 | 0.523553 | [
"MIT"
] | VPKSoft/MageANuGet | MakeANuGet/FormMain.cs | 61,428 | C# |
using System.IO;
using System.Threading.Tasks;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
using UnityEngine;
namespace AssetLens
{
internal static class PackageSystem
{
internal static async Task<string> GetVersion()
{
ListRequest list = Client.List(false);
while (!list.IsCompleted)
{
await Task.Delay(10);
}
if (list.Status == StatusCode.Success)
{
var result = list.Result;
foreach (PackageInfo info in result)
{
if (info.name == Constants.PackageName)
{
return info.version;
}
}
return string.Empty;
}
Debug.LogError($"{list.Status} : {list.Error}");
return string.Empty;
}
internal static async Task<string> Uninstall()
{
RemoveRequest request = Client.Remove(Constants.PackageName);
while (!request.IsCompleted)
{
await Task.Delay(10);
}
if (request.Status == StatusCode.Success)
{
return $"Removed : {request.PackageIdOrName}";
}
return $"Failed : {request.Error.message}";
}
internal static bool IsReadOnlyPackage(this string path)
{
return Path.GetFullPath(path).Contains("PackageCache");
}
}
} | 19.683333 | 64 | 0.668078 | [
"MIT"
] | seonghwan-dev/Reference | Packages/com.calci.assetlens/Editor/Common/PackageSystem.cs | 1,183 | C# |
namespace FreshBooks.Api.ContractorUpdate {
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.freshbooks.com/api/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://www.freshbooks.com/api/", IsNullable=false)]
public partial class response: BaseResponse {
private byte contractor_idField;
private string statusField;
/// <remarks/>
public byte contractor_id {
get {
return this.contractor_idField;
}
set {
this.contractor_idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string status {
get {
return this.statusField;
}
set {
this.statusField = value;
}
}
}
}
| 30.1 | 111 | 0.574751 | [
"MIT"
] | mattjcowan/FreshBooks.Api | src/FreshBooks.Api/ContractorUpdateResponse.cs | 1,206 | C# |
using System;
namespace WslManager.ViewModels
{
public sealed class AsyncDownloadContext : NotifiableModel
{
private Uri _url;
private string _downloadedFilePath;
public Uri Url
{
get => _url;
set
{
if (value != _url)
{
_url = value;
NotifyPropertyChanged();
}
}
}
public string DownloadedFilePath
{
get => _downloadedFilePath;
set
{
if (value != _downloadedFilePath)
{
_downloadedFilePath = value;
NotifyPropertyChanged();
}
}
}
}
}
| 21.243243 | 62 | 0.416031 | [
"MIT"
] | anaymalpani/WSLMANAGER | src/WslManager/ViewModels/AsyncDownloadContext.cs | 788 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using JsonSubTypes;
using Newtonsoft.Json;
using Bitmovin.Api.Sdk.Common;
using Bitmovin.Api.Sdk.Models;
namespace Bitmovin.Api.Sdk.Models
{
/// <summary>
/// BroadcastTsSubtitleInputStreamConfiguration
/// </summary>
public class BroadcastTsSubtitleInputStreamConfiguration
{
/// <summary>
/// The UUID of the subtitle stream to which this configuration belongs to. This has to be an ID of an subtitle stream that has been added to the current muxing.
/// </summary>
[JsonProperty(PropertyName = "streamId")]
public string StreamId { get; set; }
/// <summary>
/// An integer value. Packet Identifier (PID) for this stream.
/// </summary>
[JsonProperty(PropertyName = "packetIdentifier")]
public int? PacketIdentifier { get; set; }
/// <summary>
/// The rate parameter determines the maximum rate in bits per second that should be used for the subtitle stream. The valid range is `100` to `60 000 000` bps or `0`. If the value is set to 0, we will examine the first 100 packets of subtitle packet data and use the highest rate that was computed. If the value is set too low, not enough to accommodate the subtitle bit-rate, then some PES packets corresponding to DVB subtitle stream will be dropped. This parameter is optional and the default value is 0.
/// </summary>
[JsonProperty(PropertyName = "rate")]
public int? Rate { get; set; }
}
}
| 44.135135 | 547 | 0.688304 | [
"MIT"
] | bitmovin/bitmovin-api-sdk-dotnet | src/Bitmovin.Api.Sdk/Models/BroadcastTsSubtitleInputStreamConfiguration.cs | 1,633 | C# |
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Stryker.Core.Mutants;
using System.Collections.Generic;
namespace Stryker.Core.Mutators
{
public class BinaryExpressionMutator : MutatorBase<BinaryExpressionSyntax>, IMutator
{
private Dictionary<SyntaxKind, IEnumerable<SyntaxKind>> _kindsToMutate { get; set; }
public BinaryExpressionMutator()
{
_kindsToMutate = new Dictionary<SyntaxKind, IEnumerable<SyntaxKind>>
{
{SyntaxKind.SubtractExpression, new List<SyntaxKind> { SyntaxKind.AddExpression } },
{SyntaxKind.AddExpression, new List<SyntaxKind> {SyntaxKind.SubtractExpression } },
{SyntaxKind.MultiplyExpression, new List<SyntaxKind> {SyntaxKind.DivideExpression } },
{SyntaxKind.DivideExpression, new List<SyntaxKind> {SyntaxKind.MultiplyExpression } },
{SyntaxKind.ModuloExpression, new List<SyntaxKind> {SyntaxKind.MultiplyExpression } },
{SyntaxKind.GreaterThanExpression, new List<SyntaxKind> {SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanOrEqualExpression } },
{SyntaxKind.LessThanExpression, new List<SyntaxKind> {SyntaxKind.GreaterThanExpression, SyntaxKind.LessThanOrEqualExpression } },
{SyntaxKind.GreaterThanOrEqualExpression, new List<SyntaxKind> { SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression } },
{SyntaxKind.LessThanOrEqualExpression, new List<SyntaxKind> { SyntaxKind.GreaterThanExpression, SyntaxKind.LessThanExpression } },
{SyntaxKind.EqualsExpression, new List<SyntaxKind> {SyntaxKind.NotEqualsExpression } },
{SyntaxKind.NotEqualsExpression, new List<SyntaxKind> {SyntaxKind.EqualsExpression } },
{SyntaxKind.LogicalAndExpression, new List<SyntaxKind> {SyntaxKind.LogicalOrExpression } },
{SyntaxKind.LogicalOrExpression, new List<SyntaxKind> {SyntaxKind.LogicalAndExpression } },
{SyntaxKind.LeftShiftExpression, new List<SyntaxKind> {SyntaxKind.RightShiftExpression } },
{SyntaxKind.RightShiftExpression, new List<SyntaxKind> {SyntaxKind.LeftShiftExpression } },
{SyntaxKind.BitwiseOrExpression, new List<SyntaxKind> {SyntaxKind.BitwiseAndExpression } },
{SyntaxKind.BitwiseAndExpression, new List<SyntaxKind> {SyntaxKind.BitwiseOrExpression } },
};
}
public override IEnumerable<Mutation> ApplyMutations(BinaryExpressionSyntax node)
{
if(_kindsToMutate.ContainsKey(node.Kind()))
{
// skip string additions
if (node.Kind() == SyntaxKind.AddExpression && (node.Left.IsAStringExpression()||node.Right.IsAStringExpression()))
{
yield break;
}
foreach(var mutationKind in _kindsToMutate[node.Kind()])
{
var replacementNode = SyntaxFactory.BinaryExpression(mutationKind, node.Left, node.Right);
// make sure the trivia stays in place for displaying
replacementNode = replacementNode.WithOperatorToken(replacementNode.OperatorToken.WithTriviaFrom(node.OperatorToken));
var mutatorType = GetMutatorType(mutationKind);
yield return new Mutation()
{
OriginalNode = node,
ReplacementNode = replacementNode,
DisplayName = $"{mutatorType} mutation",
Type = mutatorType
};
}
}
else if (node.Kind() == SyntaxKind.ExclusiveOrExpression)
{
// Place both a logical and an integral mutation. Only one will compile, the other will be removed. See: https://github.com/stryker-mutator/stryker-net/issues/664
yield return GetLogicalMutation(node);
yield return GetIntegralMutation(node);
}
}
private Mutator GetMutatorType(SyntaxKind kind)
{
string kindString = kind.ToString();
if (kindString.StartsWith("Logical"))
{
return Mutator.Logical;
}
else if (kindString.Contains("Equals")
|| kindString.Contains("Greater")
|| kindString.Contains("Less"))
{
return Mutator.Equality;
}
else if (kindString.StartsWith("Bitwise") || kindString.Contains("Shift"))
{
return Mutator.Bitwise;
}
else
{
return Mutator.Arithmetic;
}
}
private Mutation GetLogicalMutation(BinaryExpressionSyntax node)
{
var replacementNode = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, node.Left, node.Right);
replacementNode = replacementNode.WithOperatorToken(replacementNode.OperatorToken.WithTriviaFrom(node.OperatorToken));
return new Mutation
{
OriginalNode = node,
ReplacementNode = replacementNode,
DisplayName = "Logical mutation",
Type = Mutator.Logical
};
}
private Mutation GetIntegralMutation(BinaryExpressionSyntax node)
{
var replacementNode = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, SyntaxFactory.ParenthesizedExpression(node));
return new Mutation
{
OriginalNode = node,
ReplacementNode = replacementNode,
DisplayName = "Bitwise mutation",
Type = Mutator.Bitwise
};
}
}
}
| 49.241667 | 178 | 0.615502 | [
"Apache-2.0"
] | Danghor/stryker-net | src/Stryker.Core/Stryker.Core/Mutators/BinaryExpressionMutator.cs | 5,911 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Xml
{
/// <summary>
/// This class defines a set of common XML namespaces for sharing across multiple source files.
/// </summary>
internal static class XmlReservedNs
{
internal const string NsXml = "http://www.w3.org/XML/1998/namespace";
internal const string NsXmlNs = "http://www.w3.org/2000/xmlns/";
};
}
| 34.533333 | 101 | 0.687259 | [
"MIT"
] | 690486439/corefx | src/System.Xml.ReaderWriter/src/System/Xml/XmlReservedNS.cs | 518 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HubVpn")]
[assembly: AssemblyDescription("Gojek VPN Util")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Berkedel Lab")]
[assembly: AssemblyProduct("HubVpn")]
[assembly: AssemblyCopyright("Copyright © Akhmad Syaikhul Hadi 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 41.358491 | 96 | 0.756387 | [
"MIT"
] | berkedel/HubVpn | Properties/AssemblyInfo.cs | 2,195 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Runtime.Serialization;
using Nest.Utf8Json;
namespace Nest
{
/// <summary>
/// A snapshot lifecycle configuration
/// </summary>
[ReadAs(typeof(SnapshotLifecycleConfig))]
[InterfaceDataContract]
public interface ISnapshotLifecycleConfig
{
[DataMember(Name = "ignore_unavailable")]
bool? IgnoreUnavailable { get; set; }
[DataMember(Name = "include_global_state")]
bool? IncludeGlobalState { get; set; }
/// <summary>
/// The indices to snapshot
/// </summary>
[DataMember(Name = "indices")]
[JsonFormatter(typeof(IndicesMultiSyntaxFormatter))]
Indices Indices { get; set; }
}
public class SnapshotLifecycleConfig : ISnapshotLifecycleConfig
{
/// <inheritdoc />
public bool? IgnoreUnavailable { get; set; }
/// <inheritdoc />
public bool? IncludeGlobalState { get; set; }
/// <inheritdoc />
public Indices Indices { get; set; }
}
public class SnapshotLifecycleConfigDescriptor : DescriptorBase<SnapshotLifecycleConfigDescriptor, ISnapshotLifecycleConfig>, ISnapshotLifecycleConfig
{
bool? ISnapshotLifecycleConfig.IgnoreUnavailable { get; set; }
bool? ISnapshotLifecycleConfig.IncludeGlobalState { get; set; }
Indices ISnapshotLifecycleConfig.Indices { get; set; }
public SnapshotLifecycleConfigDescriptor Indices(IndexName index) => Indices((Indices)index);
public SnapshotLifecycleConfigDescriptor Indices<T>() where T : class => Indices(typeof(T));
public SnapshotLifecycleConfigDescriptor Indices(Indices indices) => Assign(indices, (a, v) => a.Indices = v);
public SnapshotLifecycleConfigDescriptor IgnoreUnavailable(bool? ignoreUnavailable = true) => Assign(ignoreUnavailable, (a, v) => a.IgnoreUnavailable = v);
public SnapshotLifecycleConfigDescriptor IncludeGlobalState(bool? includeGlobalState = true) => Assign(includeGlobalState, (a, v) => a.IncludeGlobalState = v);
}
}
| 34.566667 | 161 | 0.751205 | [
"Apache-2.0"
] | Jiasyuan/elasticsearch-net | src/Nest/XPack/Slm/SnapshotLifecycleConfig.cs | 2,074 | C# |
using UnityEngine;
namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityRigidbody
{
[TaskCategory("Basic/Rigidbody")]
[TaskDescription("Sets the is kinematic value of the Rigidbody. Returns Success.")]
public class SetIsKinematic : Action
{
[Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
public SharedGameObject targetGameObject;
[Tooltip("The is kinematic value of the Rigidbody")]
public SharedBool isKinematic;
// cache the rigidbody component
private Rigidbody rigidbody;
private GameObject prevGameObject;
public override void OnStart()
{
var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
if (currentGameObject != prevGameObject) {
rigidbody = currentGameObject.GetComponent<Rigidbody>();
prevGameObject = currentGameObject;
}
}
public override TaskStatus OnUpdate()
{
if (rigidbody == null) {
Debug.LogWarning("Rigidbody is null");
return TaskStatus.Failure;
}
rigidbody.isKinematic = isKinematic.Value;
return TaskStatus.Success;
}
public override void OnReset()
{
targetGameObject = null;
isKinematic = false;
}
}
} | 32.4 | 100 | 0.596022 | [
"Apache-2.0"
] | brustlinker/unity_behaviortree_sk | Assets/Behavior Designer/Runtime/Basic Tasks/Rigidbody/SetIsKinematic.cs | 1,458 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Mime;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Events;
using BTCPayServer.Filters;
using BTCPayServer.Logging;
using BTCPayServer.HostedServices;
using BTCPayServer.Models;
using BTCPayServer.Models.InvoicingModels;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Plugins.CoinSwitch;
using BTCPayServer.Rating;
using BTCPayServer.Security;
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Invoices.Export;
using BTCPayServer.Services.Rates;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using NBitcoin;
using NBitpayClient;
using NBXplorer;
using Newtonsoft.Json.Linq;
using BitpayCreateInvoiceRequest = BTCPayServer.Models.BitpayCreateInvoiceRequest;
using StoreData = BTCPayServer.Data.StoreData;
namespace BTCPayServer.Controllers
{
public partial class InvoiceController
{
[HttpGet]
[Route("invoices/{invoiceId}/deliveries/{deliveryId}/request")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> WebhookDelivery(string invoiceId, string deliveryId)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery()
{
InvoiceId = new[] { invoiceId },
UserId = GetUserId()
})).FirstOrDefault();
if (invoice is null)
return NotFound();
var delivery = await _InvoiceRepository.GetWebhookDelivery(invoiceId, deliveryId);
if (delivery is null)
return NotFound();
return this.File(delivery.GetBlob().Request, "application/json");
}
[HttpPost]
[Route("invoices/{invoiceId}/deliveries/{deliveryId}/redeliver")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> RedeliverWebhook(string storeId, string invoiceId, string deliveryId)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery()
{
InvoiceId = new[] { invoiceId },
StoreId = new[] { storeId },
UserId = GetUserId()
})).FirstOrDefault();
if (invoice is null)
return NotFound();
var delivery = await _InvoiceRepository.GetWebhookDelivery(invoiceId, deliveryId);
if (delivery is null)
return NotFound();
var newDeliveryId = await WebhookNotificationManager.Redeliver(deliveryId);
if (newDeliveryId is null)
return NotFound();
TempData[WellKnownTempData.SuccessMessage] = "Successfully planned a redelivery";
return RedirectToAction(nameof(Invoice),
new
{
invoiceId
});
}
[HttpGet]
[Route("invoices/{invoiceId}")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> Invoice(string invoiceId)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery()
{
InvoiceId = new[] { invoiceId },
UserId = GetUserId(),
IncludeAddresses = true,
IncludeEvents = true,
IncludeArchived = true,
})).FirstOrDefault();
if (invoice == null)
return NotFound();
var store = await _StoreRepository.FindStore(invoice.StoreId);
var model = new InvoiceDetailsModel()
{
StoreId = store.Id,
StoreName = store.StoreName,
StoreLink = Url.Action(nameof(StoresController.UpdateStore), "Stores", new { storeId = store.Id }),
Id = invoice.Id,
State = invoice.GetInvoiceState().ToString(),
TransactionSpeed = invoice.SpeedPolicy == SpeedPolicy.HighSpeed ? "high" :
invoice.SpeedPolicy == SpeedPolicy.MediumSpeed ? "medium" :
invoice.SpeedPolicy == SpeedPolicy.LowMediumSpeed ? "low-medium" :
"low",
RefundEmail = invoice.RefundMail,
CreatedDate = invoice.InvoiceTime,
ExpirationDate = invoice.ExpirationTime,
MonitoringDate = invoice.MonitoringExpiration,
Fiat = _CurrencyNameTable.DisplayFormatCurrency(invoice.Price, invoice.Currency),
TaxIncluded = _CurrencyNameTable.DisplayFormatCurrency(invoice.Metadata.TaxIncluded ?? 0.0m, invoice.Currency),
NotificationUrl = invoice.NotificationURL?.AbsoluteUri,
RedirectUrl = invoice.RedirectURL?.AbsoluteUri,
TypedMetadata = invoice.Metadata,
StatusException = invoice.ExceptionStatus,
Events = invoice.Events,
PosData = PosDataParser.ParsePosData(invoice.Metadata.PosData),
Archived = invoice.Archived,
CanRefund = CanRefund(invoice.GetInvoiceState()),
Deliveries = (await _InvoiceRepository.GetWebhookDeliveries(invoiceId))
.Select(c => new Models.StoreViewModels.DeliveryViewModel(c))
.ToList()
};
model.Addresses = invoice.HistoricalAddresses.Select(h =>
new InvoiceDetailsModel.AddressModel
{
Destination = h.GetAddress(),
PaymentMethod = h.GetPaymentMethodId().ToPrettyString(),
Current = !h.UnAssigned.HasValue
}).ToArray();
var details = InvoicePopulatePayments(invoice);
model.CryptoPayments = details.CryptoPayments;
model.Payments = details.Payments;
return View(model);
}
bool CanRefund(InvoiceState invoiceState)
{
return invoiceState.Status == InvoiceStatusLegacy.Confirmed ||
invoiceState.Status == InvoiceStatusLegacy.Complete ||
(invoiceState.Status == InvoiceStatusLegacy.Expired &&
(invoiceState.ExceptionStatus == InvoiceExceptionStatus.PaidLate ||
invoiceState.ExceptionStatus == InvoiceExceptionStatus.PaidOver ||
invoiceState.ExceptionStatus == InvoiceExceptionStatus.PaidPartial)) ||
invoiceState.Status == InvoiceStatusLegacy.Invalid;
}
[HttpGet]
[Route("invoices/{invoiceId}/refund")]
[AllowAnonymous]
public async Task<IActionResult> Refund(string invoiceId, CancellationToken cancellationToken)
{
using var ctx = _dbContextFactory.CreateContext();
ctx.ChangeTracker.QueryTrackingBehavior = Microsoft.EntityFrameworkCore.QueryTrackingBehavior.NoTracking;
var invoice = await ctx.Invoices.Include(i => i.Payments)
.Include(i => i.CurrentRefund)
.Include(i => i.CurrentRefund.PullPaymentData)
.Where(i => i.Id == invoiceId)
.FirstOrDefaultAsync();
if (invoice is null)
return NotFound();
if (invoice.CurrentRefund?.PullPaymentDataId is null && GetUserId() is null)
return NotFound();
if (!CanRefund(invoice.GetInvoiceState()))
return NotFound();
if (invoice.CurrentRefund?.PullPaymentDataId is string ppId && !invoice.CurrentRefund.PullPaymentData.Archived)
{
// TODO: Having dedicated UI later on
return RedirectToAction(nameof(PullPaymentController.ViewPullPayment),
"PullPayment",
new { pullPaymentId = ppId });
}
else
{
var paymentMethods = invoice.GetBlob(_NetworkProvider).GetPaymentMethods();
var options = paymentMethods
.Select(o => o.GetId())
.Select(o => o.CryptoCode)
.Where(o => _NetworkProvider.GetNetwork<BTCPayNetwork>(o) is BTCPayNetwork n && !n.ReadonlyWallet)
.Distinct()
.OrderBy(o => o)
.Select(o => new PaymentMethodId(o, PaymentTypes.BTCLike))
.ToList();
var defaultRefund = invoice.Payments
.Select(p => p.GetBlob(_NetworkProvider))
.Select(p => p?.GetPaymentMethodId())
.FirstOrDefault(p => p != null && p.PaymentType == BitcoinPaymentType.Instance);
// TODO: What if no option?
var refund = new RefundModel();
refund.Title = "Select a payment method";
refund.AvailablePaymentMethods = new SelectList(options, nameof(PaymentMethodId.CryptoCode), nameof(PaymentMethodId.CryptoCode));
refund.SelectedPaymentMethod = defaultRefund?.ToString() ?? options.Select(o => o.CryptoCode).First();
// Nothing to select, skip to next
if (refund.AvailablePaymentMethods.Count() == 1)
{
return await Refund(invoiceId, refund, cancellationToken);
}
return View(refund);
}
}
[HttpPost]
[Route("invoices/{invoiceId}/refund")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> Refund(string invoiceId, RefundModel model, CancellationToken cancellationToken)
{
using var ctx = _dbContextFactory.CreateContext();
var invoice = await _InvoiceRepository.GetInvoice(invoiceId);
if (invoice is null)
return NotFound();
var store = await _StoreRepository.FindStore(invoice.StoreId, GetUserId());
if (store is null)
return NotFound();
if (!CanRefund(invoice.GetInvoiceState()))
return NotFound();
var paymentMethodId = new PaymentMethodId(model.SelectedPaymentMethod, PaymentTypes.BTCLike);
var cdCurrency = _CurrencyNameTable.GetCurrencyData(invoice.Currency, true);
var paymentMethodDivisibility = _CurrencyNameTable.GetCurrencyData(paymentMethodId.CryptoCode, false)?.Divisibility ?? 8;
RateRules rules;
RateResult rateResult;
CreatePullPayment createPullPayment;
switch (model.RefundStep)
{
case RefundSteps.SelectPaymentMethod:
model.RefundStep = RefundSteps.SelectRate;
model.Title = "What to refund?";
var paymentMethod = invoice.GetPaymentMethods()[paymentMethodId];
var paidCurrency =
Math.Round(paymentMethod.Calculate().Paid.ToDecimal(MoneyUnit.BTC) * paymentMethod.Rate,
cdCurrency.Divisibility);
model.CryptoAmountThen = Math.Round(paidCurrency / paymentMethod.Rate, paymentMethodDivisibility);
model.RateThenText =
_CurrencyNameTable.DisplayFormatCurrency(model.CryptoAmountThen, paymentMethodId.CryptoCode,
true);
rules = store.GetStoreBlob().GetRateRules(_NetworkProvider);
rateResult = await _RateProvider.FetchRate(
new Rating.CurrencyPair(paymentMethodId.CryptoCode, invoice.Currency), rules,
cancellationToken);
//TODO: What if fetching rate failed?
if (rateResult.BidAsk is null)
{
ModelState.AddModelError(nameof(model.SelectedRefundOption),
$"Impossible to fetch rate: {rateResult.EvaluatedRule}");
return View(model);
}
model.CryptoAmountNow = Math.Round(paidCurrency / rateResult.BidAsk.Bid, paymentMethodDivisibility);
model.CurrentRateText =
_CurrencyNameTable.DisplayFormatCurrency(model.CryptoAmountNow, paymentMethodId.CryptoCode,
true);
model.FiatAmount = paidCurrency;
model.FiatText = _CurrencyNameTable.DisplayFormatCurrency(model.FiatAmount, invoice.Currency, true);
return View(model);
case RefundSteps.SelectRate:
createPullPayment = new HostedServices.CreatePullPayment();
createPullPayment.Name = $"Refund {invoice.Id}";
createPullPayment.PaymentMethodIds = new[] { paymentMethodId };
createPullPayment.StoreId = invoice.StoreId;
switch (model.SelectedRefundOption)
{
case "RateThen":
createPullPayment.Currency = paymentMethodId.CryptoCode;
createPullPayment.Amount = model.CryptoAmountThen;
break;
case "CurrentRate":
createPullPayment.Currency = paymentMethodId.CryptoCode;
createPullPayment.Amount = model.CryptoAmountNow;
break;
case "Fiat":
createPullPayment.Currency = invoice.Currency;
createPullPayment.Amount = model.FiatAmount;
break;
case "Custom":
model.Title = "How much to refund?";
model.CustomCurrency = invoice.Currency;
model.CustomAmount = model.FiatAmount;
model.RefundStep = RefundSteps.SelectCustomAmount;
return View(model);
default:
ModelState.AddModelError(nameof(model.SelectedRefundOption), "Invalid choice");
return View(model);
}
break;
case RefundSteps.SelectCustomAmount:
if (model.CustomAmount <= 0)
{
model.AddModelError(refundModel => refundModel.CustomAmount, "Amount must be greater than 0", this);
}
if (string.IsNullOrEmpty(model.CustomCurrency) ||
_CurrencyNameTable.GetCurrencyData(model.CustomCurrency, false) == null)
{
ModelState.AddModelError(nameof(model.CustomCurrency), "Invalid currency");
}
if (!ModelState.IsValid)
{
return View(model);
}
rules = store.GetStoreBlob().GetRateRules(_NetworkProvider);
rateResult = await _RateProvider.FetchRate(
new Rating.CurrencyPair(paymentMethodId.CryptoCode, model.CustomCurrency), rules,
cancellationToken);
//TODO: What if fetching rate failed?
if (rateResult.BidAsk is null)
{
ModelState.AddModelError(nameof(model.SelectedRefundOption),
$"Impossible to fetch rate: {rateResult.EvaluatedRule}");
return View(model);
}
createPullPayment = new HostedServices.CreatePullPayment();
createPullPayment.Name = $"Refund {invoice.Id}";
createPullPayment.PaymentMethodIds = new[] { paymentMethodId };
createPullPayment.StoreId = invoice.StoreId;
createPullPayment.Currency = model.CustomCurrency;
createPullPayment.Amount = model.CustomAmount;
break;
default:
throw new ArgumentOutOfRangeException();
}
var ppId = await _paymentHostedService.CreatePullPayment(createPullPayment);
this.TempData.SetStatusMessageModel(new StatusMessageModel()
{
Html = "Share this page with a customer so they can claim a refund <br />Once claimed you need to initiate a refund from Wallet > Payouts",
Severity = StatusMessageModel.StatusSeverity.Success
});
(await ctx.Invoices.FindAsync(invoice.Id)).CurrentRefundId = ppId;
ctx.Refunds.Add(new RefundData()
{
InvoiceDataId = invoice.Id,
PullPaymentDataId = ppId
});
await ctx.SaveChangesAsync(cancellationToken);
// TODO: Having dedicated UI later on
return RedirectToAction(nameof(PullPaymentController.ViewPullPayment),
"PullPayment",
new { pullPaymentId = ppId });
}
private InvoiceDetailsModel InvoicePopulatePayments(InvoiceEntity invoice)
{
return new InvoiceDetailsModel
{
Archived = invoice.Archived,
Payments = invoice.GetPayments(false),
CryptoPayments = invoice.GetPaymentMethods().Select(
data =>
{
var accounting = data.Calculate();
var paymentMethodId = data.GetId();
return new InvoiceDetailsModel.CryptoPayment
{
PaymentMethodId = paymentMethodId,
PaymentMethod = paymentMethodId.ToPrettyString(),
Due = _CurrencyNameTable.DisplayFormatCurrency(accounting.Due.ToDecimal(MoneyUnit.BTC),
paymentMethodId.CryptoCode),
Paid = _CurrencyNameTable.DisplayFormatCurrency(
accounting.CryptoPaid.ToDecimal(MoneyUnit.BTC),
paymentMethodId.CryptoCode),
Overpaid = _CurrencyNameTable.DisplayFormatCurrency(
accounting.OverpaidHelper.ToDecimal(MoneyUnit.BTC), paymentMethodId.CryptoCode),
Address = data.GetPaymentMethodDetails().GetPaymentDestination(),
Rate = ExchangeRate(data)
};
}).ToList()
};
}
[HttpPost("invoices/{invoiceId}/archive")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> ToggleArchive(string invoiceId)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery()
{
InvoiceId = new[] { invoiceId },
UserId = GetUserId(),
IncludeAddresses = true,
IncludeEvents = true,
IncludeArchived = true,
})).FirstOrDefault();
if (invoice == null)
return NotFound();
await _InvoiceRepository.ToggleInvoiceArchival(invoiceId, !invoice.Archived);
TempData.SetStatusMessageModel(new StatusMessageModel()
{
Severity = StatusMessageModel.StatusSeverity.Success,
Message = invoice.Archived ? "The invoice has been unarchived and will appear in the invoice list by default again." : "The invoice has been archived and will no longer appear in the invoice list by default."
});
return RedirectToAction(nameof(invoice), new { invoiceId });
}
[HttpPost]
public async Task<IActionResult> MassAction(string command, string[] selectedItems)
{
if (selectedItems != null)
{
switch (command)
{
case "archive":
await _InvoiceRepository.MassArchive(selectedItems);
TempData[WellKnownTempData.SuccessMessage] = $"{selectedItems.Length} invoice(s) archived.";
break;
}
}
return RedirectToAction(nameof(ListInvoices));
}
[HttpGet]
[Route("i/{invoiceId}")]
[Route("i/{invoiceId}/{paymentMethodId}")]
[Route("invoice")]
[AcceptMediaTypeConstraint("application/bitcoin-paymentrequest", false)]
[XFrameOptionsAttribute(null)]
[ReferrerPolicyAttribute("origin")]
public async Task<IActionResult> Checkout(string invoiceId, string id = null, string paymentMethodId = null,
[FromQuery] string view = null, [FromQuery] string lang = null)
{
//Keep compatibility with Bitpay
invoiceId = invoiceId ?? id;
id = invoiceId;
//
var model = await GetInvoiceModel(invoiceId, paymentMethodId == null ? null : PaymentMethodId.Parse(paymentMethodId), lang);
if (model == null)
return NotFound();
if (view == "modal")
model.IsModal = true;
_CSP.Add(new ConsentSecurityPolicy("script-src", "'unsafe-eval'")); // Needed by Vue
if (!string.IsNullOrEmpty(model.CustomCSSLink) &&
Uri.TryCreate(model.CustomCSSLink, UriKind.Absolute, out var uri))
{
_CSP.Clear();
}
if (!string.IsNullOrEmpty(model.CustomLogoLink) &&
Uri.TryCreate(model.CustomLogoLink, UriKind.Absolute, out uri))
{
_CSP.Clear();
}
return View(nameof(Checkout), model);
}
[HttpGet]
[Route("invoice-noscript")]
public async Task<IActionResult> CheckoutNoScript(string invoiceId, string id = null, string paymentMethodId = null, [FromQuery] string lang = null)
{
//Keep compatibility with Bitpay
invoiceId = invoiceId ?? id;
id = invoiceId;
//
var model = await GetInvoiceModel(invoiceId, paymentMethodId == null ? null : PaymentMethodId.Parse(paymentMethodId), lang);
if (model == null)
return NotFound();
return View(model);
}
private async Task<PaymentModel> GetInvoiceModel(string invoiceId, PaymentMethodId paymentMethodId, string lang)
{
var invoice = await _InvoiceRepository.GetInvoice(invoiceId);
if (invoice == null)
return null;
var store = await _StoreRepository.FindStore(invoice.StoreId);
bool isDefaultPaymentId = false;
if (paymentMethodId == null)
{
paymentMethodId = store.GetDefaultPaymentId(_NetworkProvider);
isDefaultPaymentId = true;
}
BTCPayNetworkBase network = _NetworkProvider.GetNetwork<BTCPayNetworkBase>(paymentMethodId.CryptoCode);
if (network == null && isDefaultPaymentId)
{
//TODO: need to look into a better way for this as it does not scale
network = _NetworkProvider.GetAll().OfType<BTCPayNetwork>().FirstOrDefault();
paymentMethodId = new PaymentMethodId(network.CryptoCode, PaymentTypes.BTCLike);
}
if (invoice == null || network == null)
return null;
if (!invoice.Support(paymentMethodId))
{
if (!isDefaultPaymentId)
return null;
var paymentMethodTemp = invoice
.GetPaymentMethods()
.FirstOrDefault(c => paymentMethodId.CryptoCode == c.GetId().CryptoCode);
if (paymentMethodTemp == null)
paymentMethodTemp = invoice.GetPaymentMethods().First();
network = paymentMethodTemp.Network;
paymentMethodId = paymentMethodTemp.GetId();
}
var paymentMethod = invoice.GetPaymentMethod(paymentMethodId);
var paymentMethodDetails = paymentMethod.GetPaymentMethodDetails();
if (!paymentMethodDetails.Activated)
{
await _InvoiceRepository.ActivateInvoicePaymentMethod(_EventAggregator, _NetworkProvider,
_paymentMethodHandlerDictionary, store, invoice, paymentMethod.GetId());
return await GetInvoiceModel(invoiceId, paymentMethodId, lang);
}
var dto = invoice.EntityToDTO();
var storeBlob = store.GetStoreBlob();
var accounting = paymentMethod.Calculate();
var paymentMethodHandler = _paymentMethodHandlerDictionary[paymentMethodId];
var divisibility = _CurrencyNameTable.GetNumberFormatInfo(paymentMethod.GetId().CryptoCode, false)?.CurrencyDecimalDigits;
var model = new PaymentModel()
{
Activated = paymentMethodDetails.Activated,
CryptoCode = network.CryptoCode,
RootPath = this.Request.PathBase.Value.WithTrailingSlash(),
OrderId = invoice.Metadata.OrderId,
InvoiceId = invoice.Id,
DefaultLang = lang ?? invoice.DefaultLanguage ?? storeBlob.DefaultLang ?? "en",
CustomCSSLink = storeBlob.CustomCSS,
CustomLogoLink = storeBlob.CustomLogo,
HtmlTitle = storeBlob.HtmlTitle ?? "BTCPay Invoice",
CryptoImage = Request.GetRelativePathOrAbsolute(paymentMethodHandler.GetCryptoImage(paymentMethodId)),
BtcAddress = paymentMethodDetails.GetPaymentDestination(),
BtcDue = accounting.Due.ShowMoney(divisibility),
InvoiceCurrency = invoice.Currency,
OrderAmount = (accounting.TotalDue - accounting.NetworkFee).ShowMoney(divisibility),
OrderAmountFiat = OrderAmountFromInvoice(network.CryptoCode, invoice),
CustomerEmail = invoice.RefundMail,
RequiresRefundEmail = storeBlob.RequiresRefundEmail,
ExpirationSeconds = Math.Max(0, (int)(invoice.ExpirationTime - DateTimeOffset.UtcNow).TotalSeconds),
MaxTimeSeconds = (int)(invoice.ExpirationTime - invoice.InvoiceTime).TotalSeconds,
MaxTimeMinutes = (int)(invoice.ExpirationTime - invoice.InvoiceTime).TotalMinutes,
ItemDesc = invoice.Metadata.ItemDesc,
Rate = ExchangeRate(paymentMethod),
MerchantRefLink = invoice.RedirectURL?.AbsoluteUri ?? "/",
RedirectAutomatically = invoice.RedirectAutomatically,
StoreName = store.StoreName,
TxCount = accounting.TxRequired,
BtcPaid = accounting.Paid.ShowMoney(divisibility),
#pragma warning disable CS0618 // Type or member is obsolete
Status = invoice.StatusString,
#pragma warning restore CS0618 // Type or member is obsolete
NetworkFee = paymentMethodDetails.GetNextNetworkFee(),
IsMultiCurrency = invoice.GetPayments(false).Select(p => p.GetPaymentMethodId()).Concat(new[] { paymentMethod.GetId() }).Distinct().Count() > 1,
StoreId = store.Id,
AvailableCryptos = invoice.GetPaymentMethods()
.Where(i => i.Network != null)
.Select(kv =>
{
var availableCryptoPaymentMethodId = kv.GetId();
var availableCryptoHandler = _paymentMethodHandlerDictionary[availableCryptoPaymentMethodId];
return new PaymentModel.AvailableCrypto()
{
PaymentMethodId = kv.GetId().ToString(),
CryptoCode = kv.Network?.CryptoCode ?? kv.GetId().CryptoCode,
PaymentMethodName = availableCryptoHandler.GetPaymentMethodName(availableCryptoPaymentMethodId),
IsLightning =
kv.GetId().PaymentType == PaymentTypes.LightningLike,
CryptoImage = Request.GetRelativePathOrAbsolute(availableCryptoHandler.GetCryptoImage(availableCryptoPaymentMethodId)),
Link = Url.Action(nameof(Checkout),
new
{
invoiceId = invoiceId,
paymentMethodId = kv.GetId().ToString()
})
};
}).Where(c => c.CryptoImage != "/")
.OrderByDescending(a => a.CryptoCode == "BTC").ThenBy(a => a.PaymentMethodName).ThenBy(a => a.IsLightning ? 1 : 0)
.ToList()
};
paymentMethodHandler.PreparePaymentModel(model, dto, storeBlob, paymentMethod);
model.UISettings = paymentMethodHandler.GetCheckoutUISettings();
model.PaymentMethodId = paymentMethodId.ToString();
var expiration = TimeSpan.FromSeconds(model.ExpirationSeconds);
model.TimeLeft = expiration.PrettyPrint();
return model;
}
private string OrderAmountFromInvoice(string cryptoCode, InvoiceEntity invoiceEntity)
{
// if invoice source currency is the same as currently display currency, no need for "order amount from invoice"
if (cryptoCode == invoiceEntity.Currency)
return null;
return _CurrencyNameTable.DisplayFormatCurrency(invoiceEntity.Price, invoiceEntity.Currency);
}
private string ExchangeRate(PaymentMethod paymentMethod)
{
string currency = paymentMethod.ParentEntity.Currency;
return _CurrencyNameTable.DisplayFormatCurrency(paymentMethod.Rate, currency);
}
[HttpGet]
[Route("i/{invoiceId}/status")]
[Route("i/{invoiceId}/{paymentMethodId}/status")]
[Route("invoice/{invoiceId}/status")]
[Route("invoice/{invoiceId}/{paymentMethodId}/status")]
[Route("invoice/status")]
public async Task<IActionResult> GetStatus(string invoiceId, string paymentMethodId = null, [FromQuery] string lang = null)
{
var model = await GetInvoiceModel(invoiceId, paymentMethodId == null ? null : PaymentMethodId.Parse(paymentMethodId), lang);
if (model == null)
return NotFound();
return Json(model);
}
[HttpGet]
[Route("i/{invoiceId}/status/ws")]
[Route("i/{invoiceId}/{paymentMethodId}/status/ws")]
[Route("invoice/{invoiceId}/status/ws")]
[Route("invoice/{invoiceId}/{paymentMethodId}/status")]
[Route("invoice/status/ws")]
public async Task<IActionResult> GetStatusWebSocket(string invoiceId)
{
if (!HttpContext.WebSockets.IsWebSocketRequest)
return NotFound();
var invoice = await _InvoiceRepository.GetInvoice(invoiceId);
if (invoice == null || invoice.Status == InvoiceStatusLegacy.Complete || invoice.Status == InvoiceStatusLegacy.Invalid || invoice.Status == InvoiceStatusLegacy.Expired)
return NotFound();
var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
CompositeDisposable leases = new CompositeDisposable();
try
{
leases.Add(_EventAggregator.Subscribe<Events.InvoiceDataChangedEvent>(async o => await NotifySocket(webSocket, o.InvoiceId, invoiceId)));
leases.Add(_EventAggregator.Subscribe<Events.InvoiceNewPaymentDetailsEvent>(async o => await NotifySocket(webSocket, o.InvoiceId, invoiceId)));
leases.Add(_EventAggregator.Subscribe<Events.InvoiceEvent>(async o => await NotifySocket(webSocket, o.Invoice.Id, invoiceId)));
while (true)
{
var message = await webSocket.ReceiveAsync(DummyBuffer, default(CancellationToken));
if (message.MessageType == WebSocketMessageType.Close)
break;
}
}
catch (WebSocketException) { }
finally
{
leases.Dispose();
await webSocket.CloseSocket();
}
return new EmptyResult();
}
readonly ArraySegment<Byte> DummyBuffer = new ArraySegment<Byte>(new Byte[1]);
private async Task NotifySocket(WebSocket webSocket, string invoiceId, string expectedId)
{
if (invoiceId != expectedId || webSocket.State != WebSocketState.Open)
return;
using CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(5000);
try
{
await webSocket.SendAsync(DummyBuffer, WebSocketMessageType.Binary, true, cts.Token);
}
catch { try { webSocket.Dispose(); } catch { } }
}
[HttpPost]
[Route("i/{invoiceId}/UpdateCustomer")]
[Route("invoice/UpdateCustomer")]
public async Task<IActionResult> UpdateCustomer(string invoiceId, [FromBody] UpdateCustomerModel data)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await _InvoiceRepository.UpdateInvoice(invoiceId, data).ConfigureAwait(false);
return Ok("{}");
}
[HttpGet]
[Route("invoices")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> ListInvoices(InvoicesModel model = null)
{
model = this.ParseListQuery(model ?? new InvoicesModel());
var fs = new SearchString(model.SearchTerm);
var storeIds = fs.GetFilterArray("storeid") != null ? fs.GetFilterArray("storeid") : new List<string>().ToArray();
model.StoreIds = storeIds;
InvoiceQuery invoiceQuery = GetInvoiceQuery(model.SearchTerm, model.TimezoneOffset ?? 0);
var counting = _InvoiceRepository.GetInvoicesTotal(invoiceQuery);
invoiceQuery.Take = model.Count;
invoiceQuery.Skip = model.Skip;
var list = await _InvoiceRepository.GetInvoices(invoiceQuery);
foreach (var invoice in list)
{
var state = invoice.GetInvoiceState();
model.Invoices.Add(new InvoiceModel()
{
Status = state,
ShowCheckout = invoice.Status == InvoiceStatusLegacy.New,
Date = invoice.InvoiceTime,
InvoiceId = invoice.Id,
OrderId = invoice.Metadata.OrderId ?? string.Empty,
RedirectUrl = invoice.RedirectURL?.AbsoluteUri ?? string.Empty,
AmountCurrency = _CurrencyNameTable.DisplayFormatCurrency(invoice.Price, invoice.Currency),
CanMarkInvalid = state.CanMarkInvalid(),
CanMarkComplete = state.CanMarkComplete(),
Details = InvoicePopulatePayments(invoice),
});
}
model.Total = await counting;
return View(model);
}
private InvoiceQuery GetInvoiceQuery(string searchTerm = null, int timezoneOffset = 0)
{
var fs = new SearchString(searchTerm);
var invoiceQuery = new InvoiceQuery()
{
TextSearch = fs.TextSearch,
UserId = GetUserId(),
Unusual = fs.GetFilterBool("unusual"),
IncludeArchived = fs.GetFilterBool("includearchived") ?? false,
Status = fs.GetFilterArray("status"),
ExceptionStatus = fs.GetFilterArray("exceptionstatus"),
StoreId = fs.GetFilterArray("storeid"),
ItemCode = fs.GetFilterArray("itemcode"),
OrderId = fs.GetFilterArray("orderid"),
StartDate = fs.GetFilterDate("startdate", timezoneOffset),
EndDate = fs.GetFilterDate("enddate", timezoneOffset)
};
return invoiceQuery;
}
[HttpGet]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> Export(string format, string searchTerm = null, int timezoneOffset = 0)
{
var model = new InvoiceExport(_CurrencyNameTable);
InvoiceQuery invoiceQuery = GetInvoiceQuery(searchTerm, timezoneOffset);
invoiceQuery.Skip = 0;
invoiceQuery.Take = int.MaxValue;
var invoices = await _InvoiceRepository.GetInvoices(invoiceQuery);
var res = model.Process(invoices, format);
var cd = new ContentDisposition
{
FileName = $"btcpay-export-{DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture)}.{format}",
Inline = true
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
return Content(res, "application/" + format);
}
private SelectList GetPaymentMethodsSelectList()
{
return new SelectList(_paymentMethodHandlerDictionary.Distinct().SelectMany(handler =>
handler.GetSupportedPaymentMethods()
.Select(id => new SelectListItem(id.ToPrettyString(), id.ToString()))),
nameof(SelectListItem.Value),
nameof(SelectListItem.Text));
}
[HttpGet]
[Route("invoices/create")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> CreateInvoice()
{
var stores = new SelectList(await _StoreRepository.GetStoresByUserId(GetUserId()), nameof(StoreData.Id), nameof(StoreData.StoreName), null);
if (!stores.Any())
{
TempData[WellKnownTempData.ErrorMessage] = "You need to create at least one store before creating a transaction";
return RedirectToAction(nameof(UserStoresController.ListStores), "UserStores");
}
return View(new CreateInvoiceModel() { Stores = stores, AvailablePaymentMethods = GetPaymentMethodsSelectList() });
}
[HttpPost]
[Route("invoices/create")]
[Authorize(Policy = Policies.CanCreateInvoice, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> CreateInvoice(CreateInvoiceModel model, CancellationToken cancellationToken)
{
var stores = await _StoreRepository.GetStoresByUserId(GetUserId());
model.Stores = new SelectList(stores, nameof(StoreData.Id), nameof(StoreData.StoreName), model.StoreId);
model.AvailablePaymentMethods = GetPaymentMethodsSelectList();
var store = HttpContext.GetStoreData();
if (!ModelState.IsValid)
{
return View(model);
}
if (!store.GetSupportedPaymentMethods(_NetworkProvider).Any())
{
ModelState.AddModelError(nameof(model.StoreId), "You need to configure the derivation scheme in order to create an invoice");
return View(model);
}
try
{
var result = await CreateInvoiceCore(new BitpayCreateInvoiceRequest()
{
Price = model.Amount.Value,
Currency = model.Currency,
PosData = model.PosData,
OrderId = model.OrderId,
//RedirectURL = redirect + "redirect",
NotificationURL = model.NotificationUrl,
ItemDesc = model.ItemDesc,
FullNotifications = true,
BuyerEmail = model.BuyerEmail,
SupportedTransactionCurrencies = model.SupportedTransactionCurrencies?.ToDictionary(s => s, s => new InvoiceSupportedTransactionCurrency()
{
Enabled = true
})
}, store, HttpContext.Request.GetAbsoluteRoot(), cancellationToken: cancellationToken);
TempData[WellKnownTempData.SuccessMessage] = $"Invoice {result.Data.Id} just created!";
return RedirectToAction(nameof(ListInvoices));
}
catch (BitpayHttpException ex)
{
ModelState.TryAddModelError(nameof(model.Currency), $"Error: {ex.Message}");
return View(model);
}
}
[HttpPost]
[Route("invoices/{invoiceId}/changestate/{newState}")]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie)]
[BitpayAPIConstraint(false)]
public async Task<IActionResult> ChangeInvoiceState(string invoiceId, string newState)
{
var invoice = (await _InvoiceRepository.GetInvoices(new InvoiceQuery()
{
InvoiceId = new[] { invoiceId },
UserId = GetUserId()
})).FirstOrDefault();
var model = new InvoiceStateChangeModel();
if (invoice == null)
{
model.NotFound = true;
return NotFound(model);
}
if (newState == "invalid")
{
await _InvoiceRepository.MarkInvoiceStatus(invoiceId, InvoiceStatus.Invalid);
model.StatusString = new InvoiceState("invalid", "marked").ToString();
}
else if (newState == "complete")
{
await _InvoiceRepository.MarkInvoiceStatus(invoiceId, InvoiceStatus.Settled);
model.StatusString = new InvoiceState("complete", "marked").ToString();
}
return Json(model);
}
public class InvoiceStateChangeModel
{
public bool NotFound { get; set; }
public string StatusString { get; set; }
}
private string GetUserId()
{
return _UserManager.GetUserId(User);
}
public class PosDataParser
{
public static Dictionary<string, object> ParsePosData(string posData)
{
var result = new Dictionary<string, object>();
if (string.IsNullOrEmpty(posData))
{
return result;
}
try
{
var jObject = JObject.Parse(posData);
foreach (var item in jObject)
{
switch (item.Value.Type)
{
case JTokenType.Array:
var items = item.Value.AsEnumerable().ToList();
for (var i = 0; i < items.Count; i++)
{
result.TryAdd($"{item.Key}[{i}]", ParsePosData(items[i].ToString()));
}
break;
case JTokenType.Object:
result.TryAdd(item.Key, ParsePosData(item.Value.ToString()));
break;
default:
result.TryAdd(item.Key, item.Value.ToString());
break;
}
}
}
catch
{
result.TryAdd(string.Empty, posData);
}
return result;
}
}
}
}
| 48.725134 | 224 | 0.564972 | [
"MIT"
] | Falci/btcpayserver | BTCPayServer/Controllers/InvoiceController.UI.cs | 45,558 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Mod.CatsV3.WebApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
| 28.725 | 110 | 0.600522 | [
"MIT"
] | EOP-OMB/CATSV3 | Server/Mod.CatsV3.Server/Mod.CatsV3.WebApi/Controllers/WeatherForecastController.cs | 1,151 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.