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 |
|---|---|---|---|---|---|---|---|---|
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Media.Core
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
#endif
public partial class MediaStreamSourceSampleRequestDeferral
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public void Complete()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.Core.MediaStreamSourceSampleRequestDeferral", "void MediaStreamSourceSampleRequestDeferral.Complete()");
}
#endif
}
}
| 32.105263 | 196 | 0.770492 | [
"Apache-2.0"
] | nv-ksavaria/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Core/MediaStreamSourceSampleRequestDeferral.cs | 610 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.IoT.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoT.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListBillingGroups Request Marshaller
/// </summary>
public class ListBillingGroupsRequestMarshaller : IMarshaller<IRequest, ListBillingGroupsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListBillingGroupsRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListBillingGroupsRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.IoT");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-05-28";
request.HttpMethod = "GET";
if (publicRequest.IsSetMaxResults())
request.Parameters.Add("maxResults", StringUtils.FromInt(publicRequest.MaxResults));
if (publicRequest.IsSetNamePrefixFilter())
request.Parameters.Add("namePrefixFilter", StringUtils.FromString(publicRequest.NamePrefixFilter));
if (publicRequest.IsSetNextToken())
request.Parameters.Add("nextToken", StringUtils.FromString(publicRequest.NextToken));
request.ResourcePath = "/billing-groups";
request.UseQueryString = true;
return request;
}
private static ListBillingGroupsRequestMarshaller _instance = new ListBillingGroupsRequestMarshaller();
internal static ListBillingGroupsRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListBillingGroupsRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.904255 | 149 | 0.651935 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/ListBillingGroupsRequestMarshaller.cs | 3,281 | C# |
// Main Contributors: Everyone (fair share)
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Diagnostics;
using MonkeyQuest.MonkeyQuest.Logic;
using MonkeyQuest.MonkeyQuest.UI;
using MonkeyQuest.Test;
namespace Tester
{
public static class TestMain
{
[STAThread]
public static void Main()
{
// Load XML map
// you need to 'Rebuild Solution' so that the xml will be output the the debug directory
//Tests:
//1st map
//-Objects are being added succesfully.
//-Collidables are colliding.
//-Organics a la AI (& by extension monkeys etc) are killed & removed when impacted from above by other collidables.
//-Gravitational fields are functional.
//-Anti-Gravitional fields work :P (if bananas can hold the crates up) a.k.a. objects on board that are not bound to gravity don't have all motions thrust upon them blindly.
//2nd map
//In addition to most from above
//-Monkey collects bananas, which are removed from board.
//3rd map
//In addition to most tests from above
//-Controllables [monkey] can push crates left & right unless obstructed by another collidable
//-Controllables [monkey] dont die unless in contact with AI
//-AI doesn't die unless impacted from above by crate or controllable
//4th map
//In addition to (1st & 2nd map tests)
//Monkey collecting all bananas leads to emergence of door
//Collecting all bananas (i.e. controllable fulfilling specified objectives) reveals door a.k.a means to progress to next level.
//Collision with door results in signal for next level
//Weapons kill the monnnstaaaaar! AI is removed when weapons collide into them.
string[] mapPathArray = { "Resources/Maps/Test.xml", "Resources/Maps/CollisionTestMap.xml", "Resources/Maps/CrateTestMap.xml", "Resources/Maps/DoorTestMap.xml" };
TestPackage boardPackage = new TestPackage(mapPathArray, new MonkeyBoardUI(null), new MonkeyMainBarUI(null), true);
Application app = new Application();
TestUIWindow window;
// creates the UI for window
window = new TestUIWindow(boardPackage);
// start the timer
boardPackage.Start();
app.Run(window);
System.Diagnostics.Debug.WriteLine("Board Debug");
}
}
}
| 41.867647 | 194 | 0.595012 | [
"MIT"
] | guangie88/cs2103-monkey-quest | Tester/TestMain.cs | 2,849 | C# |
////////////////////////////////////////////////////////////////////////////////////////////////////
//// ////
//// Copyright (c) 2016 - present, CERTH-ITI, Artica ////
//// ////
////////////////////////////////////////////////////////////////////////////////////////////////////
using Microsoft.Band;
using Microsoft.Band.Sensors;
using SenseLib.DataFrames.MSBand;
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace SenseLib
{
namespace DataFrames
{
namespace MSBand
{
[DataContract]
public struct HeartRateDataBand
{
private int data;
private DateTime timeStamp;
[DataMember]
public int Data { get { return data; } set { data = value; } }
[DataMember]
public DateTime DataTimeStamp { get { return timeStamp; } set { timeStamp = value; } }
}
[DataContract]
public struct SkinTemperatureDataBand
{
private double data;
private DateTime timeStamp;
[DataMember]
public double Data { get { return data; } set { data = value; } }
[DataMember]
public DateTime DataTimeStamp { get { return timeStamp; } set { timeStamp = value; } }
}
[DataContract]
public struct CaloriesDataBand
{
private long dataTotal;
private long dateToday;
private DateTime timeStamp;
[DataMember]
public long DataTotal { get { return dataTotal; } set { dataTotal = value; } }
[DataMember]
public long DataToday { get { return dateToday; } set { dateToday = value; } }
[DataMember]
public DateTime DataTimeStamp { get { return timeStamp; } set { timeStamp = value; } }
}
[DataContract]
public struct GyroscopeDataBand
{
private double accelerationX;
private double accelerationY;
private double accelerationZ;
private double angularVelocityX;
private double angularVelocityY;
private double angularVelocityZ;
private DateTime timeStamp;
[DataMember]
public double AccelerationX { get { return accelerationX; } set { accelerationX = value; } }
[DataMember]
public double AccelerationY { get { return accelerationY; } set { accelerationY = value; } }
[DataMember]
public double AccelerationZ { get { return accelerationZ; } set { accelerationZ = value; } }
[DataMember]
public double AngularVelocityX { get { return angularVelocityX; } set { angularVelocityX = value; } }
[DataMember]
public double AngularVelocityY { get { return angularVelocityY; } set { angularVelocityY = value; } }
[DataMember]
public double AngularVelocityZ { get { return angularVelocityZ; } set { angularVelocityZ = value; } }
[DataMember]
public DateTime DataTimeStamp { get { return timeStamp; } set { timeStamp = value; } }
}
[DataContract]
public struct PedometerDataBand
{
private long stepsToday;
private long stepsTotal;
private DateTime timeStamp;
[DataMember]
public long StepsToday { get { return stepsToday; } set { stepsToday = value; } }
[DataMember]
public long StepsTotal { get { return stepsTotal; } set { stepsTotal = value; } }
[DataMember]
public DateTime DataTimeStamp { get { return timeStamp; } set { timeStamp = value; } }
}
[DataContract]
public struct DistanceDataBand
{
private long distanteToday;
private double pace;
private double speed;
private DateTime timeStamp;
[DataMember]
public long DistanteToday { get { return distanteToday; } set { distanteToday = value; } }
[DataMember]
public double Pace { get { return pace; } set { pace = value; } }
[DataMember]
public double Speed { get { return speed; } set { speed = value; } }
[DataMember]
public DateTime DataTimeStamp { get { return timeStamp; } set { timeStamp = value; } }
}
[DataContract]
public struct GalvanicSkinResponse
{
private long gsr;
private DateTime timeStamp;
[DataMember]
public long Gsr { get { return gsr; } set { gsr = value; } }
[DataMember]
public DateTime DataTimeStamp { get { return timeStamp; } set { timeStamp = value; } }
}
[DataContract]
public class MSBandFrame
{
[DataMember]
public string SensorID { get; set; }
[DataMember]
public DateTime TimeStamp { get; set; }
[DataMember]
public HeartRateDataBand HeartRateData { get; set; }
[DataMember]
public SkinTemperatureDataBand SkinTemperatureData { get; set; }
[DataMember]
public CaloriesDataBand CaloriesData { get; set; }
[DataMember]
public GyroscopeDataBand GyroscopeData { get; set; }
[DataMember]
public PedometerDataBand PedometerData { get; set; }
[DataMember]
public DistanceDataBand DistanceData { get; set; }
[DataMember]
public GalvanicSkinResponse GalvanicSkinResponseData { get; set; }
}
}
}
namespace Acquisition
{
namespace MSBand
{
public sealed class BandSession
{
private static BandSession instance = null;
public IBandInfo[] bandInfo { get; set; }
public IBandClient[] bandClient { get; set; }
public string[] bandName { get; set; }
public static BandSession Instance
{
get
{
if (instance == null)
{
instance = new BandSession();
}
return instance;
}
}
private BandSession() { }
}
public struct BandSelection
{
public bool heartRate;
public bool skinTemperature;
public bool pedometer;
public bool calories;
public bool distance;
public bool accelerometer;
public bool gyroscope;
public bool gsr;
public BandSelection(bool init)
{
heartRate = init;
skinTemperature = init;
accelerometer = init;
calories = init;
gyroscope = init;
pedometer = init;
distance = init;
gsr = init;
}
public BandSelection(bool[] init)
{
heartRate = init[0];
skinTemperature = init[1];
accelerometer = init[2];
calories = init[3];
gyroscope = init[4];
pedometer = init[5];
distance = init[6];
gsr = init[7];
}
}
public class MSBandSenseLib
{
private const int sleepTime = 3;
private const int maxIdleTime = 3 * 60 * 1000;
/// <summary> Indicates whether connection to the band has been lost. </summary>
public bool IsIdle { get; private set; }
public IBandClient bandClient { get; set; }
public string bandName { get; private set; }
public BandSelection bandSelection { get; set; }
// Local data
private HeartRateDataBand heartRateData;
private SkinTemperatureDataBand skinTemperatureData;
private PedometerDataBand pedometerData;
private CaloriesDataBand caloriesData;
private DistanceDataBand distanceData;
private GyroscopeDataBand gyroscopeData;
private GalvanicSkinResponse galvanicData;
private readonly object myLock;
private MSBandFrame bandFrame;
private DateTime[] sendTime;
public MSBandSenseLib(IBandClient vBandClient, BandSelection vBandSelection, string vBandName)
{
bandClient = vBandClient;
bandSelection = vBandSelection;
bandName = vBandName;
IsIdle = false;
myLock = new object();
bandFrame = new MSBandFrame();
bandFrame.SensorID = vBandName;
sendTime = new DateTime[2];
}
public void UpdateBandAcquisition(IBandClient vBandClient, string vBandName)
{
bandClient = vBandClient;
bandName = vBandName;
bandFrame.SensorID = vBandName;
try
{
OpenSensor();
}
catch (Exception)
{
}
}
public bool IsSensorAvailable(int msTimeout)
{
if (bandClient == null)
return false;
return true;
}
public void OpenSensor()
{
p_readHeartReate();
p_readingSkinTemperature();
p_readingPedometer();
p_readingCalories();
p_readingDistance();
p_readingGyroscope();
p_readingGalvanic();
}
public void CloseSensor()
{
p_stopReading();
}
public MSBandFrame GetFrame()
{
DateTime totalTime = DateTime.Now;
while (sendTime[0] == sendTime[1])
{
Task.Delay(sleepTime).Wait();
if (DateTime.Now.AddTicks(-totalTime.Ticks).Ticks / 10000.0 > maxIdleTime)
{
IsIdle = true;
return null;
}
}
Task.Delay(1).Wait();
IsIdle = false;
sendTime[1] = sendTime[0];
lock (myLock)
{
bandFrame.TimeStamp = sendTime[0];
bandFrame.HeartRateData = heartRateData;
bandFrame.SkinTemperatureData = skinTemperatureData;
bandFrame.PedometerData = pedometerData;
bandFrame.CaloriesData = caloriesData;
bandFrame.DistanceData = distanceData;
bandFrame.GyroscopeData = gyroscopeData;
bandFrame.GalvanicSkinResponseData = galvanicData;
return bandFrame;
}
}
public byte[] FrameToBytes(MSBandFrame frame)
{
lock (myLock)
{
return Utils.Serialization.SerializeXML(frame);
}
}
public MSBandFrame BytesToFrame(byte[] frameBytes)
{
return Utils.Serialization.DeserializeXML<MSBandFrame>(frameBytes);
}
#region Start / Stop reading
public async void p_readHeartReate()
{
bandClient.SensorManager.HeartRate.ReadingChanged += HeartRate_ReadingChanged;
await bandClient.SensorManager.HeartRate.StartReadingsAsync();
}
public async void p_readingSkinTemperature()
{
bandClient.SensorManager.SkinTemperature.ReadingChanged += SkinTemperature_ReadingChanged;
await bandClient.SensorManager.SkinTemperature.StartReadingsAsync();
}
public async void p_readingPedometer()
{
bandClient.SensorManager.Pedometer.ReadingChanged += Pedometer_ReadingChanged;
await bandClient.SensorManager.Pedometer.StartReadingsAsync();
}
public async void p_readingCalories()
{
bandClient.SensorManager.Calories.ReadingChanged += Calories_ReadingChanged;
await bandClient.SensorManager.Calories.StartReadingsAsync();
}
public async void p_readingDistance()
{
bandClient.SensorManager.Distance.ReadingChanged += Distance_ReadingChanged;
await bandClient.SensorManager.Distance.StartReadingsAsync();
}
public async void p_readingGyroscope()
{
bandClient.SensorManager.Gyroscope.ReadingChanged += Gyroscope_ReadingChanged;
await bandClient.SensorManager.Gyroscope.StartReadingsAsync();
}
public async void p_readingGalvanic()
{
bandClient.SensorManager.Gsr.ReadingChanged += Gsr_ReadingChanged;
await bandClient.SensorManager.Gsr.StartReadingsAsync();
}
private async void p_stopReading()
{
await bandClient.SensorManager.HeartRate.StopReadingsAsync();
await bandClient.SensorManager.SkinTemperature.StopReadingsAsync();
await bandClient.SensorManager.Pedometer.StopReadingsAsync();
await bandClient.SensorManager.Calories.StopReadingsAsync();
await bandClient.SensorManager.Distance.StopReadingsAsync();
await bandClient.SensorManager.Accelerometer.StopReadingsAsync();
await bandClient.SensorManager.Gyroscope.StopReadingsAsync();
await bandClient.SensorManager.Gsr.StopReadingsAsync();
}
#endregion
#region Readers
private void HeartRate_ReadingChanged(object sender, BandSensorReadingEventArgs<IBandHeartRateReading> e)
{
lock (myLock)
{
sendTime[0] = DateTime.Now;
heartRateData.Data = e.SensorReading.HeartRate;
heartRateData.DataTimeStamp = sendTime[0];
}
}
private void SkinTemperature_ReadingChanged(object sender, BandSensorReadingEventArgs<IBandSkinTemperatureReading> e)
{
lock (myLock)
{
sendTime[0] = DateTime.Now;
skinTemperatureData.Data = e.SensorReading.Temperature;
skinTemperatureData.DataTimeStamp = sendTime[0];
}
}
private void Pedometer_ReadingChanged(object sender, BandSensorReadingEventArgs<IBandPedometerReading> e)
{
lock (myLock)
{
sendTime[0] = DateTime.Now;
pedometerData.StepsToday = e.SensorReading.StepsToday;
pedometerData.StepsTotal = e.SensorReading.TotalSteps;
pedometerData.DataTimeStamp = sendTime[0];
}
}
private void Calories_ReadingChanged(object sender, BandSensorReadingEventArgs<IBandCaloriesReading> e)
{
lock (myLock)
{
sendTime[0] = DateTime.Now;
caloriesData.DataTotal = e.SensorReading.Calories;
caloriesData.DataToday = e.SensorReading.CaloriesToday;
caloriesData.DataTimeStamp = sendTime[0];
}
}
private void Distance_ReadingChanged(object sender, BandSensorReadingEventArgs<IBandDistanceReading> e)
{
lock (myLock)
{
sendTime[0] = DateTime.Now;
distanceData.DistanteToday = e.SensorReading.DistanceToday;
distanceData.Pace = e.SensorReading.Pace;
distanceData.Speed = e.SensorReading.Speed;
distanceData.DataTimeStamp = sendTime[0];
}
}
private void Gyroscope_ReadingChanged(object sender, BandSensorReadingEventArgs<IBandGyroscopeReading> e)
{
lock (myLock)
{
sendTime[0] = DateTime.Now;
gyroscopeData.AccelerationX = e.SensorReading.AccelerationX;
gyroscopeData.AccelerationY = e.SensorReading.AccelerationY;
gyroscopeData.AccelerationZ = e.SensorReading.AccelerationZ;
gyroscopeData.AngularVelocityX = e.SensorReading.AngularVelocityX;
gyroscopeData.AngularVelocityY = e.SensorReading.AngularVelocityY;
gyroscopeData.AngularVelocityZ = e.SensorReading.AngularVelocityZ;
gyroscopeData.DataTimeStamp = sendTime[0];
}
}
private void Gsr_ReadingChanged(object sender, BandSensorReadingEventArgs<IBandGsrReading> e)
{
lock (myLock)
{
sendTime[0] = DateTime.Now;
galvanicData.Gsr = e.SensorReading.Resistance;
galvanicData.DataTimeStamp = sendTime[0];
}
}
#endregion
}
}
}
namespace Utils
{
/// <summary>Provides methods for Serializing arbitrary objects using an XML format.</summary>
public static class Serialization
{
/// <summary>Serializes the given object into a byte array using an XML format.</summary>
public static byte[] SerializeXML(object obj)
{
byte[] result;
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
using (MemoryStream memStream = new MemoryStream())
{
serializer.WriteObject(memStream, obj);
memStream.Position = 0;
result = new byte[memStream.Length];
memStream.Read(result, 0, (int)memStream.Length);
return result;
}
}
/// <summary>De-serializes the given object into type T using an XML format.</summary>
public static T DeserializeXML<T>(byte[] obj)
{
object result;
DataContractSerializer deserializer = new DataContractSerializer(typeof(T));
using (MemoryStream memStream = new MemoryStream(obj))
{
memStream.Position = 0;
result = deserializer.ReadObject(memStream);
return (T)result;
}
}
}
}
} | 37.682373 | 134 | 0.4711 | [
"MIT"
] | tomastheod-ITI/SenseLib | MSBandSenseLib.cs | 21,594 | C# |
/*
* Copyright © 2017 Cloudveil Technology Inc.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace CloudVeilGUI.CustomFormElements
{
public class BlurredFrame : Frame
{
}
}
| 23 | 69 | 0.729977 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | JackBro/Filter-Windows | CloudVeilGUI/CloudVeilGUI/CustomFormElements/BlurredFrame.cs | 440 | C# |
// Copyright (c) Alexander Bogarsukov.
// Licensed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
namespace UnityFx.Purchasing.Validation
{
/// <summary>
/// Amazon Store validation result.
/// </summary>
/// <seealso cref="AmazonStoreReceipt"/>
public class AmazonStoreValidationResult : IPurchaseValidationResult
{
#region interface
/// <summary>
/// Returns the status code. Read only.
/// </summary>
public int StatusCode { get; }
/// <summary>
/// The Amazon Store receipt (id any). Read only.
/// </summary>
public AmazonStoreReceipt Receipt { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AmazonStoreValidationResult"/> class.
/// </summary>
internal AmazonStoreValidationResult(int status, string rawResponse, AmazonStoreReceipt receipt)
{
StatusCode = status;
RawResult = rawResponse;
Receipt = receipt;
}
#endregion
#region IPurchaseValidationResult
/// <inheritdoc/>
public string RawResult { get; }
/// <inheritdoc/>
public string Status { get; internal set; }
/// <inheritdoc/>
public bool IsOK => StatusCode == 0;
/// <inheritdoc/>
public bool IsFailed => StatusCode != 0;
#endregion
#region IEnumerable
/// <inheritdoc/>
public IEnumerator<IPurchaseReceipt> GetEnumerator()
{
return GetEnumeratorInternal();
}
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumeratorInternal();
}
#endregion
#region implementation
private IEnumerator<IPurchaseReceipt> GetEnumeratorInternal()
{
if (Receipt != null)
{
yield return Receipt;
}
}
#endregion
}
}
| 20.682353 | 100 | 0.68942 | [
"MIT"
] | Arvtesh/UnityFx.Purchasing | src/UnityFx.Purchasing.Validation/AmazonStore/AmazonStoreValidationResult.cs | 1,760 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.EventGrid.Latest.Outputs
{
[OutputType]
public sealed class EventHubEventSubscriptionDestinationResponse
{
/// <summary>
/// Type of the endpoint for the event subscription destination.
/// </summary>
public readonly string EndpointType;
/// <summary>
/// The Azure Resource Id that represents the endpoint of an Event Hub destination of an event subscription.
/// </summary>
public readonly string? ResourceId;
[OutputConstructor]
private EventHubEventSubscriptionDestinationResponse(
string endpointType,
string? resourceId)
{
EndpointType = endpointType;
ResourceId = resourceId;
}
}
}
| 30.027778 | 116 | 0.665125 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/EventGrid/Latest/Outputs/EventHubEventSubscriptionDestinationResponse.cs | 1,081 | C# |
using System;
using CoreTelephony;
using Foundation;
using UIKit;
namespace Xamarin.Essentials
{
public static partial class PhoneDialer
{
const string noNetworkProviderCode = "65535";
internal static bool IsSupported => UIApplication.SharedApplication.CanOpenUrl(CreateNsUrl(new string('0', 10)));
static async void PlatformOpen(string number)
{
ValidateOpen(number);
var nsUrl = CreateNsUrl(number);
await Launcher.PlatformOpenAsync(nsUrl);
}
static NSUrl CreateNsUrl(string number) => new NSUrl(new Uri($"tel:{number}").AbsoluteUri);
}
}
| 22.84 | 115 | 0.751313 | [
"MIT"
] | dhindrik/maui | src/Essentials/src/Xamarin.Essentials/PhoneDialer/PhoneDialer.ios.cs | 573 | 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 Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class ExportTests
{
[Fact]
public static void ExportAsCert()
{
using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
{
byte[] rawData = c1.Export(X509ContentType.Cert);
Assert.Equal(X509ContentType.Cert, X509Certificate2.GetCertContentType(rawData));
Assert.Equal(TestData.MsCertificate, rawData);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // SerializedCert not supported on Unix
public static void ExportAsSerializedCert_Windows()
{
using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
{
byte[] serializedCert = c1.Export(X509ContentType.SerializedCert);
Assert.Equal(X509ContentType.SerializedCert, X509Certificate2.GetCertContentType(serializedCert));
using (X509Certificate2 c2 = new X509Certificate2(serializedCert))
{
byte[] rawData = c2.Export(X509ContentType.Cert);
Assert.Equal(TestData.MsCertificate, rawData);
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // SerializedCert not supported on Unix
public static void ExportAsSerializedCert_Unix()
{
using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
{
Assert.Throws<PlatformNotSupportedException>(() => c1.Export(X509ContentType.SerializedCert));
}
}
[Fact]
[ActiveIssue(16705, TestPlatforms.OSX)]
public static void ExportAsPfx()
{
using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
{
byte[] pfx = c1.Export(X509ContentType.Pkcs12);
Assert.Equal(X509ContentType.Pkcs12, X509Certificate2.GetCertContentType(pfx));
using (X509Certificate2 c2 = new X509Certificate2(pfx))
{
byte[] rawData = c2.Export(X509ContentType.Cert);
Assert.Equal(TestData.MsCertificate, rawData);
}
}
}
[Fact]
[ActiveIssue(16705, TestPlatforms.OSX)]
public static void ExportAsPfxWithPassword()
{
const string password = "PLACEHOLDER";
using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
{
byte[] pfx = c1.Export(X509ContentType.Pkcs12, password);
Assert.Equal(X509ContentType.Pkcs12, X509Certificate2.GetCertContentType(pfx));
using (X509Certificate2 c2 = new X509Certificate2(pfx, password))
{
byte[] rawData = c2.Export(X509ContentType.Cert);
Assert.Equal(TestData.MsCertificate, rawData);
}
}
}
[Fact]
[ActiveIssue(16705, TestPlatforms.OSX)]
public static void ExportAsPfxVerifyPassword()
{
const string password = "PLACEHOLDER";
using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate))
{
byte[] pfx = c1.Export(X509ContentType.Pkcs12, password);
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(pfx, "WRONGPASSWORD"));
}
}
[Fact]
public static void ExportAsPfxWithPrivateKeyVerifyPassword()
{
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
{
Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey");
const string password = "PLACEHOLDER";
byte[] pfx = cert.Export(X509ContentType.Pkcs12, password);
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(pfx, "WRONGPASSWORD"));
using (var cert2 = new X509Certificate2(pfx, password))
{
Assert.Equal(cert, cert2);
Assert.True(cert2.HasPrivateKey, "cert2.HasPrivateKey");
}
}
}
[Fact]
public static void ExportAsPfxWithPrivateKey()
{
using (X509Certificate2 cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable))
{
Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey");
byte[] pfxBytes = cert.Export(X509ContentType.Pkcs12);
using (X509Certificate2 fromPfx = new X509Certificate2(pfxBytes))
{
Assert.Equal(cert, fromPfx);
Assert.True(fromPfx.HasPrivateKey, "fromPfx.HasPrivateKey");
byte[] origSign;
byte[] copySign;
using (RSA origPriv = cert.GetRSAPrivateKey())
{
origSign = origPriv.SignData(pfxBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
using (RSA copyPriv = fromPfx.GetRSAPrivateKey())
{
copySign = copyPriv.SignData(pfxBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
using (RSA origPub = cert.GetRSAPublicKey())
{
Assert.True(
origPub.VerifyData(pfxBytes, copySign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1),
"oPub v copySig");
}
using (RSA copyPub = fromPfx.GetRSAPublicKey())
{
Assert.True(
copyPub.VerifyData(pfxBytes, origSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1),
"copyPub v oSig");
}
}
}
}
}
}
| 38.854545 | 140 | 0.564031 | [
"MIT"
] | CyberSys/corefx-mono | src/System.Security.Cryptography.X509Certificates/tests/ExportTests.cs | 6,411 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebAppWithIdentity.Models;
namespace WebAppWithIdentity.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 23.386364 | 112 | 0.597668 | [
"MIT"
] | CNinnovation/ASPNETCoreOct2018 | Day3/WebAppWithIdentity/WebAppWithIdentity/Controllers/HomeController.cs | 1,031 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using SyncKusto.Models;
namespace SyncKusto.Validation.ErrorMessages.Specifications
{
public class DefaultOperationErrorSpecification : IOperationErrorMessageSpecification
{
public INonEmptyStringState Match(Exception exception)
{
switch (exception)
{
case AggregateException ae:
foreach (Exception innerException in ae.InnerExceptions)
{
return Match(innerException);
}
break;
default:
return new NonEmptyString(exception.Message);
}
return new UninitializedString();
}
}
} | 29.571429 | 89 | 0.57971 | [
"MIT"
] | Bhaskers-Blu-Org2/synckusto | SyncKusto/Validation/ErrorMessages/Specifications/DefaultOperationErrorSpecification.cs | 830 | C# |
using Unity.Entities;
using UnityEngine;
#if UNITY_EDITOR
public class AbilityAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new Ability.AbilityControl());
}
}
#endif
| 19.277778 | 109 | 0.775216 | [
"MIT"
] | The-ULTIMATE-MULTIPLAYER-EXPERIENCE/Ultimate-Archery-Multiplayer-Unity-Game | DOTSSample-master/Assets/Unity.Sample.Game.Authoring/Ability/AbilityAuthoring.cs | 349 | 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void BitwiseClear_Vector64_Single()
{
var test = new SimpleBinaryOpTest__BitwiseClear_Vector64_Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__BitwiseClear_Vector64_Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Single> _fld1;
public Vector64<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__BitwiseClear_Vector64_Single testClass)
{
var result = AdvSimd.BitwiseClear(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__BitwiseClear_Vector64_Single testClass)
{
fixed (Vector64<Single>* pFld1 = &_fld1)
fixed (Vector64<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector64((Single*)(pFld1)),
AdvSimd.LoadVector64((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector64<Single> _clsVar1;
private static Vector64<Single> _clsVar2;
private Vector64<Single> _fld1;
private Vector64<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__BitwiseClear_Vector64_Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
}
public SimpleBinaryOpTest__BitwiseClear_Vector64_Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.BitwiseClear(
Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseClear), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseClear), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.BitwiseClear(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Single>* pClsVar1 = &_clsVar1)
fixed (Vector64<Single>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector64((Single*)(pClsVar1)),
AdvSimd.LoadVector64((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr);
var result = AdvSimd.BitwiseClear(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr));
var result = AdvSimd.BitwiseClear(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__BitwiseClear_Vector64_Single();
var result = AdvSimd.BitwiseClear(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__BitwiseClear_Vector64_Single();
fixed (Vector64<Single>* pFld1 = &test._fld1)
fixed (Vector64<Single>* pFld2 = &test._fld2)
{
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector64((Single*)(pFld1)),
AdvSimd.LoadVector64((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.BitwiseClear(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Single>* pFld1 = &_fld1)
fixed (Vector64<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector64((Single*)(pFld1)),
AdvSimd.LoadVector64((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.BitwiseClear(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector64((Single*)(&test._fld1)),
AdvSimd.LoadVector64((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Single> op1, Vector64<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(Helpers.BitwiseClear(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.BitwiseClear)}<Single>(Vector64<Single>, Vector64<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 42.403013 | 188 | 0.587449 | [
"MIT"
] | Davilink/runtime | src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/BitwiseClear.Vector64.Single.cs | 22,516 | C# |
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace DCSoftDotfuscate
{
[ComVisible(false)]
public class GStream8 : Stream
{
private const int int_0 = 1;
private const int int_1 = 2;
private const int int_2 = 3;
private const int int_3 = 4;
private const int int_4 = 5;
private const int int_5 = 6;
private const int int_6 = 7;
private int int_7;
private int int_8;
private int int_9;
private bool bool_0;
private int int_10;
private int int_11;
private GInterface25 ginterface25_0 = new GClass579();
private bool[] bool_1 = new bool[256];
private int int_12;
private byte[] byte_0 = new byte[256];
private byte[] byte_1 = new byte[256];
private byte[] byte_2 = new byte[18002];
private byte[] byte_3 = new byte[18002];
private int[] int_13;
private byte[] byte_4;
private int[] int_14 = new int[256];
private int[][] int_15 = new int[6][];
private int[][] int_16 = new int[6][];
private int[][] int_17 = new int[6][];
private int[] int_18 = new int[6];
private Stream stream_0;
private bool bool_2;
private int int_19 = -1;
private int int_20 = 1;
private int int_21;
private int int_22;
private int int_23;
private uint uint_0;
private int int_24;
private int int_25;
private int int_26;
private int int_27;
private int int_28;
private int int_29;
private int int_30;
private int int_31;
private byte byte_5;
private bool bool_3 = true;
public override bool CanRead => stream_0.CanRead;
public override bool CanSeek => stream_0.CanSeek;
public override bool CanWrite => false;
public override long Length => stream_0.Length;
public override long Position
{
get
{
return stream_0.Position;
}
set
{
throw new NotSupportedException("BZip2InputStream position cannot be set");
}
}
public GStream8(Stream stream_1)
{
for (int i = 0; i < 6; i++)
{
int_15[i] = new int[258];
int_16[i] = new int[258];
int_17[i] = new int[258];
}
method_7(stream_1);
method_3();
method_4();
method_15();
}
public bool method_0()
{
return bool_3;
}
public void method_1(bool bool_4)
{
bool_3 = bool_4;
}
public override void Flush()
{
if (stream_0 != null)
{
stream_0.Flush();
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("BZip2InputStream Seek not supported");
}
public override void SetLength(long value)
{
throw new NotSupportedException("BZip2InputStream SetLength not supported");
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("BZip2InputStream Write not supported");
}
public override void WriteByte(byte value)
{
throw new NotSupportedException("BZip2InputStream WriteByte not supported");
}
public override int Read(byte[] buffer, int offset, int count)
{
int num = 15;
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
int num2 = 0;
while (true)
{
if (num2 < count)
{
int num3 = ReadByte();
if (num3 == -1)
{
break;
}
buffer[offset + num2] = (byte)num3;
num2++;
continue;
}
return count;
}
return num2;
}
public override void Close()
{
if (method_0() && stream_0 != null)
{
stream_0.Close();
}
}
public override int ReadByte()
{
if (bool_2)
{
return -1;
}
int result = int_19;
switch (int_20)
{
case 3:
method_18();
break;
case 4:
method_19();
break;
case 6:
method_20();
break;
case 7:
method_21();
break;
}
return result;
}
private void method_2()
{
int_12 = 0;
for (int i = 0; i < 256; i++)
{
if (bool_1[i])
{
byte_0[int_12] = (byte)i;
byte_1[i] = (byte)int_12;
int_12++;
}
}
}
private void method_3()
{
char c = method_10();
char c2 = method_10();
char c3 = method_10();
char c4 = method_10();
if (c != 'B' || c2 != 'Z' || c3 != 'h' || c4 < '1' || c4 > '9')
{
bool_2 = true;
return;
}
method_22(c4 - 48);
uint_0 = 0u;
}
private void method_4()
{
char c = method_10();
char c2 = method_10();
char c3 = method_10();
char c4 = method_10();
char c5 = method_10();
char c6 = method_10();
if (c == '\u0017' && c2 == 'r' && c3 == 'E' && c4 == '8' && c5 == 'P' && c6 == '\u0090')
{
method_6();
return;
}
if (c != '1' || c2 != 'A' || c3 != 'Y' || c4 != '&' || c5 != 'S' || c6 != 'Y')
{
smethod_2();
bool_2 = true;
return;
}
int_21 = method_12();
bool_0 = (method_9(1) == 1);
method_14();
ginterface25_0.imethod_1();
int_20 = 1;
}
private void method_5()
{
int_23 = (int)ginterface25_0.imethod_0();
if (int_21 != int_23)
{
smethod_3();
}
uint_0 = (uint)(((int)(uint_0 << 1) & -1) | (int)(uint_0 >> 31));
uint_0 ^= (uint)int_23;
}
private void method_6()
{
int_22 = method_12();
if (int_22 != (int)uint_0)
{
smethod_3();
}
bool_2 = true;
}
private void method_7(Stream stream_1)
{
stream_0 = stream_1;
int_11 = 0;
int_10 = 0;
}
private void method_8()
{
int num = 0;
try
{
num = stream_0.ReadByte();
}
catch (Exception)
{
smethod_0();
}
if (num == -1)
{
smethod_0();
}
int_10 = ((int_10 << 8) | (num & 0xFF));
int_11 += 8;
}
private int method_9(int int_32)
{
while (int_11 < int_32)
{
method_8();
}
int result = (int_10 >> int_11 - int_32) & ((1 << int_32) - 1);
int_11 -= int_32;
return result;
}
private char method_10()
{
return (char)method_9(8);
}
private int method_11(int int_32)
{
return method_9(int_32);
}
private int method_12()
{
int num = method_9(8);
num = ((num << 8) | method_9(8));
num = ((num << 8) | method_9(8));
return (num << 8) | method_9(8);
}
private void method_13()
{
char[][] array = new char[6][];
for (int i = 0; i < 6; i++)
{
array[i] = new char[258];
}
bool[] array2 = new bool[16];
for (int i = 0; i < 16; i++)
{
array2[i] = (method_9(1) == 1);
}
for (int i = 0; i < 16; i++)
{
if (array2[i])
{
for (int j = 0; j < 16; j++)
{
bool_1[i * 16 + j] = (method_9(1) == 1);
}
}
else
{
for (int j = 0; j < 16; j++)
{
bool_1[i * 16 + j] = false;
}
}
}
method_2();
int num = int_12 + 2;
int num2 = method_9(3);
int num3 = method_9(15);
for (int i = 0; i < num3; i++)
{
int j = 0;
while (method_9(1) == 1)
{
j++;
}
byte_3[i] = (byte)j;
}
byte[] array3 = new byte[6];
for (int k = 0; k < num2; k++)
{
array3[k] = (byte)k;
}
for (int i = 0; i < num3; i++)
{
int k = byte_3[i];
byte b = array3[k];
while (k > 0)
{
array3[k] = array3[k - 1];
k--;
}
array3[0] = b;
byte_2[i] = b;
}
for (int l = 0; l < num2; l++)
{
int num4 = method_9(5);
for (int i = 0; i < num; i++)
{
while (method_9(1) == 1)
{
num4 = ((method_9(1) != 0) ? (num4 - 1) : (num4 + 1));
}
array[l][i] = (char)num4;
}
}
for (int l = 0; l < num2; l++)
{
int num5 = 32;
int num6 = 0;
for (int i = 0; i < num; i++)
{
num6 = Math.Max(num6, array[l][i]);
num5 = Math.Min(num5, array[l][i]);
}
smethod_4(int_15[l], int_16[l], int_17[l], array[l], num5, num6, num);
int_18[l] = num5;
}
}
private void method_14()
{
int num = 1;
byte[] array = new byte[256];
int num2 = 100000 * int_9;
int_8 = method_11(24);
method_13();
int num3 = int_12 + 1;
int num4 = -1;
int num5 = 0;
for (int i = 0; i <= 255; i++)
{
int_14[i] = 0;
}
for (int i = 0; i <= 255; i++)
{
array[i] = (byte)i;
}
int_7 = -1;
if (num5 == 0)
{
num4++;
num5 = 50;
}
num5--;
int num6 = byte_2[num4];
int num7 = int_18[num6];
int num8 = method_9(num7);
while (true)
{
if (num8 > int_15[num6][num7])
{
if (num7 > 20)
{
break;
}
num7++;
while (int_11 < 1)
{
method_8();
}
int num9 = (int_10 >> int_11 - 1) & 1;
int_11--;
num8 = ((num8 << 1) | num9);
continue;
}
if (num8 - int_16[num6][num7] < 0 || num8 - int_16[num6][num7] >= 258)
{
throw new GException22("Bzip data error");
}
int num10 = int_17[num6][num8 - int_16[num6][num7]];
while (num10 != num3)
{
if (num10 == 0 || num10 == 1)
{
int num11 = -1;
int num12 = 1;
do
{
if (num10 != 0)
{
if (num10 == 1)
{
num11 += 2 * num12;
}
}
else
{
num11 += num12;
}
num12 <<= 1;
if (num5 == 0)
{
num4++;
num5 = 50;
}
num5--;
num6 = byte_2[num4];
num7 = int_18[num6];
num8 = method_9(num7);
while (num8 > int_15[num6][num7])
{
num7++;
while (int_11 < 1)
{
method_8();
}
int num9 = (int_10 >> int_11 - 1) & 1;
int_11--;
num8 = ((num8 << 1) | num9);
}
num10 = int_17[num6][num8 - int_16[num6][num7]];
}
while (num10 == 0 || num10 == 1);
num11++;
byte b = byte_0[array[0]];
int_14[b] += num11;
while (num11 > 0)
{
int_7++;
byte_4[int_7] = b;
num11--;
}
if (int_7 >= num2)
{
smethod_1();
}
continue;
}
int_7++;
if (int_7 >= num2)
{
smethod_1();
}
byte b2 = array[num10 - 1];
int_14[byte_0[b2]]++;
byte_4[int_7] = byte_0[b2];
for (int num13 = num10 - 1; num13 > 0; num13--)
{
array[num13] = array[num13 - 1];
}
array[0] = b2;
if (num5 == 0)
{
num4++;
num5 = 50;
}
num5--;
num6 = byte_2[num4];
num7 = int_18[num6];
num8 = method_9(num7);
while (num8 > int_15[num6][num7])
{
num7++;
while (int_11 < 1)
{
method_8();
}
int num9 = (int_10 >> int_11 - 1) & 1;
int_11--;
num8 = ((num8 << 1) | num9);
}
num10 = int_17[num6][num8 - int_16[num6][num7]];
}
return;
}
throw new GException22("Bzip data error");
}
private void method_15()
{
int[] array = new int[257];
array[0] = 0;
Array.Copy(int_14, 0, array, 1, 256);
for (int i = 1; i <= 256; i++)
{
array[i] += array[i - 1];
}
for (int i = 0; i <= int_7; i++)
{
byte b = byte_4[i];
int_13[array[b]] = i;
array[b]++;
}
array = null;
int_27 = int_13[int_8];
int_24 = 0;
int_30 = 0;
int_26 = 256;
if (bool_0)
{
int_28 = 0;
int_29 = 0;
method_16();
}
else
{
method_17();
}
}
private void method_16()
{
if (int_30 <= int_7)
{
int_25 = int_26;
int_26 = byte_4[int_27];
int_27 = int_13[int_27];
if (int_28 == 0)
{
int_28 = Class220.int_10[int_29];
int_29++;
if (int_29 == 512)
{
int_29 = 0;
}
}
int_28--;
int_26 ^= ((int_28 == 1) ? 1 : 0);
int_30++;
int_19 = int_26;
int_20 = 3;
ginterface25_0.imethod_2(int_26);
}
else
{
method_5();
method_4();
method_15();
}
}
private void method_17()
{
if (int_30 <= int_7)
{
int_25 = int_26;
int_26 = byte_4[int_27];
int_27 = int_13[int_27];
int_30++;
int_19 = int_26;
int_20 = 6;
ginterface25_0.imethod_2(int_26);
}
else
{
method_5();
method_4();
method_15();
}
}
private void method_18()
{
if (int_26 != int_25)
{
int_20 = 2;
int_24 = 1;
method_16();
return;
}
int_24++;
if (int_24 >= 4)
{
byte_5 = byte_4[int_27];
int_27 = int_13[int_27];
if (int_28 == 0)
{
int_28 = Class220.int_10[int_29];
int_29++;
if (int_29 == 512)
{
int_29 = 0;
}
}
int_28--;
byte_5 ^= (byte)((int_28 == 1) ? 1 : 0);
int_31 = 0;
int_20 = 4;
method_19();
}
else
{
int_20 = 2;
method_16();
}
}
private void method_19()
{
if (int_31 < byte_5)
{
int_19 = int_26;
ginterface25_0.imethod_2(int_26);
int_31++;
}
else
{
int_20 = 2;
int_30++;
int_24 = 0;
method_16();
}
}
private void method_20()
{
if (int_26 != int_25)
{
int_20 = 5;
int_24 = 1;
method_17();
return;
}
int_24++;
if (int_24 >= 4)
{
byte_5 = byte_4[int_27];
int_27 = int_13[int_27];
int_20 = 7;
int_31 = 0;
method_21();
}
else
{
int_20 = 5;
method_17();
}
}
private void method_21()
{
if (int_31 < byte_5)
{
int_19 = int_26;
ginterface25_0.imethod_2(int_26);
int_31++;
}
else
{
int_20 = 5;
int_30++;
int_24 = 0;
method_17();
}
}
private void method_22(int int_32)
{
int num = 8;
if (0 > int_32 || int_32 > 9 || 0 > int_9 || int_9 > 9)
{
throw new GException22("Invalid block size");
}
int_9 = int_32;
if (int_32 != 0)
{
int num2 = 100000 * int_32;
byte_4 = new byte[num2];
int_13 = new int[num2];
}
}
private static void smethod_0()
{
throw new EndOfStreamException("BZip2 input stream end of compressed stream");
}
private static void smethod_1()
{
throw new GException22("BZip2 input stream block overrun");
}
private static void smethod_2()
{
throw new GException22("BZip2 input stream bad block header");
}
private static void smethod_3()
{
throw new GException22("BZip2 input stream crc error");
}
private static void smethod_4(int[] int_32, int[] int_33, int[] int_34, char[] char_0, int int_35, int int_36, int int_37)
{
int num = 0;
for (int i = int_35; i <= int_36; i++)
{
for (int j = 0; j < int_37; j++)
{
if (char_0[j] == i)
{
int_34[num] = j;
num++;
}
}
}
for (int i = 0; i < 23; i++)
{
int_33[i] = 0;
}
for (int i = 0; i < int_37; i++)
{
int_33[char_0[i] + 1]++;
}
for (int i = 1; i < 23; i++)
{
int_33[i] += int_33[i - 1];
}
for (int i = 0; i < 23; i++)
{
int_32[i] = 0;
}
int num2 = 0;
for (int i = int_35; i <= int_36; i++)
{
num2 += int_33[i + 1] - int_33[i];
int_32[i] = num2 - 1;
num2 <<= 1;
}
for (int i = int_35 + 1; i <= int_36; i++)
{
int_33[i] = (int_32[i - 1] + 1 << 1) - int_33[i];
}
}
}
}
| 17.355972 | 124 | 0.506612 | [
"MIT"
] | h1213159982/HDF | Example/WinForm/Editor/DCWriter/DCSoft.Writer.Cleaned/DCSoftDotfuscate/GStream8.cs | 14,822 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.Text;
using System.Threading.Tasks;
namespace System.ServiceModel.Dispatcher
{
internal class ImmutableDispatchRuntime
{
readonly private int _correlationCount;
readonly private ConcurrencyBehavior _concurrency;
readonly private IDemuxer _demuxer;
readonly private ErrorBehavior _error;
private readonly bool _enableFaults;
private InstanceBehavior _instance;
private readonly bool _manualAddressing;
private readonly ThreadBehavior _thread;
private readonly bool _validateMustUnderstand;
private readonly bool _sendAsynchronously;
private readonly MessageRpcProcessor _processMessage1;
private readonly MessageRpcProcessor _processMessage11;
private readonly MessageRpcProcessor _processMessage2;
private readonly MessageRpcProcessor _processMessage3;
private readonly MessageRpcProcessor _processMessage31;
private readonly MessageRpcProcessor _processMessage4;
private readonly MessageRpcProcessor _processMessage41;
private readonly MessageRpcProcessor _processMessage5;
private readonly MessageRpcProcessor _processMessage6;
private readonly MessageRpcProcessor _processMessage7;
private readonly MessageRpcProcessor _processMessage8;
private readonly MessageRpcProcessor _processMessage9;
private readonly MessageRpcProcessor _processMessageCleanup;
private readonly MessageRpcProcessor _processMessageCleanupError;
private static AsyncCallback s_onReplyCompleted = Fx.ThunkCallback(new AsyncCallback(OnReplyCompletedCallback));
internal ImmutableDispatchRuntime(DispatchRuntime dispatch)
{
_concurrency = new ConcurrencyBehavior(dispatch);
_error = new ErrorBehavior(dispatch.ChannelDispatcher);
_enableFaults = dispatch.EnableFaults;
_instance = new InstanceBehavior(dispatch, this);
_manualAddressing = dispatch.ManualAddressing;
_thread = new ThreadBehavior(dispatch);
_sendAsynchronously = dispatch.ChannelDispatcher.SendAsynchronously;
_correlationCount = dispatch.MaxParameterInspectors;
DispatchOperationRuntime unhandled = new DispatchOperationRuntime(dispatch.UnhandledDispatchOperation, this);
ActionDemuxer demuxer = new ActionDemuxer();
for (int i = 0; i < dispatch.Operations.Count; i++)
{
DispatchOperation operation = dispatch.Operations[i];
DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this);
demuxer.Add(operation.Action, operationRuntime);
}
demuxer.SetUnhandled(unhandled);
_demuxer = demuxer;
_processMessage1 = ProcessMessage1;
_processMessage11 = ProcessMessage11;
_processMessage2 = ProcessMessage2;
_processMessage3 = ProcessMessage3;
_processMessage31 = ProcessMessage31;
_processMessage4 = ProcessMessage4;
_processMessage41 = ProcessMessage41;
_processMessage5 = ProcessMessage5;
_processMessage6 = ProcessMessage6;
_processMessage7 = ProcessMessage7;
_processMessage8 = ProcessMessage8;
_processMessage9 = ProcessMessage9;
_processMessageCleanup = ProcessMessageCleanup;
_processMessageCleanupError = ProcessMessageCleanupError;
}
internal int CorrelationCount
{
get { return _correlationCount; }
}
internal bool EnableFaults
{
get { return _enableFaults; }
}
internal bool ManualAddressing
{
get { return _manualAddressing; }
}
internal bool ValidateMustUnderstand
{
get { return _validateMustUnderstand; }
}
internal void AfterReceiveRequest(ref MessageRpc rpc)
{
// IDispatchMessageInspector would normally be called here. That interface isn't in contract.
}
private void Reply(ref MessageRpc rpc)
{
rpc.RequestContextThrewOnReply = true;
rpc.SuccessfullySendReply = false;
try
{
rpc.RequestContext.Reply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime());
rpc.RequestContextThrewOnReply = false;
rpc.SuccessfullySendReply = true;
if (WcfEventSource.Instance.DispatchMessageStopIsEnabled())
{
WcfEventSource.Instance.DispatchMessageStop(rpc.EventTraceActivity);
}
}
catch (CommunicationException e)
{
_error.HandleError(e);
}
catch (TimeoutException e)
{
_error.HandleError(e);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!_error.HandleError(e))
{
rpc.RequestContextThrewOnReply = true;
rpc.CanSendReply = false;
}
}
}
private void BeginReply(ref MessageRpc rpc)
{
bool success = false;
try
{
IResumeMessageRpc resume = rpc.Pause();
rpc.AsyncResult = rpc.RequestContext.BeginReply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime(),
s_onReplyCompleted, resume);
success = true;
if (rpc.AsyncResult.CompletedSynchronously)
{
rpc.UnPause();
}
}
catch (CommunicationException e)
{
_error.HandleError(e);
}
catch (TimeoutException e)
{
_error.HandleError(e);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!_error.HandleError(e))
{
rpc.RequestContextThrewOnReply = true;
rpc.CanSendReply = false;
}
}
finally
{
if (!success)
{
rpc.UnPause();
}
}
}
internal bool Dispatch(ref MessageRpc rpc, bool isOperationContextSet)
{
rpc.ErrorProcessor = _processMessage8;
rpc.NextProcessor = _processMessage1;
return rpc.Process(isOperationContextSet);
}
private bool EndReply(ref MessageRpc rpc)
{
bool success = false;
try
{
rpc.RequestContext.EndReply(rpc.AsyncResult);
rpc.RequestContextThrewOnReply = false;
success = true;
if (WcfEventSource.Instance.DispatchMessageStopIsEnabled())
{
WcfEventSource.Instance.DispatchMessageStop(rpc.EventTraceActivity);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
return success;
}
private void SetActivityIdOnThread(ref MessageRpc rpc)
{
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null)
{
// Propogate the ActivityId to the service operation
EventTraceActivityHelper.SetOnThread(rpc.EventTraceActivity);
}
}
private void TransferChannelFromPendingList(ref MessageRpc rpc)
{
if (rpc.Channel.IsPending)
{
rpc.Channel.IsPending = false;
ChannelDispatcher channelDispatcher = rpc.Channel.ChannelDispatcher;
IInstanceContextProvider provider = _instance.InstanceContextProvider;
if (!InstanceContextProviderBase.IsProviderSessionful(provider) &&
!InstanceContextProviderBase.IsProviderSingleton(provider))
{
IChannel proxy = rpc.Channel.Proxy as IChannel;
if (!rpc.InstanceContext.IncomingChannels.Contains(proxy))
{
channelDispatcher.Channels.Add(proxy);
}
}
channelDispatcher.PendingChannels.Remove(rpc.Channel.Binder.Channel);
}
}
private void AddMessageProperties(Message message, OperationContext context, ServiceChannel replyChannel)
{
if (context.InternalServiceChannel == replyChannel)
{
if (context.HasOutgoingMessageHeaders)
{
message.Headers.CopyHeadersFrom(context.OutgoingMessageHeaders);
}
if (context.HasOutgoingMessageProperties)
{
message.Properties.MergeProperties(context.OutgoingMessageProperties);
}
}
}
private static void OnReplyCompletedCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
IResumeMessageRpc resume = result.AsyncState as IResumeMessageRpc;
if (resume == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SRServiceModel.SFxInvalidAsyncResultState0);
}
resume.Resume(result);
}
private void PrepareReply(ref MessageRpc rpc)
{
RequestContext context = rpc.OperationContext.RequestContext;
Exception exception = null;
bool thereIsAnUnhandledException = false;
if (!rpc.Operation.IsOneWay)
{
if ((context != null) && (rpc.Reply != null))
{
try
{
rpc.CanSendReply = PrepareAndAddressReply(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
thereIsAnUnhandledException = !_error.HandleError(e);
exception = e;
}
}
}
if (rpc.Operation.IsOneWay)
{
rpc.CanSendReply = false;
}
if (!rpc.Operation.IsOneWay && (context != null) && (rpc.Reply != null))
{
if (exception != null)
{
// We don't call ProvideFault again, since we have already passed the
// point where SFx addresses the reply, and it is reasonable for
// ProvideFault to expect that SFx will address the reply. Instead
// we always just do 'internal server error' processing.
rpc.Error = exception;
_error.ProvideOnlyFaultOfLastResort(ref rpc);
try
{
rpc.CanSendReply = PrepareAndAddressReply(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
}
}
else if ((exception != null) && thereIsAnUnhandledException)
{
rpc.Abort();
}
}
private bool PrepareAndAddressReply(ref MessageRpc rpc)
{
bool canSendReply = true;
if (!_manualAddressing)
{
if (!object.ReferenceEquals(rpc.RequestID, null))
{
System.ServiceModel.Channels.RequestReplyCorrelator.PrepareReply(rpc.Reply, rpc.RequestID);
}
if (!rpc.Channel.HasSession)
{
canSendReply = System.ServiceModel.Channels.RequestReplyCorrelator.AddressReply(rpc.Reply, rpc.ReplyToInfo);
}
}
AddMessageProperties(rpc.Reply, rpc.OperationContext, rpc.Channel);
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null)
{
rpc.Reply.Properties[EventTraceActivity.Name] = rpc.EventTraceActivity;
}
return canSendReply;
}
internal DispatchOperationRuntime GetOperation(ref Message message)
{
return _demuxer.GetOperation(ref message);
}
private interface IDemuxer
{
DispatchOperationRuntime GetOperation(ref Message request);
}
internal bool IsConcurrent(ref MessageRpc rpc)
{
return _concurrency.IsConcurrent(ref rpc);
}
internal void ProcessMessage1(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage11;
if (!rpc.IsPaused)
{
ProcessMessage11(ref rpc);
}
}
internal void ProcessMessage11(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage2;
if (rpc.Operation.IsOneWay)
{
rpc.RequestContext.Reply(null);
rpc.OperationContext.RequestContext = null;
}
else
{
if (!rpc.Channel.IsReplyChannel &&
((object)rpc.RequestID == null) &&
(rpc.Operation.Action != MessageHeaders.WildcardAction))
{
CommunicationException error = new CommunicationException(SRServiceModel.SFxOneWayMessageToTwoWayMethod0);
throw TraceUtility.ThrowHelperError(error, rpc.Request);
}
if (!_manualAddressing)
{
EndpointAddress replyTo = rpc.ReplyToInfo.ReplyTo;
if (replyTo != null && replyTo.IsNone && rpc.Channel.IsReplyChannel)
{
CommunicationException error = new CommunicationException(SRServiceModel.SFxRequestReplyNone);
throw TraceUtility.ThrowHelperError(error, rpc.Request);
}
}
}
if (_concurrency.IsConcurrent(ref rpc))
{
rpc.Channel.IncrementActivity();
rpc.SuccessfullyIncrementedActivity = true;
}
_instance.EnsureInstanceContext(ref rpc);
this.TransferChannelFromPendingList(ref rpc);
if (!rpc.IsPaused)
{
this.ProcessMessage2(ref rpc);
}
}
private void ProcessMessage2(ref MessageRpc rpc)
{
// Run dispatch message inspectors
rpc.NextProcessor = _processMessage3;
this.AfterReceiveRequest(ref rpc);
_concurrency.LockInstance(ref rpc);
if (!rpc.IsPaused)
{
this.ProcessMessage3(ref rpc);
}
}
private void ProcessMessage3(ref MessageRpc rpc)
{
// Manage transactions, can likely go away
rpc.NextProcessor = _processMessage31;
rpc.SuccessfullyLockedInstance = true;
if (!rpc.IsPaused)
{
this.ProcessMessage31(ref rpc);
}
}
private void ProcessMessage31(ref MessageRpc rpc)
{
// More transaction stuff, can likely go away
rpc.NextProcessor = _processMessage4;
if (!rpc.IsPaused)
{
this.ProcessMessage4(ref rpc);
}
}
private void ProcessMessage4(ref MessageRpc rpc)
{
// Bind request to synchronization context if needed
rpc.NextProcessor = _processMessage41;
try
{
_thread.BindThread(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
}
if (!rpc.IsPaused)
{
this.ProcessMessage41(ref rpc);
}
}
private void ProcessMessage41(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage5;
// This needs to happen after LockInstance--LockInstance guarantees
// in-order delivery, so we can't receive the next message until we
// have acquired the lock.
//
// This also needs to happen after BindThread, since
// running on UI thread should guarantee in-order delivery if
// the SynchronizationContext is single threaded.
if (_concurrency.IsConcurrent(ref rpc))
{
rpc.EnsureReceive();
}
_instance.EnsureServiceInstance(ref rpc);
if (!rpc.IsPaused)
{
this.ProcessMessage5(ref rpc);
}
}
private void ProcessMessage5(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage6;
bool success = false;
try
{
// If async call completes in sync, it tells us through the gate below
rpc.PrepareInvokeContinueGate();
SetActivityIdOnThread(ref rpc);
rpc.Operation.InvokeBegin(ref rpc);
success = true;
}
finally
{
try
{
if (rpc.IsPaused)
{
// Check if the callback produced the async result and set it back on the RPC on this stack
// and proceed only if the gate was signaled by the callback and completed synchronously
if (rpc.UnlockInvokeContinueGate(out rpc.AsyncResult))
{
rpc.UnPause();
}
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (success && !rpc.IsPaused)
{
throw;
}
_error.HandleError(e);
}
}
// Proceed if rpc is unpaused and invoke begin was successful.
if (!rpc.IsPaused)
{
this.ProcessMessage6(ref rpc);
}
}
private void ProcessMessage6(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage7;
try
{
_thread.BindEndThread(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
}
if (!rpc.IsPaused)
{
this.ProcessMessage7(ref rpc);
}
}
private void ProcessMessage7(ref MessageRpc rpc)
{
rpc.NextProcessor = null;
rpc.Operation.InvokeEnd(ref rpc);
// this never pauses
this.ProcessMessage8(ref rpc);
}
private void ProcessMessage8(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage9;
try
{
_error.ProvideMessageFault(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
this.PrepareReply(ref rpc);
if (rpc.CanSendReply)
{
rpc.ReplyTimeoutHelper = new TimeoutHelper(rpc.Channel.OperationTimeout);
}
if (!rpc.IsPaused)
{
this.ProcessMessage9(ref rpc);
}
}
private void ProcessMessage9(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessageCleanup;
if (rpc.CanSendReply)
{
if (rpc.Reply != null)
{
TraceUtility.MessageFlowAtMessageSent(rpc.Reply, rpc.EventTraceActivity);
}
if (_sendAsynchronously)
{
this.BeginReply(ref rpc);
}
else
{
this.Reply(ref rpc);
}
}
if (!rpc.IsPaused)
{
this.ProcessMessageCleanup(ref rpc);
}
}
private void ProcessMessageCleanup(ref MessageRpc rpc)
{
Fx.Assert(
!object.ReferenceEquals(rpc.ErrorProcessor, _processMessageCleanupError),
"ProcessMessageCleanup run twice on the same MessageRpc!");
rpc.ErrorProcessor = _processMessageCleanupError;
bool replyWasSent = false;
if (rpc.CanSendReply)
{
if (_sendAsynchronously)
{
replyWasSent = this.EndReply(ref rpc);
}
else
{
replyWasSent = rpc.SuccessfullySendReply;
}
}
try
{
try
{
if (rpc.DidDeserializeRequestBody)
{
rpc.Request.Close();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
rpc.DisposeParameters(false); //Dispose all input/output/return parameters
if (rpc.FaultInfo.IsConsideredUnhandled)
{
if (!replyWasSent)
{
rpc.AbortRequestContext();
rpc.AbortChannel();
}
else
{
rpc.CloseRequestContext();
rpc.CloseChannel();
}
rpc.AbortInstanceContext();
}
else
{
if (rpc.RequestContextThrewOnReply)
{
rpc.AbortRequestContext();
}
else
{
rpc.CloseRequestContext();
}
}
if ((rpc.Reply != null) && (rpc.Reply != rpc.ReturnParameter))
{
try
{
rpc.Reply.Close();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
}
if ((rpc.FaultInfo.Fault != null) && (rpc.FaultInfo.Fault.State != MessageState.Closed))
{
// maybe ProvideFault gave a Message, but then BeforeSendReply replaced it
// in that case, we need to close the one from ProvideFault
try
{
rpc.FaultInfo.Fault.Close();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
}
try
{
rpc.OperationContext.FireOperationCompleted();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
_instance.AfterReply(ref rpc, _error);
if (rpc.SuccessfullyLockedInstance)
{
try
{
_concurrency.UnlockInstance(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
Fx.Assert("Exceptions should be caught by callee");
rpc.InstanceContext.FaultInternal();
_error.HandleError(e);
}
}
if (rpc.SuccessfullyIncrementedActivity)
{
try
{
rpc.Channel.DecrementActivity();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
}
}
finally
{
if (rpc.Activity != null && DiagnosticUtility.ShouldUseActivity)
{
rpc.Activity.Stop();
}
}
_error.HandleError(ref rpc);
}
private void ProcessMessageCleanupError(ref MessageRpc rpc)
{
_error.HandleError(ref rpc);
}
private class ActionDemuxer : IDemuxer
{
private readonly HybridDictionary _map;
private DispatchOperationRuntime _unhandled;
internal ActionDemuxer()
{
_map = new HybridDictionary();
}
internal void Add(string action, DispatchOperationRuntime operation)
{
if (_map.Contains(action))
{
DispatchOperationRuntime existingOperation = (DispatchOperationRuntime)_map[action];
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxActionDemuxerDuplicate, existingOperation.Name, operation.Name, action)));
}
_map.Add(action, operation);
}
internal void SetUnhandled(DispatchOperationRuntime operation)
{
_unhandled = operation;
}
public DispatchOperationRuntime GetOperation(ref Message request)
{
string action = request.Headers.Action;
if (action == null)
{
action = MessageHeaders.WildcardAction;
}
DispatchOperationRuntime operation = (DispatchOperationRuntime)_map[action];
if (operation != null)
{
return operation;
}
return _unhandled;
}
}
}
}
| 31.940265 | 214 | 0.487047 | [
"MIT"
] | Bencargs/wcf | src/dotnet-svcutil/lib/src/FrameworkFork/System.ServiceModel/System/ServiceModel/Dispatcher/ImmutableDispatchRuntime.cs | 28,874 | C# |
using System.Threading;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Universalis.Application.Uploads.Schema;
using Universalis.Entities.Uploads;
namespace Universalis.Application.Uploads.Behaviors
{
public interface IUploadBehavior
{
/// <summary>
/// Whether or not this upload behavior should be executed.
/// </summary>
/// <param name="parameters">The request parameters.</param>
/// <returns><see langword="true" /> if the behavior should be executed, otherwise <see langword="false" />.</returns>
public bool ShouldExecute(UploadParameters parameters);
/// <summary>
/// Executes the upload behavior.
/// </summary>
/// <param name="source">The upload application.</param>
/// <param name="parameters">The request parameters.</param>
/// <param name="cancellationToken"></param>
/// <returns>An <see cref="IActionResult"/> if the request should return early, or <see langword="null" /> if the request should continue.</returns>
public Task<IActionResult> Execute(TrustedSource source, UploadParameters parameters, CancellationToken cancellationToken = default);
}
} | 45.222222 | 156 | 0.683047 | [
"MIT"
] | Universalis-FFXIV/Universalis | src/Universalis.Application/Uploads/Behaviors/IUploadBehavior.cs | 1,223 | C# |
// FILE AUTOGENERATED. DO NOT MODIFY
using System;
namespace Starfield.Core.Block.Blocks {
[Block("minecraft:stonecutter", 676, 14854, 14857, 14854)]
public class BlockStonecutter : BlockBase {
public override ushort State {
get {
if(Facing == "north") {
return 14854;
}
if(Facing == "south") {
return 14855;
}
if(Facing == "west") {
return 14856;
}
if(Facing == "east") {
return 14857;
}
return DefaultState;
}
set {
if(value == 14854) {
Facing = "north";
}
if(value == 14855) {
Facing = "south";
}
if(value == 14856) {
Facing = "west";
}
if(value == 14857) {
Facing = "east";
}
}
}
public string Facing { get; set; } = "north";
public BlockStonecutter() {
State = DefaultState;
}
public BlockStonecutter(ushort state) : base(state) {
if(state < MinimumState || state > MaximumState) {
throw new ArgumentOutOfRangeException("state");
}
State = state;
}
public BlockStonecutter(string facing) {
Facing = facing;
}
}
} | 24.132353 | 64 | 0.381475 | [
"MIT"
] | StarfieldMC/Starfield | Starfield.Core/Block/Blocks/BlockStonecutter.cs | 1,641 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Consumption.Test.ScenarioTests.ScenarioTest;
using Microsoft.Azure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
namespace Microsoft.Azure.Commands.Consumption.Test.ScenarioTests
{
public class UsageDetailsTests
{
private ServiceManagemenet.Common.Models.XunitTracingInterceptor _logger;
public UsageDetailsTests(Xunit.Abstractions.ITestOutputHelper output)
{
_logger = new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output);
ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(_logger);
TestExecutionHelpers.SetUpSessionAndProfile();
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestListUsageDetails()
{
TestController.NewInstance.RunPowerShellTest(_logger, "Test-ListUsageDetails");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestListUsageDetailsWithExpand()
{
TestController.NewInstance.RunPowerShellTest(_logger, "Test-ListUsageDetailsWithExpand");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestListUsageDetailsWithFilter()
{
TestController.NewInstance.RunPowerShellTest(_logger, "Test-ListUsageDetailsWithFilter");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestListInvoiceUsageDetails()
{
TestController.NewInstance.RunPowerShellTest(_logger, "Test-ListInvoiceUsageDetails");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestListInvoiceUsageDetailsWithExpand()
{
TestController.NewInstance.RunPowerShellTest(_logger, "Test-ListInvoiceUsageDetailsWithExpand");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestListInvoiceUsageDetailsWithFilter()
{
TestController.NewInstance.RunPowerShellTest(_logger, "Test-ListInvoiceUsageDetailsWithFilter");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestListBillingPeriodUsageDetails()
{
TestController.NewInstance.RunPowerShellTest(_logger, "Test-ListBillingPeriodUsageDetails");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestListBillingPeriodUsageDetailsWithExpand()
{
TestController.NewInstance.RunPowerShellTest(_logger, "Test-ListBillingPeriodUsageDetailsWithExpand");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestListBillingPeriodUsageDetailsWithFilter()
{
TestController.NewInstance.RunPowerShellTest(_logger, "Test-ListBillingPeriodUsageDetailsWithFilter");
}
}
}
| 39.72449 | 115 | 0.655536 | [
"MIT"
] | AzureDataBox/azure-powershell | src/ResourceManager/Consumption/Commands.Consumption.Test/ScenarioTests/UsageDetailsTests.cs | 3,798 | C# |
using Amazon;
using Amazon.CloudFront;
using Amazon.Runtime;
using Autofac;
namespace MountAws.Services.Cloudfront;
public class CloudfrontRegistrar : IServiceRegistrar
{
public void Register(ContainerBuilder builder)
{
builder.RegisterType<AmazonCloudFrontClient>().As<IAmazonCloudFront>()
.UsingConstructor(typeof(AWSCredentials), typeof(RegionEndpoint));
}
} | 26.333333 | 78 | 0.762025 | [
"Apache-2.0"
] | andyalm/mount-aws | MountAws/Services/Cloudfront/CloudfrontRegistrar.cs | 395 | C# |
using System.Collections.Generic;
using Fabric.Identity.API.Infrastructure.QueryStringBinding;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Primitives;
using Xunit;
namespace Fabric.Identity.UnitTests
{
public class SeparatedQueryStringValueProviderTests
{
private static QueryCollection GetQueryStringValues()
{
var userIdString =
new StringValues(
"hqcatalyst\\foo.bar:windows,hqcatalyst\\foo.bar1:windows,hqcatalyst\\foo.bar2:windows,hqcatalyst\\foo.bar3:windows");
var queryString = new Dictionary<string, StringValues>();
queryString.Add("clientid", new StringValues("foo"));
queryString.Add("userids", userIdString);
queryString.Add("empty", string.Empty);
return new QueryCollection(queryString);
}
public static IEnumerable<object[]> GetQueryStringProviders()
{
yield return new object[]
{
new SeparatedQueryStringValueProvider(GetQueryStringValues(), ","), "userids", 4,
"no const key - query string was not split by comma"
};
yield return new object[]
{
new SeparatedQueryStringValueProvider("userids", GetQueryStringValues(), ","), "userids", 4,
"query string was not split by comma"
};
yield return new object[]
{
new SeparatedQueryStringValueProvider(GetQueryStringValues(), ","), "foo", 0,
"no const key - no values should be found when key is not in querystring"
};
yield return new object[]
{
new SeparatedQueryStringValueProvider("foo", GetQueryStringValues(), ","), "foo", 0,
"no values should be found when key is not in querystring"
};
yield return new object[]
{
new SeparatedQueryStringValueProvider(new QueryCollection(), ","), "foo", 0,
"no const key - no values should be found when query string is empty"
};
yield return new object[]
{
new SeparatedQueryStringValueProvider("foo", new QueryCollection(), ","), "foo", 0,
"no values should be found when query string is empty"
};
yield return new object[]
{
new SeparatedQueryStringValueProvider(GetQueryStringValues(), "-"), "userids", 1,
"no const key - no values should be found when separator is not in query string value"
};
yield return new object[]
{
new SeparatedQueryStringValueProvider("userids", GetQueryStringValues(), "-"), "userids", 1,
"no values should be found when separator is not in query string value"
};
yield return new object[]
{
new SeparatedQueryStringValueProvider("foo", GetQueryStringValues(), ","), "userids", 1,
"no separation should be done when key passed does not match const key"
};
yield return new object[]
{
new SeparatedQueryStringValueProvider(GetQueryStringValues(), ","), "empty", 1,
"a single empty value should be returned when query string value is empty"
};
}
[Theory]
[MemberData(nameof(GetQueryStringProviders))]
public void GetValue_Test(SeparatedQueryStringValueProvider separatedQueryStringValueProvider, string key,
int expectedResultCount, string message)
{
var results = separatedQueryStringValueProvider.GetValue(key);
Assert.True(expectedResultCount.Equals(results.Values.Count),
$"result count: {results.Values.Count} - {message}");
}
}
} | 44.258427 | 138 | 0.589236 | [
"Apache-2.0"
] | HealthCatalyst/Fabric.Identity | Fabric.Identity.UnitTests/SeparatedQueryStringValueProviderTests.cs | 3,941 | C# |
using Newtonsoft.Json;
namespace IctBaden.Api1NCE.Models
{
public class ProductInformation
{
[JsonProperty("product_id")]
public long ProductId { get; set; }
/// <summary>
/// Quantity of SIM with this product ordered
/// </summary>
[JsonProperty("quantity")]
public long Quantity { get; set; }
}
} | 24.466667 | 53 | 0.594005 | [
"MIT"
] | FrankPfattheicher/IctBaden.1NCE | src/IctBaden.1NCE/Models/ProductInformation.cs | 367 | C# |
namespace Tewirai.Models
{
public class CqCoreConfig
{
public string WorkingDirectory { get; set; }
public string ExcutableName { get; set; }
public uint WsListenPort { get; set; }
}
}
| 22.2 | 52 | 0.621622 | [
"MIT"
] | DCTewi/Tewirai | Models/CqCoreConfig.cs | 224 | C# |
using Moq;
using NUnit.Framework;
using Parse;
using Parse.Internal;
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
// TODO (hallucinogen): mock ParseACL, ParseObject, ParseUser once we have their Interfaces
namespace ParseTest {
[TestFixture]
public class EncoderTests {
/// <summary>
/// A <see cref="ParseEncoder"/> that's used only for testing. This class is used to test
/// <see cref="ParseEncoder"/>'s base methods.
/// </summary>
private class ParseEncoderTestClass : ParseEncoder {
private static readonly ParseEncoderTestClass instance = new ParseEncoderTestClass();
public static ParseEncoderTestClass Instance {
get {
return instance;
}
}
protected override IDictionary<string, object> EncodeParseObject(ParseObject value) {
return null;
}
}
[Test]
public void TestIsValidType() {
Assert.IsTrue(ParseEncoder.IsValidType(322));
Assert.IsTrue(ParseEncoder.IsValidType(0.3f));
Assert.IsTrue(ParseEncoder.IsValidType(new byte[]{ 1, 2, 3, 4 }));
Assert.IsTrue(ParseEncoder.IsValidType("corgi"));
Assert.IsTrue(ParseEncoder.IsValidType(new ParseObject("Corgi")));
Assert.IsTrue(ParseEncoder.IsValidType(new ParseACL()));
Assert.IsTrue(ParseEncoder.IsValidType(new ParseFile("Corgi", new byte[0])));
Assert.IsTrue(ParseEncoder.IsValidType(new ParseGeoPoint(1, 2)));
Assert.IsTrue(ParseEncoder.IsValidType(new ParseRelation<ParseObject>(new ParseObject("Corgi"), "corgi")));
Assert.IsTrue(ParseEncoder.IsValidType(new DateTime()));
Assert.IsTrue(ParseEncoder.IsValidType(new List<object>()));
Assert.IsTrue(ParseEncoder.IsValidType(new Dictionary<string, string>()));
Assert.IsTrue(ParseEncoder.IsValidType(new Dictionary<string, object>()));
Assert.IsFalse(ParseEncoder.IsValidType(new ParseAddOperation(new List<object>())));
Assert.IsFalse(ParseEncoder.IsValidType(Task<ParseObject>.FromResult(new ParseObject("Corgi"))));
Assert.Throws<MissingMethodException>(() => ParseEncoder.IsValidType(new Dictionary<object, object>()));
Assert.Throws<MissingMethodException>(() => ParseEncoder.IsValidType(new Dictionary<object, string>()));
}
[Test]
public void TestEncodeDate() {
DateTime dateTime = new DateTime(1990, 8, 30, 12, 3, 59);
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(dateTime) as IDictionary<string, object>;
Assert.AreEqual("Date", value["__type"]);
Assert.AreEqual("1990-08-30T12:03:59.000Z", value["iso"]);
}
[Test]
public void TestEncodeBytes() {
byte[] bytes = new byte[] { 1, 2, 3, 4 };
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(bytes) as IDictionary<string, object>;
Assert.AreEqual("Bytes", value["__type"]);
Assert.AreEqual(Convert.ToBase64String(new byte[] { 1, 2, 3, 4 }), value["base64"]);
}
[Test]
public void TestEncodeParseObjectWithNoObjectsEncoder() {
ParseObject obj = new ParseObject("Corgi");
Assert.Throws<ArgumentException>(() => NoObjectsEncoder.Instance.Encode(obj));
}
[Test]
public void TestEncodeParseObjectWithPointerOrLocalIdEncoder() {
// TODO (hallucinogen): we can't make an object with ID without saving for now. Let's revisit this after we make IParseObject
}
[Test]
public void TestEncodeParseFile() {
ParseFile file1 = new ParseFile("Corgi.png", new Uri("http://corgi.xyz/gogo.png"));
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(file1) as IDictionary<string, object>;
Assert.AreEqual("File", value["__type"]);
Assert.AreEqual("Corgi.png", value["name"]);
Assert.AreEqual("http://corgi.xyz/gogo.png", value["url"]);
ParseFile file2 = new ParseFile(null, new MemoryStream(new byte[] { 1, 2, 3, 4 }));
Assert.Throws<InvalidOperationException>(() => ParseEncoderTestClass.Instance.Encode(file2));
}
[Test]
public void TestEncodeParseGeoPoint() {
ParseGeoPoint point = new ParseGeoPoint(3.22, 32.2);
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(point) as IDictionary<string, object>;
Assert.AreEqual("GeoPoint", value["__type"]);
Assert.AreEqual(3.22, value["latitude"]);
Assert.AreEqual(32.2, value["longitude"]);
}
[Test]
public void TestEncodeACL() {
ParseACL acl1 = new ParseACL();
IDictionary<string, object> value1 = ParseEncoderTestClass.Instance.Encode(acl1) as IDictionary<string, object>;
Assert.IsNotNull(value1);
Assert.AreEqual(0, value1.Keys.Count);
ParseACL acl2 = new ParseACL();
acl2.PublicReadAccess = true;
acl2.PublicWriteAccess = true;
IDictionary<string, object> value2 = ParseEncoderTestClass.Instance.Encode(acl2) as IDictionary<string, object>;
Assert.AreEqual(1, value2.Keys.Count);
IDictionary<string, object> publicAccess = value2["*"] as IDictionary<string, object>;
Assert.AreEqual(2, publicAccess.Keys.Count);
Assert.IsTrue((bool)publicAccess["read"]);
Assert.IsTrue((bool)publicAccess["write"]);
// TODO (hallucinogen): mock ParseUser and test SetReadAccess and SetWriteAccess
}
[Test]
public void TestEncodeParseRelation() {
var obj = new ParseObject("Corgi");
ParseRelation<ParseObject> relation = new ParseRelation<ParseObject>(obj, "nano", "Husky");
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(relation) as IDictionary<string, object>;
Assert.AreEqual("Relation", value["__type"]);
Assert.AreEqual("Husky", value["className"]);
}
[Test]
public void TestEncodeParseFieldOperation() {
var incOps = new ParseIncrementOperation(1);
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(incOps) as IDictionary<string, object>;
Assert.AreEqual("Increment", value["__op"]);
Assert.AreEqual(1, value["amount"]);
// Other operations are tested in FieldOperationTests
}
[Test]
public void TestEncodeList() {
IList<object> list = new List<object>();
list.Add(new ParseGeoPoint(0, 0));
list.Add("item");
list.Add(new byte[] { 1, 2, 3, 4 });
list.Add(new string[] { "hikaru", "hanatan", "ultimate" });
list.Add(new Dictionary<string, object>() {
{ "elements", new int[] { 1, 2, 3 } },
{ "mystic", "cage" },
{ "listAgain", new List<object>() { "xilia", "zestiria", "symphonia" } }
});
IList<object> value = ParseEncoderTestClass.Instance.Encode(list) as IList<object>;
var item0 = value[0] as IDictionary<string, object>;
Assert.AreEqual("GeoPoint", item0["__type"]);
Assert.AreEqual(0.0, item0["latitude"]);
Assert.AreEqual(0.0, item0["longitude"]);
Assert.AreEqual("item", value[1]);
var item2 = value[2] as IDictionary<string, object>;
Assert.AreEqual("Bytes", item2["__type"]);
var item3 = value[3] as IList<object>;
Assert.AreEqual("hikaru", item3[0]);
Assert.AreEqual("hanatan", item3[1]);
Assert.AreEqual("ultimate", item3[2]);
var item4 = value[4] as IDictionary<string, object>;
Assert.IsTrue(item4["elements"] is IList<object>);
Assert.AreEqual("cage", item4["mystic"]);
Assert.IsTrue(item4["listAgain"] is IList<object>);
}
[Test]
public void TestEncodeDictionary() {
IDictionary<string, object> dict = new Dictionary<string, object>() {
{ "item", "random" },
{ "list", new List<object>(){ "vesperia", "abyss", "legendia" } },
{ "array", new int[] { 1, 2, 3 } },
{ "geo", new ParseGeoPoint(0, 0) },
{ "validDict", new Dictionary<string, object>(){ { "phantasia", "jbf" } } }
};
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(dict) as IDictionary<string, object>;
Assert.AreEqual("random", value["item"]);
Assert.IsTrue(value["list"] is IList<object>);
Assert.IsTrue(value["array"] is IList<object>);
Assert.IsTrue(value["geo"] is IDictionary<string, object>);
Assert.IsTrue(value["validDict"] is IDictionary<string, object>);
IDictionary<object, string> invalidDict = new Dictionary<object, string>();
Assert.Throws<MissingMethodException>(() => ParseEncoderTestClass.Instance.Encode(invalidDict));
IDictionary<string, object> childInvalidDict = new Dictionary<string, object>() {
{ "validDict", new Dictionary<object, string>(){ { new ParseACL(), "jbf" } } }
};
Assert.Throws<MissingMethodException>(() => ParseEncoderTestClass.Instance.Encode(childInvalidDict));
}
}
}
| 43.945274 | 131 | 0.670554 | [
"BSD-3-Clause"
] | Julien-Mialon/Parse-SDK-dotNET | ParseTest.Unit/EncoderTests.cs | 8,833 | C# |
// Copyright © 2020 Sovren Group, Inc. All rights reserved.
// This file is provided for use by, or on behalf of, Sovren licensees
// within the terms of their license of Sovren products or Sovren customers
// within the Terms of Service pertaining to the Sovren SaaS products.
using Sovren.Models.API.Matching.Request;
namespace Sovren.Models.API.Matching
{
/// <summary>
/// Request body for a search request
/// </summary>
public class SearchRequest : SearchMatchRequestBase
{
/// <summary>
/// Used to choose which results to return from the list.
/// </summary>
public PaginationSettings PaginationSettings { get; set; }
}
}
| 32.761905 | 75 | 0.688953 | [
"Apache-2.0"
] | sovren/sovren-dotnet | src/Sovren.SDK/Models/API/Matching/SearchRequest.cs | 689 | C# |
using Library.Domain.Core;
using Library.Service.Identity.Domain.DataAccessors;
using Library.Service.Inventory.Domain.DataAccessors;
using Library.Service.Rental.Domain.DataAccessors;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace Library.Service.Handler
{
public class AppsettingInventoryReadDBConnectionStringProvider : IInventoryReadDBConnectionStringProvider
{
private IConfigurationRoot _configuration = null;
public AppsettingInventoryReadDBConnectionStringProvider()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_configuration = builder.Build();
}
public string ConnectionString
{
get
{
return _configuration["inventoryReadDBConnectionString"];
}
}
}
public class AppsettingInventoryWriteDBConnectionStringProvider : IInventoryWriteDBConnectionStringProvider
{
private IConfigurationRoot _configuration = null;
public AppsettingInventoryWriteDBConnectionStringProvider()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_configuration = builder.Build();
}
public string ConnectionString
{
get
{
return _configuration["inventoryWriteDBConnectionString"];
}
}
}
public class AppsettingRentalReadDBConnectionStringProvider : IRentalReadDBConnectionStringProvider
{
private IConfigurationRoot _configuration = null;
public AppsettingRentalReadDBConnectionStringProvider()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_configuration = builder.Build();
}
public string ConnectionString
{
get
{
return _configuration["rentalReadDBConnectionString"];
}
}
}
public class AppsettingRentalWriteDBConnectionStringProvider : IRentalWriteDBConnectionStringProvider
{
private IConfigurationRoot _configuration = null;
public AppsettingRentalWriteDBConnectionStringProvider()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_configuration = builder.Build();
}
public string ConnectionString
{
get
{
return _configuration["rentalWriteDBConnectionString"];
}
}
}
public class AppsettingLogDBConnectionStringProvider : ILogDBConnectionStringProvider
{
private IConfigurationRoot _configuration = null;
public AppsettingLogDBConnectionStringProvider()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_configuration = builder.Build();
}
public string ConnectionString
{
get
{
return _configuration["logDBConnectionString"];
}
}
}
public class AppsettingIdentityReadDBConnectionStringProvider : IIdentityReadDBConnectionStringProvider
{
private IConfigurationRoot _configuration = null;
public AppsettingIdentityReadDBConnectionStringProvider()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_configuration = builder.Build();
}
public string ConnectionString
{
get
{
return _configuration["identityReadDBConnectionString"];
}
}
}
public class AppsettingIdentityWriteDBConnectionStringProvider : IIdentityWriteDBConnectionStringProvider
{
private IConfigurationRoot _configuration = null;
public AppsettingIdentityWriteDBConnectionStringProvider()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_configuration = builder.Build();
}
public string ConnectionString
{
get
{
return _configuration["identityWriteDBConnectionString"];
}
}
}
} | 25.447853 | 109 | 0.724928 | [
"Apache-2.0"
] | lamondlu/BookLibrary | src/Library.Service.Handler/AppsettingDBConnectionStringProvider.cs | 4,148 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Roslynator.CSharp.Refactorings.Tests
{
internal class ReplaceStringFormatWithInterpolatedStringRefactoring
{
public void Foo()
{
string name = "name";
string value = "value";
string s = string.Format("name: {0:f}, value: {1}", name, value);
s = string.Format("name: {0:f}, value: {1} \" {2}", "{\"name\"}", "{\"value\"}", (true) ? "" : "");
s = string.Format(@"name: {0:f}, value: {1} "" {2}", @"{""name""}", @"{""value""}", (true) ? "" : "");
s =
string.Format(
" {0} {1} {2} ",
s,
s,
s);
}
}
}
| 31.888889 | 160 | 0.478513 | [
"Apache-2.0"
] | ADIX7/Roslynator | src/Tests/Refactorings.Tests.Old/ReplaceStringFormatWithInterpolatedStringRefactoring.cs | 863 | C# |
using ScriptEngine.Machine.Contexts;
using System.Windows.Forms;
namespace osf
{
[ContextClass ("КлРежимОтображения", "ClView")]
public class ClView : AutoContext<ClView>
{
private int m_largeIcon = (int)View.LargeIcon; // 0 Каждый элемент отображается в виде полноразмерного значка с меткой под ним.
private int m_details = (int)View.Details; // 1 Каждый элемент отображается в отдельной строке. Дополнительные сведения о каждом элементе распределены по колонкам. Крайняя левая колонка содержит небольшой значок и метку, а последующие колонки содержат вложенные элементы. В колонке отображается заголовок. Пользователь может изменить размер каждой колонки.
private int m_smallIcon = (int)View.SmallIcon; // 2 Каждый элемент отображается в виде небольшого значка с меткой справа.
private int m_list = (int)View.List; // 3 Каждый элемент отображается в виде небольшого значка с меткой справа. Элементы располагаются в колонках без заголовков колонок.
[ContextProperty("БольшойЗначок", "LargeIcon")]
public int LargeIcon
{
get { return m_largeIcon; }
}
[ContextProperty("МаленькийЗначок", "SmallIcon")]
public int SmallIcon
{
get { return m_smallIcon; }
}
[ContextProperty("Подробно", "Details")]
public int Details
{
get { return m_details; }
}
[ContextProperty("Список", "List")]
public int List
{
get { return m_list; }
}
}
}
| 38.7 | 366 | 0.672481 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | EvilBeaver/OneScriptForms | cs/View.cs | 2,110 | C# |
using System;
class B
{
static void Main() => Console.WriteLine(new string('x', Console.ReadLine().Length));
}
| 17.142857 | 86 | 0.65 | [
"MIT"
] | sakapon/AtCoder-Contests | CSharp/Contests2020/ABC154/B.cs | 122 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the organizations-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Organizations.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Organizations.Model.Internal.MarshallTransformations
{
/// <summary>
/// LeaveOrganization Request Marshaller
/// </summary>
public class LeaveOrganizationRequestMarshaller : IMarshaller<IRequest, LeaveOrganizationRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((LeaveOrganizationRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(LeaveOrganizationRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Organizations");
string target = "AWSOrganizationsV20161128.LeaveOrganization";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28";
request.HttpMethod = "POST";
request.ResourcePath = "/";
var content = "{}";
request.Content = System.Text.Encoding.UTF8.GetBytes(content);
return request;
}
private static LeaveOrganizationRequestMarshaller _instance = new LeaveOrganizationRequestMarshaller();
internal static LeaveOrganizationRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static LeaveOrganizationRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.595506 | 149 | 0.652485 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Organizations/Generated/Model/Internal/MarshallTransformations/LeaveOrganizationRequestMarshaller.cs | 3,079 | C# |
using System.ComponentModel;
namespace Progress.Sitefinity.AspNetCore.Widgets.Models.Image
{
/// <summary>
/// The enum with the sizing modes of an image.
/// </summary>
public enum ImageDisplayMode
{
/// <summary>
/// The responsive.
/// </summary>
Responsive,
/// <summary>
/// Original size.
/// </summary>
[Description("Original size")]
OriginalSize,
/// <summary>
/// Use thumbnail.
/// </summary>
[Description("Use thumbnail")]
Thumbnail,
/// <summary>
/// Custom size.
/// </summary>
[Description("Custom size")]
CustomSize,
}
}
| 21.088235 | 61 | 0.509066 | [
"Apache-2.0"
] | Sitefinity/sitefinity-aspnetcore-mvc-widgets | Progress.Sitefinity.AspNetCore.Widgets/Models/Image/ImageDisplayMode.cs | 719 | C# |
using System;
namespace _8_2_1_Static_ZADACA
{
public class Static
{
private Static() { }
public static double Zbroj(double a, double b)
{
return a + b;
}
public static double Kub(double broj)
{
return broj * broj * broj;
}
public static double Udaljenost(double x1, double y1, double x2, double y2)
{
return Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
public static double Fahrenheit(double stupnjevaCelzijusa)
{
return ((double)9 / 5) * stupnjevaCelzijusa + 32;
}
}
} | 23.357143 | 83 | 0.519878 | [
"MIT"
] | staman1702/AlgebraCSharp2019-1 | ConsoleApp1/8_2_1_Static_ZADACA/Static.cs | 656 | C# |
using BrewLib.UserInterface;
using BrewLib.UserInterface.Skinning.Styles;
using BrewLib.Util;
using OpenTK;
using StorybrewEditor.ScreenLayers;
using StorybrewEditor.UserInterface.Skinning.Styles;
using System;
namespace StorybrewEditor.UserInterface
{
public class PathSelector : Widget
{
private PathSelectorMode mode;
private LinearLayout layout;
private Textbox textbox;
private Button button;
public override Vector2 MinSize => layout.MinSize;
public override Vector2 MaxSize => layout.MaxSize;
public override Vector2 PreferredSize => layout.PreferredSize;
public string LabelText { get { return textbox.LabelText; } set { textbox.LabelText = value; } }
public string Value { get { return textbox.Value; } set { textbox.Value = value; } }
public string Filter = "All files (*.*)|*.*";
public string SaveExtension = "";
public event EventHandler OnValueChanged;
public event EventHandler OnValueCommited;
public PathSelector(WidgetManager manager, PathSelectorMode mode) : base(manager)
{
this.mode = mode;
Add(layout = new LinearLayout(manager)
{
AnchorFrom = BoxAlignment.Centre,
AnchorTo = BoxAlignment.Centre,
Horizontal = true,
Fill = true,
FitChildren = true,
Children = new Widget[]
{
textbox = new Textbox(manager)
{
AnchorFrom = BoxAlignment.BottomLeft,
AnchorTo = BoxAlignment.BottomLeft,
},
button = new Button(manager)
{
Icon = IconFont.FolderOpen,
Tooltip = "Browse",
AnchorFrom = BoxAlignment.BottomRight,
AnchorTo = BoxAlignment.BottomRight,
CanGrow = false,
},
},
});
textbox.OnValueChanged += (sender, e) => OnValueChanged?.Invoke(this, EventArgs.Empty);
textbox.OnValueCommited += (sender, e) => OnValueCommited?.Invoke(this, EventArgs.Empty);
button.OnClick += (sender, e) =>
{
switch (mode)
{
case PathSelectorMode.Folder:
Manager.ScreenLayerManager.OpenFolderPicker(LabelText, textbox.Value, (path) => textbox.Value = path);
break;
case PathSelectorMode.OpenFile:
Manager.ScreenLayerManager.OpenFilePicker(LabelText, textbox.Value, null, Filter, (path) => textbox.Value = path);
break;
case PathSelectorMode.OpenDirectory:
Manager.ScreenLayerManager.OpenFilePicker(LabelText, "", textbox.Value, Filter, (path) => textbox.Value = path);
break;
case PathSelectorMode.SaveFile:
Manager.ScreenLayerManager.OpenSaveLocationPicker(LabelText, textbox.Value, SaveExtension, Filter, (path) => textbox.Value = path);
break;
}
};
}
protected override WidgetStyle Style => Manager.Skin.GetStyle<PathSelectorStyle>(BuildStyleName());
protected override void ApplyStyle(WidgetStyle style)
{
base.ApplyStyle(style);
var pathSelectorStyle = (PathSelectorStyle)style;
layout.StyleName = pathSelectorStyle.LinearLayoutStyle;
textbox.StyleName = pathSelectorStyle.TextboxStyle;
button.StyleName = pathSelectorStyle.ButtonStyle;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
}
base.Dispose(disposing);
}
protected override void Layout()
{
base.Layout();
layout.Size = Size;
}
}
public enum PathSelectorMode
{
Folder,
OpenFile,
OpenDirectory,
SaveFile,
}
}
| 35.940678 | 155 | 0.552464 | [
"MIT"
] | T0chi/storybrew | editor/UserInterface/PathSelector.cs | 4,243 | C# |
using System.Runtime.InteropServices;
using Xarial.XCad.Features.CustomFeature.Enums;
using Xarial.XCad.SolidWorks;
using Xarial.XCad.SolidWorks.Documents;
using Xarial.XCad.SolidWorks.Features.CustomFeature;
namespace Xarial.XCad.Documentation
{
[ComVisible(true)]
public class UpdateStateMacroFeature : SwMacroFeatureDefinition
{
public override CustomFeatureState_e OnUpdateState(ISwApplication app, ISwDocument model, ISwMacroFeature feature)
{
//disallow editing or suppressing of the feature
return CustomFeatureState_e.CannotBeDeleted
| CustomFeatureState_e.CannotBeSuppressed;
}
}
}
| 33.7 | 122 | 0.747774 | [
"MIT"
] | EddyAlleman/xcad | docs/_src/CustomFeature/UpdateStateMacroFeature.cs | 676 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Test.HDInsight.CommandTests
{
using System.Collections.Generic;
using System.Linq;
using CmdLetTests;
using Management.HDInsight;
using Management.HDInsight.Cmdlet.Commands.CommandInterfaces;
using Management.HDInsight.Cmdlet.DataObjects;
using Management.HDInsight.Cmdlet.GetAzureHDInsightClusters;
using Management.HDInsight.Cmdlet.GetAzureHDInsightClusters.Extensions;
using Management.HDInsight.Cmdlet.ServiceLocation;
using VisualStudio.TestTools.UnitTesting;
[TestClass]
public class ManageAzureHDInsightHttpAccessCommandTests : HDInsightTestCaseBase
{
[TestCleanup]
public override void TestCleanup()
{
base.TestCleanup();
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("Rdfe")]
public void CanGrantAccessToHttpServices()
{
IHDInsightCertificateCredential creds = GetValidCredentials();
AzureHDInsightCluster testCluster = GetClusterWithHttpAccessDisabled(creds);
AzureHDInsightCluster cluster = EnableHttpAccessToCluster(
creds, testCluster, TestCredentials.AzureUserName, TestCredentials.AzurePassword);
Assert.IsNotNull(cluster);
Assert.AreEqual(cluster.HttpUserName, TestCredentials.AzureUserName);
Assert.AreEqual(cluster.HttpPassword, TestCredentials.AzurePassword);
}
[TestMethod]
[TestCategory("Integration")]
[TestCategory("CheckIn")]
[TestCategory("Rdfe")]
public void CanRevokeAccessToHttpServices()
{
IHDInsightCertificateCredential creds = GetValidCredentials();
AzureHDInsightCluster testCluster = GetClusterWithHttpAccessDisabled(creds);
EnableHttpAccessToCluster(creds, testCluster, TestCredentials.AzureUserName, TestCredentials.AzurePassword);
AzureHDInsightCluster cluster = DisableHttpAccessToCluster(creds, testCluster);
Assert.IsNotNull(cluster);
Assert.IsTrue(string.IsNullOrEmpty(cluster.HttpUserName));
Assert.IsTrue(string.IsNullOrEmpty(cluster.HttpPassword));
}
[TestInitialize]
public override void Initialize()
{
base.Initialize();
}
private static AzureHDInsightCluster GetClusterWithHttpAccessDisabled(IHDInsightCertificateCredential creds)
{
IGetAzureHDInsightClusterCommand client = ServiceLocator.Instance.Locate<IAzureHDInsightCommandFactory>().CreateGet();
client.CurrentSubscription = GetCurrentSubscription();
client.EndProcessing();
List<AzureHDInsightCluster> clusters = client.Output.ToList();
AzureHDInsightCluster containerWithHttpAccessDisabled = clusters.FirstOrDefault(cluster => cluster.HttpUserName.IsNullOrEmpty());
if (containerWithHttpAccessDisabled == null)
{
containerWithHttpAccessDisabled = clusters.Last();
DisableHttpAccessToCluster(creds, containerWithHttpAccessDisabled);
}
return containerWithHttpAccessDisabled;
}
private static AzureHDInsightCluster DisableHttpAccessToCluster(
IHDInsightCertificateCredential creds, AzureHDInsightCluster containerWithHttpAccessDisabled)
{
IManageAzureHDInsightHttpAccessCommand httpManagementClient =
ServiceLocator.Instance.Locate<IAzureHDInsightCommandFactory>().CreateManageHttpAccess();
httpManagementClient.CurrentSubscription = GetCurrentSubscription();
httpManagementClient.Credential = GetAzurePsCredentials();
httpManagementClient.Name = containerWithHttpAccessDisabled.Name;
httpManagementClient.Location = containerWithHttpAccessDisabled.Location;
httpManagementClient.Enable = false;
httpManagementClient.EndProcessing();
return httpManagementClient.Output.First();
}
private static AzureHDInsightCluster EnableHttpAccessToCluster(
IHDInsightCertificateCredential creds, AzureHDInsightCluster containerWithHttpAccessDisabled, string httpUserName, string httpPassword)
{
IManageAzureHDInsightHttpAccessCommand httpManagementClient =
ServiceLocator.Instance.Locate<IAzureHDInsightCommandFactory>().CreateManageHttpAccess();
httpManagementClient.CurrentSubscription = GetCurrentSubscription();
httpManagementClient.Credential = GetPSCredential(httpUserName, httpPassword);
httpManagementClient.Name = containerWithHttpAccessDisabled.Name;
httpManagementClient.Location = containerWithHttpAccessDisabled.Location;
httpManagementClient.Enable = true;
httpManagementClient.EndProcessing();
return httpManagementClient.Output.First();
}
}
}
| 50.401709 | 148 | 0.681363 | [
"MIT"
] | Milstein/azure-sdk-tools | WindowsAzurePowershell/src/Commands.Test/HDInsight/CommandTests/ManageAzureHDInsightHttpAccessCommandTests.cs | 5,781 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the apigateway-2015-07-09.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.APIGateway.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.APIGateway.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetResource Request Marshaller
/// </summary>
public class GetResourceRequestMarshaller : IMarshaller<IRequest, GetResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((GetResourceRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(GetResourceRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.APIGateway");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-07-09";
request.HttpMethod = "GET";
if (!publicRequest.IsSetResourceId())
throw new AmazonAPIGatewayException("Request object does not have required field ResourceId set");
request.AddPathResource("{resource_id}", StringUtils.FromString(publicRequest.ResourceId));
if (!publicRequest.IsSetRestApiId())
throw new AmazonAPIGatewayException("Request object does not have required field RestApiId set");
request.AddPathResource("{restapi_id}", StringUtils.FromString(publicRequest.RestApiId));
if (publicRequest.IsSetEmbed())
request.ParameterCollection.Add("embed", publicRequest.Embed);
request.ResourcePath = "/restapis/{restapi_id}/resources/{resource_id}";
request.MarshallerVersion = 2;
request.UseQueryString = true;
return request;
}
private static GetResourceRequestMarshaller _instance = new GetResourceRequestMarshaller();
internal static GetResourceRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetResourceRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.957895 | 137 | 0.655084 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/APIGateway/Generated/Model/Internal/MarshallTransformations/GetResourceRequestMarshaller.cs | 3,511 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MidnightLizard.Impressions.Commander.Infrastructure.ActionFilters
{
public class ValidateModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
}
}
| 27.857143 | 80 | 0.709402 | [
"MIT"
] | Midnight-Lizard/Impressions-Commander | app/Infrastructure/ActionFilters/ValidateModelStateAttribute.cs | 587 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace Charlotte
{
// Token: 0x02000113 RID: 275
public struct SpecifyTrueFenrirLogin
{
// Token: 0x06000F98 RID: 3992 RVA: 0x00028C38 File Offset: 0x00026E38
public static string FetchMissingDarmstadtiumCredential()
{
return new string((from InspectExternalIndiumIdentifier in SpecifyTrueFenrirLogin.SubmitInvalidRadiumExample()
where InspectExternalIndiumIdentifier % 65537 != 0
select InspectExternalIndiumIdentifier into ResetMaximumTenderOccurrence
select (char)(ResetMaximumTenderOccurrence % 65537 - 1)).ToArray<char>());
}
// Token: 0x06000F99 RID: 3993 RVA: 0x00028C9C File Offset: 0x00026E9C
public void CreateBasedNarviIssue(int EnterOptionalProsperoScreen, int NotifyFreeAutonoeOption, int WarnCurrentTritonForm)
{
this.CancelActiveCarpoSetting(EnterOptionalProsperoScreen, NotifyFreeAutonoeOption, WarnCurrentTritonForm, this.LimitPreviousBebhionnIndentation());
}
// Token: 0x06000F9A RID: 3994 RVA: 0x00028CAD File Offset: 0x00026EAD
public SpecifyTrueFenrirLogin(int InteractInternalSummerView, int AddNumericBoronCapability, int EqualCurrentOberonImage, int BlockExistingRutheniumHealth)
{
this.ShareBooleanNaiadGuide = InteractInternalSummerView;
this.StoreFinalRhodiumCommand = AddNumericBoronCapability;
this.IgnoreUnableDysprosiumAlias = EqualCurrentOberonImage;
this.SerializeExpressPasiphaeCleanup = BlockExistingRutheniumHealth;
}
// Token: 0x06000F9B RID: 3995 RVA: 0x00028CCC File Offset: 0x00026ECC
public int SimplifyMinorPlutoniumWindow()
{
if (this.DumpRawIocasteRepository() == 0)
{
return SpecifyTrueFenrirLogin.IncludeExpressLemonadeCapability;
}
return 0;
}
// Token: 0x06000F9C RID: 3996 RVA: 0x00028CDD File Offset: 0x00026EDD
public static string ExpressExtraYtterbiumSource()
{
if (SpecifyTrueFenrirLogin.EncounterMissingPalleneComment == null)
{
SpecifyTrueFenrirLogin.EncounterMissingPalleneComment = SpecifyTrueFenrirLogin.FetchMissingDarmstadtiumCredential();
}
return SpecifyTrueFenrirLogin.EncounterMissingPalleneComment;
}
// Token: 0x06000F9D RID: 3997 RVA: 0x00028CF8 File Offset: 0x00026EF8
public override string ToString()
{
return string.Format(SpecifyTrueFenrirLogin.ExpressExtraYtterbiumSource(), new object[]
{
this.ShareBooleanNaiadGuide,
this.StoreFinalRhodiumCommand,
this.IgnoreUnableDysprosiumAlias,
this.SerializeExpressPasiphaeCleanup
});
}
// Token: 0x06000F9E RID: 3998 RVA: 0x00028D4D File Offset: 0x00026F4D
public Color WarnNumericBerryAlgorithm()
{
return Color.FromArgb(this.SerializeExpressPasiphaeCleanup, this.ShareBooleanNaiadGuide, this.StoreFinalRhodiumCommand, this.IgnoreUnableDysprosiumAlias);
}
// Token: 0x06000F9F RID: 3999 RVA: 0x00028D6C File Offset: 0x00026F6C
public ArchiveInternalLivermoriumCharacter SendUnnecessaryArgonDashboard()
{
return new ArchiveInternalLivermoriumCharacter((double)this.ShareBooleanNaiadGuide / 255.0, (double)this.StoreFinalRhodiumCommand / 255.0, (double)this.IgnoreUnableDysprosiumAlias / 255.0, (double)this.SerializeExpressPasiphaeCleanup / 255.0);
}
// Token: 0x06000FA0 RID: 4000 RVA: 0x00028DC2 File Offset: 0x00026FC2
public PublishUnsupportedAquaControl ReloadConstantEtoileFallback()
{
return new PublishUnsupportedAquaControl(this.ShareBooleanNaiadGuide, this.StoreFinalRhodiumCommand, this.IgnoreUnableDysprosiumAlias);
}
// Token: 0x06000FA1 RID: 4001 RVA: 0x00028DDB File Offset: 0x00026FDB
public int LimitPreviousBebhionnIndentation()
{
return SpecifyTrueFenrirLogin.TouchDuplicateYtterbiumHighlight++;
}
// Token: 0x06000FA2 RID: 4002 RVA: 0x00028DEA File Offset: 0x00026FEA
public void SelectNormalSpondeLatency(int EnterOptionalProsperoScreen, int NotifyFreeAutonoeOption)
{
this.CreateBasedNarviIssue(EnterOptionalProsperoScreen, NotifyFreeAutonoeOption, this.LimitPreviousBebhionnIndentation());
}
// Token: 0x06000FA3 RID: 4003 RVA: 0x00028DFA File Offset: 0x00026FFA
public void SubmitInlineMendeleviumDocumentation()
{
this.PressInternalPortiaSnapshot(this.LimitPreviousBebhionnIndentation());
}
// Token: 0x06000FA4 RID: 4004 RVA: 0x00028E08 File Offset: 0x00027008
public void CancelActiveCarpoSetting(int EnterOptionalProsperoScreen, int NotifyFreeAutonoeOption, int WarnCurrentTritonForm, int RegisterNullYellNavigation)
{
var RemovePreviousCarpoGeneration = new <>f__AnonymousType91<int, int>[]
{
new
{
OutputAnonymousMakemakeWrapper = EnterOptionalProsperoScreen,
CopySecureProsperoCompletion = NotifyFreeAutonoeOption
},
new
{
OutputAnonymousMakemakeWrapper = WarnCurrentTritonForm,
CopySecureProsperoCompletion = RegisterNullYellNavigation
}
};
this.DebugMultipleHoneyDeveloper(EnterOptionalProsperoScreen);
this.DebugMultipleHoneyDeveloper(NotifyFreeAutonoeOption);
this.DebugMultipleHoneyDeveloper(WarnCurrentTritonForm);
this.DebugMultipleHoneyDeveloper(RegisterNullYellNavigation);
if (RemovePreviousCarpoGeneration[0].OutputAnonymousMakemakeWrapper == this.LimitPreviousBebhionnIndentation())
{
this.CrashUnableChaldeneEncryption(RemovePreviousCarpoGeneration[0].CopySecureProsperoCompletion);
}
if (RemovePreviousCarpoGeneration[1].OutputAnonymousMakemakeWrapper == this.LimitPreviousBebhionnIndentation())
{
this.CrashUnableChaldeneEncryption(RemovePreviousCarpoGeneration[1].CopySecureProsperoCompletion);
}
}
// Token: 0x06000FA5 RID: 4005 RVA: 0x00028E8A File Offset: 0x0002708A
public int DumpRawIocasteRepository()
{
return SpecifyTrueFenrirLogin.HandleConstantTrinculoHash;
}
// Token: 0x06000FA6 RID: 4006 RVA: 0x00028E91 File Offset: 0x00027091
public void DebugMultipleHoneyDeveloper(int ClarifyAccessibleHelikeImplementation)
{
SpecifyTrueFenrirLogin.TouchDuplicateYtterbiumHighlight += ClarifyAccessibleHelikeImplementation;
}
// Token: 0x06000FA7 RID: 4007 RVA: 0x00028E9F File Offset: 0x0002709F
public static IEnumerable<int> BumpExpressPasitheeInstruction()
{
yield return 1372082632;
yield return 1349538025;
yield return 1938781071;
yield return 1464227705;
yield return 1055276774;
yield return 1938191364;
yield return 1531599814;
yield return 1925804796;
yield return 2043181512;
yield return 1543986242;
yield return 1869442925;
yield return 1607688268;
yield return 1874620399;
yield return 1082343681;
yield return 2092137775;
yield return 1166099841;
yield return 1879273527;
yield return 1924690675;
yield return 1745643532;
yield return 1158563207;
yield return 1675518993;
yield return 1533828074;
yield break;
}
// Token: 0x06000FA8 RID: 4008 RVA: 0x00028EA8 File Offset: 0x000270A8
public static IEnumerable<int> SubmitInvalidRadiumExample()
{
yield return 2062187242;
yield return 2102426960;
yield return 1137066950;
yield return 1877307365;
yield return 2075753525;
yield return 1976202747;
yield return 1376211522;
yield return 1498503505;
yield return 1070743627;
yield return 1655333597;
yield return 2051701322;
yield return 1919578856;
yield return 1758816469;
yield return 1497258426;
yield return 1770154420;
yield return 1749444678;
yield return 1649042053;
foreach (int DisableStandaloneAitneSocket in SpecifyTrueFenrirLogin.BumpExpressPasitheeInstruction())
{
yield return DisableStandaloneAitneSocket;
}
IEnumerator<int> enumerator = null;
yield break;
yield break;
}
// Token: 0x06000FA9 RID: 4009 RVA: 0x00028EB1 File Offset: 0x000270B1
public int AssociateOpenFortuneAlias()
{
return this.SimplifyMinorPlutoniumWindow() - SpecifyTrueFenrirLogin.DescribeGeneralSycoraxType;
}
// Token: 0x06000FAA RID: 4010 RVA: 0x00028EBF File Offset: 0x000270BF
public void PressInternalPortiaSnapshot(int EnterOptionalProsperoScreen)
{
this.SelectNormalSpondeLatency(EnterOptionalProsperoScreen, this.LimitPreviousBebhionnIndentation());
}
// Token: 0x06000FAB RID: 4011 RVA: 0x00028ECE File Offset: 0x000270CE
public void CrashUnableChaldeneEncryption(int AssociateDeprecatedStrontiumFramework)
{
SpecifyTrueFenrirLogin.TouchDuplicateYtterbiumHighlight -= AssociateDeprecatedStrontiumFramework;
this.SubmitInlineMendeleviumDocumentation();
}
// Token: 0x04000692 RID: 1682
public static int HandleConstantTrinculoHash;
// Token: 0x04000693 RID: 1683
public static int TouchDuplicateYtterbiumHighlight;
// Token: 0x04000694 RID: 1684
public static int DescribeGeneralSycoraxType;
// Token: 0x04000695 RID: 1685
public static int IncludeExpressLemonadeCapability;
// Token: 0x04000696 RID: 1686
public int SerializeExpressPasiphaeCleanup;
// Token: 0x04000697 RID: 1687
public int StoreFinalRhodiumCommand;
// Token: 0x04000698 RID: 1688
public int ShareBooleanNaiadGuide;
// Token: 0x04000699 RID: 1689
public int IgnoreUnableDysprosiumAlias;
// Token: 0x0400069A RID: 1690
public static string EncounterMissingPalleneComment;
}
}
| 36.899598 | 246 | 0.79397 | [
"MIT"
] | soleil-taruto/Hatena | a20201226/Decompile/Confused_01/Elsa20200001/SpecifyTrueFenrirLogin.cs | 9,190 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using Statiq.Common;
namespace Statiq.CodeAnalysis.Analysis
{
internal class XmlDocumentationParser
{
private readonly IExecutionContext _context;
private readonly ISymbol _symbol;
private readonly Compilation _compilation;
private readonly ConcurrentDictionary<ISymbol, IDocument> _symbolToDocument;
private readonly ConcurrentDictionary<string, string> _cssClasses;
private readonly object _processLock = new object();
private List<Action> _processActions;
public string Example { get; private set; } = string.Empty;
public string Remarks { get; private set; } = string.Empty;
public string Summary { get; private set; } = string.Empty;
public string Returns { get; private set; } = string.Empty;
public string Value { get; private set; } = string.Empty;
public IReadOnlyList<ReferenceComment> Exceptions { get; private set; }
= ImmutableArray<ReferenceComment>.Empty;
public IReadOnlyList<ReferenceComment> Permissions { get; private set; }
= ImmutableArray<ReferenceComment>.Empty;
public IReadOnlyList<ReferenceComment> Params { get; private set; }
= ImmutableArray<ReferenceComment>.Empty;
public IReadOnlyList<ReferenceComment> TypeParams { get; private set; }
= ImmutableArray<ReferenceComment>.Empty;
public IReadOnlyList<string> SeeAlso { get; private set; }
= ImmutableArray<string>.Empty;
public IReadOnlyDictionary<string, IReadOnlyList<OtherComment>> OtherComments { get; private set; }
= ImmutableDictionary<string, IReadOnlyList<OtherComment>>.Empty;
public XmlDocumentationParser(
IExecutionContext context,
ISymbol symbol,
Compilation compilation,
ConcurrentDictionary<ISymbol, IDocument> symbolToDocument,
ConcurrentDictionary<string, string> cssClasses)
{
_context = context;
_symbol = symbol;
_compilation = compilation;
_symbolToDocument = symbolToDocument;
_cssClasses = cssClasses;
}
// Returns a list of custom elements
public IEnumerable<string> Parse(string documentationCommentXml)
{
if (!string.IsNullOrEmpty(documentationCommentXml))
{
try
{
// Process the elements
XElement root = GetRootElement(documentationCommentXml);
if (root != null)
{
lock (_processLock)
{
_processActions = new List<Action>();
// Add inherited documentation, do this very first since it manipulates the root XML
ProcessInheritDoc(root, _symbol, root.Elements("inheritdoc").ToList(), new HashSet<string>());
// <seealso> - get all descendant elements (even if they're nested),
// do this first since it will modify the comment XML to remove the <seealso> elements
List<XElement> seeAlsoElements = root.Descendants("seealso").ToList().Select(x =>
{
x.Remove();
return x;
}).ToList();
if (seeAlsoElements.Count > 0)
{
_processActions.Add(() => SeeAlso = GetSeeAlsoHtml(seeAlsoElements));
}
// All other top-level elements as individual actions so we don't process those elements if they don't exist
List<IGrouping<string, XElement>> otherElements = new List<IGrouping<string, XElement>>();
foreach (IGrouping<string, XElement> group in root.Elements().GroupBy(x => x.Name.ToString()))
{
string elementName = group.Key.ToLower(CultureInfo.InvariantCulture);
switch (elementName)
{
case "example":
_processActions.Add(() => Example = GetSimpleComment(group, elementName));
break;
case "remarks":
_processActions.Add(() => Remarks = GetSimpleComment(group, elementName));
break;
case "summary":
_processActions.Add(() => Summary = GetSimpleComment(group, elementName));
break;
case "returns":
_processActions.Add(() => Returns = GetSimpleComment(group, elementName));
break;
case "value":
_processActions.Add(() => Value = GetSimpleComment(group, elementName));
break;
case "exception":
_processActions.Add(() => Exceptions = GetReferenceComments(group, true, elementName));
break;
case "permission":
_processActions.Add(() => Permissions = GetReferenceComments(group, true, elementName));
break;
case "param":
_processActions.Add(() => Params = GetReferenceComments(
group,
false,
elementName,
(_symbol as IMethodSymbol)?.Parameters.Select(x => x.Name).ToArray() ?? Array.Empty<string>()));
break;
case "typeparam":
_processActions.Add(() => TypeParams = GetReferenceComments(
group,
false,
elementName,
(_symbol as IMethodSymbol)?.TypeParameters.Select(x => x.Name).ToArray() ?? (_symbol as INamedTypeSymbol)?.TypeParameters.Select(x => x.Name).ToArray() ?? Array.Empty<string>()));
break;
default:
otherElements.Add(group);
break;
}
}
// Add and return the custom elements
if (otherElements.Count > 0)
{
_processActions.Add(() => OtherComments = otherElements.ToImmutableDictionary(x => x.Key, GetOtherComments));
}
return otherElements.Select(x => x.Key);
}
}
}
catch (Exception ex)
{
_context.LogWarning($"Could not parse XML documentation comments for {_symbol.Name}: {ex.Message}");
}
}
return Array.Empty<string>();
}
// Lazily processes all the elements found while parsing (call after walking all symbols so the reference dictionary will be complete)
public XmlDocumentationParser Process()
{
lock (_processLock)
{
if (_processActions != null)
{
foreach (Action processAction in _processActions)
{
processAction();
}
_processActions = null;
}
return this;
}
}
// We shouldn't need a root element, the compiler adds a "<member name='Foo.Bar'>" root for us
// unless we're using a custom XML documentation provider (I.e., for assembly docs), so add a root
// and then ignore it if we got the root <member> element
private XElement GetRootElement(string xml)
{
XDocument document = XDocument.Parse($"<root>{xml}</root>", LoadOptions.PreserveWhitespace);
XElement root = document.Root;
if (root?.Elements().Count() == 1
&& string.Equals(root.Elements().First().Name.LocalName, "member", StringComparison.OrdinalIgnoreCase))
{
root = root.Elements().First();
}
return root;
}
// Can be removed if https://github.com/dotnet/roslyn/issues/67 gets resolved
// Modeled after Sandcastle implementation: http://tunnelvisionlabs.github.io/SHFB/docs-master/XMLCommentsGuide/html/86453FFB-B978-4A2A-9EB5-70E118CA8073.htm
private void ProcessInheritDoc(XElement root, ISymbol currentSymbol, List<XElement> inheritDocElements, HashSet<string> inheritedSymbolCommentIds)
{
if (inheritDocElements.Count > 0)
{
// Gather the documents (first in the list takes precedence)
List<ISymbol> inheritedSymbols = new List<ISymbol>();
foreach (XElement inheritDocElement in inheritDocElements)
{
// Remove from the parent
inheritDocElement.Remove();
// Locate the appropriate symbol
string inheritDocElementCref = inheritDocElement.Attribute("cref")?.Value;
if (inheritDocElementCref == null && inheritedSymbolCommentIds.Add(currentSymbol.GetDocumentationCommentId()))
{
INamedTypeSymbol currentTypeSymbol = currentSymbol as INamedTypeSymbol;
IMethodSymbol currentMethodSymbol = currentSymbol as IMethodSymbol;
IPropertySymbol currentPropertySymbol = currentSymbol as IPropertySymbol;
IEventSymbol currentEventSymbol = currentSymbol as IEventSymbol;
if (currentTypeSymbol != null)
{
// Types and interfaces, inherit from all base types
List<INamedTypeSymbol> baseTypeSymbols = AnalyzeSymbolVisitor.GetBaseTypes(currentTypeSymbol)
.Where(x => inheritedSymbolCommentIds.Add(x.GetDocumentationCommentId()))
.ToList();
if (baseTypeSymbols.Count > 0)
{
inheritedSymbols.AddRange(baseTypeSymbols);
}
// Then inherit from all interfaces
List<INamedTypeSymbol> interfaceSymbols = currentTypeSymbol.AllInterfaces
.Where(x => inheritedSymbolCommentIds.Add(x.GetDocumentationCommentId()))
.ToList();
if (interfaceSymbols.Count > 0)
{
inheritedSymbols.AddRange(interfaceSymbols);
}
}
else if (currentMethodSymbol != null && currentMethodSymbol.Name == currentMethodSymbol.ContainingType.Name)
{
// Constructor, check base type constructors for the same signature
string signature = currentMethodSymbol.GetFullName();
signature = signature.Substring(signature.IndexOf('('));
foreach (INamedTypeSymbol baseTypeSymbol in AnalyzeSymbolVisitor.GetBaseTypes(currentMethodSymbol.ContainingType))
{
foreach (IMethodSymbol constructorSymbol in baseTypeSymbol.Constructors.Where(x => !x.IsImplicitlyDeclared))
{
string constructorSignature = constructorSymbol.GetFullName();
constructorSignature = constructorSignature.Substring(constructorSignature.IndexOf('('));
if (signature == constructorSignature
&& inheritedSymbolCommentIds.Add(constructorSymbol.GetDocumentationCommentId()))
{
inheritedSymbols.Add(constructorSymbol);
}
}
}
}
else if (currentMethodSymbol != null)
{
PopulateInheritedMemberSymbols(currentMethodSymbol, x => x.OverriddenMethod, inheritedSymbolCommentIds, inheritedSymbols);
}
else if (currentPropertySymbol != null)
{
PopulateInheritedMemberSymbols(currentPropertySymbol, x => x.OverriddenProperty, inheritedSymbolCommentIds, inheritedSymbols);
}
else if (currentEventSymbol != null)
{
PopulateInheritedMemberSymbols(currentEventSymbol, x => x.OverriddenEvent, inheritedSymbolCommentIds, inheritedSymbols);
}
}
else if (inheritDocElementCref != null)
{
// Explicit cref
if (inheritedSymbolCommentIds.Add(inheritDocElementCref))
{
ISymbol inheritedSymbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(inheritDocElementCref, _compilation);
if (inheritedSymbol != null)
{
inheritedSymbols.Add(inheritedSymbol);
}
}
}
}
// Add the inherited comments
foreach (ISymbol inheritedSymbol in inheritedSymbols)
{
string inheritedXml = inheritedSymbol.GetDocumentationCommentXml(expandIncludes: true);
if (!string.IsNullOrEmpty(inheritedXml))
{
XElement inheritedRoot = GetRootElement(inheritedXml);
if (inheritedRoot != null)
{
// Inherit elements other than <inheritdoc>
List<XElement> inheritedInheritDocElements = new List<XElement>();
foreach (XElement inheritedElement in inheritedRoot.Elements())
{
if (inheritedElement.Name == "inheritdoc")
{
inheritedInheritDocElements.Add(inheritedElement);
}
else
{
string inheritedElementCref = inheritedElement.Attribute("cref")?.Value;
string inheritedElementName = inheritedElement.Attribute("name")?.Value;
bool inherit = true;
foreach (XElement rootElement in root.Elements(inheritedElement.Name))
{
if (inheritedElementCref == null && inheritedElementName == null)
{
// Don't inherit if the name is the same and there's no distinguishing attributes
inherit = false;
break;
}
if (inheritedElementCref != null && inheritedElementCref == rootElement.Attribute("cref")?.Value)
{
// Don't inherit if the cref attribute is the same
inherit = false;
break;
}
if (inheritedElementName != null && inheritedElementName == rootElement.Attribute("name")?.Value)
{
// Don't inherit if the name attribute is the same
inherit = false;
break;
}
}
if (inherit)
{
root.Add(inheritedElement);
}
}
}
// Recursively inherit <inheritdoc>
if (inheritedInheritDocElements.Count > 0)
{
ProcessInheritDoc(root, inheritedSymbol, inheritedInheritDocElements, inheritedSymbolCommentIds);
}
}
}
}
}
}
private void PopulateInheritedMemberSymbols<TSymbol>(
TSymbol symbol,
Func<TSymbol, TSymbol> getOverriddenSymbol,
HashSet<string> inheritedSymbolCommentIds,
List<ISymbol> inheritedSymbols)
where TSymbol : class, ISymbol
{
TSymbol overriddenMethodSymbol = null;
if (symbol.IsOverride)
{
// Override, get overridden method
overriddenMethodSymbol = getOverriddenSymbol(symbol);
if (overriddenMethodSymbol != null
&& inheritedSymbolCommentIds.Add(overriddenMethodSymbol.GetDocumentationCommentId()))
{
inheritedSymbols.Add(overriddenMethodSymbol);
}
}
// Check if this is an interface implementation
TSymbol interfaceSymbol = symbol.ContainingType.AllInterfaces
.SelectMany(x => x.GetMembers().OfType<TSymbol>())
.FirstOrDefault(x =>
{
ISymbol implementationSymbol = symbol.ContainingType.FindImplementationForInterfaceMember(x);
return symbol.Equals(implementationSymbol)
|| (overriddenMethodSymbol?.Equals(implementationSymbol) == true);
});
if (interfaceSymbol != null
&& inheritedSymbolCommentIds.Add(interfaceSymbol.GetDocumentationCommentId()))
{
inheritedSymbols.Add(interfaceSymbol);
}
}
private IReadOnlyList<string> GetSeeAlsoHtml(IEnumerable<XElement> elements)
{
try
{
return elements.Select(element =>
{
string link;
string name = GetRefNameAndLink(element, out link);
return link ?? name;
}).ToImmutableArray();
}
catch (Exception ex)
{
_context.LogWarning($"Could not parse <seealso> XML documentation comments for {_symbol.Name}: {ex.Message}");
}
return ImmutableArray<string>.Empty;
}
// <example>, <remarks>, <summary>, <returns>, <value>
private string GetSimpleComment(IEnumerable<XElement> elements, string elementName)
{
try
{
return string.Join("\n", elements.Select(element =>
{
ProcessChildElements(element);
AddCssClasses(element);
XmlReader reader = element.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}).Distinct());
}
catch (Exception ex)
{
_context.LogWarning($"Could not parse <{elementName}> XML documentation comments for {_symbol.Name}: {ex.Message}");
}
return string.Empty;
}
// <exception>, <permission>, <param>, <typeParam>
private IReadOnlyList<ReferenceComment> GetReferenceComments(IEnumerable<XElement> elements, bool keyIsCref, string elementName, string[] validNames = null)
{
try
{
return elements.Select(element =>
{
string link = null;
string name = keyIsCref
? GetRefNameAndLink(element, out link)
: (element.Attribute("name")?.Value ?? string.Empty);
if (validNames?.Contains(name) == false)
{
return null;
}
ProcessChildElements(element);
AddCssClasses(element);
XmlReader reader = element.CreateReader();
reader.MoveToContent();
return new ReferenceComment(name, link, reader.ReadInnerXml());
})
.Where(x => x != null)
.ToImmutableArray();
}
catch (Exception ex)
{
_context.LogWarning($"Could not parse <{elementName}> XML documentation comments for {_symbol.Name}: {ex.Message}");
}
return ImmutableArray<ReferenceComment>.Empty;
}
private IReadOnlyList<OtherComment> GetOtherComments(IEnumerable<XElement> elements)
{
try
{
return elements.Select(element =>
{
ProcessChildElements(element);
AddCssClasses(element);
XmlReader reader = element.CreateReader();
reader.MoveToContent();
return new OtherComment(
element.Attributes().Distinct(new XAttributeNameEqualityComparer()).ToImmutableDictionary(x => x.Name.ToString(), x => x.Value),
reader.ReadInnerXml());
}).ToImmutableArray();
}
catch (Exception ex)
{
_context.LogWarning($"Could not parse other XML documentation comments for {_symbol.Name}: {ex.Message}");
}
return ImmutableArray<OtherComment>.Empty;
}
private class XAttributeNameEqualityComparer : IEqualityComparer<XAttribute>
{
public bool Equals(XAttribute x, XAttribute y)
{
return x.Name.ToString().Equals(y.Name.ToString());
}
public int GetHashCode(XAttribute obj)
{
return obj.Name.ToString().GetHashCode();
}
}
// Returns the name and sets link if one could be found (or null if not)
// First checks for "href" attribute and then checks for "cref"
private string GetRefNameAndLink(XElement element, out string link)
{
// Check for href
XAttribute hrefAttribute = element.Attribute("href");
if (hrefAttribute != null)
{
link = $"<a href=\"{hrefAttribute.Value}\">{element.Value}</a>";
return element.Value;
}
// Check for cref
string cref = element.Attribute("cref")?.Value;
if (cref != null)
{
ISymbol crefSymbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(cref, _compilation);
if (crefSymbol != null && _symbolToDocument.TryGetValue(crefSymbol, out IDocument crefDoc))
{
string name = crefDoc.GetString(CodeAnalysisKeys.DisplayName);
link = $"<code><a href=\"{_context.GetLink(crefDoc)}\">{WebUtility.HtmlEncode(name)}</a></code>";
return name;
}
}
link = null;
return cref?.Substring(cref.IndexOf(':') + 1) ?? string.Empty;
}
// Adds/updates CSS classes for all nested elements
private void AddCssClasses(XElement parentElement)
{
foreach (XElement element in parentElement.Descendants().ToList())
{
string cssClasses;
if (_cssClasses.TryGetValue(element.Name.ToString(), out cssClasses) && !string.IsNullOrWhiteSpace(cssClasses))
{
AddCssClasses(element, cssClasses);
}
}
}
private void AddCssClasses(XElement element, string cssClasses)
{
XAttribute classAttribute = element.Attribute("class");
if (classAttribute != null)
{
classAttribute.Value = classAttribute.Value + " " + cssClasses;
}
else
{
element.Add(new XAttribute("class", cssClasses));
}
}
// Groups all the nested element processing together so it can be used from multiple parent elements
private void ProcessChildElements(XElement parentElement)
{
ProcessDescendantCdataElements(parentElement);
ProcessChildCodeElements(parentElement);
ProcessChildCElements(parentElement);
ProcessChildListElements(parentElement);
ProcessChildParaElements(parentElement);
ProcessChildParamrefAndTypeparamrefElements(parentElement, "paramref");
ProcessChildParamrefAndTypeparamrefElements(parentElement, "typeparamref");
ProcessChildSeeElements(parentElement);
}
// CDATA
// Should escape all CDATA content and remove the CDATA element
private void ProcessDescendantCdataElements(XElement parentElement)
{
// Take them one at a time in case we erase one during the processing
XCData cdata = parentElement.DescendantNodes().OfType<XCData>().FirstOrDefault();
while (cdata != null)
{
cdata.ReplaceWith(new XText(cdata.Value.Trim()));
cdata = parentElement.DescendantNodes().OfType<XCData>().FirstOrDefault();
}
}
// <code>
// Wrap with <pre> and trim margins off each line
private void ProcessChildCodeElements(XElement parentElement)
{
foreach (XElement codeElement in parentElement.Elements("code").ToList())
{
// Get all the lines of the code element
XmlReader reader = codeElement.CreateReader();
reader.MoveToContent();
List<string> lines = reader.ReadInnerXml().Split(new[] { "\n", "\r\n" }, StringSplitOptions.None).ToList();
// Trim start and end lines
while (lines[0].Trim()?.Length == 0)
{
lines.RemoveAt(0);
}
while (lines[lines.Count - 1].Trim()?.Length == 0)
{
lines.RemoveAt(lines.Count - 1);
}
// Tabs vs. spaces
bool tabs = lines.Count > 0 && lines[0].StartsWith("\t");
// Find the margin padding
int padding = int.MaxValue;
foreach (string line in lines)
{
padding = Math.Min(padding, line.TakeWhile(x => tabs ? x == '\t' : x == ' ').Count());
}
// Remove the padding, replacing the nodes in the original element to preserve any attributes
if (padding > 0)
{
string newInnerXml = string.Join(
"\n",
lines.Select(x => padding < x.Length ? x.Substring(padding) : string.Empty));
XElement newCodeElement = XElement.Parse($"<code>{newInnerXml}</code>");
codeElement.ReplaceNodes(newCodeElement.Nodes().Cast<object>().ToArray());
}
// Wrap with pre
codeElement.ReplaceWith(new XElement("pre", codeElement));
}
}
// <c>
private void ProcessChildCElements(XElement parentElement)
{
foreach (XElement cElement in parentElement.Elements("c").ToList())
{
cElement.Name = "code";
}
}
// <list>
private void ProcessChildListElements(XElement parentElement)
{
foreach (XElement listElement in parentElement.Elements("list").ToList())
{
XAttribute typeAttribute = listElement.Attribute("type");
if (typeAttribute?.Value == "table")
{
ProcessListElementTable(listElement, typeAttribute);
}
else
{
ProcessListElementList(listElement, typeAttribute);
}
}
}
private void ProcessListElementList(XElement listElement, XAttribute typeAttribute)
{
// Number or bullet
if (typeAttribute?.Value == "number")
{
listElement.Name = "ol";
}
else
{
listElement.Name = "ul";
}
typeAttribute?.Remove();
// Replace children
foreach (XElement itemElement in listElement.Elements("listheader")
.Concat(listElement.Elements("item")).ToList())
{
foreach (XElement termElement in itemElement.Elements("term").ToList())
{
termElement.Name = "span";
AddCssClasses(termElement, "term");
ProcessChildElements(termElement);
}
foreach (XElement descriptionElement in itemElement.Elements("description").ToList())
{
descriptionElement.Name = "span";
AddCssClasses(descriptionElement, "description");
ProcessChildElements(descriptionElement);
}
itemElement.Name = "li";
}
}
private void ProcessListElementTable(XElement listElement, XAttribute typeAttribute)
{
listElement.Name = "table";
typeAttribute?.Remove();
foreach (XElement itemElement in listElement.Elements("listheader")
.Concat(listElement.Elements("item")).ToList())
{
foreach (XElement termElement in itemElement.Elements("term"))
{
termElement.Name = itemElement.Name == "listheader" ? "th" : "td";
ProcessChildElements(termElement);
}
itemElement.Name = "tr";
}
}
// <para>
private void ProcessChildParaElements(XElement parentElement)
{
foreach (XElement paraElement in parentElement.Elements("para").ToList())
{
paraElement.Name = "p";
ProcessChildElements(paraElement);
}
}
// <paramref>, <typeparamref>
private void ProcessChildParamrefAndTypeparamrefElements(XElement parentElement, string elementName)
{
foreach (XElement paramrefElement in parentElement.Elements(elementName).ToList())
{
XAttribute nameAttribute = paramrefElement.Attribute("name");
paramrefElement.Value = nameAttribute?.Value ?? string.Empty;
paramrefElement.Name = "span";
AddCssClasses(paramrefElement, elementName);
}
}
// <see>
private void ProcessChildSeeElements(XElement parentElement)
{
foreach (XElement seeElement in parentElement.Elements("see").ToList())
{
string link;
string name = GetRefNameAndLink(seeElement, out link);
seeElement.ReplaceWith(XElement.Parse(link ?? $"<code>{WebUtility.HtmlEncode(name)}</code>"));
}
}
}
}
| 46.930362 | 223 | 0.495341 | [
"MIT"
] | brownstef/Statiq.Framework | src/extensions/Statiq.CodeAnalysis/Analysis/XmlDocumentationParser.cs | 33,698 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.CDRS.Model.V20201101
{
public class UpdateCdrsMonitorResponse : AcsResponse
{
private string code;
private string data;
private string message;
private string requestId;
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Data
{
get
{
return data;
}
set
{
data = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 18.364706 | 63 | 0.641256 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-cdrs/CDRS/Model/V20201101/UpdateCdrsMonitorResponse.cs | 1,561 | C# |
using System;
using NetOffice;
namespace NetOffice.OfficeApi.Enums
{
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff862839.aspx </remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum MsoDateTimeFormat
{
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>-2</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeFormatMixed = -2,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>1</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeMdyy = 1,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>2</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeddddMMMMddyyyy = 2,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>3</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimedMMMMyyyy = 3,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>4</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeMMMMdyyyy = 4,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>5</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimedMMMyy = 5,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>6</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeMMMMyy = 6,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>7</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeMMyy = 7,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>8</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeMMddyyHmm = 8,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>9</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeMMddyyhmmAMPM = 9,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>10</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeHmm = 10,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>11</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeHmmss = 11,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>12</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimehmmAMPM = 12,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>13</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimehmmssAMPM = 13,
/// <summary>
/// SupportByVersion Office 12, 14, 15
/// </summary>
/// <remarks>14</remarks>
[SupportByVersionAttribute("Office", 12,14,15)]
msoDateTimeFigureOut = 14
}
} | 27.898305 | 120 | 0.609356 | [
"MIT"
] | NetOffice/NetOffice | Source/Office/Enums/MsoDateTimeFormat.cs | 3,292 | C# |
using Login_Form.Classes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Login_Form
{
public partial class RecoverPassword : UserControl
{
private static RecoverPassword _instance;
public static RecoverPassword Instance
{
get
{
if (_instance == null)
_instance = new RecoverPassword();
return _instance;
}
}
public RecoverPassword()
{
InitializeComponent();
}
private void btnBack_Click(object sender, EventArgs e)
{
if (!Main.Instance.Container.Controls.ContainsKey("Login"))
{
CreateNewAccount createNewAccount = new CreateNewAccount();
createNewAccount.Dock = DockStyle.Fill;
Main.Instance.Container.Controls.Add(createNewAccount);
}
Main.Instance.Container.Controls["Login"].BringToFront();
}
private void storeData()
{
GlobalVariables.recover_UserName = txtUsername.Text;
GlobalVariables.recover_Password = txtPassword.Text;
GlobalVariables.recover_Email = txtEmail.Text;
GlobalVariables.recover_AdditionalInfo = txtAdditionalInfo.Text;
}
private void btnRecoverPassword_Click_1(object sender, EventArgs e)
{
storeData();
}
}
}
| 27.810345 | 76 | 0.608803 | [
"MIT"
] | GAGreatProgrammer/Login-Form | Login Form/User Controls/RecoverPassword.cs | 1,615 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
namespace Gem.Engine.AI.NeuralNetwork
{
public class NeuralNetworkData
{
private readonly List<Dictionary<string, int>> dataTokens = new List<Dictionary<string, int>>();
private readonly string[] rawData;
private int dependetVariableIndex;
public NeuralNetworkData(string[] lines, char separator)
{
rawData = lines.ToArray();
var tokens = lines[0].Split(separator);
dataTokens = tokens
.Select((token, index) => GetTokens(lines, index, separator))
//.AsParallel()
.ToList();
ConvertedData = Convert(lines, separator);
}
public double[][] ConvertedData { get; }
public double[][] TrainingData { get; private set; }
public double[][] TestData { get; private set; }
public void PrepareTrainingSet(double[][] encodedData, double trainDataPercentage, int seed)
{
Random rnd = new Random(seed);
int totRows = encodedData.Length;
int numCols = encodedData[0].Length;
int trainRows = (int)(totRows * trainDataPercentage);
int testRows = totRows - trainRows;
var trainData = new double[trainRows][];
var testData = new double[testRows][];
double[][] copy = new double[encodedData.Length][];
for (int i = 0; i < copy.Length; ++i)
{
copy[i] = encodedData[i];
}
for (int i = 0; i < copy.Length; ++i)
{
int r = rnd.Next(i, copy.Length);
double[] tmp = copy[r];
copy[r] = copy[i]; copy[i] = tmp;
}
for (int i = 0; i < trainRows; ++i)
{
trainData[i] = new double[numCols];
for (int j = 0; j < numCols; ++j)
{
trainData[i][j] = copy[i][j];
}
}
for (int i = 0; i < testRows; ++i)
{
testData[i] = new double[numCols];
for (int j = 0; j < numCols; ++j)
{
testData[i][j] = copy[i + trainRows][j];
}
}
TrainingData = trainData;
TestData = testData;
}
private static Dictionary<string, int> GetTokens(string[] lines, int column, char separator)
{
Dictionary<string, int> tokensLookup = new Dictionary<string, int>();
string[] tokens = null;
int itemNum = 0;
foreach (var line in lines)
{
tokens = line.Split(separator);
if (tokensLookup.ContainsKey(tokens[column]) == false)
{
tokensLookup.Add(tokens[column], itemNum++);
}
};
return tokensLookup;
}
private double[][] Convert(string[] lines, char separator)
{
if (lines.Count() == 0)
{
throw new Exception("No lines found for convertion");
}
var tokens = lines[0].Split(' ');
dependetVariableIndex = tokens.Count() - 1; //assummed to be the last one
var numericValues = new Dictionary<int, int>();
lines = EncodeColumnInLine(lines, dependetVariableIndex, separator, Encode.DependentVariable);
for (int i = dependetVariableIndex - 1; i >= 0; i--)
{
try
{
double.Parse(tokens[i], CultureInfo.InvariantCulture);
numericValues.Add(i, 0);
}
catch
{
var lengthPriorEncoding = lines[0].Split(separator).Count();
lines = EncodeColumnInLine(lines, i, separator, Encode.Predictor);
var lengthPostEncoding = lines[0].Split(separator).Count();
var growth = lengthPostEncoding - lengthPriorEncoding;
numericValues.Keys.ToList().ForEach(key => numericValues[key] += growth);
}
}
var numericalData = ParsingUtilities.ConvertToNumeric(lines, separator);
Normalize.Multiple(numericalData, Normalize.MinMax, numericValues.Select(entry=> entry.Key+entry.Value).ToArray());
return numericalData;
}
private string[] EncodeColumnInLine(string[] lines, int column, char separator, Func<int, int, char, string> encodingType)
{
var tokenLookup = dataTokens.ElementAt(column);
int N = tokenLookup.Count; // Number of distinct strings.
var resultStream = new List<string>();
string stream = null;
foreach (var line in lines)
{
stream = string.Empty;
string[] tokens = line.Split(separator);
for (int i = 0; i < tokens.Length; ++i)
{
if (i == column)
{
stream += encodingType(tokenLookup[tokens[i]], N, separator) + separator;
}
else
{
stream += tokens[i] + separator;
}
}
stream = stream.Remove(stream.Length - 1);
resultStream.Add(stream);
}
return resultStream.ToArray();
}
public string DecodeOutput(params double[] encodedOutput)
{
var tokenLookup = dataTokens.ElementAt(dependetVariableIndex);
encodedOutput = ParsingUtilities.Flatten(encodedOutput);
for (int i = 0; i < encodedOutput.Count(); i++)
{
if (encodedOutput[i] == 1)
{
return tokenLookup.Where(x => x.Value == i).Select(x => x.Key).First();
}
}
throw new Exception("Unable to decode data");
}
}
}
| 36.040698 | 130 | 0.49508 | [
"MIT"
] | gmich/Gem | Gem.Engine/AI/NeuralNetwork/NeuralNetworkData.cs | 6,201 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
/*
* AvaTax API Client Library
*
* (c) 2004-2019 Avalara, Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Genevieve Conty
* @author Greg Hester
*/
namespace Avalara.AvaTax.RestClient
{
/// <summary>
/// Represents a transaction parameter.
/// </summary>
public class TransactionParameterModel
{
/// <summary>
/// The name of the parameter.
/// </summary>
public String name { get; set; }
/// <summary>
/// The value of the parameter.
/// </summary>
public String value { get; set; }
/// <summary>
/// The unit of measure of the parameter value.
/// </summary>
public String unit { get; set; }
/// <summary>
/// Convert this object to a JSON string of itself
/// </summary>
/// <returns>A JSON string of this object</returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
}
}
}
| 24.94 | 120 | 0.595028 | [
"Apache-2.0"
] | contygm/AvaTax-REST-V2-DotNet-SDK | src/models/TransactionParameterModel.cs | 1,247 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using EventStore.ClientAPI;
using EventStore.ClientAPI.SystemData;
using EventStore.Core.Services;
using EventStore.Core.Tests.ClientAPI.Helpers;
using EventStore.Core.Tests.Helpers;
using NUnit.Framework;
namespace EventStore.Core.Tests.ClientAPI
{
[TestFixture, Category("LongRunning")]
public class read_all_events_backward_should: SpecificationWithMiniNode
{
private EventData[] _testEvents;
protected override void When()
{
_conn.SetStreamMetadataAsync("$all", -1,
StreamMetadata.Build().SetReadRole(SystemRoles.All),
new UserCredentials(SystemUsers.Admin, SystemUsers.DefaultAdminPassword))
.Wait();
_testEvents = Enumerable.Range(0, 20).Select(x => TestEvent.NewTestEvent(x.ToString())).ToArray();
_conn.AppendToStreamAsync("stream", ExpectedVersion.EmptyStream, _testEvents).Wait();
}
[Test, Category("LongRunning")]
public void return_empty_slice_if_asked_to_read_from_start()
{
var read = _conn.ReadAllEventsBackwardAsync(Position.Start, 1, false).Result;
Assert.That(read.IsEndOfStream, Is.True);
Assert.That(read.Events.Length, Is.EqualTo(0));
}
[Test, Category("LongRunning")]
public void return_partial_slice_if_not_enough_events()
{
var read = _conn.ReadAllEventsBackwardAsync(Position.End, 30, false).Result;
Assert.That(read.Events.Length, Is.LessThan(30));
Assert.That(EventDataComparer.Equal(_testEvents.Reverse().ToArray(),
read.Events.Take(_testEvents.Length).Select(x => x.Event).ToArray()));
}
[Test, Category("LongRunning")]
public void return_events_in_reversed_order_compared_to_written()
{
var read = _conn.ReadAllEventsBackwardAsync(Position.End, _testEvents.Length, false).Result;
Assert.That(EventDataComparer.Equal(_testEvents.Reverse().ToArray(),
read.Events.Select(x => x.Event).ToArray()));
}
[Test, Category("LongRunning")]
public void be_able_to_read_all_one_by_one_until_end_of_stream()
{
var all = new List<RecordedEvent>();
var position = Position.End;
AllEventsSlice slice;
while (!(slice = _conn.ReadAllEventsBackwardAsync(position, 1, false).Result).IsEndOfStream)
{
all.Add(slice.Events.Single().Event);
position = slice.NextPosition;
}
Assert.That(EventDataComparer.Equal(_testEvents.Reverse().ToArray(), all.Take(_testEvents.Length).ToArray()));
}
[Test, Category("LongRunning")]
public void be_able_to_read_events_slice_at_time()
{
var all = new List<RecordedEvent>();
var position = Position.End;
AllEventsSlice slice;
while (!(slice = _conn.ReadAllEventsBackwardAsync(position, 5, false).Result).IsEndOfStream)
{
all.AddRange(slice.Events.Select(x => x.Event));
position = slice.NextPosition;
}
Assert.That(EventDataComparer.Equal(_testEvents.Reverse().ToArray(), all.Take(_testEvents.Length).ToArray()));
}
}
}
| 40.149425 | 122 | 0.62067 | [
"Apache-2.0"
] | bartelink/EventStore | src/EventStore.Core.Tests/ClientAPI/read_all_events_backward_should.cs | 3,495 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class GotoKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$
return true;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"return true;
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (true) {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGoto()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"goto $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInClass()
{
await VerifyAbsenceAsync(
@"class C
{
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssignment()
{
await VerifyKeywordAsync(AddInsideMethod(
@" if (b != 0) {
count <<= 2;
char[] newBuffer = new char[count];
for (int copy = 0; copy < j; copy++)
newBuffer[copy] = buffer[copy];
buffer = newBuffer;
$$ Restart;
}"));
}
}
}
| 28.42735 | 74 | 0.63199 | [
"MIT"
] | Acidburn0zzz/roslyn | src/EditorFeatures/CSharpTest2/Recommendations/GotoKeywordRecommenderTests.cs | 3,328 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2019 Jeffrey Su & Suzhou Senparc Network Technology Co.,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.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2019 Senparc
文件名:JsApiTicketContainer.cs
文件功能描述:通用接口JsApiTicket容器,用于自动管理JsApiTicket,如果过期会重新获取
创建标识:Senparc - 20150313
修改标识:Senparc - 20150313
修改描述:整理接口
修改标识:Senparc - 20160312
修改描述:升级Container,继承自BaseContainer<JsApiTicketBag>
修改标识:Senparc - 20160318
修改描述:v3.3.4 使用FlushCache.CreateInstance使注册过程立即生效
修改标识:Senparc - 20160717
修改描述:v3.3.8 添加注册过程中的Name参数
修改标识:Senparc - 20160803
修改描述:v4.1.2 使用ApiUtility.GetExpireTime()方法处理过期
修改标识:Senparc - 20160804
修改描述:v4.1.3 增加TryGetTicketAsync,GetTicketAsync,GetTicketResultAsync的异步方法
修改标识:Senparc - 20160813
修改描述:v4.1.5 添加TryReRegister()方法,处理分布式缓存重启(丢失)的情况
修改标识:Senparc - 20160813
修改描述:v4.1.6 完善GetToken()方法
修改标识:Senparc - 20160813
修改描述:v4.1.8 修改命名空间为Senparc.Weixin.Work.Containers
修改标识:Senparc - 20161003
修改描述:v4.1.11 修复GetTicketResult()方法中的CheckRegistered()参数错误(少了appSecret)
修改标识:Senparc - 20180614
修改描述:CO2NET v0.1.0 ContainerBag 取消属性变动通知机制,使用手动更新缓存
修改标识:Senparc - 20180707
修改描述:v2.0.9 1、Container 的 Register() 的微信参数自动添加到 Config.SenparcWeixinSetting.Items 下
2、AccessTokenBag 的 AppId 和 Secret 属性名称改为 CorpId 和 CorpSecret
修改标识:Senparc - 20181226
修改描述:v3.3.2 修改 DateTime 为 DateTimeOffset
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Senparc.CO2NET.CacheUtility;
using Senparc.Weixin.Containers;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.Work.CommonAPIs;
using Senparc.Weixin.Work.Entities;
using Senparc.Weixin.Work.Exceptions;
using Senparc.Weixin.Utilities.WeixinUtility;
using Senparc.CO2NET.Extensions;
namespace Senparc.Weixin.Work.Containers
{
/// <summary>
/// JsApiTicketBag
/// </summary>
[Serializable]
public class JsApiTicketBag : BaseContainerBag
{
public string CoprId { get; set; }
// {
// get { return _appId; }
//#if NET35 || NET40
// set { this.SetContainerProperty(ref _appId, value, "AppId"); }
//#else
// set { this.SetContainerProperty(ref _appId, value); }
//#endif
// }
public string CorpSecret { get; set; }
// {
// get { return _appSecret; }
//#if NET35 || NET40
// set { this.SetContainerProperty(ref _appSecret, value, "AppSecret"); }
//#else
// set { this.SetContainerProperty(ref _appSecret, value); }
//#endif
// }
public JsApiTicketResult JsApiTicketResult { get; set; }
// {
// get { return _jsApiTicketResult; }
//#if NET35 || NET40
// set { this.SetContainerProperty(ref _jsApiTicketResult, value, "JsApiTicketResult"); }
//#else
// set { this.SetContainerProperty(ref _jsApiTicketResult, value); }
//#endif
// }
public DateTimeOffset ExpireTime { get; set; }
// {
// get { return _expireTime; }
//#if NET35 || NET40
// set { this.SetContainerProperty(ref _expireTime, value, "ExpireTime"); }
//#else
// set { this.SetContainerProperty(ref _expireTime, value); }
//#endif
// }
/// <summary>
/// 只针对这个AppId的锁
/// </summary>
internal object Lock = new object();
//private DateTime _expireTime;
//private JsApiTicketResult _jsApiTicketResult;
//private string _appSecret;
//private string _appId;
}
/// <summary>
/// 通用接口JsApiTicket容器,用于自动管理JsApiTicket,如果过期会重新获取
/// </summary>
public class JsApiTicketContainer : BaseContainer<JsApiTicketBag>
{
private const string UN_REGISTER_ALERT = "此AppId尚未注册,JsApiTicketContainer.Register完成注册(全局执行一次即可)!";
/// <summary>
/// 注册应用凭证信息,此操作只是注册,不会马上获取Ticket,并将清空之前的Ticket,
/// </summary>
/// <param name="appId"></param>
/// <param name="appSecret"></param>
/// <param name="name">标记JsApiTicket名称(如微信公众号名称),帮助管理员识别。当 name 不为 null 和 空值时,本次注册内容将会被记录到 Senparc.Weixin.Config.SenparcWeixinSetting.Items[name] 中,方便取用。</param>
/// 此接口无异步方法
private static string BuildingKey(string corpId, string corpSecret)
{
return corpId + corpSecret;
}
public static void Register(string corpId, string corpSecret, string name = null)
{
//记录注册信息,RegisterFunc委托内的过程会在缓存丢失之后自动重试
RegisterFunc = () =>
{
//using (FlushCache.CreateInstance())
//{
var bag = new JsApiTicketBag()
{
Name = name,
CoprId = corpId,
CorpSecret = corpSecret,
ExpireTime = DateTimeOffset.MinValue,
JsApiTicketResult = new JsApiTicketResult()
};
Update(BuildingKey(corpId, corpSecret), bag,null);
return bag;
//}
};
RegisterFunc();
if (!name.IsNullOrEmpty())
{
Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].WeixinCorpId = corpId;
Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].WeixinCorpSecret = corpSecret;
}
}
#region 同步方法
/// <summary>
/// 使用完整的应用凭证获取Ticket,如果不存在将自动注册
/// </summary>
/// <param name="appId"></param>
/// <param name="appSecret"></param>
/// <param name="getNewTicket"></param>
/// <returns></returns>
public static string TryGetTicket(string appId, string appSecret, bool getNewTicket = false)
{
if (!CheckRegistered(BuildingKey(appId, appSecret)) || getNewTicket)
{
Register(appId, appSecret);
}
return GetTicket(appId, appSecret, getNewTicket);
}
/// <summary>
/// 获取可用Ticket
/// </summary>
/// <param name="appId"></param>
/// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
/// <returns></returns>
public static string GetTicket(string appId, string appSecret, bool getNewTicket = false)
{
return GetTicketResult(appId, appSecret, getNewTicket).ticket;
}
/// <summary>
/// 获取可用Ticket
/// </summary>
/// <param name="appId"></param>
/// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
/// <returns></returns>
public static JsApiTicketResult GetTicketResult(string appId, string appSecret, bool getNewTicket = false)
{
if (!CheckRegistered(BuildingKey(appId, appSecret)))
{
throw new WeixinWorkException(UN_REGISTER_ALERT);
}
var jsApiTicketBag = TryGetItem(BuildingKey(appId, appSecret));
lock (jsApiTicketBag.Lock)
{
if (getNewTicket || jsApiTicketBag.ExpireTime <= SystemTime.Now)
{
//已过期,重新获取
jsApiTicketBag.JsApiTicketResult = CommonApi.GetTicket(jsApiTicketBag.CoprId, jsApiTicketBag.CorpSecret);
jsApiTicketBag.ExpireTime = ApiUtility.GetExpireTime(jsApiTicketBag.JsApiTicketResult.expires_in);
Update(jsApiTicketBag, null);//更新到缓存
}
}
return jsApiTicketBag.JsApiTicketResult;
}
///// <summary>
///// 检查是否已经注册
///// </summary>
///// <param name="appId"></param>
///// <returns></returns>
///// 此接口无异步方法
//public new static bool CheckRegistered(string appId)
//{
// return Cache.CheckExisted(appId);
//}
#endregion
#if !NET35 && !NET40
#region 异步方法
/// <summary>
/// 【异步方法】使用完整的应用凭证获取Ticket,如果不存在将自动注册
/// </summary>
/// <param name="appId"></param>
/// <param name="appSecret"></param>
/// <param name="getNewTicket"></param>
/// <returns></returns>
public static async Task<string> TryGetTicketAsync(string appId, string appSecret, bool getNewTicket = false)
{
if (!CheckRegistered(BuildingKey(appId, appSecret)) || getNewTicket)
{
Register(appId, appSecret);
}
return await GetTicketAsync(appId, appSecret, getNewTicket);
}
/// <summary>
/// 【异步方法】获取可用Ticket
/// </summary>
/// <param name="appId"></param>
/// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
/// <returns></returns>
public static async Task<string> GetTicketAsync(string appId, string appSecret, bool getNewTicket = false)
{
var result = await GetTicketResultAsync(appId, appSecret, getNewTicket);
return result.ticket;
}
/// <summary>
/// 【异步方法】获取可用Ticket
/// </summary>
/// <param name="appId"></param>
/// <param name="getNewTicket">是否强制重新获取新的Ticket</param>
/// <returns></returns>
public static async Task<JsApiTicketResult> GetTicketResultAsync(string appId, string appSecret, bool getNewTicket = false)
{
if (!CheckRegistered(BuildingKey(appId, appSecret)))
{
throw new WeixinWorkException(UN_REGISTER_ALERT);
}
var jsApiTicketBag = TryGetItem(BuildingKey(appId, appSecret));
//lock (jsApiTicketBag.Lock)
{
if (getNewTicket || jsApiTicketBag.ExpireTime <= SystemTime.Now)
{
//已过期,重新获取
var jsApiTicketResult = await CommonApi.GetTicketAsync(jsApiTicketBag.CoprId, jsApiTicketBag.CorpSecret);
jsApiTicketBag.JsApiTicketResult = jsApiTicketResult;
//jsApiTicketBag.JsApiTicketResult = CommonApi.GetTicket(jsApiTicketBag.AppId, jsApiTicketBag.AppSecret);
jsApiTicketBag.ExpireTime = ApiUtility.GetExpireTime(jsApiTicketBag.JsApiTicketResult.expires_in);
Update(jsApiTicketBag, null);//更新到缓存
}
}
return jsApiTicketBag.JsApiTicketResult;
}
#endregion
#endif
}
}
| 35.696594 | 169 | 0.577363 | [
"Apache-2.0"
] | DavidAlphaFox/WeiXinMPSDK | src/Senparc.Weixin.Work/Senparc.Weixin.Work/Containers/JsApiTicketContainer.cs | 12,816 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Harmony;
using TMPro;
namespace BS_Utils.Gameplay.HarmonyPatches
{
[HarmonyPatch(typeof(StandardLevelScenesTransitionSetupDataSO),
new Type[] {
typeof(IDifficultyBeatmap),
typeof(GameplayModifiers),
typeof(PlayerSpecificSettings),
typeof(PracticeSettings),
typeof(bool)})]
[HarmonyPatch("Init", MethodType.Normal)]
class BlahBlahGrabTheLevelData
{
static void Prefix(StandardLevelScenesTransitionSetupDataSO __instance, IDifficultyBeatmap difficultyBeatmap, GameplayModifiers gameplayModifiers, PlayerSpecificSettings playerSpecificSettings, PracticeSettings practiceSettings, bool useTestNoteCutSoundEffects)
{
Plugin.LevelData.GameplayCoreSceneSetupData = new GameplayCoreSceneSetupData(difficultyBeatmap, gameplayModifiers, playerSpecificSettings, practiceSettings, useTestNoteCutSoundEffects);
Plugin.LevelData.IsSet = true;
__instance.didFinishEvent += __instance_didFinishEvent;
}
private static void __instance_didFinishEvent(StandardLevelScenesTransitionSetupDataSO levelScenesTransitionSetupDataSO, LevelCompletionResults levelCompletionResults)
{
Plugin.TriggerLevelFinishEvent(levelScenesTransitionSetupDataSO, levelCompletionResults);
}
}
}
| 44.529412 | 269 | 0.734478 | [
"MIT"
] | sc2ad/Beat-Saber-Utils | Beat Saber Utils/Gameplay/HarmonyPatches/BlahBlahGrabTheLevelData.cs | 1,516 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Response to UserCallCenterEnhancedReportingScheduledReportGetRequest.
/// <see cref="UserCallCenterEnhancedReportingScheduledReportGetRequest"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""e2c537e3e39483b96620673a7012ffdd:6839"",""children"":[{""__type"":""Choice:#BroadWorksConnector.Ocip.Validation"",""id"":""e2c537e3e39483b96620673a7012ffdd:6851"",""optional"":true}]}]")]
public class UserCallCenterEnhancedReportingScheduledReportGetResponse : BroadWorksConnector.Ocip.Models.C.OCIDataResponse
{
private string _description;
[XmlElement(ElementName = "description", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
[MinLength(1)]
[MaxLength(80)]
public string Description
{
get => _description;
set
{
DescriptionSpecified = true;
_description = value;
}
}
[XmlIgnore]
protected bool DescriptionSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterReportTemplateKey _reportTemplate;
[XmlElement(ElementName = "reportTemplate", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.CallCenterReportTemplateKey ReportTemplate
{
get => _reportTemplate;
set
{
ReportTemplateSpecified = true;
_reportTemplate = value;
}
}
[XmlIgnore]
protected bool ReportTemplateSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterReportSchedule _schedule;
[XmlElement(ElementName = "schedule", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.CallCenterReportSchedule Schedule
{
get => _schedule;
set
{
ScheduleSpecified = true;
_schedule = value;
}
}
[XmlIgnore]
protected bool ScheduleSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterReportSamplingPeriod _samplingPeriod;
[XmlElement(ElementName = "samplingPeriod", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.CallCenterReportSamplingPeriod SamplingPeriod
{
get => _samplingPeriod;
set
{
SamplingPeriodSpecified = true;
_samplingPeriod = value;
}
}
[XmlIgnore]
protected bool SamplingPeriodSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.DayOfWeek _startDayOfWeek;
[XmlElement(ElementName = "startDayOfWeek", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.DayOfWeek StartDayOfWeek
{
get => _startDayOfWeek;
set
{
StartDayOfWeekSpecified = true;
_startDayOfWeek = value;
}
}
[XmlIgnore]
protected bool StartDayOfWeekSpecified { get; set; }
private string _reportTimeZone;
[XmlElement(ElementName = "reportTimeZone", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
[MinLength(1)]
[MaxLength(127)]
public string ReportTimeZone
{
get => _reportTimeZone;
set
{
ReportTimeZoneSpecified = true;
_reportTimeZone = value;
}
}
[XmlIgnore]
protected bool ReportTimeZoneSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterReportDateFormat _reportDateFormat;
[XmlElement(ElementName = "reportDateFormat", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.CallCenterReportDateFormat ReportDateFormat
{
get => _reportDateFormat;
set
{
ReportDateFormatSpecified = true;
_reportDateFormat = value;
}
}
[XmlIgnore]
protected bool ReportDateFormatSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterReportTimeFormat _reportTimeFormat;
[XmlElement(ElementName = "reportTimeFormat", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.CallCenterReportTimeFormat ReportTimeFormat
{
get => _reportTimeFormat;
set
{
ReportTimeFormatSpecified = true;
_reportTimeFormat = value;
}
}
[XmlIgnore]
protected bool ReportTimeFormatSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterReportInterval _reportInterval;
[XmlElement(ElementName = "reportInterval", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.CallCenterReportInterval ReportInterval
{
get => _reportInterval;
set
{
ReportIntervalSpecified = true;
_reportInterval = value;
}
}
[XmlIgnore]
protected bool ReportIntervalSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterReportFileFormat _reportFormat;
[XmlElement(ElementName = "reportFormat", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.CallCenterReportFileFormat ReportFormat
{
get => _reportFormat;
set
{
ReportFormatSpecified = true;
_reportFormat = value;
}
}
[XmlIgnore]
protected bool ReportFormatSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterScheduledReportAgentSelectionRead _agent;
[XmlElement(ElementName = "agent", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.CallCenterScheduledReportAgentSelectionRead Agent
{
get => _agent;
set
{
AgentSpecified = true;
_agent = value;
}
}
[XmlIgnore]
protected bool AgentSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterScheduledReportCallCenterSelection _callCenter;
[XmlElement(ElementName = "callCenter", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6851")]
public BroadWorksConnector.Ocip.Models.CallCenterScheduledReportCallCenterSelection CallCenter
{
get => _callCenter;
set
{
CallCenterSpecified = true;
_callCenter = value;
}
}
[XmlIgnore]
protected bool CallCenterSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterScheduledReportDNISSelection _dnis;
[XmlElement(ElementName = "dnis", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6851")]
public BroadWorksConnector.Ocip.Models.CallCenterScheduledReportDNISSelection Dnis
{
get => _dnis;
set
{
DnisSpecified = true;
_dnis = value;
}
}
[XmlIgnore]
protected bool DnisSpecified { get; set; }
private int _callCompletionThresholdSeconds;
[XmlElement(ElementName = "callCompletionThresholdSeconds", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
[MinInclusive(1)]
[MaxInclusive(7200)]
public int CallCompletionThresholdSeconds
{
get => _callCompletionThresholdSeconds;
set
{
CallCompletionThresholdSecondsSpecified = true;
_callCompletionThresholdSeconds = value;
}
}
[XmlIgnore]
protected bool CallCompletionThresholdSecondsSpecified { get; set; }
private int _shortDurationThresholdSeconds;
[XmlElement(ElementName = "shortDurationThresholdSeconds", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
[MinInclusive(1)]
[MaxInclusive(7200)]
public int ShortDurationThresholdSeconds
{
get => _shortDurationThresholdSeconds;
set
{
ShortDurationThresholdSecondsSpecified = true;
_shortDurationThresholdSeconds = value;
}
}
[XmlIgnore]
protected bool ShortDurationThresholdSecondsSpecified { get; set; }
private List<int> _serviceLevelThresholdSeconds = new List<int>();
[XmlElement(ElementName = "serviceLevelThresholdSeconds", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
[MinInclusive(1)]
[MaxInclusive(7200)]
public List<int> ServiceLevelThresholdSeconds
{
get => _serviceLevelThresholdSeconds;
set
{
ServiceLevelThresholdSecondsSpecified = true;
_serviceLevelThresholdSeconds = value;
}
}
[XmlIgnore]
protected bool ServiceLevelThresholdSecondsSpecified { get; set; }
private BroadWorksConnector.Ocip.Models.CallCenterScheduledReportServiceLevelInclusions _serviceLevelInclusions;
[XmlElement(ElementName = "serviceLevelInclusions", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
public BroadWorksConnector.Ocip.Models.CallCenterScheduledReportServiceLevelInclusions ServiceLevelInclusions
{
get => _serviceLevelInclusions;
set
{
ServiceLevelInclusionsSpecified = true;
_serviceLevelInclusions = value;
}
}
[XmlIgnore]
protected bool ServiceLevelInclusionsSpecified { get; set; }
private int _serviceLevelObjectivePercentage;
[XmlElement(ElementName = "serviceLevelObjectivePercentage", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
[MinInclusive(0)]
[MaxInclusive(100)]
public int ServiceLevelObjectivePercentage
{
get => _serviceLevelObjectivePercentage;
set
{
ServiceLevelObjectivePercentageSpecified = true;
_serviceLevelObjectivePercentage = value;
}
}
[XmlIgnore]
protected bool ServiceLevelObjectivePercentageSpecified { get; set; }
private List<int> _abandonedCallThresholdSeconds = new List<int>();
[XmlElement(ElementName = "abandonedCallThresholdSeconds", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
[MinInclusive(1)]
[MaxInclusive(7200)]
public List<int> AbandonedCallThresholdSeconds
{
get => _abandonedCallThresholdSeconds;
set
{
AbandonedCallThresholdSecondsSpecified = true;
_abandonedCallThresholdSeconds = value;
}
}
[XmlIgnore]
protected bool AbandonedCallThresholdSecondsSpecified { get; set; }
private List<string> _emailAddress = new List<string>();
[XmlElement(ElementName = "emailAddress", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:6839")]
[MinLength(1)]
[MaxLength(80)]
public List<string> EmailAddress
{
get => _emailAddress;
set
{
EmailAddressSpecified = true;
_emailAddress = value;
}
}
[XmlIgnore]
protected bool EmailAddressSpecified { get; set; }
}
}
| 34.033505 | 273 | 0.61242 | [
"MIT"
] | Rogn/broadworks-connector-net | BroadworksConnector/Ocip/Models/UserCallCenterEnhancedReportingScheduledReportGetResponse.cs | 13,205 | C# |
using System.Collections.Generic;
using System.Linq;
using UDVF.Runtime.Scripts.ChartEffectors;
using UDVF.Runtime.Scripts.Charts.RenderCommands;
using UnityEngine;
using UnityEngine.UI;
namespace UDVF.Runtime.Scripts.Charts
{
[ExecuteInEditMode]
[RequireComponent(typeof(CanvasRenderer))]
public abstract class ChartBaseRenderer : MaskableGraphic
{
protected Vector3[] _CornersArray = new Vector3[4];
protected List<ChartRenderCommand> _RenderBuffer
= new List<ChartRenderCommand>();
public void UpdateData()
{
SetAllDirty();
}
protected override void OnPopulateMesh(VertexHelper vh)
{
rectTransform.GetLocalCorners(_CornersArray);
vh.Clear();
_RenderBuffer.Clear();
ProcessBuffer();
ProcessEffectors();
Render(vh);
}
protected virtual void Render(VertexHelper vh)
{
var commands = _RenderBuffer.OrderBy(command => command.SortingOrder);
foreach (var command in commands)
{
command.SetTransformCoordsFunc(GetRealChartPos);
command.Render(vh);
}
}
private void ProcessEffectors()
{
var effectors = GetComponents<ChartEffector>();
if (effectors.Length > 0)
{
foreach (ChartEffector chartEffector in effectors)
{
_RenderBuffer.AddRange(chartEffector.GenerateRenderCommands(this));
}
}
}
protected abstract void ProcessBuffer();
public virtual Vector2 GetRealChartPos(Vector2 pos)
{
return new Vector2(
Mathf.LerpUnclamped(_CornersArray[0].x, _CornersArray[2].x, pos.x),
Mathf.LerpUnclamped(_CornersArray[0].y, _CornersArray[2].y, pos.y)
);
}
protected override void OnValidate()
{
base.OnValidate();
SetVerticesDirty();
}
}
}
| 29.074627 | 82 | 0.624743 | [
"MIT"
] | Nox7atra/udvf | Assets/UDVF/Runtime/Scripts/Renderers/ChartBaseRenderer.cs | 1,948 | C# |
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using MQTTnet.Client.Publishing;
using MQTTnet.Client.Subscribing;
using MQTTnet.Client.Unsubscribing;
using MQTTnet.Exceptions;
using MQTTnet.Packets;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using MqttClientSubscribeResult = MQTTnet.Client.Subscribing.MqttClientSubscribeResult;
namespace MQTTnet.Formatter.V5
{
public sealed class MqttV500DataConverter : IMqttDataConverter
{
public MqttPublishPacket CreatePublishPacket(MqttApplicationMessage applicationMessage)
{
if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
var packet = new MqttPublishPacket
{
Topic = applicationMessage.Topic,
Payload = applicationMessage.Payload,
QualityOfServiceLevel = applicationMessage.QualityOfServiceLevel,
Retain = applicationMessage.Retain,
Dup = applicationMessage.Dup,
Properties = new MqttPublishPacketProperties
{
ContentType = applicationMessage.ContentType,
CorrelationData = applicationMessage.CorrelationData,
MessageExpiryInterval = applicationMessage.MessageExpiryInterval,
PayloadFormatIndicator = applicationMessage.PayloadFormatIndicator,
ResponseTopic = applicationMessage.ResponseTopic,
SubscriptionIdentifiers = applicationMessage.SubscriptionIdentifiers,
TopicAlias = applicationMessage.TopicAlias
}
};
if (applicationMessage.UserProperties != null)
{
packet.Properties.UserProperties = new List<MqttUserProperty>();
packet.Properties.UserProperties.AddRange(applicationMessage.UserProperties);
}
return packet;
}
public MqttPubAckPacket CreatePubAckPacket(MqttPublishPacket publishPacket, MqttApplicationMessageReceivedReasonCode reasonCode)
{
if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket));
return new MqttPubAckPacket
{
PacketIdentifier = publishPacket.PacketIdentifier,
ReasonCode = (MqttPubAckReasonCode)(int)reasonCode
};
}
public MqttPubRecPacket CreatePubRecPacket(MqttPublishPacket publishPacket, MqttApplicationMessageReceivedReasonCode reasonCode)
{
if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket));
return new MqttPubRecPacket
{
PacketIdentifier = publishPacket.PacketIdentifier,
ReasonCode = (MqttPubRecReasonCode)(int)reasonCode
};
}
public MqttPubCompPacket CreatePubCompPacket(MqttPubRelPacket pubRelPacket, MqttApplicationMessageReceivedReasonCode reasonCode)
{
if (pubRelPacket == null) throw new ArgumentNullException(nameof(pubRelPacket));
return new MqttPubCompPacket
{
PacketIdentifier = pubRelPacket.PacketIdentifier,
ReasonCode = (MqttPubCompReasonCode)(int)reasonCode
};
}
public MqttPubRelPacket CreatePubRelPacket(MqttPubRecPacket pubRecPacket, MqttApplicationMessageReceivedReasonCode reasonCode)
{
if (pubRecPacket == null) throw new ArgumentNullException(nameof(pubRecPacket));
return new MqttPubRelPacket
{
PacketIdentifier = pubRecPacket.PacketIdentifier,
ReasonCode = (MqttPubRelReasonCode)(int)reasonCode
};
}
public MqttApplicationMessage CreateApplicationMessage(MqttPublishPacket publishPacket)
{
if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket));
return new MqttApplicationMessage
{
Topic = publishPacket.Topic,
Payload = publishPacket.Payload,
QualityOfServiceLevel = publishPacket.QualityOfServiceLevel,
Retain = publishPacket.Retain,
Dup = publishPacket.Dup,
ResponseTopic = publishPacket.Properties?.ResponseTopic,
ContentType = publishPacket.Properties?.ContentType,
CorrelationData = publishPacket.Properties?.CorrelationData,
MessageExpiryInterval = publishPacket.Properties?.MessageExpiryInterval,
SubscriptionIdentifiers = publishPacket.Properties?.SubscriptionIdentifiers,
TopicAlias = publishPacket.Properties?.TopicAlias,
PayloadFormatIndicator = publishPacket.Properties?.PayloadFormatIndicator,
UserProperties = publishPacket.Properties?.UserProperties ?? new List<MqttUserProperty>()
};
}
public MqttClientAuthenticateResult CreateClientConnectResult(MqttConnAckPacket connAckPacket)
{
if (connAckPacket == null) throw new ArgumentNullException(nameof(connAckPacket));
return new MqttClientAuthenticateResult
{
IsSessionPresent = connAckPacket.IsSessionPresent,
ResultCode = (MqttClientConnectResultCode)(int)(connAckPacket.ReasonCode ?? 0),
WildcardSubscriptionAvailable = connAckPacket.Properties?.WildcardSubscriptionAvailable,
RetainAvailable = connAckPacket.Properties?.RetainAvailable,
AssignedClientIdentifier = connAckPacket.Properties?.AssignedClientIdentifier,
AuthenticationMethod = connAckPacket.Properties?.AuthenticationMethod,
AuthenticationData = connAckPacket.Properties?.AuthenticationData,
MaximumPacketSize = connAckPacket.Properties?.MaximumPacketSize,
ReasonString = connAckPacket.Properties?.ReasonString,
ReceiveMaximum = connAckPacket.Properties?.ReceiveMaximum,
MaximumQoS = connAckPacket.Properties?.MaximumQoS ?? MqttQualityOfServiceLevel.ExactlyOnce,
ResponseInformation = connAckPacket.Properties?.ResponseInformation,
TopicAliasMaximum = connAckPacket.Properties?.TopicAliasMaximum,
ServerReference = connAckPacket.Properties?.ServerReference,
ServerKeepAlive = connAckPacket.Properties?.ServerKeepAlive,
SessionExpiryInterval = connAckPacket.Properties?.SessionExpiryInterval,
SubscriptionIdentifiersAvailable = connAckPacket.Properties?.SubscriptionIdentifiersAvailable,
SharedSubscriptionAvailable = connAckPacket.Properties?.SharedSubscriptionAvailable,
UserProperties = connAckPacket.Properties?.UserProperties
};
}
public MqttConnectPacket CreateConnectPacket(MqttApplicationMessage willApplicationMessage, IMqttClientOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
return new MqttConnectPacket
{
ClientId = options.ClientId,
Username = options.Credentials?.Username,
Password = options.Credentials?.Password,
CleanSession = options.CleanSession,
KeepAlivePeriod = (ushort)options.KeepAlivePeriod.TotalSeconds,
WillMessage = willApplicationMessage,
Properties = new MqttConnectPacketProperties
{
AuthenticationMethod = options.AuthenticationMethod,
AuthenticationData = options.AuthenticationData,
WillDelayInterval = options.WillDelayInterval,
MaximumPacketSize = options.MaximumPacketSize,
ReceiveMaximum = options.ReceiveMaximum,
RequestProblemInformation = options.RequestProblemInformation,
RequestResponseInformation = options.RequestResponseInformation,
SessionExpiryInterval = options.SessionExpiryInterval,
TopicAliasMaximum = options.TopicAliasMaximum,
UserProperties = options.UserProperties
}
};
}
public MqttConnAckPacket CreateConnAckPacket(MqttConnectionValidatorContext connectionValidatorContext)
{
if (connectionValidatorContext == null) throw new ArgumentNullException(nameof(connectionValidatorContext));
return new MqttConnAckPacket
{
ReasonCode = connectionValidatorContext.ReasonCode,
Properties = new MqttConnAckPacketProperties
{
UserProperties = connectionValidatorContext.ResponseUserProperties,
AuthenticationMethod = connectionValidatorContext.AuthenticationMethod,
AuthenticationData = connectionValidatorContext.ResponseAuthenticationData,
AssignedClientIdentifier = connectionValidatorContext.AssignedClientIdentifier,
ReasonString = connectionValidatorContext.ReasonString,
TopicAliasMaximum = ushort.MaxValue
}
};
}
public MqttClientSubscribeResult CreateClientSubscribeResult(MqttSubscribePacket subscribePacket, MqttSubAckPacket subAckPacket)
{
if (subscribePacket == null) throw new ArgumentNullException(nameof(subscribePacket));
if (subAckPacket == null) throw new ArgumentNullException(nameof(subAckPacket));
if (subAckPacket.ReasonCodes.Count != subscribePacket.TopicFilters.Count)
{
throw new MqttProtocolViolationException("The reason codes are not matching the topic filters [MQTT-3.9.3-1].");
}
var result = new MqttClientSubscribeResult();
result.Items.AddRange(subscribePacket.TopicFilters.Select((t, i) =>
new MqttClientSubscribeResultItem(t, (MqttClientSubscribeResultCode)subAckPacket.ReasonCodes[i])));
return result;
}
public MqttClientUnsubscribeResult CreateClientUnsubscribeResult(MqttUnsubscribePacket unsubscribePacket, MqttUnsubAckPacket unsubAckPacket)
{
if (unsubscribePacket == null) throw new ArgumentNullException(nameof(unsubscribePacket));
if (unsubAckPacket == null) throw new ArgumentNullException(nameof(unsubAckPacket));
if (unsubAckPacket.ReasonCodes.Count != unsubscribePacket.TopicFilters.Count)
{
throw new MqttProtocolViolationException("The return codes are not matching the topic filters [MQTT-3.9.3-1].");
}
var result = new MqttClientUnsubscribeResult();
result.Items.AddRange(unsubscribePacket.TopicFilters.Select((t, i) =>
new MqttClientUnsubscribeResultItem(t, (MqttClientUnsubscribeResultCode)unsubAckPacket.ReasonCodes[i])));
return result;
}
public MqttSubscribePacket CreateSubscribePacket(MqttClientSubscribeOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
var packet = new MqttSubscribePacket
{
Properties = new MqttSubscribePacketProperties()
};
packet.TopicFilters.AddRange(options.TopicFilters);
packet.Properties.SubscriptionIdentifier = options.SubscriptionIdentifier;
packet.Properties.UserProperties = options.UserProperties;
return packet;
}
public MqttSubAckPacket CreateSubAckPacket(MqttSubscribePacket subscribePacket, Server.MqttClientSubscribeResult subscribeResult)
{
if (subscribePacket == null) throw new ArgumentNullException(nameof(subscribePacket));
if (subscribeResult == null) throw new ArgumentNullException(nameof(subscribeResult));
var subackPacket = new MqttSubAckPacket
{
PacketIdentifier = subscribePacket.PacketIdentifier
};
subackPacket.ReasonCodes.AddRange(subscribeResult.ReasonCodes);
return subackPacket;
}
public MqttUnsubscribePacket CreateUnsubscribePacket(MqttClientUnsubscribeOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
var packet = new MqttUnsubscribePacket
{
Properties = new MqttUnsubscribePacketProperties()
};
packet.TopicFilters.AddRange(options.TopicFilters);
packet.Properties.UserProperties = options.UserProperties;
return packet;
}
public MqttUnsubAckPacket CreateUnsubAckPacket(MqttUnsubscribePacket unsubscribePacket, List<MqttUnsubscribeReasonCode> reasonCodes)
{
if (unsubscribePacket == null) throw new ArgumentNullException(nameof(unsubscribePacket));
if (reasonCodes == null) throw new ArgumentNullException(nameof(reasonCodes));
return new MqttUnsubAckPacket
{
PacketIdentifier = unsubscribePacket.PacketIdentifier,
ReasonCodes = reasonCodes
};
}
public MqttDisconnectPacket CreateDisconnectPacket(MqttClientDisconnectOptions options)
{
var packet = new MqttDisconnectPacket();
if (options == null)
{
packet.ReasonCode = MqttDisconnectReasonCode.NormalDisconnection;
}
else
{
packet.ReasonCode = (MqttDisconnectReasonCode)options.ReasonCode;
}
return packet;
}
public MqttClientPublishResult CreateClientPublishResult(MqttPubAckPacket pubAckPacket)
{
var result = new MqttClientPublishResult
{
ReasonCode = MqttClientPublishReasonCode.Success,
ReasonString = pubAckPacket?.Properties?.ReasonString,
UserProperties = pubAckPacket?.Properties?.UserProperties
};
if (pubAckPacket != null)
{
// QoS 0 has no response. So we treat it as a success always.
// Both enums have the same values. So it can be easily converted.
result.ReasonCode = (MqttClientPublishReasonCode)(int)(pubAckPacket.ReasonCode ?? 0);
result.PacketIdentifier = pubAckPacket.PacketIdentifier;
}
return result;
}
public MqttClientPublishResult CreateClientPublishResult(MqttPubRecPacket pubRecPacket, MqttPubCompPacket pubCompPacket)
{
if (pubRecPacket == null || pubCompPacket == null)
{
return new MqttClientPublishResult
{
ReasonCode = MqttClientPublishReasonCode.UnspecifiedError
};
}
// The PUBCOMP is the last packet in QoS 2. So we use the results from that instead of PUBREC.
if (pubCompPacket.ReasonCode == MqttPubCompReasonCode.PacketIdentifierNotFound)
{
return new MqttClientPublishResult
{
PacketIdentifier = pubCompPacket.PacketIdentifier,
ReasonCode = MqttClientPublishReasonCode.UnspecifiedError,
ReasonString = pubCompPacket.Properties?.ReasonString,
UserProperties = pubCompPacket.Properties?.UserProperties
};
}
var result = new MqttClientPublishResult
{
PacketIdentifier = pubCompPacket.PacketIdentifier,
ReasonCode = MqttClientPublishReasonCode.Success,
ReasonString = pubCompPacket.Properties?.ReasonString,
UserProperties = pubCompPacket.Properties?.UserProperties
};
if (pubRecPacket.ReasonCode.HasValue)
{
// Both enums share the same values.
result.ReasonCode = (MqttClientPublishReasonCode)(pubRecPacket.ReasonCode ?? 0);
}
return result;
}
}
} | 45.490358 | 148 | 0.64967 | [
"MIT"
] | 765643729/MQTTnet | Source/MQTTnet/Formatter/V5/MqttV500DataConverter.cs | 16,515 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Pomodoro
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.833333 | 43 | 0.666667 | [
"MIT"
] | korn3l/Pomodoro | Pomodoro/App.xaml.cs | 341 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DataMigration.V20180715Preview.Inputs
{
/// <summary>
/// Properties for the task that collects user tables for the given list of Oracle schemas
/// </summary>
public sealed class GetUserTablesOracleTaskPropertiesArgs : Pulumi.ResourceArgs
{
[Input("clientData")]
private InputMap<string>? _clientData;
/// <summary>
/// Key value pairs of client data to attach meta data information to task
/// </summary>
public InputMap<string> ClientData
{
get => _clientData ?? (_clientData = new InputMap<string>());
set => _clientData = value;
}
/// <summary>
/// Task input
/// </summary>
[Input("input")]
public Input<Inputs.GetUserTablesOracleTaskInputArgs>? Input { get; set; }
/// <summary>
/// Task type.
/// Expected value is 'GetUserTablesOracle'.
/// </summary>
[Input("taskType", required: true)]
public Input<string> TaskType { get; set; } = null!;
public GetUserTablesOracleTaskPropertiesArgs()
{
}
}
}
| 30.479167 | 94 | 0.619959 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataMigration/V20180715Preview/Inputs/GetUserTablesOracleTaskPropertiesArgs.cs | 1,463 | C# |
using Com.Ctrip.Framework.Apollo.Enums;
namespace Com.Ctrip.Framework.Apollo.Util
{
public sealed class EnvUtils
{
public static Env? transformEnv(string envName)
{
if (string.IsNullOrEmpty(envName))
{
return null;
}
string tempEnvName = envName.ToUpper();
switch (tempEnvName)
{
case "LPT":
return Env.LPT;
case "FAT":
case "FWS":
return Env.FAT;
case "UAT":
return Env.UAT;
case "PRO":
case "PROD": //just in case
return Env.PRO;
case "DEV":
return Env.DEV;
case "LOCAL":
return Env.LOCAL;
default:
//handle ctrip subenv such as fat44 from ReleaseInfo
if (tempEnvName.Contains("FAT") || tempEnvName.Contains("FWS"))
{
return Env.FAT;
}
//handle ctrip subenv such as lpt44 from ReleaseInfo
if (tempEnvName.Contains("LPT"))
{
return Env.LPT;
}
//handle ctrip env such as uat_nt from ReleaseInfo
if (tempEnvName.Contains("UAT"))
{
return Env.UAT;
}
//just in case
if (tempEnvName.Contains("PRO"))
{
return Env.PRO;
}
return null;
}
}
}
}
| 30.637931 | 83 | 0.384356 | [
"Apache-2.0"
] | 307209239/apollo-net | Apollo/Util/EnvUtils.cs | 1,779 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
namespace Microsoft.CodeAnalysis
{
internal static class CommonAttributeDataExtensions
{
public static bool TryGetGuidAttributeValue(this AttributeData attrData, out string? guidString)
{
if (attrData.CommonConstructorArguments.Length == 1)
{
object? value = attrData.CommonConstructorArguments[0].ValueInternal;
if (value == null || value is string)
{
guidString = (string?)value;
return true;
}
}
guidString = null;
return false;
}
}
}
| 29.758621 | 104 | 0.595597 | [
"MIT"
] | 06needhamt/roslyn | src/Compilers/Core/Portable/Symbols/CommonAttributeDataExtensions.cs | 865 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Compute.V20200601.Outputs
{
[OutputType]
public sealed class VirtualMachineIdentityResponse
{
/// <summary>
/// The principal id of virtual machine identity. This property will only be provided for a system assigned identity.
/// </summary>
public readonly string PrincipalId;
/// <summary>
/// The tenant id associated with the virtual machine. This property will only be provided for a system assigned identity.
/// </summary>
public readonly string TenantId;
/// <summary>
/// The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine.
/// </summary>
public readonly string? Type;
/// <summary>
/// The list of user identities associated with the Virtual Machine. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.VirtualMachineIdentityResponseUserAssignedIdentities>? UserAssignedIdentities;
[OutputConstructor]
private VirtualMachineIdentityResponse(
string principalId,
string tenantId,
string? type,
ImmutableDictionary<string, Outputs.VirtualMachineIdentityResponseUserAssignedIdentities>? userAssignedIdentities)
{
PrincipalId = principalId;
TenantId = tenantId;
Type = type;
UserAssignedIdentities = userAssignedIdentities;
}
}
}
| 43.48 | 302 | 0.698712 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Compute/V20200601/Outputs/VirtualMachineIdentityResponse.cs | 2,174 | C# |
namespace Phoenix.Infrastructure.Extensions {
public class ErrorInfo {
public ErrorInfo(string propertyName, string errorMessage, object @object = null) {
PropertyName = propertyName;
ErrorMessage = errorMessage;
Object = @object;
}
public string PropertyName { get; private set; }
public string ErrorMessage { get; private set; }
public object Object { get; private set; }
}
} | 31 | 91 | 0.627957 | [
"MIT"
] | m-sadegh-sh/Phoenix | src/Phoenix.Infrastructure/Extensions/ErrorInfo.cs | 467 | 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/ShlObj_core.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='EXP_SZ_LINK.xml' path='doc/member[@name="EXP_SZ_LINK"]/*' />
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe partial struct EXP_SZ_LINK
{
/// <include file='EXP_SZ_LINK.xml' path='doc/member[@name="EXP_SZ_LINK.cbSize"]/*' />
[NativeTypeName("DWORD")]
public uint cbSize;
/// <include file='EXP_SZ_LINK.xml' path='doc/member[@name="EXP_SZ_LINK.dwSignature"]/*' />
[NativeTypeName("DWORD")]
public uint dwSignature;
/// <include file='EXP_SZ_LINK.xml' path='doc/member[@name="EXP_SZ_LINK.szTarget"]/*' />
[NativeTypeName("CHAR [260]")]
public fixed sbyte szTarget[260];
/// <include file='EXP_SZ_LINK.xml' path='doc/member[@name="EXP_SZ_LINK.swzTarget"]/*' />
[NativeTypeName("WCHAR [260]")]
public fixed ushort swzTarget[260];
}
| 39.233333 | 145 | 0.707732 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/ShlObj_core/EXP_SZ_LINK.cs | 1,179 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rothbard_Engine
{
/// <summary>
/// Allows a class to receive keyboard event data
/// </summary>
public interface IKeyboardListener
{
/// <summary>
/// Receives keyboard event data
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
void OnNewKeyboardInput(object sender, IKeyboardInput args);
}
} | 25.047619 | 68 | 0.631179 | [
"Apache-2.0"
] | ReidGiles/Rothbard-Engine | Rothbard-Engine/Rothbard-Engine/Input/IKeyboardListener.cs | 528 | C# |
namespace DoubleDispatch.Dispatch
{
using System;
public class SingleDispatcher
{
public void Dispatch(Base @base)
{
Console.WriteLine($"Method {nameof(Dispatch)}({nameof(Base)}) - type: {@base.GetType()}");
}
public void Dispatch(Foo foo)
{
Console.WriteLine($"Method {nameof(Dispatch)}({nameof(Foo)}) - type: {foo.GetType()}");
}
public void Dispatch(Bar bar)
{
Console.WriteLine($"Method {nameof(Dispatch)}({nameof(Bar)}) - type: {bar.GetType()}");
}
public void Dispatch(Baz baz)
{
Console.WriteLine($"Method {nameof(Dispatch)}({nameof(Baz)}) - type: {baz.GetType()}");
}
}
}
| 25.724138 | 102 | 0.542895 | [
"MIT"
] | aliostad/deep-learning-lang-detection | data/test/csharp/49da791160e8764d41622708122ade4ebec8907dSingleDispatcher.cs | 748 | C# |
namespace EmplSys.WebAPI.App_Start
{
using Data;
using System.Data.Entity;
public static class DatabaseConfig
{
public static void Initialize()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<EmplSysDbContext, Configuration>());
}
}
} | 23.461538 | 107 | 0.662295 | [
"MIT"
] | dirk-dagger-667/EmployeeManagement | EmplSys.WebAPI/App_Start/DatabaseConfig.cs | 307 | C# |
#pragma checksum "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4c2f42991e3949141b797d5d11b576d646735fcc"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Livro_Novo), @"mvc.1.0.view", @"/Views/Livro/Novo.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Livro/Novo.cshtml", typeof(AspNetCore.Views_Livro_Novo))]
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:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\_ViewImports.cshtml"
using Alura.ListaLeitura.Modelos;
#line default
#line hidden
#line 2 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\_ViewImports.cshtml"
using Alura.ListaLeitura.Seguranca;
#line default
#line hidden
#line 3 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\_ViewImports.cshtml"
using Alura.ListaLeitura.WebApp.Models;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4c2f42991e3949141b797d5d11b576d646735fcc", @"/Views/Livro/Novo.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"09a6afb971af4a7689ac482a01ffc16df74495f1", @"/Views/_ViewImports.cshtml")]
public class Views_Livro_Novo : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<LivroUpload>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("livro img-fluid"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("imgCapa"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/images/capas/capa-vazia.png"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("control-label"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rows", new global::Microsoft.AspNetCore.Html.HtmlString("5"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("row"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("role", new global::Microsoft.AspNetCore.Html.HtmlString("form"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("enctype", new global::Microsoft.AspNetCore.Html.HtmlString("multipart/form-data"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Novo", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.TextAreaTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(20, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 3 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
Layout = "~/Views/Shared/_Layout.cshtml";
#line default
#line hidden
BeginContext(76, 39, true);
WriteLiteral("\r\n<h2>Novo Livro</h2>\r\n\r\n<main>\r\n\r\n ");
EndContext();
BeginContext(115, 2626, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4f62bda287e34977b400c919c6237795", async() => {
BeginContext(207, 93, true);
WriteLiteral("\r\n\r\n <div class=\"col-5 text-center\">\r\n <div class=\"capa\">\r\n ");
EndContext();
BeginContext(300, 208, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "8bf6cb0df47844c3a818c33536135f2c", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "alt", 1, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line 18 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
AddHtmlAttributeValue("", 449, Model.Titulo, 449, 13, false);
#line default
#line hidden
EndAddHtmlAttributeValues(__tagHelperExecutionContext);
BeginWriteTagHelperAttribute();
#line 19 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
Write(Model.Id);
#line default
#line hidden
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__tagHelperExecutionContext.AddHtmlAttribute("data-id", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(508, 376, true);
WriteLiteral(@"
<p class=""py-3"">
<label class=""btn btn-outline-dark"">
Alterar Capa
<input id=""ImagemCapa"" name=""Capa"" type=""file"" class=""d-none"" accept=""image/x-png"" />
</label>
</p>
</div>
</div>
<div class=""col-5"">
");
EndContext();
BeginContext(884, 66, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "7e97d9a7c4304e319495839865601019", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper);
#line 31 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary = global::Microsoft.AspNetCore.Mvc.Rendering.ValidationSummary.ModelOnly;
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-summary", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(950, 58, true);
WriteLiteral("\r\n\r\n <div class=\"form-group\">\r\n ");
EndContext();
BeginContext(1008, 54, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ae26f216b6aa4427951cf62b98bf47d2", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#line 34 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Titulo);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1062, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1080, 47, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "6f0d6e55857e488e98b237423a3c2023", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#line 35 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Titulo);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1127, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1145, 61, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "eb5ec332aad040eba475ea7ab05c18b5", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#line 36 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Titulo);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1206, 78, true);
WriteLiteral("\r\n </div>\r\n\r\n <div class=\"form-group\">\r\n ");
EndContext();
BeginContext(1284, 57, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "43c73e277bfe45828c9008ee5b6d744c", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#line 40 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Subtitulo);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1341, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1359, 50, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "49457d8807644f7289f9e73984db3013", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#line 41 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Subtitulo);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1409, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1427, 64, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05f3572053fa4647b81d24feaff86c2b", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#line 42 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Subtitulo);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1491, 78, true);
WriteLiteral("\r\n </div>\r\n\r\n <div class=\"form-group\">\r\n ");
EndContext();
BeginContext(1569, 54, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "8527e1da1c48400794f563a4f47d0298", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#line 46 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Resumo);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1623, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1641, 68, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("textarea", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1ce1dbdd03c84d50a1a712501d78e6aa", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.TextAreaTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper);
#line 47 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Resumo);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_TextAreaTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1709, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1727, 61, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "8f525f740d114dca9dc9618b7b43e62b", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#line 48 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Resumo);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1788, 76, true);
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
EndContext();
BeginContext(1864, 53, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "0f6c2635cc0e40b3a2d4c3d81ecb82e8", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#line 51 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Autor);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1917, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1935, 46, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "1581248a16bf481c87fd343342c9872a", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#line 52 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Autor);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1981, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1999, 60, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "400d0e7b8e784488b3a04ad614d3637e", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#line 53 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Autor);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2059, 78, true);
WriteLiteral("\r\n </div>\r\n\r\n <div class=\"form-group\">\r\n ");
EndContext();
BeginContext(2137, 53, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "6a738866f14d48efba9aef77624c559d", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#line 57 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Lista);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2190, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(2208, 265, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("select", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "94db73086945475b8e2d57c25efc6de6", async() => {
BeginContext(2253, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 59 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
foreach (var tipo in Enum.GetValues(typeof(TipoListaLeitura)))
{
#line default
#line hidden
BeginContext(2363, 24, true);
WriteLiteral(" ");
EndContext();
BeginContext(2387, 36, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "648329b35a79436a9d852048e21291de", async() => {
BeginContext(2410, 4, false);
#line 61 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
Write(tipo);
#line default
#line hidden
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper);
BeginWriteTagHelperAttribute();
#line 61 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
WriteLiteral(tipo);
#line default
#line hidden
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("value", __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2423, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 62 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
}
#line default
#line hidden
BeginContext(2448, 16, true);
WriteLiteral(" ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper);
#line 58 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Lista);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_SelectTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2473, 18, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(2491, 60, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4f27e27adaae4918b72a618116654b84", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#line 64 "C:\jose-guilherme\kentech\treinamento-kentech\api-rest-aspnet-core\Alura.WebAPI\Alura.WebAPI.WebApp\Views\Livro\Novo.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Lista);
#line default
#line hidden
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2551, 183, true);
WriteLiteral("\r\n </div>\r\n\r\n <footer class=\"form-group\">\r\n <button class=\"btn btn-outline-success\">GRAVAR</button>\r\n </footer>\r\n </div>\r\n\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_9);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_10.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_11.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_11);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2741, 15, true);
WriteLiteral("\r\n\r\n</main>\r\n\r\n");
EndContext();
DefineSection("Scripts", async() => {
BeginContext(2773, 812, true);
WriteLiteral(@"
<script>
$(function () {
$('#ImagemCapa').change(function () {
console.log(""chegou aqui!"");
var input = this;
var url = $(this).val();
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == ""png"")) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgCapa').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
else {
$('#imgCapa').attr('src', '~/images/capas/capa-vazia.png');
}
});
});
</script>
");
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<LivroUpload> Html { get; private set; }
}
}
#pragma warning restore 1591
| 73.678019 | 365 | 0.70466 | [
"MIT"
] | zehguilherme/treinamento-kentech | api-rest-aspnet-core/Alura.WebAPI/Alura.WebAPI.WebApp/obj/Debug/netcoreapp2.1/Razor/Views/Livro/Novo.cshtml.g.cs | 47,596 | C# |
/*
* ProcessMaker API
*
* This ProcessMaker I/O API provides access to a BPMN 2.0 compliant workflow engine api that is designed to be used as a microservice to support enterprise cloud applications. The current Alpha 1.0 version supports most of the descriptive class of the BPMN 2.0 specification.
*
* OpenAPI spec version: 1.0.0
* Contact: support@processmaker.io
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace ProcessMaker.PMIO.Model
{
/// <summary>
/// GroupUpdateItem
/// </summary>
[DataContract]
public partial class GroupUpdateItem : IEquatable<GroupUpdateItem>
{
/// <summary>
/// Initializes a new instance of the <see cref="GroupUpdateItem" /> class.
/// </summary>
[JsonConstructorAttribute]
protected GroupUpdateItem() { }
/// <summary>
/// Initializes a new instance of the <see cref="GroupUpdateItem" /> class.
/// </summary>
/// <param name="Data">Data (required).</param>
public GroupUpdateItem(Group Data = null)
{
// to ensure "Data" is required (not null)
if (Data == null)
{
throw new InvalidDataException("Data is a required property for GroupUpdateItem and cannot be null");
}
else
{
this.Data = Data;
}
}
/// <summary>
/// Gets or Sets Data
/// </summary>
[DataMember(Name="data", EmitDefaultValue=false)]
public Group Data { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class GroupUpdateItem {\n");
sb.Append(" Data: ").Append(Data).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as GroupUpdateItem);
}
/// <summary>
/// Returns true if GroupUpdateItem instances are equal
/// </summary>
/// <param name="other">Instance of GroupUpdateItem to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GroupUpdateItem other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Data == other.Data ||
this.Data != null &&
this.Data.Equals(other.Data)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Data != null)
hash = hash * 59 + this.Data.GetHashCode();
return hash;
}
}
}
}
| 33.8 | 277 | 0.576289 | [
"Apache-2.0"
] | ProcessMaker/pmio-sdk-csharp | src/ProcessMaker.PMIO/Model/GroupUpdateItem.cs | 4,736 | C# |
namespace Brainary.Commons.Helpers
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Brainary.Commons.Extensions;
/// <summary>
/// Enum helper methods
/// </summary>
public class EnumHelper
{
/// <summary>
/// Get <see cref="NameValueCollection"/> from enum type with number name format
/// </summary>
/// <typeparam name="T">Enum type</typeparam>
/// <returns><see cref="NameValueCollection"/></returns>
public static NameValueCollection ToCollection<T>() where T : struct
{
return ToCollection<T>("D");
}
/// <summary>
/// Get <see cref="NameValueCollection"/> from enum type with number name format
/// </summary>
/// <param name="enumType">Enum type</param>
/// <returns><see cref="NameValueCollection"/></returns>
public static NameValueCollection ToCollection(Type enumType)
{
return ToCollection(enumType, "D");
}
/// <summary>
/// Get <see cref="NameValueCollection"/> from enum type with specified name format
/// </summary>
/// <typeparam name="T">Enum type</typeparam>
/// <param name="nameFormat">Enum value format</param>
/// <returns><see cref="NameValueCollection"/></returns>
public static NameValueCollection ToCollection<T>(string nameFormat) where T : struct
{
return ToCollection(typeof(T), nameFormat);
}
/// <summary>
/// Get <see cref="NameValueCollection"/> from enum type with specified name format
/// </summary>
/// <param name="enumType">Enum type</param>
/// <param name="nameFormat">Name format</param>
/// <returns><see cref="NameValueCollection"/></returns>
public static NameValueCollection ToCollection(Type enumType, string nameFormat)
{
if (!enumType.IsEnum)
throw new InvalidOperationException("Type must be enum");
var collection = new NameValueCollection();
foreach (var @enum in Enum.GetValues(enumType).Cast<Enum>())
{
collection.Add(@enum.ToString(nameFormat), @enum.GetDisplayName());
}
return collection;
}
/// <summary>
/// Get dictionary from enum type with number key format
/// </summary>
/// <typeparam name="T">Enum type</typeparam>
/// <returns>Collection</returns>
public static IDictionary<string, string> ToDictionary<T>() where T : struct
{
return ToDictionary<T>("D");
}
/// <summary>
/// Get dictionary from enum type with number key format
/// </summary>
/// <param name="enumType">Enum type</param>
/// <returns>Collection</returns>
public static IDictionary<string, string> ToDictionary(Type enumType)
{
return ToDictionary(enumType, "D");
}
/// <summary>
/// Get dictionary from enum type with specified key format
/// </summary>
/// <typeparam name="T">Enum type</typeparam>
/// <param name="keyFormat">Key format</param>
/// <returns>Collection</returns>
public static IDictionary<string, string> ToDictionary<T>(string keyFormat) where T : struct
{
return ToDictionary(typeof(T), keyFormat);
}
/// <summary>
/// Get dictionary from enum type with specified key format
/// </summary>
/// <param name="enumType">Enum type</param>
/// <param name="keyFormat">Key format</param>
/// <returns>Collection</returns>
public static IDictionary<string, string> ToDictionary(Type enumType, string keyFormat)
{
if (!enumType.IsEnum)
throw new InvalidOperationException("Type must be enum");
return Enum.GetValues(enumType)
.Cast<Enum>()
.ToDictionary(k => k.ToString(keyFormat), v => v.GetDisplayName());
}
}
} | 36.946903 | 100 | 0.580599 | [
"Apache-2.0"
] | AthosXtreme/Brainary.Commons | Solution/Brainary.Commons/Helpers/EnumHelper.cs | 4,177 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Umbraco.ModelsBuilder.Embedded v8.13.0
//
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.ModelsBuilder.Embedded;
namespace Umbraco.Web.PublishedModels
{
/// <summary>Contenido Encabezado Ajustes</summary>
[PublishedModel("contenidoEncabezadoAjustes")]
public partial class ContenidoEncabezadoAjustes : PublishedElementModel, IAjustes, IEncabezado
{
// helpers
#pragma warning disable 0109 // new is redundant
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "8.13.0")]
public new const string ModelTypeAlias = "contenidoEncabezadoAjustes";
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "8.13.0")]
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "8.13.0")]
public new static IPublishedContentType GetModelContentType()
=> PublishedModelUtility.GetModelContentType(ModelItemType, ModelTypeAlias);
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "8.13.0")]
public static IPublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<ContenidoEncabezadoAjustes, TValue>> selector)
=> PublishedModelUtility.GetModelPropertyType(GetModelContentType(), selector);
#pragma warning restore 0109
// ctor
public ContenidoEncabezadoAjustes(IPublishedElement content)
: base(content)
{ }
// properties
///<summary>
/// Color Sobrepuesto
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "8.13.0")]
[ImplementPropertyType("colorSobrepuesto")]
public virtual object ColorSobrepuesto => this.Value("colorSobrepuesto");
///<summary>
/// Estilo
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "8.13.0")]
[ImplementPropertyType("estilo")]
public virtual string Estilo => global::Umbraco.Web.PublishedModels.Ajustes.GetEstilo(this);
///<summary>
/// Titulo
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder.Embedded", "8.13.0")]
[ImplementPropertyType("titulo")]
public virtual string Titulo => global::Umbraco.Web.PublishedModels.Encabezado.GetTitulo(this);
}
}
| 40.652174 | 130 | 0.729412 | [
"MIT"
] | ManiPeralta/KitDeInicio-Source | KitDeInicioDos/Models/ContenidoEncabezadoAjustes.generated.cs | 2,805 | C# |
using UnityEngine;
using Dest.Math;
namespace Dest.Math.Tests
{
[ExecuteInEditMode]
public class Test_IntrRay3Polygon3 : Test_Base
{
public Transform Ray;
public Transform PolygonPlane;
public Transform[] PolygonPoints;
private void OnDrawGizmos()
{
Ray3 ray = CreateRay3(Ray);
Plane3 polygonPlane = CreatePlane3(PolygonPlane);
Polygon3 polygon = new Polygon3(PolygonPoints.Length, polygonPlane);
for (int i = 0; i < PolygonPoints.Length; ++i)
{
polygon.SetVertexProjected(i, PolygonPoints[i].position);
}
polygon.UpdateEdges();
Ray3Polygon3Intr info;
bool find = Intersection.FindRay3Polygon3(ref ray, polygon, out info);
FiguresColor();
DrawPolygon(polygon);
DrawRay(ref ray);
if (find)
{
ResultsColor();
DrawPoint(info.Point);
}
LogInfo(info.IntersectionType);
}
}
}
| 20.804878 | 73 | 0.704572 | [
"MIT"
] | zhlnpu/SmartphoneVR2-ARinVR | SmartPhoneVR-stage2-pc-ARinVR/Assets/MathLibraryForUnity/Tests/Scripts/Intersection/3D/Test_IntrRay3Polygon3.cs | 855 | C# |
namespace LinFx.Extensions.ObjectMapping
{
/// <summary>
/// Defines a simple interface to automatically map objects.
/// </summary>
public interface IObjectMapper
{
/// <summary>
/// Gets the underlying <see cref="IAutoObjectMappingProvider"/> object that is used for auto object mapping.
/// </summary>
IAutoObjectMappingProvider AutoObjectMappingProvider { get; }
/// <summary>
/// Converts an object to another. Creates a new object of <see cref="TDestination"/>.
/// </summary>
/// <typeparam name="TDestination">Type of the destination object</typeparam>
/// <typeparam name="TSource">Type of the source object</typeparam>
/// <param name="source">Source object</param>
TDestination Map<TSource, TDestination>(TSource source);
/// <summary>
/// Execute a mapping from the source object to the existing destination object
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="source">Source object</param>
/// <param name="destination">Destination object</param>
/// <returns>Returns the same <see cref="destination"/> object after mapping operation</returns>
TDestination Map<TSource, TDestination>(TSource source, TDestination destination);
}
/// <summary>
/// Defines a simple interface to automatically map objects for a specific context.
/// </summary>
public interface IObjectMapper<TContext> : IObjectMapper
{
}
/// <summary>
/// Maps an object to another.
/// Implement this interface to override object to object mapping for specific types.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TDestination"></typeparam>
public interface IObjectMapper<in TSource, TDestination>
{
/// <summary>
/// Converts an object to another. Creates a new object of <see cref="TDestination"/>.
/// </summary>
/// <param name="source">Source object</param>
TDestination Map(TSource source);
/// <summary>
/// Execute a mapping from the source object to the existing destination object
/// </summary>
/// <param name="source">Source object</param>
/// <param name="destination">Destination object</param>
/// <returns>Returns the same <see cref="destination"/> object after mapping operation</returns>
TDestination Map(TSource source, TDestination destination);
}
}
| 41.809524 | 117 | 0.64123 | [
"MIT"
] | linfx/linfx | src/LinFx/Extensions/ObjectMapping/IObjectMapper.cs | 2,636 | C# |
/*
Copyright (c) 2018, Kevin Pope, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using CsvHelper;
using MatterHackers.Agg;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.Library;
using MatterHackers.MatterControl.PartPreviewWindow;
using MatterHackers.VectorMath;
namespace MatterHackers.MatterControl.PrintHistory
{
public class HistoryListView : FlowLayoutWidget, IListContentView
{
private readonly ThemeConfig theme = ApplicationController.Instance.Theme;
public int ThumbWidth { get; } = 50;
public int ThumbHeight { get; } = 50;
// Parameterless constructor required for ListView
public HistoryListView()
: base(FlowDirection.TopToBottom)
{
}
public HistoryListView(ThemeConfig theme)
: base(FlowDirection.TopToBottom)
{
this.theme = theme;
}
public ListViewItemBase AddItem(ListViewItem item)
{
var historyRowItem = item.Model as PrintHistoryItem;
var detailsView = new PrintHistoryListItem(item, this.ThumbWidth, this.ThumbHeight, historyRowItem?.PrintTask, theme);
this.AddChild(detailsView);
return detailsView;
}
public void ClearItems()
{
}
public void BeginReload()
{
}
public void EndReload()
{
}
}
} | 32.955056 | 121 | 0.792704 | [
"BSD-2-Clause"
] | MrnB/MatterControl | MatterControlLib/History/HistoryListView.cs | 2,935 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Igneel.IA.Resources
{
public abstract class ComputeBuffer: ResourceAllocator
{
protected CPUAccess cpuAccess;
protected GPUAccess gpuAccess;
protected IntPtr pter;
protected int lenght;
public ComputeBuffer(CPUAccess cpuAccess, GPUAccess gpuAccess, int lenght)
{
this.cpuAccess = cpuAccess;
this.gpuAccess = gpuAccess;
this.lenght = lenght;
}
public CPUAccess CpuAccess => cpuAccess;
public GPUAccess GpuAcess => gpuAccess;
public int Lenght => lenght;
public IntPtr DataPointer => pter;
public bool IsLocked { get; protected set; }
public abstract IntPtr Lock(CPUAccess cpuAccess = CPUAccess.Read);
public abstract void UnLock();
public abstract ComputeBuffer Clone();
}
public static class BufferExt
{
public static ComputeBufferView<T> ViewAs<T>(this ComputeBuffer buffer, int offset = 0)
where T:struct
{
if (!buffer.IsLocked)
throw new InvalidOperationException($"Must call {nameof(buffer)}.{nameof(ComputeBuffer.Lock)} first");
var elemetSize = ClrRuntime.Runtime.SizeOf<T>();
return new ComputeBufferView<T>(buffer.DataPointer + offset * elemetSize, buffer.Lenght / elemetSize);
}
public static void Write(this ComputeBuffer buffer, byte [] data, int offset = 0)
{
buffer.Lock();
try
{
ClrRuntime.Runtime.Copy(data, buffer.DataPointer, offset, data.Length);
}
finally
{
buffer.UnLock();
}
}
}
}
| 26.913043 | 118 | 0.602046 | [
"Apache-2.0"
] | ansel86castro/Igneel | Engine/Igneel.IA/Resources/ComputeBuffer.cs | 1,859 | C# |
using Contoso.Web.Flow.Cache;
using Contoso.Web.Flow.Requests;
using Contoso.Web.Flow.ScreenSettings.Views;
using LogicBuilder.RulesDirector;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Contoso.Web.Flow.Dialogs
{
public interface IDialogHandler
{
IEnumerable<ValidationResult> GetErrors(RequestBase request);
ScreenSettingsBase GetScreenSettings(RequestBase request, IEnumerable<ValidationResult> errors);
void Complete(IFlowManager flowManager, RequestBase request);
}
}
| 30.947368 | 104 | 0.792517 | [
"MIT"
] | BlaiseD/LogicBuilder.Samples | .NetCore/Contoso/Contoso.Web.Flow/Dialogs/IDialogHandler.cs | 590 | C# |
using System.Collections.Generic;
using System.Linq;
namespace Ernestoyaquello.TwoPlayerZeroSumGameEngine.Models
{
/// <summary>
/// A model implementing this base class will represent the board state and hold its data.
/// For example, in a game like Connect 4, it will contain the information about where each chip is.
/// </summary>
/// <typeparam name="TMoveInfo">The type of moves that the board represented by this state makes use of.</typeparam>
public abstract class BaseBoardState<TMoveInfo> where TMoveInfo : BaseMoveInfo
{
internal List<TMoveInfo> History { get; private set; }
internal StateCache<TMoveInfo> CachedData { get; set; }
protected BaseBoardState()
{
History = new List<TMoveInfo>();
CachedData = new StateCache<TMoveInfo>();
}
public BaseBoardState<TMoveInfo> CloneBoardState()
{
var clone = Clone();
clone.History = History.ToList();
clone.CachedData = CachedData.Clone();
return clone;
}
/// <summary>
/// Returns a copy of the object.
/// </summary>
/// <returns>A copy of the object.</returns>
protected abstract BaseBoardState<TMoveInfo> Clone();
/// <summary>
/// Gets the string representation of the board based on its current state.
/// </summary>
/// <returns>The string representation of the board on its current state.</returns>
public override abstract string ToString();
}
}
| 35.636364 | 120 | 0.630102 | [
"Apache-2.0"
] | ernestoyaquello/TwoPlayerZeroSumGameEngine | Ernestoyaquello.TwoPlayerZeroSumGameEngine/Models/BaseBoardState.cs | 1,570 | C# |
using System;
using System.Linq;
namespace ConcurrencyUtilities.Benchmarks
{
public class BenchmarkResult
{
public readonly string Name;
public readonly string TypeName;
public readonly int Threads;
public readonly int TotalSeconds;
public readonly long RecordedTimeInNano;
public readonly long[] OperationsPerThread;
public readonly long[] TimePerThread;
public BenchmarkResult(string name, string typeName, int threads, int totalSeconds,
long recordedTimeInNano, long[] operationsperThread, long[] timePerThread)
{
this.Name = name;
this.TypeName = typeName;
this.Threads = threads;
this.TotalSeconds = totalSeconds;
this.RecordedTimeInNano = recordedTimeInNano;
this.OperationsPerThread = operationsperThread;
this.TimePerThread = timePerThread;
}
public long TotalOperations { get { return this.OperationsPerThread.Sum(); } }
public long RecordedTime { get { return BenchmarkRunner.NanoToSeconds(this.RecordedTimeInNano); } }
public long OverallOperationsPerSecond
{
get
{
if (this.RecordedTime == 0)
{
return -1;
}
return this.TotalOperations / RecordedTime;
}
}
public long AverageOperationDuration
{
get
{
return (long)Math.Round(this.OperationsPerThread.Select((c, i) => this.TimePerThread[i] / (double)c).Average());
}
}
public long AverageOpsPerSecondPerThread
{
get
{
return (long)Math.Round(this.OperationsPerThread.Select((c, i) =>
this.TimePerThread[i] == 0 ? -1 : c / BenchmarkRunner.NanoToSeconds(this.TimePerThread[i])).Average());
}
}
}
}
| 30.584615 | 128 | 0.577968 | [
"Apache-2.0"
] | cyotek/ConcurrencyUtilities | Tests/ConcurrencyUtilities.Benchmarks/BenchmarkResult.cs | 1,990 | C# |
// ReSharper disable VirtualMemberCallInConstructor
namespace OurRecipes.Data.Models
{
using System;
using Microsoft.AspNetCore.Identity;
using OurRecipes.Data.Common.Models;
public class ApplicationRole : IdentityRole, IAuditInfo, IDeletableEntity
{
public ApplicationRole()
: this(null)
{
}
public ApplicationRole(string name)
: base(name)
{
this.Id = Guid.NewGuid().ToString();
}
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public bool IsDeleted { get; set; }
public DateTime? DeletedOn { get; set; }
}
}
| 22.387097 | 77 | 0.603746 | [
"MIT"
] | JustAleks14/OurRecipes | Data/OurRecipes.Data.Models/ApplicationRole.cs | 696 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
namespace Apache.Geode.Client.FwkLib
{
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
//using Region = Apache.Geode.Client.IRegion<Object, Object>;
public class DupChecker<TKey, TVal> : CacheListenerAdapter<TKey, TVal>, IDisposable
{
/*
Note:
Currently, for failoverTestHAEventIDMap.xml, PerfTests.DoSerialPuts has a hardcoded
keycount of 1000 and values are put serially from 1 to 1000.
*/
#region Private members
int m_ops = 0;
Dictionary<TKey, TVal> m_map = new Dictionary<TKey, TVal>();
#endregion
#region Private methods
private void check(EntryEvent<TKey, TVal> ev)
{
m_ops++;
TKey key = ev.Key;
TVal value = ev.NewValue;
FwkTest<TKey, TVal> currTest = FwkTest<TKey, TVal>.CurrentTest;
if (m_map.ContainsKey((TKey)key))
{
TVal old = m_map[(TKey)key];
currTest.FwkAssert(value.Equals(old) , "DupChecker: Duplicate detected. Existing value is {0}, New value is {1}",
old, value);
}
m_map[(TKey)key] = value;
}
private void validate()
{
FwkTest<TKey, TVal> currTest = FwkTest<TKey, TVal>.CurrentTest;
currTest.FwkInfo("DupChecker: got {0} keys.", m_map.Count);
currTest.FwkAssert(m_map.Count == 1000, "DupChecker: Expected 1000 keys for the region, actual is {0}.", m_map.Count);
currTest.FwkInfo("DupChecker: got {0} ops.", m_ops);
currTest.FwkAssert(m_ops == 1000000, "DupChecker: Expected 1,000,000 events (1000 per key) for the region, actual is {0}.",
m_ops);
foreach (object item in m_map.Values)
{
int checkval = (int)item;
currTest.FwkAssert(checkval == 1000, "DupChecker: Expected 1000 as final value, actual is {0}.", checkval);
}
}
#endregion
#region ICacheListener Members
public override void AfterCreate(EntryEvent<TKey, TVal> ev)
{
check(ev);
}
public override void AfterUpdate(EntryEvent<TKey, TVal> ev)
{
check(ev);
}
#endregion
protected virtual void Dispose(bool disposing)
{
FwkTest<TKey, TVal> currTest = FwkTest<TKey, TVal>.CurrentTest;
currTest.FwkInfo("DupChecker: validating");
validate();
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
public DupChecker()
{
FwkTest<TKey, TVal> currTest = FwkTest<TKey, TVal>.CurrentTest;
currTest.FwkInfo("DupChecker: created");
}
~DupChecker()
{
Dispose(false);
}
}
}
| 26.210526 | 129 | 0.659495 | [
"Apache-2.0"
] | austxcodemonkey/geode-native | tests/cli/NewFwkLib/PerfTest/DupChecker.cs | 3,486 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OgrePlugin;
using Engine;
namespace libRocketPlugin
{
public class RocketRenderQueueListener : RenderQueueListener
{
private Context context;
private RenderInterfaceOgre3D renderInterface;
private IntSize2 renderDimensions;
private bool requiresTextureFlipping;
public event Action FrameCompleted;
public RocketRenderQueueListener(Context context, RenderInterfaceOgre3D renderInterface)
{
this.context = context;
this.renderInterface = renderInterface;
Vector2i dimensions = context.Dimensions;
renderDimensions = new IntSize2(dimensions.X, dimensions.Y);
}
public void preRenderQueues()
{
}
public void postRenderQueues()
{
if (FrameCompleted != null)
{
FrameCompleted.Invoke();
}
}
public void renderQueueStarted(byte queueGroupId, string invocation, ref bool skipThisInvocation)
{
if (queueGroupId == 100)
{
context.Update();
renderInterface.ConfigureRenderSystem(renderDimensions.Width, renderDimensions.Height, requiresTextureFlipping);
context.Render();
}
}
public void renderQueueEnded(byte queueGroupId, string invocation, ref bool repeatThisInvocation)
{
}
public IntSize2 RenderDimensions
{
get
{
return renderDimensions;
}
set
{
renderDimensions = value;
}
}
public bool RequiresTextureFlipping
{
get
{
return requiresTextureFlipping;
}
set
{
requiresTextureFlipping = value;
}
}
}
}
| 26.125 | 129 | 0.542105 | [
"MIT"
] | AnomalousMedical/Engine | libRocketPlugin/Plugin/RocketRenderQueueListener.cs | 2,092 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.Packets;
using XmlRpcCore;
using Logger = OpenMetaverse.Logger;
namespace GridProxy
{
public class ProxyFrame
{
public Proxy proxy;
private Dictionary<string, CommandDelegate> commandDelegates = new Dictionary<string, CommandDelegate>();
private bool logLogin = false;
public delegate void CommandDelegate(string[] words);
public string[] Args { get; private set; }
public UUID AgentID { get; private set; }
public UUID SessionID { get; private set; }
public UUID SecureSessionID { get; private set; }
public UUID InventoryRoot { get; private set; }
public void AddCommand(string cmd, CommandDelegate deleg)
{
commandDelegates[cmd] = deleg;
}
public ProxyFrame(string[] args)
{
Init(args, null);
}
public ProxyFrame(string[] args, ProxyConfig proxyConfig)
{
Init(args, proxyConfig);
}
private void Init(string[] args, ProxyConfig proxyConfig)
{
//bool externalPlugin = false;
this.Args = args;
if (proxyConfig == null)
{
proxyConfig = new ProxyConfig("GridProxy", "Austin Jennings / Andrew Ortman", args, true);
}
proxy = new Proxy(proxyConfig);
// add delegates for login
proxy.AddLoginRequestDelegate(new XmlRpcRequestDelegate(LoginRequest));
proxy.AddLoginResponseDelegate(new XmlRpcResponseDelegate(LoginResponse));
// add a delegate for outgoing chat
proxy.AddDelegate(PacketType.ChatFromViewer, Direction.Outgoing, new PacketDelegate(ChatFromViewerOut));
// handle command line arguments
foreach (string arg in args)
if (arg == "--log-login")
logLogin = true;
else if (arg.Substring(0, 2) == "--")
{
int ipos = arg.IndexOf("=", StringComparison.Ordinal);
if (ipos != -1)
{
string sw = arg.Substring(0, ipos);
string val = arg.Substring(ipos + 1);
Logger.Log("arg '" + sw + "' val '" + val + "'", Helpers.LogLevel.Debug);
if (sw == "--load")
{
//externalPlugin = true;
LoadPlugin(val);
}
}
}
commandDelegates["/load"] = new CommandDelegate(CmdLoad);
}
private void CmdLoad(string[] words)
{
if (words.Length != 2)
SayToUser("Usage: /load <plugin name>");
else
{
try
{
LoadPlugin(words[1]);
}
catch (Exception e)
{
Logger.Log("LoadPlugin exception", Helpers.LogLevel.Error, e);
}
}
}
public void LoadPlugin(string name)
{
Assembly assembly = Assembly.LoadFile(Path.GetFullPath(name));
foreach (Type t in assembly.GetTypes())
{
try
{
if (t.IsSubclassOf(typeof(ProxyPlugin)))
{
ConstructorInfo info = t.GetConstructor(new Type[] { typeof(ProxyFrame) });
ProxyPlugin plugin = (ProxyPlugin)info.Invoke(new object[] { this });
plugin.Init();
}
}
catch (Exception e)
{
Logger.Log("LoadPlugin exception", Helpers.LogLevel.Error, e);
}
}
}
// LoginRequest: dump a login request to the console
private void LoginRequest(object sender, XmlRpcRequestEventArgs e)
{
if (logLogin)
{
Console.WriteLine("==> Login Request");
Console.WriteLine(e.m_Request);
}
}
// Loginresponse: dump a login response to the console
private void LoginResponse(XmlRpcResponse response)
{
System.Collections.Hashtable values = (System.Collections.Hashtable)response.Value;
if (values.Contains("agent_id"))
AgentID = new UUID((string)values["agent_id"]);
if (values.Contains("session_id"))
SessionID = new UUID((string)values["session_id"]);
if (values.Contains("secure_session_id"))
SecureSessionID = new UUID((string)values["secure_session_id"]);
if (values.Contains("inventory-root"))
{
InventoryRoot = new UUID(
(string)((System.Collections.Hashtable)(((System.Collections.ArrayList)values["inventory-root"])[0]))?["folder_id"]
);
if (logLogin)
{
Console.WriteLine("inventory root: " + InventoryRoot);
}
}
if (logLogin)
{
Console.WriteLine("<== Login Response");
Console.WriteLine(response);
}
}
// ChatFromViewerOut: outgoing ChatFromViewer delegate; check for Analyst commands
private Packet ChatFromViewerOut(Packet packet, IPEndPoint sim)
{
// deconstruct the packet
ChatFromViewerPacket cpacket = (ChatFromViewerPacket)packet;
string message = System.Text.Encoding.UTF8.GetString(cpacket.ChatData.Message).Replace("\0", "");
if (message.Length > 1 && message[0] == '/')
{
string[] words = message.Split(' ');
if (commandDelegates.ContainsKey(words[0]))
{
// this is an Analyst command; act on it and drop the chat packet
((CommandDelegate)commandDelegates[words[0]])(words);
return null;
}
}
return packet;
}
/// <summary>
/// Send a message to the viewer
/// </summary>
/// <param name="message">A string containing the message to send</param>
public void SayToUser(string message)
{
SayToUser("GridProxy", message);
}
/// <summary>
/// Send a message to the viewer
/// </summary>
/// <param name="fromName">A string containing text indicating the origin of the message</param>
/// <param name="message">A string containing the message to send</param>
public void SayToUser(string fromName, string message)
{
ChatFromSimulatorPacket packet = new ChatFromSimulatorPacket();
packet.ChatData.SourceID = UUID.Random();
packet.ChatData.FromName = Utils.StringToBytes(fromName);
packet.ChatData.OwnerID = AgentID;
packet.ChatData.SourceType = (byte)2;
packet.ChatData.ChatType = (byte)1;
packet.ChatData.Audible = (byte)1;
packet.ChatData.Position = new Vector3(0, 0, 0);
packet.ChatData.Message = Utils.StringToBytes(message);
proxy.InjectPacket(packet, Direction.Incoming);
}
}
public abstract class ProxyPlugin : MarshalByRefObject
{
// public abstract ProxyPlugin(ProxyFrame main);
public abstract void Init();
}
}
| 34.336283 | 135 | 0.524742 | [
"BSD-3-Clause"
] | Utopia-Skye/libremetaverse | Programs/GridProxy/GridProxyLoader.cs | 7,760 | C# |
// <auto-generated />
using System;
using Gradebook.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Gradebook.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20210131165858_AbsenceNowHasAnId")]
partial class AbsenceNowHasAnId
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.8")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Gradebook.Data.Models.Absences.Absence", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("Period")
.HasColumnType("int");
b.Property<int>("StudentSubjectId")
.HasColumnType("int");
b.Property<int>("StudentSubjectStudentId")
.HasColumnType("int");
b.Property<int>("StudentSubjectSubjectId")
.HasColumnType("int");
b.Property<int>("TeacherId")
.HasColumnType("int");
b.Property<int>("Type")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("TeacherId");
b.HasIndex("StudentSubjectStudentId", "StudentSubjectSubjectId");
b.ToTable("Absences");
});
modelBuilder.Entity("Gradebook.Data.Models.ApplicationRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Gradebook.Data.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UniqueGradebookId")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Gradebook.Data.Models.Class", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Letter")
.IsRequired()
.HasColumnType("nvarchar(1)");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int?>("SchoolId")
.HasColumnType("int");
b.Property<int?>("TeacherId")
.HasColumnType("int");
b.Property<int>("Year")
.HasColumnType("int");
b.Property<int>("YearCreated")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("SchoolId");
b.HasIndex("TeacherId")
.IsUnique()
.HasFilter("[TeacherId] IS NOT NULL");
b.ToTable("Classes");
});
modelBuilder.Entity("Gradebook.Data.Models.Grades.Grade", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("Period")
.HasColumnType("int");
b.Property<int>("StudentSubjectId")
.HasColumnType("int");
b.Property<int>("StudentSubjectStudentId")
.HasColumnType("int");
b.Property<int>("StudentSubjectSubjectId")
.HasColumnType("int");
b.Property<int>("TeacherId")
.HasColumnType("int");
b.Property<int>("Type")
.HasColumnType("int");
b.Property<decimal>("Value")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("TeacherId");
b.HasIndex("StudentSubjectStudentId", "StudentSubjectSubjectId");
b.ToTable("Grades");
});
modelBuilder.Entity("Gradebook.Data.Models.Parent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("UniqueId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("UserType")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("UniqueId")
.IsUnique();
b.ToTable("Parents");
});
modelBuilder.Entity("Gradebook.Data.Models.Principal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("UniqueId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("UserType")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("UniqueId")
.IsUnique();
b.ToTable("Principals");
});
modelBuilder.Entity("Gradebook.Data.Models.School", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("PrincipalId")
.HasColumnType("int");
b.Property<string>("SchoolImageName")
.HasColumnType("nvarchar(max)");
b.Property<int>("Type")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("PrincipalId")
.IsUnique();
b.ToTable("Schools");
});
modelBuilder.Entity("Gradebook.Data.Models.Setting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Settings");
});
modelBuilder.Entity("Gradebook.Data.Models.Student", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("BirthDate")
.HasColumnType("datetime2");
b.Property<int?>("ClassId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("PersonalIdentificationNumber")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<int>("SchoolId")
.HasColumnType("int");
b.Property<string>("UniqueId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("UserType")
.HasColumnType("int");
b.Property<string>("Username")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ClassId");
b.HasIndex("IsDeleted");
b.HasIndex("SchoolId");
b.HasIndex("UniqueId")
.IsUnique();
b.ToTable("Students");
});
modelBuilder.Entity("Gradebook.Data.Models.StudentParent", b =>
{
b.Property<int>("StudentId")
.HasColumnType("int");
b.Property<int>("ParentId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("Id")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.HasKey("StudentId", "ParentId");
b.HasIndex("IsDeleted");
b.HasIndex("ParentId");
b.ToTable("StudentParents");
});
modelBuilder.Entity("Gradebook.Data.Models.StudentSubject", b =>
{
b.Property<int>("StudentId")
.HasColumnType("int");
b.Property<int>("SubjectId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("Id")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.HasKey("StudentId", "SubjectId");
b.HasIndex("IsDeleted");
b.HasIndex("SubjectId");
b.ToTable("StudentSubjects");
});
modelBuilder.Entity("Gradebook.Data.Models.Subject", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("SchoolYear")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("TeacherId")
.HasColumnType("int");
b.Property<int>("YearGrade")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("TeacherId");
b.ToTable("Subjects");
});
modelBuilder.Entity("Gradebook.Data.Models.Teacher", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("SchoolId")
.HasColumnType("int");
b.Property<string>("UniqueId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("UserType")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("SchoolId");
b.HasIndex("UniqueId")
.IsUnique();
b.ToTable("Teachers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Gradebook.Data.Models.Absences.Absence", b =>
{
b.HasOne("Gradebook.Data.Models.Teacher", "Teacher")
.WithMany()
.HasForeignKey("TeacherId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Gradebook.Data.Models.StudentSubject", "StudentSubject")
.WithMany("Absences")
.HasForeignKey("StudentSubjectStudentId", "StudentSubjectSubjectId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Gradebook.Data.Models.Class", b =>
{
b.HasOne("Gradebook.Data.Models.School", null)
.WithMany("Classes")
.HasForeignKey("SchoolId");
b.HasOne("Gradebook.Data.Models.Teacher", "Teacher")
.WithOne("Class")
.HasForeignKey("Gradebook.Data.Models.Class", "TeacherId");
});
modelBuilder.Entity("Gradebook.Data.Models.Grades.Grade", b =>
{
b.HasOne("Gradebook.Data.Models.Teacher", "Teacher")
.WithMany()
.HasForeignKey("TeacherId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Gradebook.Data.Models.StudentSubject", "StudentSubject")
.WithMany("Grades")
.HasForeignKey("StudentSubjectStudentId", "StudentSubjectSubjectId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Gradebook.Data.Models.School", b =>
{
b.HasOne("Gradebook.Data.Models.Principal", "Principal")
.WithOne("School")
.HasForeignKey("Gradebook.Data.Models.School", "PrincipalId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Gradebook.Data.Models.Student", b =>
{
b.HasOne("Gradebook.Data.Models.Class", "Class")
.WithMany("Students")
.HasForeignKey("ClassId");
b.HasOne("Gradebook.Data.Models.School", "School")
.WithMany("Students")
.HasForeignKey("SchoolId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Gradebook.Data.Models.StudentParent", b =>
{
b.HasOne("Gradebook.Data.Models.Parent", "Parent")
.WithMany("StudentParents")
.HasForeignKey("ParentId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Gradebook.Data.Models.Student", "Student")
.WithMany("StudentParents")
.HasForeignKey("StudentId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Gradebook.Data.Models.StudentSubject", b =>
{
b.HasOne("Gradebook.Data.Models.Student", "Student")
.WithMany("StudentSubjects")
.HasForeignKey("StudentId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Gradebook.Data.Models.Subject", "Subject")
.WithMany("StudentSubjects")
.HasForeignKey("SubjectId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Gradebook.Data.Models.Subject", b =>
{
b.HasOne("Gradebook.Data.Models.Teacher", "Teacher")
.WithMany()
.HasForeignKey("TeacherId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Gradebook.Data.Models.Teacher", b =>
{
b.HasOne("Gradebook.Data.Models.School", "School")
.WithMany("Teachers")
.HasForeignKey("SchoolId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Gradebook.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Gradebook.Data.Models.ApplicationUser", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Gradebook.Data.Models.ApplicationUser", null)
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Gradebook.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Gradebook.Data.Models.ApplicationUser", null)
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Gradebook.Data.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.413973 | 125 | 0.441368 | [
"MIT"
] | Plotso/Gradebook | Data/Gradebook.Data/Migrations/20210131165858_AbsenceNowHasAnId.Designer.cs | 34,923 | C# |
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Prism.Ninject.Forms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Prism.Ninject.Forms")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("6.2")]
[assembly: AssemblyFileVersion("6.2.0")]
[assembly: AssemblyInformationalVersion("6.2.0-pre3")]
| 37 | 77 | 0.77887 | [
"Apache-2.0"
] | camostars/hello_world | Source/Xamarin/Prism.Ninject.Forms/Properties/AssemblyInfo.cs | 817 | C# |
using Microsoft.Reactive.Testing;
using NUnit.Framework;
using Shouldly;
using System.Reactive;
namespace Annex.Reactive.Test
{
public sealed class ObservableEx_VoidTest : ReactiveTest
{
[Test]
public void IsSingleton() => ObservableEx.Void.ShouldBeSameAs(ObservableEx.Void);
[Test]
public void ReturnsCompletedSequence() =>
new TestScheduler()
.Start(() => ObservableEx.Void)
.Messages
.AssertEqual(
OnNext(200, Unit.Default),
OnCompleted<Unit>(200));
}
}
| 26.217391 | 89 | 0.595357 | [
"MIT"
] | gtbuchanan/annex-net | test/Annex.Reactive.Test/ObservableEx_VoidTest.cs | 603 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SIQuester.ViewModel;
namespace SIQuester
{
/// <summary>
/// Логика взаимодействия для ImportDBStorageView.xaml
/// </summary>
public partial class ImportDBStorageView : UserControl
{
private bool _blockFlag;
public ImportDBStorageView()
{
InitializeComponent();
}
private void TreeView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
Import();
}
private void Import()
{
if (tree.SelectedItem is DBNode item)
{
if (item.Children == null)
{
item.PropertyChanged += (sender2, e2) =>
{
var item2 = (DBNode)sender2;
if (item2.Children.Length == 0)
{
Dispatcher.BeginInvoke(new Action(() =>
{
((ImportDBStorageViewModel)DataContext).Select(item2);
}));
}
};
}
else if (item.Children.Length == 0)
{
((ImportDBStorageViewModel)DataContext).Select(item);
}
}
}
private void Tree_Expanded(object sender, RoutedEventArgs e)
{
if (_blockFlag)
return;
var node = (DBNode)((TreeViewItem)e.OriginalSource).DataContext;
if (node == null)
return;
if (node.Children.Length == 1 && node.Children[0] == null)
((ImportDBStorageViewModel)DataContext).LoadChildren(node);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (tree.SelectedItem is DBNode node)
{
if (node.Children.Length == 1 && node.Children[0] == null)
((ImportDBStorageViewModel)DataContext).LoadChildren(node);
_blockFlag = true;
try
{
node.IsExpanded = true;
}
finally
{
_blockFlag = false;
}
}
Import();
}
}
}
| 28.263158 | 86 | 0.491993 | [
"MIT"
] | CrafterKolyan/SI-Remastered | src/SIQuester/SIQuester/View/ImportDBStorageView.xaml.cs | 2,710 | C# |
using Klyte.Commons.Interfaces;
using System.Xml.Serialization;
namespace Klyte.WriteTheSigns.Xml
{
public class SeedInstanceHighwayShield : IIdentifiable
{
[XmlIgnore]
public ushort SeedId { get; private set; }
[XmlAttribute("seedId")]
public long? Id { get => SeedId; set => SeedId = (ushort)(value ?? 0); }
[XmlAttribute("shieldLayoutName")]
public string ShieldLayoutName { get; set; }
}
}
| 25.444444 | 80 | 0.644105 | [
"MIT"
] | klyte45/WriteTheSigns | Xml/BoardDescriptor/SeedInstanceHighwayShield.cs | 460 | C# |
using System;
using Newtonsoft.Json;
namespace CWITC.DataObjects
{
public class FeaturedEvent : BaseDataObject
{
/// <summary>
/// Gets or sets the type of the event such as: offsite, session, break, etc
/// </summary>
/// <value>The type.</value>
public string Type { get; set; }
/// <summary>
/// Gets or sets the title of the event such as: Evolve Keynote
/// </summary>
/// <value>The title.</value>
public string Title { get; set; }
/// <summary>
/// Gets or sets the descriptionof the event
/// </summary>
/// <value>The description.</value>
public string Description { get; set; }
/// <summary>
/// Gets or sets the start time.
/// </summary>
/// <value>The start time.</value>
public DateTime? StartTime { get; set; }
/// <summary>
/// Gets or sets the end time.
/// </summary>
/// <value>The end time.</value>
public DateTime? EndTime { get; set; }
public string LocationName { get; set; }
public string SponsorId { get; set; }
[JsonIgnore]
/// <summary>
/// Gets or sets the sponsor if there is one for the event
/// </summary>
/// <value>The sponsor.</value>
public virtual Sponsor Sponsor { get; set; }
[JsonIgnore]
public bool HasSponsor => Sponsor != null;
[JsonIgnore]
public bool HasLocation => !string.IsNullOrEmpty(LocationName);
[JsonIgnore]
public DateTime StartTimeOrderBy { get { return StartTime.HasValue ? StartTime.Value : DateTime.MinValue; } }
}
}
| 28.694915 | 117 | 0.559953 | [
"MIT"
] | CenWIDev/app-cwitc | src/CWITC.DataStore/DataObjects/FeaturedEvent.cs | 1,695 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using NuGet.Packaging.Core;
using Xunit;
namespace NuGet.Packaging.Test
{
public class RepositoryMetadataTests
{
[Fact]
public void RepositoryMetadataDefaultConstructor()
{
var metadata = new RepositoryMetadata();
Assert.Equal(string.Empty, metadata.Type);
Assert.Equal(string.Empty, metadata.Url);
Assert.Equal(string.Empty, metadata.Branch);
Assert.Equal(string.Empty, metadata.Commit);
}
[Theory]
[MemberData(nameof(EqualsRepositoryMetadataData))]
public void RepositoryMetadataEquals(RepositoryMetadata metadata1, RepositoryMetadata metadata2, bool equals)
{
Assert.Equal(equals, metadata1 == metadata2);
Assert.NotEqual(equals, metadata1 != metadata2);
if (metadata1 != null)
{
Assert.Equal(equals, metadata1.Equals(metadata2));
}
if (metadata1 != null && metadata2 != null)
{
Assert.Equal(equals, metadata1.GetHashCode() == metadata2.GetHashCode());
}
}
public static TheoryData EqualsRepositoryMetadataData
{
get
{
var template = new RepositoryMetadata("type", "url", "branch", "commit");
return new TheoryData<RepositoryMetadata, RepositoryMetadata, bool>
{
{ template, template, true },
{ template, null, false },
{ null, template, false },
{ new RepositoryMetadata(), new RepositoryMetadata(), true },
{ new RepositoryMetadata("type", "url", "branch", "commit"), template, true },
{ new RepositoryMetadata("TYPE", "url", "branch", "commit"), template, true },
{ new RepositoryMetadata("type", "URL", "branch", "commit"), template, false },
{ new RepositoryMetadata("type", "url", "BRANCH", "commit"), template, false },
{ new RepositoryMetadata("type", "url", "branch", "COMMIT"), template, false },
{ new RepositoryMetadata("faketype", "url", "branch", "commit"), template, false },
{ new RepositoryMetadata("type", "fakeurl", "branch", "commit"), template, false },
{ new RepositoryMetadata("type", "url", "fakebranch", "commit"), template, false },
{ new RepositoryMetadata("type", "url", "branch", "fakecommit"), template, false },
{ new RepositoryMetadata(null, "url", "branch", "commit"), template, false },
{ new RepositoryMetadata("type", null, "branch", "commit"), template, false },
{ new RepositoryMetadata("type", "url", null, "commit"), template, false },
{ new RepositoryMetadata("type", "url", "branch", null), template, false },
};
}
}
}
}
| 44.152778 | 117 | 0.55615 | [
"Apache-2.0"
] | 0xced/NuGet.Client | test/NuGet.Core.Tests/NuGet.Packaging.Test/RepositoryMetadataTests.cs | 3,179 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad {
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Microsoft.SpecExplorer.Runtime.Testing;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Spec Explorer", "3.4.2965.0")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute()]
public partial class TestScenarioS35 : PtfTestClassBase {
public TestScenarioS35() {
this.SetSwitch("ProceedControlTimeout", "100");
this.SetSwitch("QuiescenceTimeout", "10000");
}
#region Expect Delegates
public delegate void SetInformationPolicy2Delegate1(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus @return);
public delegate void CloseDelegate1(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle handleAfterClose, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus @return);
#endregion
#region Event Metadata
static System.Reflection.MethodBase CloseInfo = TestManagerHelpers.GetMethodInfo(typeof(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ILsadManagedAdapter), "Close", typeof(int), typeof(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle).MakeByRefType());
static System.Reflection.MethodBase SetInformationPolicy2Info = TestManagerHelpers.GetMethodInfo(typeof(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ILsadManagedAdapter), "SetInformationPolicy2", typeof(int), typeof(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass));
#endregion
#region Adapter Instances
private Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ILsadManagedAdapter ILsadManagedAdapterInstance;
#endregion
#region Class Initialization and Cleanup
[Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute()]
public static void ClassInitialize(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext context) {
PtfTestClassBase.Initialize(context);
}
[Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute()]
public static void ClassCleanup() {
PtfTestClassBase.Cleanup();
}
#endregion
#region Test Initialization and Cleanup
protected override void TestInitialize() {
this.InitializeTestManager();
this.ILsadManagedAdapterInstance = ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ILsadManagedAdapter)(this.Manager.GetAdapter(typeof(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ILsadManagedAdapter))));
}
protected override void TestCleanup() {
base.TestCleanup();
this.CleanupTestManager();
}
#endregion
#region Test Starting in S0
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S0() {
this.Manager.BeginTest("TestScenarioS35S0");
this.Manager.Comment("reaching state \'S0\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S1\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S24\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp0;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp1;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,7,out _)\'");
temp1 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 7u, out temp0);
this.Manager.Comment("reaching state \'S36\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp0, "policyHandle of OpenPolicy2, state S36");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp1, "return of OpenPolicy2, state S36");
this.Manager.Comment("reaching state \'S48\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp2;
this.Manager.Comment("executing step \'call SetInformationPolicy(53,PolicyLocalAccountDomainInformation)" +
"\'");
temp2 = this.ILsadManagedAdapterInstance.SetInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S60\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp2, "return of SetInformationPolicy, state S60");
this.Manager.Comment("reaching state \'S72\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp3;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp4;
this.Manager.Comment("executing step \'call QueryInformationPolicy(53,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp4 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp3);
this.Manager.Comment("reaching state \'S84\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp3, "policyInformation of QueryInformationPolicy, state S84");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp4, "return of QueryInformationPolicy, state S84");
this.Manager.Comment("reaching state \'S96\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp5;
this.Manager.Comment("executing step \'call SetInformationPolicy2(53,PolicyLocalAccountDomainInformation" +
")\'");
temp5 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S108\'");
this.Manager.Comment("checking step \'return SetInformationPolicy2/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp5, "return of SetInformationPolicy2, state S108");
this.Manager.Comment("reaching state \'S118\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp6;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp7;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(53,PolicyLocalAccountDomainInformati" +
"on,out _)\'");
temp7 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp6);
this.Manager.Comment("reaching state \'S128\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp6, "policyInformation of QueryInformationPolicy2, state S128");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp7, "return of QueryInformationPolicy2, state S128");
TestScenarioS35S138();
this.Manager.EndTest();
}
private void TestScenarioS35S138() {
this.Manager.Comment("reaching state \'S138\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp8;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp9;
this.Manager.Comment("executing step \'call Close(1,out _)\'");
temp9 = this.ILsadManagedAdapterInstance.Close(1, out temp8);
this.Manager.AddReturn(CloseInfo, null, temp8, temp9);
TestScenarioS35S143();
}
private void TestScenarioS35S143() {
this.Manager.Comment("reaching state \'S143\'");
this.Manager.ExpectReturn(this.QuiescenceTimeout, true, new ExpectedReturn(TestScenarioS35.CloseInfo, null, new CloseDelegate1(this.TestScenarioS35S0CloseChecker)));
this.Manager.Comment("reaching state \'S145\'");
}
private void TestScenarioS35S0CloseChecker(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle handleAfterClose, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus @return) {
this.Manager.Comment("checking step \'return Close/[out Null]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle.Null, handleAfterClose, "handleAfterClose of Close, state S143");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), @return, "return of Close, state S143");
}
#endregion
#region Test Starting in S10
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S10() {
this.Manager.BeginTest("TestScenarioS35S10");
this.Manager.Comment("reaching state \'S10\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S11\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S29\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp10;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp11;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1935,out _)\'");
temp11 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1935u, out temp10);
this.Manager.Comment("reaching state \'S41\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp10, "policyHandle of OpenPolicy2, state S41");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp11, "return of OpenPolicy2, state S41");
this.Manager.Comment("reaching state \'S53\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp12;
this.Manager.Comment("executing step \'call SetInformationPolicy(1,PolicyLocalAccountDomainInformation)\'" +
"");
temp12 = this.ILsadManagedAdapterInstance.SetInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S65\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp12, "return of SetInformationPolicy, state S65");
this.Manager.Comment("reaching state \'S77\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp13;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp14;
this.Manager.Comment("executing step \'call QueryInformationPolicy(53,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp14 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp13);
this.Manager.Comment("reaching state \'S89\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp13, "policyInformation of QueryInformationPolicy, state S89");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp14, "return of QueryInformationPolicy, state S89");
this.Manager.Comment("reaching state \'S101\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp15;
this.Manager.Comment("executing step \'call SetInformationPolicy2(53,PolicyLocalAccountDomainInformation" +
")\'");
temp15 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S112\'");
this.Manager.Comment("checking step \'return SetInformationPolicy2/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp15, "return of SetInformationPolicy2, state S112");
this.Manager.Comment("reaching state \'S122\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp16;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp17;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(53,PolicyLocalAccountDomainInformati" +
"on,out _)\'");
temp17 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp16);
this.Manager.Comment("reaching state \'S132\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp16, "policyInformation of QueryInformationPolicy2, state S132");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp17, "return of QueryInformationPolicy2, state S132");
TestScenarioS35S140();
this.Manager.EndTest();
}
private void TestScenarioS35S140() {
this.Manager.Comment("reaching state \'S140\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp18;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp19;
this.Manager.Comment("executing step \'call Close(1,out _)\'");
temp19 = this.ILsadManagedAdapterInstance.Close(1, out temp18);
this.Manager.AddReturn(CloseInfo, null, temp18, temp19);
TestScenarioS35S144();
}
private void TestScenarioS35S144() {
this.Manager.Comment("reaching state \'S144\'");
this.Manager.ExpectReturn(this.QuiescenceTimeout, true, new ExpectedReturn(TestScenarioS35.CloseInfo, null, new CloseDelegate1(this.TestScenarioS35S10CloseChecker)));
this.Manager.Comment("reaching state \'S146\'");
}
private void TestScenarioS35S10CloseChecker(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle handleAfterClose, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus @return) {
this.Manager.Comment("checking step \'return Close/[out Null]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle.Null, handleAfterClose, "handleAfterClose of Close, state S144");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), @return, "return of Close, state S144");
}
#endregion
#region Test Starting in S12
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S12() {
this.Manager.BeginTest("TestScenarioS35S12");
this.Manager.Comment("reaching state \'S12\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S13\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S30\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp20;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp21;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1928,out _)\'");
temp21 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1928u, out temp20);
this.Manager.Comment("reaching state \'S42\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp20, "policyHandle of OpenPolicy2, state S42");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp21, "return of OpenPolicy2, state S42");
this.Manager.Comment("reaching state \'S54\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp22;
this.Manager.Comment("executing step \'call SetInformationPolicy(53,PolicyLocalAccountDomainInformation)" +
"\'");
temp22 = this.ILsadManagedAdapterInstance.SetInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S66\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp22, "return of SetInformationPolicy, state S66");
this.Manager.Comment("reaching state \'S78\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp23;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp24;
this.Manager.Comment("executing step \'call QueryInformationPolicy(1,PolicyLocalAccountDomainInformation" +
",out _)\'");
temp24 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp23);
this.Manager.Comment("reaching state \'S90\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Invalid]:AccessDenied\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp23, "policyInformation of QueryInformationPolicy, state S90");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.AccessDenied, temp24, "return of QueryInformationPolicy, state S90");
this.Manager.Comment("reaching state \'S102\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp25;
this.Manager.Comment("executing step \'call SetInformationPolicy2(53,PolicyLocalAccountDomainInformation" +
")\'");
temp25 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S113\'");
this.Manager.Comment("checking step \'return SetInformationPolicy2/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp25, "return of SetInformationPolicy2, state S113");
this.Manager.Comment("reaching state \'S123\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp26;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp27;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(53,PolicyLocalAccountDomainInformati" +
"on,out _)\'");
temp27 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp26);
this.Manager.Comment("reaching state \'S133\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp26, "policyInformation of QueryInformationPolicy2, state S133");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp27, "return of QueryInformationPolicy2, state S133");
TestScenarioS35S139();
this.Manager.EndTest();
}
private void TestScenarioS35S139() {
this.Manager.Comment("reaching state \'S139\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp28;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp29;
this.Manager.Comment("executing step \'call Close(1,out _)\'");
temp29 = this.ILsadManagedAdapterInstance.Close(1, out temp28);
this.Manager.AddReturn(CloseInfo, null, temp28, temp29);
TestScenarioS35S143();
}
#endregion
#region Test Starting in S14
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S14() {
this.Manager.BeginTest("TestScenarioS35S14");
this.Manager.Comment("reaching state \'S14\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S15\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S31\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp30;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp31;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1928,out _)\'");
temp31 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1928u, out temp30);
this.Manager.Comment("reaching state \'S43\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp30, "policyHandle of OpenPolicy2, state S43");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp31, "return of OpenPolicy2, state S43");
this.Manager.Comment("reaching state \'S55\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp32;
this.Manager.Comment("executing step \'call SetInformationPolicy(1,PolicyLocalAccountDomainInformation)\'" +
"");
temp32 = this.ILsadManagedAdapterInstance.SetInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S67\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp32, "return of SetInformationPolicy, state S67");
this.Manager.Comment("reaching state \'S79\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp33;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp34;
this.Manager.Comment("executing step \'call QueryInformationPolicy(1,PolicyLocalAccountDomainInformation" +
",out _)\'");
temp34 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp33);
this.Manager.Comment("reaching state \'S91\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Invalid]:AccessDenied\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp33, "policyInformation of QueryInformationPolicy, state S91");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.AccessDenied, temp34, "return of QueryInformationPolicy, state S91");
this.Manager.Comment("reaching state \'S103\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp35;
this.Manager.Comment("executing step \'call SetInformationPolicy2(1,PolicyLocalAccountDomainInformation)" +
"\'");
temp35 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.AddReturn(SetInformationPolicy2Info, null, temp35);
TestScenarioS35S114();
this.Manager.EndTest();
}
private void TestScenarioS35S114() {
this.Manager.Comment("reaching state \'S114\'");
this.Manager.ExpectReturn(this.QuiescenceTimeout, true, new ExpectedReturn(TestScenarioS35.SetInformationPolicy2Info, null, new SetInformationPolicy2Delegate1(this.TestScenarioS35S14SetInformationPolicy2Checker)));
this.Manager.Comment("reaching state \'S124\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp36;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp37;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(1,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp37 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp36);
this.Manager.Comment("reaching state \'S134\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Invalid]:AccessDenied\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp36, "policyInformation of QueryInformationPolicy2, state S134");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.AccessDenied, temp37, "return of QueryInformationPolicy2, state S134");
TestScenarioS35S142();
}
private void TestScenarioS35S14SetInformationPolicy2Checker(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus @return) {
this.Manager.Comment("checking step \'return SetInformationPolicy2/Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), @return, "return of SetInformationPolicy2, state S114");
}
private void TestScenarioS35S142() {
this.Manager.Comment("reaching state \'S142\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp38;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp39;
this.Manager.Comment("executing step \'call Close(1,out _)\'");
temp39 = this.ILsadManagedAdapterInstance.Close(1, out temp38);
this.Manager.AddReturn(CloseInfo, null, temp38, temp39);
TestScenarioS35S144();
}
#endregion
#region Test Starting in S16
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S16() {
this.Manager.BeginTest("TestScenarioS35S16");
this.Manager.Comment("reaching state \'S16\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S17\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S32\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp40;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp41;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1928,out _)\'");
temp41 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1928u, out temp40);
this.Manager.Comment("reaching state \'S44\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp40, "policyHandle of OpenPolicy2, state S44");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp41, "return of OpenPolicy2, state S44");
this.Manager.Comment("reaching state \'S56\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp42;
this.Manager.Comment("executing step \'call SetInformationPolicy(53,PolicyLocalAccountDomainInformation)" +
"\'");
temp42 = this.ILsadManagedAdapterInstance.SetInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S68\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp42, "return of SetInformationPolicy, state S68");
this.Manager.Comment("reaching state \'S80\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp43;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp44;
this.Manager.Comment("executing step \'call QueryInformationPolicy(53,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp44 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp43);
this.Manager.Comment("reaching state \'S92\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp43, "policyInformation of QueryInformationPolicy, state S92");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp44, "return of QueryInformationPolicy, state S92");
this.Manager.Comment("reaching state \'S104\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp45;
this.Manager.Comment("executing step \'call SetInformationPolicy2(1,PolicyLocalAccountDomainInformation)" +
"\'");
temp45 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.AddReturn(SetInformationPolicy2Info, null, temp45);
TestScenarioS35S114();
this.Manager.EndTest();
}
#endregion
#region Test Starting in S18
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S18() {
this.Manager.BeginTest("TestScenarioS35S18");
this.Manager.Comment("reaching state \'S18\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S19\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S33\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp46;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp47;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,7,out _)\'");
temp47 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 7u, out temp46);
this.Manager.Comment("reaching state \'S45\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp46, "policyHandle of OpenPolicy2, state S45");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp47, "return of OpenPolicy2, state S45");
this.Manager.Comment("reaching state \'S57\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp48;
this.Manager.Comment("executing step \'call SetInformationPolicy(1,PolicyLocalAccountDomainInformation)\'" +
"");
temp48 = this.ILsadManagedAdapterInstance.SetInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S69\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/AccessDenied\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.AccessDenied, temp48, "return of SetInformationPolicy, state S69");
this.Manager.Comment("reaching state \'S81\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp49;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp50;
this.Manager.Comment("executing step \'call QueryInformationPolicy(1,PolicyLocalAccountDomainInformation" +
",out _)\'");
temp50 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp49);
this.Manager.Comment("reaching state \'S93\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(0)), temp49, "policyInformation of QueryInformationPolicy, state S93");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp50, "return of QueryInformationPolicy, state S93");
this.Manager.Comment("reaching state \'S105\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp51;
this.Manager.Comment("executing step \'call SetInformationPolicy2(1,PolicyLocalAccountDomainInformation)" +
"\'");
temp51 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S115\'");
this.Manager.Comment("checking step \'return SetInformationPolicy2/AccessDenied\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.AccessDenied, temp51, "return of SetInformationPolicy2, state S115");
this.Manager.Comment("reaching state \'S125\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp52;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp53;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(1,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp53 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp52);
this.Manager.Comment("reaching state \'S135\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(0)), temp52, "policyInformation of QueryInformationPolicy2, state S135");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp53, "return of QueryInformationPolicy2, state S135");
TestScenarioS35S138();
this.Manager.EndTest();
}
#endregion
#region Test Starting in S2
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S2() {
this.Manager.BeginTest("TestScenarioS35S2");
this.Manager.Comment("reaching state \'S2\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S3\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S25\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp54;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp55;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1928,out _)\'");
temp55 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1928u, out temp54);
this.Manager.Comment("reaching state \'S37\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp54, "policyHandle of OpenPolicy2, state S37");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp55, "return of OpenPolicy2, state S37");
this.Manager.Comment("reaching state \'S49\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp56;
this.Manager.Comment("executing step \'call SetInformationPolicy(53,PolicyLocalAccountDomainInformation)" +
"\'");
temp56 = this.ILsadManagedAdapterInstance.SetInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S61\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp56, "return of SetInformationPolicy, state S61");
this.Manager.Comment("reaching state \'S73\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp57;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp58;
this.Manager.Comment("executing step \'call QueryInformationPolicy(1,PolicyLocalAccountDomainInformation" +
",out _)\'");
temp58 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp57);
this.Manager.Comment("reaching state \'S85\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Invalid]:AccessDenied\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp57, "policyInformation of QueryInformationPolicy, state S85");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.AccessDenied, temp58, "return of QueryInformationPolicy, state S85");
this.Manager.Comment("reaching state \'S97\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp59;
this.Manager.Comment("executing step \'call SetInformationPolicy2(53,PolicyLocalAccountDomainInformation" +
")\'");
temp59 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S109\'");
this.Manager.Comment("checking step \'return SetInformationPolicy2/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp59, "return of SetInformationPolicy2, state S109");
this.Manager.Comment("reaching state \'S119\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp60;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp61;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(1,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp61 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp60);
this.Manager.Comment("reaching state \'S129\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Invalid]:AccessDenied\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp60, "policyInformation of QueryInformationPolicy2, state S129");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.AccessDenied, temp61, "return of QueryInformationPolicy2, state S129");
TestScenarioS35S139();
this.Manager.EndTest();
}
#endregion
#region Test Starting in S20
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S20() {
this.Manager.BeginTest("TestScenarioS35S20");
this.Manager.Comment("reaching state \'S20\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S21\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S34\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp62;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp63;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1935,out _)\'");
temp63 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1935u, out temp62);
this.Manager.Comment("reaching state \'S46\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp62, "policyHandle of OpenPolicy2, state S46");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp63, "return of OpenPolicy2, state S46");
this.Manager.Comment("reaching state \'S58\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp64;
this.Manager.Comment("executing step \'call SetInformationPolicy(53,PolicyLocalAccountDomainInformation)" +
"\'");
temp64 = this.ILsadManagedAdapterInstance.SetInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S70\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp64, "return of SetInformationPolicy, state S70");
this.Manager.Comment("reaching state \'S82\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp65;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp66;
this.Manager.Comment("executing step \'call QueryInformationPolicy(53,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp66 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp65);
this.Manager.Comment("reaching state \'S94\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp65, "policyInformation of QueryInformationPolicy, state S94");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp66, "return of QueryInformationPolicy, state S94");
this.Manager.Comment("reaching state \'S106\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp67;
this.Manager.Comment("executing step \'call SetInformationPolicy2(53,PolicyLocalAccountDomainInformation" +
")\'");
temp67 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S116\'");
this.Manager.Comment("checking step \'return SetInformationPolicy2/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp67, "return of SetInformationPolicy2, state S116");
this.Manager.Comment("reaching state \'S126\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp68;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp69;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(53,PolicyLocalAccountDomainInformati" +
"on,out _)\'");
temp69 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp68);
this.Manager.Comment("reaching state \'S136\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp68, "policyInformation of QueryInformationPolicy2, state S136");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp69, "return of QueryInformationPolicy2, state S136");
TestScenarioS35S141();
this.Manager.EndTest();
}
private void TestScenarioS35S141() {
this.Manager.Comment("reaching state \'S141\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp70;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp71;
this.Manager.Comment("executing step \'call Close(1,out _)\'");
temp71 = this.ILsadManagedAdapterInstance.Close(1, out temp70);
this.Manager.AddReturn(CloseInfo, null, temp70, temp71);
TestScenarioS35S143();
}
#endregion
#region Test Starting in S22
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S22() {
this.Manager.BeginTest("TestScenarioS35S22");
this.Manager.Comment("reaching state \'S22\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S23\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S35\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp72;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp73;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1928,out _)\'");
temp73 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1928u, out temp72);
this.Manager.Comment("reaching state \'S47\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp72, "policyHandle of OpenPolicy2, state S47");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp73, "return of OpenPolicy2, state S47");
this.Manager.Comment("reaching state \'S59\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp74;
this.Manager.Comment("executing step \'call SetInformationPolicy(1,PolicyLocalAccountDomainInformation)\'" +
"");
temp74 = this.ILsadManagedAdapterInstance.SetInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S71\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp74, "return of SetInformationPolicy, state S71");
this.Manager.Comment("reaching state \'S83\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp75;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp76;
this.Manager.Comment("executing step \'call QueryInformationPolicy(53,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp76 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp75);
this.Manager.Comment("reaching state \'S95\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp75, "policyInformation of QueryInformationPolicy, state S95");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp76, "return of QueryInformationPolicy, state S95");
this.Manager.Comment("reaching state \'S107\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp77;
this.Manager.Comment("executing step \'call SetInformationPolicy2(53,PolicyLocalAccountDomainInformation" +
")\'");
temp77 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S117\'");
this.Manager.Comment("checking step \'return SetInformationPolicy2/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp77, "return of SetInformationPolicy2, state S117");
this.Manager.Comment("reaching state \'S127\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp78;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp79;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(53,PolicyLocalAccountDomainInformati" +
"on,out _)\'");
temp79 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp78);
this.Manager.Comment("reaching state \'S137\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Invalid]:InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(1)), temp78, "policyInformation of QueryInformationPolicy2, state S137");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp79, "return of QueryInformationPolicy2, state S137");
TestScenarioS35S142();
this.Manager.EndTest();
}
#endregion
#region Test Starting in S4
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S4() {
this.Manager.BeginTest("TestScenarioS35S4");
this.Manager.Comment("reaching state \'S4\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S5\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S26\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp80;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp81;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1935,out _)\'");
temp81 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1935u, out temp80);
this.Manager.Comment("reaching state \'S38\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp80, "policyHandle of OpenPolicy2, state S38");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp81, "return of OpenPolicy2, state S38");
this.Manager.Comment("reaching state \'S50\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp82;
this.Manager.Comment("executing step \'call SetInformationPolicy(1,PolicyLocalAccountDomainInformation)\'" +
"");
temp82 = this.ILsadManagedAdapterInstance.SetInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S62\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp82, "return of SetInformationPolicy, state S62");
this.Manager.Comment("reaching state \'S74\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp83;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp84;
this.Manager.Comment("executing step \'call QueryInformationPolicy(1,PolicyLocalAccountDomainInformation" +
",out _)\'");
temp84 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp83);
this.Manager.Comment("reaching state \'S86\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(0)), temp83, "policyInformation of QueryInformationPolicy, state S86");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp84, "return of QueryInformationPolicy, state S86");
this.Manager.Comment("reaching state \'S98\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp85;
this.Manager.Comment("executing step \'call SetInformationPolicy2(1,PolicyLocalAccountDomainInformation)" +
"\'");
temp85 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.AddReturn(SetInformationPolicy2Info, null, temp85);
TestScenarioS35S110();
this.Manager.EndTest();
}
private void TestScenarioS35S110() {
this.Manager.Comment("reaching state \'S110\'");
this.Manager.ExpectReturn(this.QuiescenceTimeout, true, new ExpectedReturn(TestScenarioS35.SetInformationPolicy2Info, null, new SetInformationPolicy2Delegate1(this.TestScenarioS35S4SetInformationPolicy2Checker)));
this.Manager.Comment("reaching state \'S120\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp86;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp87;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(1,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp87 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp86);
this.Manager.Comment("reaching state \'S130\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(0)), temp86, "policyInformation of QueryInformationPolicy2, state S130");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp87, "return of QueryInformationPolicy2, state S130");
TestScenarioS35S140();
}
private void TestScenarioS35S4SetInformationPolicy2Checker(Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus @return) {
this.Manager.Comment("checking step \'return SetInformationPolicy2/Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), @return, "return of SetInformationPolicy2, state S110");
}
#endregion
#region Test Starting in S6
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S6() {
this.Manager.BeginTest("TestScenarioS35S6");
this.Manager.Comment("reaching state \'S6\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S7\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S27\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp88;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp89;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1935,out _)\'");
temp89 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1935u, out temp88);
this.Manager.Comment("reaching state \'S39\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp88, "policyHandle of OpenPolicy2, state S39");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp89, "return of OpenPolicy2, state S39");
this.Manager.Comment("reaching state \'S51\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp90;
this.Manager.Comment("executing step \'call SetInformationPolicy(53,PolicyLocalAccountDomainInformation)" +
"\'");
temp90 = this.ILsadManagedAdapterInstance.SetInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S63\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp90, "return of SetInformationPolicy, state S63");
this.Manager.Comment("reaching state \'S75\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp91;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp92;
this.Manager.Comment("executing step \'call QueryInformationPolicy(1,PolicyLocalAccountDomainInformation" +
",out _)\'");
temp92 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp91);
this.Manager.Comment("reaching state \'S87\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(0)), temp91, "policyInformation of QueryInformationPolicy, state S87");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp92, "return of QueryInformationPolicy, state S87");
this.Manager.Comment("reaching state \'S99\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp93;
this.Manager.Comment("executing step \'call SetInformationPolicy2(53,PolicyLocalAccountDomainInformation" +
")\'");
temp93 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S111\'");
this.Manager.Comment("checking step \'return SetInformationPolicy2/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp93, "return of SetInformationPolicy2, state S111");
this.Manager.Comment("reaching state \'S121\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp94;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp95;
this.Manager.Comment("executing step \'call QueryInformationPolicy2(1,PolicyLocalAccountDomainInformatio" +
"n,out _)\'");
temp95 = this.ILsadManagedAdapterInstance.QueryInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp94);
this.Manager.Comment("reaching state \'S131\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(0)), temp94, "policyInformation of QueryInformationPolicy2, state S131");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp95, "return of QueryInformationPolicy2, state S131");
TestScenarioS35S141();
this.Manager.EndTest();
}
#endregion
#region Test Starting in S8
[TestCategory("PDC")]
[TestCategory("DomainWin2008R2")]
[TestCategory("ForestWin2008R2")]
[TestCategory("MS-LSAD")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
public void LSAD_TestScenarioS35S8() {
this.Manager.BeginTest("TestScenarioS35S8");
this.Manager.Comment("reaching state \'S8\'");
this.Manager.Comment("executing step \'call Initialize(DomainController,Disable,Windows2k8,2,True)\'");
this.ILsadManagedAdapterInstance.Initialize(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ProtocolServerConfig)(0)), ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.AnonymousAccess)(0)), Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Server.Windows2k8, 2, true);
this.Manager.Comment("reaching state \'S9\'");
this.Manager.Comment("checking step \'return Initialize\'");
this.Manager.Comment("reaching state \'S28\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle temp96;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp97;
this.Manager.Comment("executing step \'call OpenPolicy2(Null,1935,out _)\'");
temp97 = this.ILsadManagedAdapterInstance.OpenPolicy2(((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.RootDirectory)(0)), 1935u, out temp96);
this.Manager.Comment("reaching state \'S40\'");
this.Manager.Comment("checking step \'return OpenPolicy2/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.Handle)(0)), temp96, "policyHandle of OpenPolicy2, state S40");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp97, "return of OpenPolicy2, state S40");
this.Manager.Comment("reaching state \'S52\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp98;
this.Manager.Comment("executing step \'call SetInformationPolicy(53,PolicyLocalAccountDomainInformation)" +
"\'");
temp98 = this.ILsadManagedAdapterInstance.SetInformationPolicy(53, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.Comment("reaching state \'S64\'");
this.Manager.Comment("checking step \'return SetInformationPolicy/InvalidHandle\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus.InvalidHandle, temp98, "return of SetInformationPolicy, state S64");
this.Manager.Comment("reaching state \'S76\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation temp99;
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp100;
this.Manager.Comment("executing step \'call QueryInformationPolicy(1,PolicyLocalAccountDomainInformation" +
",out _)\'");
temp100 = this.ILsadManagedAdapterInstance.QueryInformationPolicy(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation, out temp99);
this.Manager.Comment("reaching state \'S88\'");
this.Manager.Comment("checking step \'return QueryInformationPolicy/[out Valid]:Success\'");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.PolicyInformation)(0)), temp99, "policyInformation of QueryInformationPolicy, state S88");
TestManagerHelpers.AssertAreEqual<Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus>(this.Manager, ((Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus)(0)), temp100, "return of QueryInformationPolicy, state S88");
this.Manager.Comment("reaching state \'S100\'");
Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.ErrorStatus temp101;
this.Manager.Comment("executing step \'call SetInformationPolicy2(1,PolicyLocalAccountDomainInformation)" +
"\'");
temp101 = this.ILsadManagedAdapterInstance.SetInformationPolicy2(1, Microsoft.Protocols.TestSuites.ActiveDirectory.Lsad.InformationClass.PolicyLocalAccountDomainInformation);
this.Manager.AddReturn(SetInformationPolicy2Info, null, temp101);
TestScenarioS35S110();
this.Manager.EndTest();
}
#endregion
}
}
| 95.507328 | 302 | 0.73307 | [
"MIT"
] | 0neb1n/WindowsProtocolTestSuites | TestSuites/ADFamily/src/TestSuite/MS-LSAD/TestScenarioS35.cs | 84,715 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace XIntric.ExpressionInjection.Linq
{
public interface IQueryProvider : System.Linq.IQueryProvider
{
IQueryProvider WithFactory(Func<IQueryProvider, Type, Expression, IQueryable> factory);
System.Linq.IQueryProvider SourceProvider { get; }
new IQueryable CreateQuery(Expression expression);
new IQueryable<T> CreateQuery<T>(Expression expression);
}
internal class QueryProvider : IQueryProvider
{
public QueryProvider(System.Linq.IQueryProvider sourceprovider)
{
SourceProvider = sourceprovider;
Factory = (provider, type, expr) =>
(IQueryable)Activator.CreateInstance(
typeof(Queryable<>).MakeGenericType(type),
this, expr);
}
public QueryProvider(System.Linq.IQueryProvider sourceprovider, Func<IQueryProvider, Type, Expression, IQueryable> factory)
{
SourceProvider = sourceprovider;
Factory = factory;
}
public System.Linq.IQueryProvider SourceProvider { get; }
public virtual IQueryable CreateQuery(Expression expression)
=> (IQueryable)Factory.Invoke(this, typeof(object), expression);
public virtual IQueryable<TElement> CreateQuery<TElement>(Expression expression)
=> (IQueryable<TElement>)Factory.Invoke(this, typeof(TElement), expression);
public object Execute(Expression expression)
{
var expander = new InjectorTrapper();
var modified = expander.Visit(expression);
return SourceProvider.Execute(modified);
}
public TResult Execute<TResult>(Expression expression)
{
var expander = new InjectorTrapper();
var modified = expander.Visit(expression);
return SourceProvider.Execute<TResult>(modified);
}
System.Linq.IQueryable System.Linq.IQueryProvider.CreateQuery(Expression expression) => CreateQuery(expression);
System.Linq.IQueryable<TElement> System.Linq.IQueryProvider.CreateQuery<TElement>(Expression expression) => CreateQuery<TElement>(expression);
public IQueryProvider WithFactory(Func<IQueryProvider, Type, Expression, IQueryable> factory)
=> new QueryProvider(SourceProvider, factory);
private Func<IQueryProvider, Type, Expression, IQueryable> Factory;
}
}
| 35.816901 | 150 | 0.67676 | [
"MIT"
] | JTOne123/ExpressionInjection | XIntric.ExpressionInjection/Linq/QueryProvider.cs | 2,545 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RestWithAspnet5.Business;
using RestWithAspnet5.Data.VO;
using RestWithAspnet5.Hypermedia.Filters;
using System.Collections.Generic;
namespace RestWithAspnet5.Controllers
{
[ApiVersion("1")]
[ApiController]
[Authorize("Bearer")]
[Route("api/[controller]/v{version:apiVersion}")]
public class BookController : ControllerBase
{
private readonly ILogger<BookController> _logger;
private IBookBusiness _bookBusiness;
public BookController(ILogger<BookController> logger, IBookBusiness bookBusiness)
{
_logger = logger;
_bookBusiness = bookBusiness;
}
[HttpGet]
[ProducesResponseType(200, Type = typeof(List<BookVO>))]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(401)]
[TypeFilter(typeof(HyperMediaFilter))]
public IActionResult Get()
{
return Ok(_bookBusiness.FindAll());
}
[HttpGet("{id}")]
[ProducesResponseType(200, Type = typeof(BookVO))]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(401)]
[TypeFilter(typeof(HyperMediaFilter))]
public IActionResult Get(long id)
{
var Book = _bookBusiness.FindById(id);
if (Book == null)
{
return NotFound();
}
return Ok(Book);
}
[HttpPost]
[ProducesResponseType(200, Type = typeof(BookVO))]
[ProducesResponseType(400)]
[ProducesResponseType(401)]
[TypeFilter(typeof(HyperMediaFilter))]
public IActionResult Post([FromBody] BookVO book)
{
if (book == null)
{
return BadRequest();
}
return Ok(_bookBusiness.Create(book));
}
[HttpPut]
[ProducesResponseType(200, Type = typeof(BookVO))]
[ProducesResponseType(400)]
[ProducesResponseType(401)]
[TypeFilter(typeof(HyperMediaFilter))]
public IActionResult Update([FromBody] BookVO book)
{
if (book == null)
{
return BadRequest();
}
return Ok(_bookBusiness.Update(book));
}
[HttpDelete("{id}")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(401)]
public IActionResult Delete(long id)
{
_bookBusiness.Delete(id);
return NoContent();
}
}
} | 28.431579 | 89 | 0.588301 | [
"Apache-2.0"
] | fabiojfl16/RestWithAspnet5 | RestWithAspnet5/Controllers/BookController.cs | 2,703 | C# |
using System;
using Xamarin.Forms;
namespace WaterAddition.Helpers {
public class MessageBus {
static readonly Lazy<MessageBus> LazyInstance = new Lazy<MessageBus>(() => new MessageBus(), true);
static MessageBus Instance => LazyInstance.Value;
MessageBus() {
}
public static void SendMessage(string message) {
MessagingCenter.Send(Instance, message);
}
public static void SendMessage<TArgs>(string message, TArgs args) {
MessagingCenter.Send(Instance, message, args);
}
}
}
| 23.952381 | 101 | 0.733598 | [
"MIT"
] | Porodin/WaterAddition | WaterAddition/Helpers/MessageBus.cs | 503 | 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.TimeSeriesInsights.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Event availability information when environment contains events.
/// Contains time range of events and approximate distribution of events
/// over time.
/// </summary>
public partial class Availability
{
/// <summary>
/// Initializes a new instance of the Availability class.
/// </summary>
public Availability()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Availability class.
/// </summary>
/// <param name="range">Minimum and maximum values of event timestamp
/// ($ts) property.</param>
/// <param name="intervalSize">Interval size for the returned
/// distribution of the events. Returned interval is selected to return
/// a reasonable number of points. All intervals are the same size. On
/// the wire interval is specified in ISO-8601 duration format. One
/// month is always converted to 30 days, and one year is always 365
/// days. Examples: 1 minute is "PT1M", 1 millisecond is "PT0.001S".
/// For more information, see
/// https://www.w3.org/TR/xmlschema-2/#duration</param>
public Availability(DateTimeRange range = default(DateTimeRange), System.TimeSpan? intervalSize = default(System.TimeSpan?), IDictionary<string, int?> distribution = default(IDictionary<string, int?>))
{
Range = range;
IntervalSize = intervalSize;
Distribution = distribution;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets minimum and maximum values of event timestamp ($ts) property.
/// </summary>
[JsonProperty(PropertyName = "range")]
public DateTimeRange Range { get; private set; }
/// <summary>
/// Gets interval size for the returned distribution of the events.
/// Returned interval is selected to return a reasonable number of
/// points. All intervals are the same size. On the wire interval is
/// specified in ISO-8601 duration format. One month is always
/// converted to 30 days, and one year is always 365 days. Examples: 1
/// minute is "PT1M", 1 millisecond is "PT0.001S". For more
/// information, see https://www.w3.org/TR/xmlschema-2/#duration
/// </summary>
[JsonProperty(PropertyName = "intervalSize")]
public System.TimeSpan? IntervalSize { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "distribution")]
public IDictionary<string, int?> Distribution { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Range != null)
{
Range.Validate();
}
}
}
}
| 38.443299 | 209 | 0.613569 | [
"MIT"
] | Azure-Samples/Azure-Time-Series-Insights | gen2-sample/csharp-tsi-gen2-sample/DataPlaneClient/Generated/TimeSeriesInsights/DataPlane.TimeSeriesInsights/Generated/Models/Availability.cs | 3,729 | C# |
using System;
using System.CodeDom.Compiler;
using System.IO;
namespace SourceGeneration.Mvvm.Helpers
{
public class SourceWriter : IndentedTextWriter
{
public SourceWriter(TextWriter writer) : base(writer) { }
public IDisposable StartBlock(string text)
{
WriteLine(text);
return new BaseBlock(this);
}
public IDisposable StartFunction(string returnType, string functionName, string arguments ="", string prefix = "")
{
if (string.IsNullOrEmpty(prefix) == false)
{
Write(prefix);
}
WriteLine($"{returnType} {functionName}({arguments})");
return new BaseBlock(this);
}
public IDisposable StartProperty(string propertyType, string propertyName)
{
WriteLine($"public {propertyType} {propertyName}");
return new BaseBlock(this);
}
class BaseBlock : IDisposable
{
protected readonly IndentedTextWriter _writer;
public BaseBlock(IndentedTextWriter writer)
{
_writer = writer;
_writer.WriteLine("{");
_writer.Indent++;
}
public virtual void Dispose()
{
_writer.Indent--;
_writer.WriteLine("}");
}
}
}
}
| 26.111111 | 122 | 0.543972 | [
"MIT"
] | athulrajts/csharp-source-generation | SourceGeneration.Mvvm/Helpers/SourceWriter.cs | 1,412 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace HardwareAffinity.Data.Migrations
{
public partial class AddCartsAndCartProductsTables : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Carts",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CreatedOn = table.Column<DateTime>(nullable: false),
ModifiedOn = table.Column<DateTime>(nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
DeletedOn = table.Column<DateTime>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Carts", x => x.Id);
table.ForeignKey(
name: "FK_Carts_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "CartProducts",
columns: table => new
{
ProductId = table.Column<string>(nullable: false),
CartId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CartProducts", x => new { x.CartId, x.ProductId });
table.ForeignKey(
name: "FK_CartProducts_Carts_CartId",
column: x => x.CartId,
principalTable: "Carts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_CartProducts_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_CartProducts_ProductId",
table: "CartProducts",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Carts_IsDeleted",
table: "Carts",
column: "IsDeleted");
migrationBuilder.CreateIndex(
name: "IX_Carts_UserId",
table: "Carts",
column: "UserId",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CartProducts");
migrationBuilder.DropTable(
name: "Carts");
}
}
}
| 38.035714 | 92 | 0.477934 | [
"MIT"
] | vib1336/HardwareAffinity | src/Data/HardwareAffinity.Data/Migrations/20201211122342_AddCartsAndCartProductsTables.cs | 3,197 | C# |
using System;
using System.Collections.Generic;
using Sandbox;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Miku.Lua.Objects.Internal
{
// TODO BUG: A full table will never return when trying to access a missing key?
// Should be fine as long as we never allow full tables, which we don't.
class MikuDict
{
private struct KeyValuePair
{
public void Set( ValueSlot key, ValueSlot val )
{
Key = key;
Value = val;
}
public ValueSlot Key;
public ValueSlot Value;
}
private struct HashIndex
{
public void Set(uint hash, uint index)
{
Hash = hash;
Index = index;
}
public uint Hash;
public uint Index;
}
// Uses https://github.com/slembcke/Chipmunk2D/blob/master/src/prime.h
// Based on http://planetmath.org/encyclopedia/GoodHashTablePrimes.html [dead link]
const int INIT_CAPACITY = 8;
readonly int[] LUT_CAPACITY = new int[] {
5, 13, 23, 47, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157,
98317, 196613, 393241, 786433, 1572869, 3145739, 6291469
};
private uint ComputeIndex(uint hash)
{
return FastMod(hash, (uint)HashIndices.Length, FastModMul);
}
const float RESIZE_THRESHOLD = 0.75f;
const uint HASH_EMPTY = 0;
const uint HASH_TOMBSTONE = 1;
// We don't bother with lazy init. The table that wraps us should take care of that.
private KeyValuePair[] PairChunk = new KeyValuePair[INIT_CAPACITY];
// Hashes are cached for faster lookups and rehashes.
// They are also used to quickly scan for empty slots.
private HashIndex[] HashIndices = new HashIndex[INIT_CAPACITY];
// If used to index into LUT_CAPACITY, this should give us our current capacity.
private int SizeIndex = 0;
private ulong FastModMul = GetFastModMultiplier(INIT_CAPACITY);
public int Count { get; private set; }
private int Capacity => HashIndices.Length;
private int ResizeThreshold = (int)(INIT_CAPACITY * RESIZE_THRESHOLD);
public ValueSlot Get(ValueSlot key)
{
if (key.Kind == ValueKind.Nil)
{
return ValueSlot.NIL;
}
uint hash = Math.Max( (uint)key.GetHashCode(), 2 );
uint index = ComputeIndex( hash );
while ( true )
{
ref HashIndex current_hi = ref HashIndices[index];
if ( current_hi.Hash == HASH_EMPTY )
{
return ValueSlot.NIL;
}
if ( hash == current_hi.Hash && PairChunk[current_hi.Index].Key.Equals(key))
{
return PairChunk[HashIndices[index].Index].Value;
}
index = (index < HashIndices.Length - 1) ? index + 1 : 0;
}
}
public void Set( ValueSlot key, ValueSlot val )
{
if ( key.Kind == ValueKind.Nil )
{
return;
}
if ( val.Kind == ValueKind.Nil )
{
throw new Exception( "TODO deletion" );
}
if ( Count >= ResizeThreshold )
{
Grow();
}
uint hash = Math.Max( (uint)key.GetHashCode(), 2);
uint index = ComputeIndex( hash );
while ( true )
{
ref HashIndex current_hi = ref HashIndices[index];
// Empty slot, insert.
if (current_hi.Hash == HASH_EMPTY)
{
uint pair_index = (uint)Count; // TODO we're going to need to do other stuff here if we want to handle deletes
Count++;
PairChunk[pair_index].Set( key, val ); // this is measurably faster than constructing a new Pair.
current_hi.Set( hash, pair_index );
return;
}
// Short path: compare the hash before checking equality
if ( hash == current_hi.Hash && PairChunk[current_hi.Index].Key.Equals( key ) )
{
// Just replace the value
PairChunk[current_hi.Index].Value = val;
return;
}
index = (index < HashIndices.Length - 1) ? index + 1 : 0;
//index = Math.Min( index + 1, index - (uint)HashIndices.Length + 1 );
}
}
void Grow()
{
var old_chunk = PairChunk;
var old_his = HashIndices;
SizeIndex++;
int new_size = LUT_CAPACITY[SizeIndex];
PairChunk = new KeyValuePair[new_size];
HashIndices = new HashIndex[new_size];
ResizeThreshold = (int)(Capacity * RESIZE_THRESHOLD);
FastModMul = GetFastModMultiplier( (uint)new_size );
Array.Copy( old_chunk, PairChunk, old_chunk.Length );
for (int i=0;i< old_his.Length; i++)
{
HashIndex old_hi = old_his[i];
if ( old_hi.Hash >= 2 )
{
uint index = ComputeIndex( old_hi.Hash );
// Skip filled slots. No need to check for equality, we know all keys are unique.
while ( true )
{
ref HashIndex new_hi = ref HashIndices[index];
if ( new_hi.Hash == HASH_EMPTY ) {
// Place
new_hi = old_hi;
break;
}
index = (index < HashIndices.Length - 1) ? index + 1 : 0;
}
}
}
}
#if MIKU_CONSOLE
public static void Bench()
{
int SIZE = 62;
long sum_dict = 0;
long sum_miku = 0;
var timer = new Stopwatch();
var keys = new ValueSlot[SIZE];
var values = new ValueSlot[SIZE];
var data = new long[SIZE, 2];
for ( int i = 0; i < SIZE; i++ )
{
keys[i] = "key" + i.ToString();
values[i] = "value" + i.ToString();
}
while (sum_dict < 10_000_000)
{
{
var dict = new MikuDict();
for (int i=0;i< SIZE; i++ )
{
timer.Restart();
dict.Set( keys[i], values[i] );
data[i,0] += timer.ElapsedTicks;
sum_miku += timer.ElapsedTicks;
}
for ( int i = 0; i < SIZE; i++ )
{
timer.Restart();
var res = dict.Get( keys[i] );
data[i, 0] += timer.ElapsedTicks;
sum_miku += timer.ElapsedTicks;
if ( !res.Equals( values[i] ) )
{
throw new Exception("validation failed miku "+i+" "+res);
}
}
}
{
var dict = new Dictionary<ValueSlot,ValueSlot>();
for ( int i = 0; i < SIZE; i++ )
{
timer.Restart();
dict.Add( keys[i], values[i] );
data[i, 1] += timer.ElapsedTicks;
sum_dict += timer.ElapsedTicks;
}
for (int i = 0; i < SIZE; i++ )
{
timer.Restart();
var res = dict[keys[i]];
data[i, 1] += timer.ElapsedTicks;
sum_dict += timer.ElapsedTicks;
if ( !res.Equals( values[i] ) )
{
throw new Exception( "validation failed dict " + i + " " + res );
}
}
}
}
if (SIZE <= 1000)
{
System.Console.WriteLine("MIKU,NET");
for ( int i = 0; i < SIZE; i++ )
{
System.Console.WriteLine(data[i,0]+","+data[i,1]);
}
}
Log.Info( $"MIKU {sum_miku:n0}" );
Log.Info( $".NET {sum_dict:n0}" );
Log.Info( $"MIKU is {(float)sum_miku / sum_dict * 100}% of .NET" );
}
#endif
// From https://source.dot.net/#System.Private.CoreLib/HashHelpers.cs,de3ba4873d4ad06a
/// <summary>Returns approximate reciprocal of the divisor: ceil(2**64 / divisor).</summary>
/// <remarks>This should only be used on 64-bit.</remarks>
public static ulong GetFastModMultiplier( uint divisor ) =>
ulong.MaxValue / divisor + 1;
/// <summary>Performs a mod operation using the multiplier pre-computed with <see cref="GetFastModMultiplier"/>.</summary>
/// <remarks>This should only be used on 64-bit.</remarks>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static uint FastMod( uint value, uint divisor, ulong multiplier )
{
// We use modified Daniel Lemire's fastmod algorithm (https://github.com/dotnet/runtime/pull/406),
// which allows to avoid the long multiplication if the divisor is less than 2**31.
// This is equivalent of (uint)Math.BigMul(multiplier * value, divisor, out _). This version
// is faster than BigMul currently because we only need the high bits.
uint highbits = (uint)(((((multiplier * value) >> 32) + 1) * divisor) >> 32);
return highbits;
}
}
}
| 28.058608 | 124 | 0.625849 | [
"MIT"
] | ChurchOfMiku/hatsune-miku-compatibility-system | code/Lua/Objects/Internal/MikuDict.cs | 7,660 | C# |
using System.Collections.Generic;
using Smidas.Common;
using Smidas.Core.Stocks;
namespace Smidas.Core.Analysis
{
public interface IAktieRea : IAnalysis
{
void ExcludeDisqualifiedStocks(ref IEnumerable<Stock> stocks, AktieReaQuery.AnalysisOptionsData options);
void ExcludeDoubles(ref IEnumerable<Stock> stocks);
void CalculateARank(ref IEnumerable<Stock> stocks);
void CalculateBRank(ref IEnumerable<Stock> stocks);
void DetermineActions(ref IEnumerable<Stock> stocks, AktieReaQuery query);
}
} | 36.533333 | 113 | 0.751825 | [
"MIT"
] | Dekamik/Smidas | Smidas/Smidas.Core/Analysis/IAktieRea.cs | 548 | C# |
using System.Collections.Generic;
public static class DefinitionGenerator
{
public static void GenerateDefinitions(Dictionary<string, LangDefParam> dic)
{
// Item names and descriptions.
GenItems(dic);
}
private static void GenItems(Dictionary<string, LangDefParam> dic)
{
// Auto generate item name and description definitions.
if (Item.Items == null)
Item.LoadItems();
foreach (var item in Item.Items.Values)
{
// Descriptions.
string key = item.Prefab + "_LongDesc";
if (!dic.ContainsKey(key))
{
LangDefParam p = new LangDefParam();
p.Key = key;
p.Desription = "The long description of the '" + item.Prefab + "' item. Please copy from English as accurately as possible.";
dic.Add(key, p);
}
key = item.Prefab + "_ShortDesc";
if (!dic.ContainsKey(key))
{
LangDefParam p = new LangDefParam();
p.Key = key;
p.Desription = "The short description of the '" + item.Prefab + "' item. Please copy from English as accurately as possible.";
dic.Add(key, p);
}
// Names
key = item.Prefab + "_Name";
if (!dic.ContainsKey(key))
{
LangDefParam p = new LangDefParam();
p.Key = key;
p.Desription = "The display name of the '" + item.Prefab + "' item.";
dic.Add(key, p);
}
}
}
} | 33.102041 | 142 | 0.51233 | [
"MIT"
] | Epicguru/NotQuiteDead | Assets/Scripts/Translation/DefinitionGenerator.cs | 1,624 | C# |
using BEDA.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace BEDA.CIB.Contracts.Responses
{
/// <summary>
/// 3.17.1活期与保证金互转响应主体
/// </summary>
public class V1_DCPMGTTRNRS : IResponse
{
/// <summary>
/// 3.17.1活期与保证金互转响应主体
/// </summary>
public DCPMGTTRNRS DCPMGTTRNRS { get; set; }
}
/// <summary>
/// 3.17.1活期与保证金互转响应主体
/// </summary>
public class DCPMGTTRNRS : BIZRSBASE
{
/// <summary>
/// 3.17.1活期与保证金互转响应内容
/// </summary>
[XmlElement(Order = 2)]
public DCPMGTTRN_RSBODY RSBODY { get; set; }
}
/// <summary>
/// 3.17.1活期与保证金互转响应内容
/// </summary>
public class DCPMGTTRN_RSBODY
{
/// <summary>
/// 成员活期账户代号,18位
/// </summary>
[XmlElement(Order = 0)]
public string MEMACCT { get; set; }
/// <summary>
/// 成员活期账户名称
/// </summary>
[XmlElement(Order = 1)]
public string MEMACCTNAME { get; set; }
/// <summary>
/// 成员账号对应的担保账号,18位
/// </summary>
[XmlElement(Order = 2)]
public string MARGINACCT { get; set; }
/// <summary>
/// 成员账号对应的担保账号名称
/// </summary>
[XmlElement(Order = 3)]
public string MARGINACCTNAME { get; set; }
/// <summary>
/// 业务类型,1-活期转担保 2-担保转活期
/// </summary>
[XmlElement(Order = 4)]
public int BIZTYPE { get; set; }
/// <summary>
/// 金额,Decimal(17,2)
/// </summary>
[XmlElement(Order = 5)]
public decimal AMOUNT { get; set; }
/// <summary>
/// 凭证号
/// </summary>
[XmlElement(Order = 6)]
public string CHEQUENUM { get; set; }
/// <summary>
/// 货币符号RMB,目前仅支持RMB
/// </summary>
[XmlElement(Order = 7)]
public string CURSYM { get; set; }
/// <summary>
/// 用途,最大50位,不允许为空或空格,不允许填换行符等非法字符
/// </summary>
[XmlElement(Order = 8)]
public string PURPOSE { get; set; }
/// <summary>
/// 备注,最大60位
/// </summary>
[XmlElement(Order = 9)]
public string MEMO { get; set; }
/// <summary>
/// 客户端期望的转账执行日期,格式:YYYY-MM-DD。
/// </summary>
[XmlIgnore]
public DateTime? DTDUE { get; set; }
/// <summary>
/// 客户端期望的转账执行日期,格式:YYYY-MM-DD, 对应<see cref="DTDUE"/>
/// </summary>
[XmlElement("DTDUE", Order = 10)]
public string DTDUEStr
{
get
{
return this.DTDUE?.ToString("yyyy-MM-dd");
}
set
{
this.DTDUE = value.TryConvert<DateTime>();
}
}
/// <summary>
/// 批量指令处理状态
/// </summary>
[XmlElement(Order = 11)]
public XFERPRCSTS XFERPRCSTS { get; set; }
}
}
| 26.701754 | 61 | 0.487188 | [
"MIT"
] | fdstar/BankEnterpriseDirectAttach | src/BEDA.CIB/Contracts/Responses/3.17/V1_DCPMGTTRNRS.cs | 3,470 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using GDAPI.Objects.General;
using GDAPI.Objects.GeometryDash.LevelObjects;
namespace GDAPI.Application.Editors.Delegates
{
/// <summary>Represents a function that applies a transformation to the specified objects based on a central point.</summary>
/// <param name="affectedObjects">The objects that will be affected by this function.</param>
/// <param name="centralPoint">The central point that was taken into account while performing the action.</param>
/// <param name="registerUndoable">Determines whether this action should be registered in the undo stack after performing it.</param>
public delegate void ObjectPropertyNullableCentralPointSetter(LevelObjectCollection affectedObjects, Point? centralPoint, bool registerUndoable);
}
| 55.266667 | 149 | 0.792521 | [
"MIT"
] | AlFasGD/GDAPI | GDAPI/GDAPI/Application/Editors/Delegates/ObjectPropertyNullableCentralPointSetter.cs | 831 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace S2CCore
{
public class CleanCommand : BaseCommand
{
public CleanCommand(int agentId, int row, int col)
{
Name = "clean";
AgentId = agentId;
Location = new Coords(row, col);
}
public override string ToString()
{
return "Clean [" + Location.Row + ", " + Location.Column + "]";
}
}
}
| 21.318182 | 75 | 0.54371 | [
"MIT"
] | abhishekmishra/e2c | S2CServer/S2CCore/CleanCommand.cs | 471 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using RulesMSBuild.Tools.Bazel;
namespace build_test
{
class Program
{
static int Main(string[] args)
{
var runfiles = Runfiles.Create();
var path = args[0];
string dacpac;
if (!Path.IsPathRooted(path))
{
dacpac = runfiles.Rlocation("rules_tsql/" + path);
}
else
{
dacpac = path;
}
// Console.WriteLine(dacpac);
Console.WriteLine(string.Join(",", args));
var expectations = JObject.Parse(File.ReadAllText(runfiles.Rlocation("rules_tsql/" + args[1])));
var zip = ZipFile.OpenRead(dacpac);
var files = new Dictionary<string, ZipArchiveEntry>();
foreach (var entry in zip.Entries)
{
files[entry.FullName] = entry;
}
try
{
Assert(files, expectations);
return 0;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return 1;
}
}
private static void Assert(Dictionary<string, ZipArchiveEntry> files, JObject expectations)
{
foreach (var file in new[] {"model.xml", "DacMetadata.xml", "Origin.xml", "[Content_Types].xml"})
{
files.Should().ContainKey(file);
}
var modelEntry = files["model.xml"];
XDocument doc;
using (var reader = new XmlTextReader(modelEntry.Open()))
{
reader.Namespaces = false;
doc = XDocument.Load(reader);
}
var root = doc.Root;
root.Should().NotBeNull("Missing root document element");
var tester = new Tester(root, expectations);
tester.Assert();
}
}
public class Tester
{
private readonly XElement _model;
private readonly JObject _expectations;
private readonly Stack<string> _path;
public Tester(XElement model, JObject expectations)
{
_model = model;
_expectations = expectations;
_path = new Stack<string>();
}
public void Assert()
{
AssertImpl(_model, _expectations);
}
private void AssertImpl(XElement element, JToken token)
{
switch (token.Type)
{
case JTokenType.Object:
var obj = (JObject) token;
foreach (var prop in obj.Properties())
{
_path.Push(prop.Name);
if (prop.Value.Type == JTokenType.String)
{
AssertXpath(element, prop.Name, prop.Value.Value<string>());
}
else
{
var next = element.XPathSelectElements(prop.Name).ToList();
next.Count().Should().Be(1,
$"Expected exactly one result for xpath: {prop.Name} at {GetPath()}");
AssertImpl(next[0], prop.Value);
}
_path.Pop();
}
break;
default:
throw new NotImplementedException(token.Type.ToString());
}
}
private string GetPath()
{
return string.Join('/', _path.Reverse());
}
private void AssertXpath(XElement element, string xpath, string expectedValue)
{
var value = element.XPathEvaluate(xpath);
switch (value)
{
case IEnumerable en:
var values = en.Cast<XObject>().ToList();
values.Count.Should().Be(1, $"Expected only one result for relpath: {xpath} fullpath: {GetPath()}");
var found = values.Single();
switch (found)
{
case XAttribute att:
att.Value.Should().Be(expectedValue, $"relpath: {xpath}; fullpath: {GetPath()}");
break;
default:
throw new NotImplementedException(found.ToString());
break;
}
break;
default:
throw new NotImplementedException(value.ToString());
break;
}
}
}
} | 31.0875 | 120 | 0.470848 | [
"Apache-2.0"
] | samhowes/rules_tsql | tests/tools/build_test/Program.cs | 4,976 | C# |
using UnityEngine;
using GOAP_S.Blackboard;
using UnityEditor;
namespace GOAP_S.UI
{
[CustomEditor(typeof(GlobalBlackboardComp_GS))]
public class GlobalBlackboardComp_GS_Editor : BlackboardComp_GS_Editor
{
public override void OnInspectorGUI()
{
//Target blackboard
Blackboard_GS target_blackboard = ((GlobalBlackboardComp_GS)target).blackboard;
//Display global blackboard
GUILayout.Label("Global Variables", UIConfig_GS.left_big_style);
DisplayBlackboardVariables(GlobalBlackboard_GS.blackboard);
}
}
}
| 28.952381 | 91 | 0.699013 | [
"MIT"
] | ferranmartinvila/Unity-GOAP_S | Unity_Project/Assets/GOAP_System/Editor/Editors/GlobalBlackboardComp_GS_Editor.cs | 610 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// 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.
// File System.Windows.LocalizabilityAttribute.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows
{
[AttributeUsage(AttributeTargets.All)]
sealed public partial class LocalizabilityAttribute : Attribute
{
#region Methods and constructors
public LocalizabilityAttribute(LocalizationCategory category)
{
}
#endregion
#region Properties and indexers
public LocalizationCategory Category
{
get
{
return default(LocalizationCategory);
}
}
public Modifiability Modifiability
{
get
{
return default(Modifiability);
}
set
{
}
}
public Readability Readability
{
get
{
return default(Readability);
}
set
{
}
}
#endregion
}
}
| 32.73494 | 463 | 0.730217 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/PresentationCore/Sources/System.Windows.LocalizabilityAttribute.cs | 2,717 | C# |
using UnityEngine;
namespace CustomSceneryRegistrar.Decorators.Type
{
class TrashBinDecorator : IDecorator
{
public void Decorate(GameObject go, CustomSceneryV1 customScenery)
{
go.AddComponent<TrashBin>();
}
}
}
| 20.230769 | 74 | 0.657795 | [
"MIT"
] | ParkitectNexus/CustomSceneryRegistrar | Decorators/Type/TrashBinDecorator.cs | 265 | C# |
using System;
namespace CodeGenerator
{
public class TranslatorEventArgs : EventArgs
{
public string Message
{
get;
set;
}
public decimal Progress
{
get;
set;
}
public TranslatorEventArgs()
{
}
public TranslatorEventArgs(string message)
{
this.Message = message;
}
public TranslatorEventArgs(decimal progress)
{
this.Progress = progress;
}
}
}
| 11.764706 | 46 | 0.6625 | [
"MIT"
] | wmansfield/stencil.v2 | codegen/CodeGenerator/TranslatorEventArgs.cs | 400 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.