content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("FlopcSDK")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FlopcSDK")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("e27ec9ce-6363-4c1c-b156-7101b3834964")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.088235 | 103 | 0.733634 | [
"MIT"
] | lionelberton/FlopCSharp | src/FlopcSDK/Properties/AssemblyInfo.cs | 1,348 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Desafio.CaiqueNeves.Entidade
{
public class Produto
{
public string Nome { get; set; }
public int Preco { get; set; }
}
}
| 17.375 | 40 | 0.683453 | [
"MIT"
] | caiqueves/Praticando-Console_Application | Desafio.CaiqueNeves/Modelos/Produto.cs | 280 | C# |
// Copyright 2016 MaterialUI for Unity http://materialunity.com
// Please see license file for terms and conditions of use, and more information.
using UnityEngine;
using System;
using System.Collections.Generic;
#if UNITY_5_2
using LitJson;
#endif
namespace MaterialUI
{
public class VectorImageParserIonicons : VectorImageFontParser
{
protected override string GetIconFontUrl()
{
return "https://github.com/driftyco/ionicons/blob/master/fonts/ionicons.ttf?raw=true";
}
protected override string GetIconFontLicenseUrl()
{
return "https://github.com/driftyco/ionicons/blob/master/LICENSE?raw=true";
}
protected override string GetIconFontDataUrl()
{
return "https://raw.githubusercontent.com/driftyco/ionicons/master/builder/manifest.json?raw=true";
}
public override string GetWebsite()
{
return "http://ionicons.com/";
}
public override string GetFontName()
{
return "Ionicons";
}
protected override VectorImageSet GenerateIconSet(string fontDataContent)
{
VectorImageSet vectorImageSet = new VectorImageSet();
#if UNITY_5_2
JsonData jsonData = JsonMapper.ToObject(fontDataContent);
JsonData iconArray = jsonData["icons"];
for (int i = 0; i < iconArray.Count; i++)
{
JsonData iconData = iconArray[i];
string name = iconData["name"].ToString();
string unicode = iconData["code"].ToString();
unicode = unicode.Replace("0x", string.Empty);
vectorImageSet.iconGlyphList.Add(new Glyph(name, unicode, false));
}
#else
fontDataContent = fontDataContent.Replace("name", "m_Name").Replace("code", "m_Unicode").Replace("icons", "m_IconGlyphList");
VectorImageSet ioniconsInfo = JsonUtility.FromJson<VectorImageSet>(fontDataContent);
for (int i = 0; i < ioniconsInfo.iconGlyphList.Count; i++)
{
string name = ioniconsInfo.iconGlyphList[i].name;
string unicode = ioniconsInfo.iconGlyphList[i].unicode;
unicode = unicode.Replace("0x", string.Empty);
vectorImageSet.iconGlyphList.Add(new Glyph(name, unicode, false));
}
#endif
return vectorImageSet;
}
protected override string ExtractLicense(string fontDataLicenseContent)
{
return fontDataLicenseContent;
}
}
}
| 31.901235 | 138 | 0.623452 | [
"Apache-2.0"
] | Ianmaster231/tabekana | Tabekana/Assets/MaterialUI/Editor/Tools/Vector Image Manager/Parser/Web/VectorImageParserIonicons.cs | 2,586 | C# |
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using Kudu.Client.Infrastructure;
using Kudu.SiteManagement;
using Kudu.SiteManagement.Configuration;
using Kudu.Web.Infrastructure;
using Kudu.Web.Models;
namespace Kudu.Web.Controllers
{
public class ApplicationController : Controller
{
private readonly IApplicationService _applicationService;
private readonly KuduEnvironment _environment;
private readonly IKuduConfiguration _configuration;
private readonly ICredentialProvider _credentialProvider;
public ApplicationController(IApplicationService applicationService,
ICredentialProvider credentialProvider,
KuduEnvironment environment,
IKuduConfiguration configuration)
{
_applicationService = applicationService;
_credentialProvider = credentialProvider;
_environment = environment;
_configuration = configuration;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewBag.showAdmingWarning = !_environment.IsAdmin && _environment.RunningAgainstLocalKuduService;
base.OnActionExecuting(filterContext);
}
public ViewResult Index()
{
var applications = (from name in _applicationService.GetApplications()
orderby name
select name).ToList();
return View(applications);
}
public Task<ActionResult> Details(string slug)
{
return GetApplicationView("settings", "Details", slug);
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Create(string name)
{
string slug = name.GenerateSlug();
try
{
await _applicationService.AddApplication(slug);
return RedirectToAction("Details", new { slug });
}
catch (SiteExistsException)
{
ModelState.AddModelError("Name", "Site already exists");
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
return View("Create");
}
[HttpPost]
public async Task<ActionResult> Delete(string slug)
{
if (await _applicationService.DeleteApplication(slug))
{
return RedirectToAction("Index");
}
return HttpNotFound();
}
public async Task<ActionResult> Trace(string slug)
{
IApplication application = _applicationService.GetApplication(slug);
if (application == null)
{
return HttpNotFound();
}
ICredentials credentials = _credentialProvider.GetCredentials();
var document = await application.DownloadTrace(credentials);
return View(document);
}
[HttpPost]
[ActionName("add-custom-site-binding")]
public async Task<ActionResult> AddCustomSiteBinding(string slug, string siteBinding)
{
IApplication application = _applicationService.GetApplication(slug);
if (application == null)
{
return HttpNotFound();
}
_applicationService.AddLiveSiteBinding(slug, siteBinding);
return await GetApplicationView("settings", "Details", slug);
}
[HttpPost]
[ActionName("remove-custom-site-binding")]
public async Task<ActionResult> RemoveCustomSiteBinding(string slug, string siteBinding)
{
IApplication application = _applicationService.GetApplication(slug);
if (application == null)
{
return HttpNotFound();
}
_applicationService.RemoveLiveSiteBinding(slug, siteBinding);
return await GetApplicationView("settings", "Details", slug);
}
[HttpPost]
[ActionName("add-service-site-binding")]
public async Task<ActionResult> AddServiceSiteBinding(string slug, string siteBinding)
{
IApplication application = _applicationService.GetApplication(slug);
if (application == null)
{
return HttpNotFound();
}
_applicationService.AddServiceSiteBinding(slug, siteBinding);
return await GetApplicationView("settings", "Details", slug);
}
[HttpPost]
[ActionName("remove-service-site-binding")]
public async Task<ActionResult> RemoveServiceSiteBinding(string slug, string siteBinding)
{
IApplication application = _applicationService.GetApplication(slug);
if (application == null)
{
return HttpNotFound();
}
_applicationService.RemoveServiceSiteBinding(slug, siteBinding);
return await GetApplicationView("settings", "Details", slug);
}
private async Task<ActionResult> GetApplicationView(string tab, string viewName, string slug)
{
var application = _applicationService.GetApplication(slug);
ICredentials credentials = _credentialProvider.GetCredentials();
var repositoryInfo = await application.GetRepositoryInfo(credentials);
var appViewModel = new ApplicationViewModel(application, _configuration);
appViewModel.RepositoryInfo = repositoryInfo;
ViewBag.slug = slug;
ViewBag.tab = tab;
ViewBag.appName = appViewModel.Name;
ViewBag.siteBinding = String.Empty;
ModelState.Clear();
return View(viewName, appViewModel);
}
}
} | 32.222222 | 109 | 0.597209 | [
"Apache-2.0"
] | dotJEM/kudu | Kudu.Web/Controllers/ApplicationController.cs | 6,092 | C# |
/*
* Copyright © 2010, Denys Vuika
*
* 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.Collections;
using System.ComponentModel;
using System.Globalization;
namespace System.Windows.Controls.WpfPropertyGrid
{
/// <summary>
/// Provides a wrapper around property value to be used at presentation level.
/// </summary>
public class PropertyItemValue : INotifyPropertyChanged
{
private readonly PropertyItem _property;
#region Events
/// <summary>
/// Occurs when exception is raised at Property Value.
/// <remarks>This event is reserved for future implementations.</remarks>
/// </summary>
public event EventHandler<ValueExceptionEventArgs> PropertyValueException;
/// <summary>
/// Occurs when root value is changed.
/// <remarks>This event is reserved for future implementations.</remarks>
/// </summary>
public event EventHandler RootValueChanged;
/// <summary>
/// Occurs when sub property changed.
/// </summary>
public event EventHandler SubPropertyChanged;
#endregion
/// <summary>
/// Gets the parent property.
/// </summary>
/// <value>The parent property.</value>
public PropertyItem ParentProperty
{
get { return _property; }
}
private readonly GridEntryCollection<PropertyItem> _subProperties = new GridEntryCollection<PropertyItem>();
public GridEntryCollection<PropertyItem> SubProperties
{
get { return _subProperties; }
}
private readonly bool _hasSubProperties;
/// <summary>
/// Gets a value indicating whether encapsulated value has sub-properties.
/// </summary>
/// <remarks>This property is reserved for future implementations.</remarks>
/// <value>
/// <c>true</c> if this instance has sub properties; otherwise, <c>false</c>.
/// </value>
public bool HasSubProperties
{
get { return _hasSubProperties; }
}
#region ctor
/// <summary>
/// Initializes a new instance of the <see cref="PropertyItemValue"/> class.
/// </summary>
/// <param name="property">The property.</param>
public PropertyItemValue(PropertyItem property)
{
if (property == null) throw new ArgumentNullException("property");
this._property = property;
_hasSubProperties = property.Converter.GetPropertiesSupported();
if (_hasSubProperties)
{
object value = property.GetValue();
PropertyDescriptorCollection descriptors = property.Converter.GetProperties(value);
foreach (PropertyDescriptor d in descriptors)
{
_subProperties.Add(new PropertyItem(property.Owner, value, d));
// TODO: Move to PropertyData as a public property
NotifyParentPropertyAttribute notifyParent = d.Attributes[KnownTypes.Attributes.NotifyParentPropertyAttribute] as NotifyParentPropertyAttribute;
if (notifyParent != null && notifyParent.NotifyParent)
{
d.AddValueChanged(value, NotifySubPropertyChanged);
}
}
}
this._property.PropertyChanged += new PropertyChangedEventHandler(ParentPropertyChanged);
}
#endregion
void ParentPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "PropertyValue")
NotifyRootValueChanged();
if (e.PropertyName == "IsReadOnly")
{
OnPropertyChanged("IsReadOnly");
OnPropertyChanged("IsEditable");
}
}
#region PropertyValue implementation
/// <summary>
/// Gets a value indicating whether this instance can convert from string.
/// </summary>
/// <value>
/// <c>true</c> if this instance can convert from string; otherwise, <c>false</c>.
/// </value>
public bool CanConvertFromString
{
get { return (((_property.Converter != null) && _property.Converter.CanConvertFrom(typeof(string))) && !_property.IsReadOnly); }
}
/// <summary>
/// Clears the value.
/// </summary>
public void ClearValue()
{
_property.ClearValue();
}
/// <summary>
/// Converts the string to value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>Value instance</returns>
protected object ConvertStringToValue(string value)
{
if (_property.PropertyType == typeof(string)) return value;
//if (value.Length == 0) return null;
if (string.IsNullOrEmpty(value)) return null;
if (!_property.Converter.CanConvertFrom(typeof(string)))
throw new InvalidOperationException("Value to String conversion is not supported!");
return _property.Converter.ConvertFromString(null, GetSerializationCulture(), value);
}
/// <summary>
/// Converts the value to string.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>String presentation of the value</returns>
protected string ConvertValueToString(object value)
{
string collectionValue = string.Empty;
if (value == null) return collectionValue;
collectionValue = value as String;
if (collectionValue != null) return collectionValue;
var converter = this._property.Converter;
if (converter.CanConvertTo(typeof(string)))
collectionValue = converter.ConvertToString(null, GetSerializationCulture(), value);
else
collectionValue = value.ToString();
// TODO: refer to resources or some constant
if (string.IsNullOrEmpty(collectionValue) && (value is IEnumerable))
collectionValue = "(Collection)";
return collectionValue;
}
/// <summary>
/// Gets the value.
/// </summary>
/// <returns>Property value</returns>
protected object GetValueCore()
{
return this._property.GetValue();
}
/// <summary>
/// Gets a value indicating whether encapsulated property value is collection.
/// </summary>
/// <value>
/// <c>true</c> if encapsulated property value is collection; otherwise, <c>false</c>.
/// </value>
public bool IsCollection
{
get { return _property.IsCollection; }
}
/// <summary>
/// Gets a value indicating whether encapsulated property value is default value.
/// </summary>
/// <value>
/// <c>true</c> if encapsulated property value is default value; otherwise, <c>false</c>.
/// </value>
public bool IsDefaultValue
{
get { return _property.IsDefaultValue; }
}
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="value">The value.</param>
protected void SetValueCore(object value)
{
_property.SetValue(value);
}
// TODO: DependencyProperty validation should be placed here
/// <summary>
/// Validates the value.
/// </summary>
/// <param name="valueToValidate">The value to validate.</param>
protected void ValidateValue(object valueToValidate)
{
//throw new NotImplementedException();
// Do nothing
}
private void SetValueImpl(object value)
{
//this.ValidateValue(value);
if (ParentProperty.Validate(value))
SetValueCore(value);
NotifyValueChanged();
OnRootValueChanged();
}
/// <summary>
/// Raises the <see cref="PropertyValueException"/> event.
/// </summary>
/// <param name="e">The <see cref="WpfPropertyGrid.ValueExceptionEventArgs"/> instance containing the event data.</param>
protected virtual void OnPropertyValueException(ValueExceptionEventArgs e)
{
if (e == null) throw new ArgumentNullException("e");
if (PropertyValueException != null) PropertyValueException(this, e);
}
/// <summary>
/// Gets a value indicating whether exceptions should be cought.
/// </summary>
/// <value><c>true</c> if expceptions should be cought; otherwise, <c>false</c>.</value>
protected virtual bool CatchExceptions
{
get { return (PropertyValueException != null); }
}
/// <summary>
/// Gets or sets the string representation of the value.
/// </summary>
/// <value>The string value.</value>
public string StringValue
{
get
{
string str = string.Empty;
if (CatchExceptions)
{
try
{
str = ConvertValueToString(Value);
}
catch (Exception exception)
{
OnPropertyValueException(new ValueExceptionEventArgs("Cannot convert value to string", this, ValueExceptionSource.Get, exception));
}
return str;
}
return ConvertValueToString(Value);
}
set
{
if (CatchExceptions)
{
try
{
Value = ConvertStringToValue(value);
}
catch (Exception exception)
{
OnPropertyValueException(new ValueExceptionEventArgs("Cannot create value from string", this, ValueExceptionSource.Set, exception));
}
}
else
{
Value = ConvertStringToValue(value);
}
}
}
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>The value.</value>
public object Value
{
get
{
object valueCore = null;
if (CatchExceptions)
{
try
{
valueCore = GetValueCore();
}
catch (Exception exception)
{
OnPropertyValueException(new ValueExceptionEventArgs("Value Get Failed", this, ValueExceptionSource.Get, exception));
}
return valueCore;
}
return GetValueCore();
}
set
{
if (CatchExceptions)
{
try
{
SetValueImpl(value);
}
catch (Exception exception)
{
OnPropertyValueException(new ValueExceptionEventArgs("Value Set Failed", this, ValueExceptionSource.Set, exception));
}
}
else
{
SetValueImpl(value);
}
}
}
#endregion
#region Helper properties
/// <summary>
/// Gets a value indicating whether encapsulated property value is read only.
/// </summary>
/// <value>
/// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
/// </value>
public bool IsReadOnly
{
get { return _property.IsReadOnly; }
}
/// <summary>
/// Gets a value indicating whether encapsulated property value is editable.
/// </summary>
/// <value>
/// <c>true</c> if this instance is editable; otherwise, <c>false</c>.
/// </value>
public bool IsEditable
{
get { return !_property.IsReadOnly; }
}
#endregion
/// <summary>
/// Gets the serialization culture.
/// </summary>
/// <returns>Culture to serialize value.</returns>
protected virtual CultureInfo GetSerializationCulture()
{
return ObjectServices.GetSerializationCulture(_property.PropertyType);
}
#region INotifyPropertyChanged Members
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Called when property value is changed.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Notifies the root value changed.
/// </summary>
protected virtual void NotifyRootValueChanged()
{
OnPropertyChanged("IsDefaultValue");
OnPropertyChanged("IsMixedValue");
OnPropertyChanged("IsCollection");
OnPropertyChanged("Collection");
OnPropertyChanged("HasSubProperties");
OnPropertyChanged("SubProperties");
OnPropertyChanged("Source");
OnPropertyChanged("CanConvertFromString");
NotifyValueChanged();
OnRootValueChanged();
}
private void NotifyStringValueChanged()
{
OnPropertyChanged("StringValue");
}
/// <summary>
/// Notifies the sub property changed.
/// </summary>
protected void NotifySubPropertyChanged(object sender, EventArgs args)
{
NotifyValueChanged();
OnSubPropertyChanged();
}
private void NotifyValueChanged()
{
OnPropertyChanged("Value");
NotifyStringValueChanged();
}
private void OnRootValueChanged()
{
var handler = RootValueChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
private void OnSubPropertyChanged()
{
var handler = SubPropertyChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
#endregion
}
}
| 29.588106 | 154 | 0.627633 | [
"Apache-2.0"
] | DenisVuyka/WPG | Main/WpfPropertyGrid/PropertyItemValue.cs | 13,436 | C# |
using OfficeDevPnP.PowerShell.Commands.Base;
using Microsoft.SharePoint.Client;
using System.Management.Automation;
using OfficeDevPnP.Core.Entities;
using OfficeDevPnP.PowerShell.CmdletHelpAttributes;
namespace OfficeDevPnP.PowerShell.Commands
{
[Cmdlet(VerbsCommon.New, "SPOWeb")]
[CmdletHelp("Creates a new subweb to the current web")]
[CmdletExample(Code = @"
PS:> New-SPOWeb -Title ""Project A Web"" -Url projectA -Description ""Information about Project A"" -Locale 1033 -Template ""STS#0""", Remarks = "Creates a new subweb under the current web with url projectA", SortOrder = 1)]
public class NewWeb : SPOWebCmdlet
{
[Parameter(Mandatory = true, HelpMessage="The title of the new web")]
public string Title;
[Parameter(Mandatory = true, HelpMessage="The Url of the new web")]
public string Url;
[Parameter(Mandatory = false, HelpMessage="The description of the new web")]
public string Description = string.Empty;
[Parameter(Mandatory = false)]
public int Locale = 1033;
[Parameter(Mandatory = true, HelpMessage="The site definition template to use for the new web, e.g. STS#0")]
public string Template = string.Empty;
[Parameter(Mandatory = false, HelpMessage="By default the subweb will inherit its security from its parent, specify this switch to break this inheritance")]
public SwitchParameter BreakInheritance = false;
[Parameter(Mandatory = false, HelpMessage="Specifies whether the site inherits navigation.")]
public SwitchParameter InheritNavigation = true;
protected override void ExecuteCmdlet()
{
this.SelectedWeb.CreateWeb(Title, Url, Description, Template, Locale, !BreakInheritance,InheritNavigation);
WriteVerbose(string.Format(Properties.Resources.Web0CreatedAt1, Title, Url));
}
}
}
| 44.27907 | 224 | 0.706933 | [
"Apache-2.0"
] | GeiloStylo/PnP | Solutions/PowerShell.Commands/Commands/Web/NewWeb.cs | 1,906 | C# |
#if UNITY_EDITOR
using System;
using System.IO;
using System.Collections;
using UnityEngine;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
class PreBuildManager : IPreprocessBuildWithReport
{
public int callbackOrder { get { return 0; } }
protected string streamingAssetsPath => Application.streamingAssetsPath + "/BanubaFaceAR/";
protected BNB.ResourcesJSON files;
public void OnPreprocessBuild(BuildTarget target, string path)
{
// Do the preprocessing here
}
public void OnPreprocessBuild(BuildReport report)
{
var resourceDir = Application.dataPath + "/Resources";
if (!Directory.Exists(resourceDir))
{
Directory.CreateDirectory(resourceDir);
}
files = new BNB.ResourcesJSON();
var file = resourceDir + "/BNBResourceList.json";
ProcessDirectory(streamingAssetsPath);
File.WriteAllText(file, files.SaveToString());
}
public void ProcessDirectory(string targetDirectory)
{
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
ProcessFile(fileName);
}
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
{
ProcessDirectory(subdirectory);
}
}
public void ProcessFile(string path)
{
if (Path.GetExtension(path) == ".meta")
{
return;
}
files.resources.Add(path.Substring(streamingAssetsPath.Length));
}
}
#endif | 25.875 | 95 | 0.660628 | [
"MIT"
] | Banuba/quickstart-unity | Assets/BanubaFaceAR/BaseAssets/Scripts/PreBuildManager.cs | 1,658 | C# |
using Dapper;
using Discount.Grpc.Entities;
using Microsoft.Extensions.Configuration;
using Npgsql;
using System;
using System.Threading.Tasks;
namespace Discount.Grpc.Repositories
{
public class DiscountRepository:IDiscountRepository
{
private readonly IConfiguration _configuration;
public DiscountRepository(IConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public async Task<Coupon> GetDiscount(string productName)
{
using var connection = new NpgsqlConnection
(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var coupon = await connection.QueryFirstOrDefaultAsync<Coupon>
("SELECT * FROM Coupon WHERE ProductName = @ProductName", new { ProductName = productName });
if (coupon == null)
return new Coupon
{ ProductName = "No Discount", Amount = 0, Description = "No Discount Desc" };
return coupon;
}
public async Task<bool> CreateDiscount(Coupon coupon)
{
using var connection = new NpgsqlConnection
(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var affected =
await connection.ExecuteAsync
("INSERT INTO Coupon (ProductName, Description, Amount) VALUES (@ProductName, @Description, @Amount)",
new { ProductName = coupon.ProductName, Description = coupon.Description, Amount = coupon.Amount });
if (affected == 0)
return false;
return true;
}
public async Task<bool> UpdateDiscount(Coupon coupon)
{
using var connection = new NpgsqlConnection(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var affected = await connection.ExecuteAsync
("UPDATE Coupon SET ProductName=@ProductName, Description = @Description, Amount = @Amount WHERE Id = @Id",
new { ProductName = coupon.ProductName, Description = coupon.Description, Amount = coupon.Amount, Id = coupon.Id });
if (affected == 0)
return false;
return true;
}
public async Task<bool> DeleteDiscount(string productName)
{
using var connection = new NpgsqlConnection(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var affected = await connection.ExecuteAsync("DELETE FROM Coupon WHERE ProductName = @ProductName",
new { ProductName = productName });
if (affected == 0)
return false;
return true;
}
}
}
| 32.632911 | 138 | 0.683088 | [
"MIT"
] | simhamp/AspnetMicroservices | src/Services/Discount/Discount.Grpc/Repositories/DiscountRepository.cs | 2,580 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过下列属性集
// 控制。更改这些属性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("TVMS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("anaki")]
[assembly: AssemblyProduct("TVMS")]
[assembly: AssemblyCopyright("版权所有 (C) anaki 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 属性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("30db76f0-12e2-4659-ad84-b7158f06dfd5")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.941176 | 57 | 0.692744 | [
"MIT"
] | liyuan-rey/TVMS | code/Properties/AssemblyInfo.cs | 1,166 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace IncrementalBackup {
public class Data {
public string Path { get; set; }
public string Hash { get; set; }
public DateTime LastModified { get; set; }
}
}
| 22 | 50 | 0.651515 | [
"MIT"
] | ModerRAS/IncrementalBackup | Model.cs | 266 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rifle : Pistol
{
public float delay;
public float delayTimer;
bool fired;
public override void Update()
{
base.Update();
if (fired && Time.time >= delay + delayTimer)
{
GameObject b = Instantiate(Projectile, BSpawn.transform.position, transform.rotation);
Destroy(b, 2f);
shot.Play();
fired = false;
}
}
public override void Fire()
{
if (Time.time >= firetimer + firedelay)
{
firetimer = Time.time;
shot.Play();
Bullet bullet = Projectile.GetComponent<Bullet>();
bullet.Damage = gunDamage;
fired = true;
delayTimer = Time.time;
GameObject a = Instantiate(Projectile, BSpawn.transform.position, transform.rotation);
Destroy(a, 2f);
}
}
}
| 23.707317 | 98 | 0.559671 | [
"MIT"
] | AGGP-NHTI/Abeille | Assets/Scripts/Rifle.cs | 974 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MBODM.FtpGuest.WebApp
{
[Authorize]
[BasicAuthFilter]
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new HomeViewModel());
}
}
}
| 18 | 45 | 0.636111 | [
"MIT"
] | MBODM/FtpGuest | FtpGuest/WebApp/Controllers/HomeController.cs | 362 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Cmdlets
{
using static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Extensions;
/// <summary>Gets information about a configuration of server.</summary>
/// <remarks>
/// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}"
/// </remarks>
[global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzPostgreSqlFlexibleServerConfiguration_Get")]
[global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IConfigurationAutoGenerated))]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Description(@"Gets information about a configuration of server.")]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Generated]
public partial class GetAzPostgreSqlFlexibleServerConfiguration_Get : global::System.Management.Automation.PSCmdlet,
Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener
{
/// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary>
private string __correlationId = System.Guid.NewGuid().ToString();
/// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary>
private global::System.Management.Automation.InvocationInfo __invocationInfo;
/// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary>
private string __processRecordId;
/// <summary>
/// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation.
/// </summary>
private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource();
/// <summary>Wait for .NET debugger to attach</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter Break { get; set; }
/// <summary>The reference to the client API class.</summary>
public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.PostgreSql Client => Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Module.Instance.ClientAPI;
/// <summary>
/// The credentials, account, tenant, and subscription used for communication with Azure
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")]
[global::System.Management.Automation.ValidateNotNull]
[global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Azure)]
public global::System.Management.Automation.PSObject DefaultProfile { get; set; }
/// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; }
/// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; }
/// <summary>Accessor for our copy of the InvocationInfo.</summary>
public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } }
/// <summary>
/// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called.
/// </summary>
global::System.Action Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel;
/// <summary><see cref="IEventListener" /> cancellation token.</summary>
global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener.Token => _cancellationTokenSource.Token;
/// <summary>Backing field for <see cref="Name" /> property.</summary>
private string _name;
/// <summary>The name of the server configuration.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the server configuration.")]
[Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The name of the server configuration.",
SerializedName = @"configurationName",
PossibleTypes = new [] { typeof(string) })]
[global::System.Management.Automation.Alias("ConfigurationName")]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Path)]
public string Name { get => this._name; set => this._name = value; }
/// <summary>
/// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.HttpPipeline" /> that the remote call will use.
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.HttpPipeline Pipeline { get; set; }
/// <summary>The URI for the proxy server to use</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)]
public global::System.Uri Proxy { get; set; }
/// <summary>Credentials for a proxy server to use for the remote call</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)]
public global::System.Management.Automation.PSCredential ProxyCredential { get; set; }
/// <summary>Use the default credentials for the proxy</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; }
/// <summary>Backing field for <see cref="ResourceGroupName" /> property.</summary>
private string _resourceGroupName;
/// <summary>The name of the resource group. The name is case insensitive.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")]
[Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The name of the resource group. The name is case insensitive.",
SerializedName = @"resourceGroupName",
PossibleTypes = new [] { typeof(string) })]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Path)]
public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; }
/// <summary>Backing field for <see cref="ServerName" /> property.</summary>
private string _serverName;
/// <summary>The name of the server.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the server.")]
[Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The name of the server.",
SerializedName = @"serverName",
PossibleTypes = new [] { typeof(string) })]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Path)]
public string ServerName { get => this._serverName; set => this._serverName = value; }
/// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary>
private string[] _subscriptionId;
/// <summary>The ID of the target subscription.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")]
[Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The ID of the target subscription.",
SerializedName = @"subscriptionId",
PossibleTypes = new [] { typeof(string) })]
[Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.DefaultInfo(
Name = @"",
Description =@"",
Script = @"(Get-AzContext).Subscription.Id")]
[global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Path)]
public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; }
/// <summary>
/// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what
/// happens on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should
/// return immediately (set to true to skip further processing )</param>
partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens
/// on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IConfigurationAutoGenerated"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return
/// immediately (set to true to skip further processing )</param>
partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IConfigurationAutoGenerated> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet)
/// </summary>
protected override void BeginProcessing()
{
Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials);
if (Break)
{
Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.AttachDebugger.Break();
}
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Performs clean-up after the command execution</summary>
protected override void EndProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>
/// Intializes a new instance of the <see cref="GetAzPostgreSqlFlexibleServerConfiguration_Get" /> cmdlet class.
/// </summary>
public GetAzPostgreSqlFlexibleServerConfiguration_Get()
{
}
/// <summary>Handles/Dispatches events during the call to the REST service.</summary>
/// <param name="id">The message id</param>
/// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param>
/// <param name="messageData">Detailed message data for the message event.</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed.
/// </returns>
async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.EventData> messageData)
{
using( NoSynchronizationContext )
{
if (token.IsCancellationRequested)
{
return ;
}
switch ( id )
{
case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Verbose:
{
WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Warning:
{
WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Information:
{
var data = messageData();
WriteInformation(data, new[] { data.Message });
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Debug:
{
WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Error:
{
WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) );
return ;
}
}
await Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null );
if (token.IsCancellationRequested)
{
return ;
}
WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}");
}
}
/// <summary>Performs execution of the command.</summary>
protected override void ProcessRecord()
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
__processRecordId = System.Guid.NewGuid().ToString();
try
{
// work
using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token) )
{
asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token);
}
}
catch (global::System.AggregateException aggregateException)
{
// unroll the inner exceptions to get the root cause
foreach( var innerException in aggregateException.Flatten().InnerExceptions )
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
}
catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null)
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
finally
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletProcessRecordEnd).Wait();
}
}
/// <summary>Performs execution of the command, working asynchronously if required.</summary>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
protected async global::System.Threading.Tasks.Task ProcessRecordAsync()
{
using( NoSynchronizationContext )
{
await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
Pipeline = Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName);
if (null != HttpPipelinePrepend)
{
Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend);
}
if (null != HttpPipelineAppend)
{
Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend);
}
// get the client instance
try
{
foreach( var SubscriptionId in this.SubscriptionId )
{
await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await this.Client.FlexibleServerConfigurationsGet(SubscriptionId, ResourceGroupName, ServerName, Name, onOk, onDefault, this, Pipeline);
await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
}
catch (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.UndeclaredResponseException urexception)
{
WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ServerName=ServerName,Name=Name})
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action }
});
}
finally
{
await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletProcessRecordAsyncEnd);
}
}
}
/// <summary>Interrupts currently running code within the command.</summary>
protected override void StopProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Cancel();
base.StopProcessing();
}
/// <summary>
/// a delegate that is called when the remote service returns default (any response code not handled elsewhere).
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnDefault(responseMessage, response, ref _returnNow);
// if overrideOnDefault has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// Error Response : default
var code = (await response)?.Code;
var message = (await response)?.Message;
if ((null == code || null == message))
{
// Unrecognized Response. Create an error record based on what we have.
var ex = new Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError>(responseMessage, await response);
WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ServerName=ServerName, Name=Name })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action }
});
}
else
{
WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ServerName=ServerName, Name=Name })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty }
});
}
}
}
/// <summary>a delegate that is called when the remote service returns 200 (OK).</summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IConfigurationAutoGenerated"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IConfigurationAutoGenerated> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnOk(responseMessage, response, ref _returnNow);
// if overrideOnOk has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// onOk - response for 200 / application/json
// (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IConfigurationAutoGenerated
WriteObject((await response));
}
}
}
} | 73.53753 | 471 | 0.674229 | [
"MIT"
] | AzureSDKAutomation/azure-powershell | src/PostgreSql/generated/cmdlets/GetAzPostgreSqlFlexibleServerConfiguration_Get.cs | 29,959 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.Lambda.DynamoDBEvents;
using Amazon.Lambda.Serialization.Json;
using Amazon.S3;
using Amazon.S3.Model;
using TinyPng;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace CreateThumbnail
{
public class Function
{
private string _metadataKey = "x-amz-meta-user-profile-id";
private readonly string _imageType = ".jpg";
private readonly AmazonS3Client _s3Client;
private static readonly JsonSerializer _jsonSerializer = new JsonSerializer();
public Function()
{
_s3Client = new AmazonS3Client();
}
public async Task FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
{
context.Logger.Log("START");
foreach (var record in dynamoEvent.Records)
{
context.Logger.Log($"Event ID: {record.EventID}");
context.Logger.Log($"Event Name: {record.EventName}");
string streamRecordJson = SerializeObject(record.Dynamodb);
Console.WriteLine($"DynamoDB Record:");
Console.WriteLine(streamRecordJson);
if(!record.Dynamodb.NewImage.ContainsKey("image") || !record.Dynamodb.Keys.ContainsKey("id"))
{
context.Logger.Log("Missing data.");
continue;
}
string id = record.Dynamodb.Keys["id"].N;
string filePath = record.Dynamodb.NewImage["image"].S;
string fileName = Path.GetFileName(filePath);
context.Logger.Log($"Record id: {id}");
context.Logger.Log($"File name: {fileName}");
if (_imageType != Path.GetExtension(fileName).ToLower())
{
context.Logger.Log($"Not a supported image type");
continue;
}
try
{
string bucketName = Environment.GetEnvironmentVariable("BucketName");
var tinyPngKey = Environment.GetEnvironmentVariable("TinyPngKey");
using (var objectResponse = await _s3Client.GetObjectAsync(bucketName + "/original", fileName))
using (Stream responseStream = objectResponse.ResponseStream)
{
TinyPngClient tinyPngClient = new TinyPngClient(tinyPngKey);
using (var downloadResponse = await tinyPngClient.Compress(responseStream).Resize(150, 150).GetImageStreamData())
{
var putRequest = new PutObjectRequest
{
BucketName = bucketName + "/thumbnails",
Key = fileName,
InputStream = downloadResponse,
TagSet = new List<Tag>
{
new Tag
{
Key = "Thumbnail", Value = "true"
},
},
};
putRequest.Metadata.Add(_metadataKey, id);
await _s3Client.PutObjectAsync(putRequest);
}
}
}
catch (Exception ex)
{
context.Logger.Log($"Exception: {ex}");
// catch (AmazonS3Exception amazonS3Exception)
// {
// if (amazonS3Exception.ErrorCode != null &&
// (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
// ||
// amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
// {
// Console.WriteLine("Check the provided AWS Credentials.");
// Console.WriteLine(
// "For service sign up go to http://aws.amazon.com/s3");
// }
// else
// {
// Console.WriteLine(
// "Error occurred. Message:'{0}' when writing an object"
// , amazonS3Exception.Message);
// }
// }
}
}
context.Logger.Log("END");
}
private string SerializeObject(object streamRecord)
{
using (var ms = new MemoryStream())
{
_jsonSerializer.Serialize(streamRecord, ms);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
}
| 36.561151 | 137 | 0.493113 | [
"MIT"
] | sakowiczm/aws-profile-image | CreateThumbnail/Function.cs | 5,082 | C# |
using System;
using System.Collections.Generic;
using LINQPad.Extensibility.DataContext;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Sitecore.Linqpad.Controllers;
using Sitecore.Linqpad.Dialogs;
using Sitecore.Linqpad.Models;
using System.Xml.Linq;
namespace Sitecore.Linqpad.Tests
{
[TestClass]
public class ConnectionDialogTests
{
public TestContext TestContext { get; set; } //this needs to be named TestContext
[TestMethod, TestCategory("UI - connection dialog")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "Data\\DriverData.xml", "requiredSettings", DataAccessMethod.Sequential)]
public void SetCxSettingsNull()
{
var mockCxInfo = new Mock<IConnectionInfo>();
var element = XElement.Parse((string)this.TestContext.DataRow["driverData"]);
mockCxInfo.SetupGet(cxInfo => cxInfo.DriverData).Returns(element);
var cxSettings = new SitecoreConnectionSettings();
var mapper = new DriverDataCxSettingsMapper();
mapper.Read(mockCxInfo.Object, cxSettings);
var view = new ConnectionDialog();
view.InitializeComponent();
var driverSettings = new SitecoreDriverSettings() { CxInfo = mockCxInfo.Object, CxSettings = cxSettings, SettingsMapper = new DriverDataCxSettingsMapper() };
view.Model = driverSettings;
var controller = new DriverSettingsController(view);
controller.LoadView(driverSettings);
view.SaveViewToModelCallback = controller.SaveView;
//
//basic settings
view.ClientUrl = null;
view.Username = null;
view.Password = null;
view.WebRootPath = null;
view.ContextDatabaseName = null;
//
//advanced settings
view.NamespacesToAdd = null;
view.SearchResultType = null;
view.AppConfigReaderType = null;
view.SchemaBuilderType = null;
view.DriverInitializerType = null;
}
[TestMethod, TestCategory("UI - connection dialog")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "Data\\DriverData.xml", "requiredSettings", DataAccessMethod.Sequential)]
public void SetCxSettingsWithEmptyObjectsForAdvancedSettings()
{
var mockCxInfo = new Mock<IConnectionInfo>();
var element = XElement.Parse((string)this.TestContext.DataRow["driverData"]);
mockCxInfo.SetupGet(cxInfo => cxInfo.DriverData).Returns(element);
var cxSettings = new SitecoreConnectionSettings();
var mapper = new DriverDataCxSettingsMapper();
mapper.Read(mockCxInfo.Object, cxSettings);
var view = new ConnectionDialog();
view.InitializeComponent();
var driverSettings = new SitecoreDriverSettings() { CxInfo = mockCxInfo.Object, CxSettings = cxSettings, SettingsMapper = new DriverDataCxSettingsMapper() };
view.Model = driverSettings;
var controller = new DriverSettingsController(view);
controller.LoadView(driverSettings);
view.SaveViewToModelCallback = controller.SaveView;
//
//basic settings
view.ClientUrl = "http://localhost";
view.Username = "username";
view.Password = "password";
view.WebRootPath = @"C:\Windows\Temp";
view.ContextDatabaseName = "master";
//
//advanced settings
view.NamespacesToAdd = new HashSet<string>();
view.SearchResultType = new SelectedType();
view.AppConfigReaderType = new SelectedType();
view.SchemaBuilderType = new SelectedType();
view.DriverInitializerType = new SelectedType();
}
}
}
| 44.375 | 169 | 0.643534 | [
"MIT"
] | adamconn/sitecore-linqpad | Sitecore.Linqpad.Tests/ConnectionDialogTests.cs | 3,907 | C# |
// Copyright (c) 2019, WebsitePanel-Support.net.
// Distributed by websitepanel-support.net
// Build and fixed by Key4ce - IT Professionals
// https://www.key4ce.com
//
// Original source:
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal {
public partial class ServersEditWindowsServices {
/// <summary>
/// ServerHeaderControl1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ServerHeaderControl ServerHeaderControl1;
/// <summary>
/// btnCancel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancel;
/// <summary>
/// updatePanelProgress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdateProgress updatePanelProgress;
/// <summary>
/// ItemsUpdatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel ItemsUpdatePanel;
/// <summary>
/// itemsTimer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.Timer itemsTimer;
/// <summary>
/// gvServices control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gvServices;
}
}
| 41.923077 | 88 | 0.609174 | [
"BSD-3-Clause"
] | Key4ce/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/ServersEditWindowsServices.ascx.designer.cs | 4,360 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimaObjetos : MonoBehaviour
{
private IEnumerator coroutine;
private Animator animator;
public bool semClick;
public bool escrever;
// Start is called before the first frame update
void Start()
{
Debug.Log("Inicio "+ BancoPlayerprefs.instance.LerInformacoesInt(BancoPlayerprefs.CONST_TUTORIAL));
if (BancoPlayerprefs.instance.LerInformacoesInt(BancoPlayerprefs.CONST_TUTORIAL) == 1)
{
Debug.Log("IF DENTRO");
this.gameObject.SetActive(false);
Debug.Log("FIM IF");
}
animator = GetComponent<Animator>();
if (escrever)
{
//coroutine = waithMoveEnum();
//StartCoroutine("waithMoveEnum");
animator.SetBool("cimaBaxo", true);
Debug.Log("FIM START");
} else if(semClick)
{
animator.SetBool("arrasta", true);
}
}
// Update is called once per frame
void Update()
{
touchPlay();
}
private void touchPlay()
{
//Touch touch = Input.GetTouch(0);//simulatess();//Input.GetTouch(0); SEM SIMULADOR
Touch touch = simulatess();//Input.GetTouch(0); SEM SIMULADOR
Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
switch (touch.phase)
{
case TouchPhase.Began:
if (GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos))
{
Debug.Log("TOCO NO PORCO");
this.gameObject.SetActive(false);
}
break;
case TouchPhase.Ended:
if (GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos))
{
desativar();
}
break;
}
}
private Touch simulatess()
{
Touch touch = new Touch();
if (Input.GetMouseButtonDown(0))
{
touch = new Touch();
touch.phase = TouchPhase.Began;
touch.position = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
touch = new Touch();
touch.phase = TouchPhase.Moved;
touch.position = Input.mousePosition;
}
if (Input.GetMouseButtonUp(0))
{
touch = new Touch();
touch.phase = TouchPhase.Ended;
touch.position = Input.mousePosition;
}
return touch;
}
IEnumerator waithMoveEnum()
{
Debug.Log("Setando mão False");
this.gameObject.SetActive(false);
yield return new WaitForSecondsRealtime(3f);
Debug.Log("Setando mão TRUE");
this.gameObject.SetActive(true);
yield return new WaitForSecondsRealtime(0.5f);
}
public void desativar()
{
if (escrever)
{
BancoPlayerprefs.instance.GravarInformacoesInt(BancoPlayerprefs.CONST_TUTORIAL, 1);
this.gameObject.SetActive(false);
} else
{
if (animator.GetBool("arrasta"))
{
BancoPlayerprefs.instance.GravarInformacoesInt(BancoPlayerprefs.CONST_TUTORIAL, 1);
this.gameObject.SetActive(false);
}
animator.SetBool("arrasta", true);
}
}
}
| 29.73913 | 107 | 0.554094 | [
"Apache-2.0"
] | RamonNP/AprendendoBrincando | Assets/Script/Tutorial/AnimaObjetos.cs | 3,424 | C# |
using System;
using Examples;
namespace Examples {
public class Object1 {}
}
public class Example {
public static void Main() {
object obj1 = new Object1();
func(obj1);
}
public static void func(string s) {
/* inserted */
int _23 = 22;
}
}
| 16.6875 | 37 | 0.629213 | [
"Apache-2.0"
] | thufv/DeepFix-C- | data/Mutation/CS1503_5_mutation_02/[E]CS1503.cs | 269 | C# |
using Avalonia.Markup.Xaml;
using Avalonia.ReactiveUI;
using SextantSample.ViewModels;
namespace SextantSample.Avalonia.Views
{
public class RedView : ReactiveUserControl<RedViewModel>
{
public RedView() => AvaloniaXamlLoader.Load(this);
}
} | 23.909091 | 60 | 0.749049 | [
"MIT"
] | Gitii/Sextant | Sample/SextantSample.Avalonia/Views/RedView.xaml.cs | 265 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace ReactNative.Bridge
{
public static class DispatcherHelpers
{
private static Dispatcher _dispatcher;
internal static Dispatcher CurrentDispatcher
{
get
{
AssertDispatcherSet();
return _dispatcher;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Thread.GetApartmentState() != ApartmentState.STA)
{
throw new ArgumentException("Dispatcher must be an STA thread");
}
_dispatcher = value;
}
}
public static bool IsDispatcherSet()
{
return _dispatcher != null;
}
public static void AssertOnDispatcher()
{
if (!IsOnDispatcher())
{
throw new InvalidOperationException("Thread does not have dispatcher access.");
}
}
public static bool IsOnDispatcher()
{
AssertDispatcherSet();
return CurrentDispatcher.CheckAccess();
}
public static async void RunOnDispatcher(Action action)
{
AssertDispatcherSet();
await CurrentDispatcher.InvokeAsync(action).Task.ConfigureAwait(false);
}
public static Task<T> CallOnDispatcher<T>(Func<T> func)
{
var taskCompletionSource = new TaskCompletionSource<T>();
RunOnDispatcher(() =>
{
var result = func();
// TaskCompletionSource<T>.SetResult can call continuations
// on the awaiter of the task completion source.
Task.Run(() => taskCompletionSource.SetResult(result));
});
return taskCompletionSource.Task;
}
private static void AssertDispatcherSet()
{
if (_dispatcher == null)
{
throw new InvalidOperationException("Dispatcher has not been set");
}
}
}
}
| 25.617978 | 95 | 0.522807 | [
"MIT"
] | harunpehlivan/react-native-windows | ReactWindows/ReactNative.Net46/Bridge/DispatcherHelpers.cs | 2,282 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace barbershop.API
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 24.25 | 99 | 0.587629 | [
"Apache-2.0"
] | jodaga1992/Barbershop | barbershop.API/App_Start/RouteConfig.cs | 584 | C# |
// File generated from our OpenAPI spec
namespace Stripe
{
using Newtonsoft.Json;
public class PaymentMethodIdeal : StripeEntity<PaymentMethodIdeal>
{
/// <summary>
/// The customer's bank, if provided. Can be one of <c>abn_amro</c>, <c>asn_bank</c>,
/// <c>bunq</c>, <c>handelsbanken</c>, <c>ing</c>, <c>knab</c>, <c>moneyou</c>,
/// <c>rabobank</c>, <c>regiobank</c>, <c>sns_bank</c>, <c>triodos_bank</c>, or
/// <c>van_lanschot</c>.
/// One of: <c>abn_amro</c>, <c>asn_bank</c>, <c>bunq</c>, <c>handelsbanken</c>, <c>ing</c>,
/// <c>knab</c>, <c>moneyou</c>, <c>rabobank</c>, <c>regiobank</c>, <c>sns_bank</c>,
/// <c>triodos_bank</c>, or <c>van_lanschot</c>.
/// </summary>
[JsonProperty("bank")]
public string Bank { get; set; }
/// <summary>
/// The Bank Identifier Code of the customer's bank, if the bank was provided.
/// One of: <c>ABNANL2A</c>, <c>ASNBNL21</c>, <c>BUNQNL2A</c>, <c>FVLBNL22</c>,
/// <c>HANDNL2A</c>, <c>INGBNL2A</c>, <c>KNABNL2H</c>, <c>MOYONL21</c>, <c>RABONL2U</c>,
/// <c>RBRBNL21</c>, <c>SNSBNL2A</c>, or <c>TRIONL2U</c>.
/// </summary>
[JsonProperty("bic")]
public string Bic { get; set; }
}
}
| 43.233333 | 100 | 0.537394 | [
"Apache-2.0"
] | akaramyshev/stripe-dotnet | src/Stripe.net/Entities/PaymentMethods/PaymentMethodIdeal.cs | 1,297 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace FootballApp.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| 34.4375 | 98 | 0.677858 | [
"MIT"
] | JPiantini98/API-Football | FootballApp/FootballApp/FootballApp.iOS/AppDelegate.cs | 1,104 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MCForge
{
public class OnServerLogEvent
{
internal static List<OnServerLogEvent> events = new List<OnServerLogEvent>();
Plugin plugin;
Server.OnServerLog method;
Priority priority;
internal OnServerLogEvent(Server.OnServerLog method, Priority priority, Plugin plugin) { this.plugin = plugin; this.priority = priority; this.method = method; }
public static void Call(string message)
{
events.ForEach(delegate(OnServerLogEvent p1)
{
try
{
p1.method(message);
}
catch (Exception e) { Server.s.Log("The plugin " + p1.plugin.name + " errored when calling the Server Log Event!"); Server.ErrorLog(e); }
});
}
static void Organize()
{
List<OnServerLogEvent> temp = new List<OnServerLogEvent>();
List<OnServerLogEvent> temp2 = events;
OnServerLogEvent temp3 = null;
int i = 0;
int ii = temp2.Count;
while (i < ii)
{
foreach (OnServerLogEvent p in temp2)
{
if (temp3 == null)
temp3 = p;
else if (temp3.priority < p.priority)
temp3 = p;
}
temp.Add(temp3);
temp2.Remove(temp3);
temp3 = null;
i++;
}
events = temp;
}
/// <summary>
/// Find a event
/// </summary>
/// <param name="plugin">The plugin that registered this event</param>
/// <returns>The event</returns>
public static OnServerLogEvent Find(Plugin plugin)
{
return events.ToArray().FirstOrDefault(p => p.plugin == plugin);
}
/// <summary>
/// Register this event
/// </summary>
/// <param name="method">This is the delegate that will get called when this event occurs</param>
/// <param name="priority">The priority (imporantce) of this call</param>
/// <param name="plugin">The plugin object that is registering the event</param>
/// <param name="bypass">Register more than one of the same event</param>
public static void Register(Server.OnServerLog method, Priority priority, Plugin plugin, bool bypass = false)
{
if (Find(plugin) != null)
if (!bypass)
throw new Exception("The user tried to register 2 of the same event!");
events.Add(new OnServerLogEvent(method, priority, plugin));
Organize();
}
/// <summary>
/// UnRegister this event
/// </summary>
/// <param name="plugin">The plugin object that has this event registered</param>
public static void UnRegister(Plugin plugin)
{
if (Find(plugin) == null)
throw new Exception("This plugin doesnt have this event registered!");
events.Remove(Find(plugin));
}
}
}
| 37.383721 | 168 | 0.537481 | [
"Apache-2.0"
] | Sinjai/MCForge | Plugins/ServerEvents/OnServerLogEvent.cs | 3,217 | C# |
using System;
using System.Threading.Tasks;
using Cynosura.Core.Services.Models;
using Cynosura.Studio.Core.Infrastructure;
using Cynosura.Studio.Core.Requests.Enums;
using Cynosura.Studio.Core.Requests.Enums.Models;
using Cynosura.Studio.Web.Models;
using Cynosura.Web.Infrastructure;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Cynosura.Studio.Web.Controllers
{
[ServiceFilter(typeof(ApiExceptionFilterAttribute))]
[ValidateModel]
[Route("api")]
public class EnumController : Controller
{
private readonly IMediator _mediator;
public EnumController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost("GetEnums")]
public async Task<PageModel<EnumModel>> GetEnumsAsync([FromBody] GetEnums getEnums)
{
return await _mediator.Send(getEnums);
}
[HttpPost("GetEnum")]
public async Task<EnumModel> GetEnumAsync([FromBody] GetEnum getEnum)
{
return await _mediator.Send(getEnum);
}
[HttpPost("UpdateEnum")]
public async Task<Unit> UpdateEnumAsync([FromBody] UpdateEnum updateEnum)
{
return await _mediator.Send(updateEnum);
}
[HttpPost("CreateEnum")]
public async Task<CreatedEntity<Guid>> CreateEnumAsync([FromBody] CreateEnum createEnum)
{
return await _mediator.Send(createEnum);
}
[HttpPost("DeleteEnum")]
public async Task<Unit> DeleteEnumAsync([FromBody] DeleteEnum deleteEnum)
{
return await _mediator.Send(deleteEnum);
}
[HttpPost("GenerateEnum")]
public async Task<Unit> GenerateEnumAsync([FromBody] GenerateEnum generateEnum)
{
return await _mediator.Send(generateEnum);
}
}
}
| 29.40625 | 96 | 0.660468 | [
"MIT"
] | FroHenK/Cynosura.Studio | Cynosura.Studio.Web/Controllers/EnumController.cs | 1,884 | C# |
using Culqi.Entities;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace Culqi.Exceptions
{
public class CulqiException : Exception
{
public CulqiException()
{
}
public CulqiException(string message)
: base(message)
{
}
public CulqiException(string message, Exception err)
: base(message, err)
{
}
public CulqiException(HttpStatusCode httpStatusCode, CulqiError CulqiError, string message)
: base(message)
{
this.HttpStatusCode = httpStatusCode;
this.CulqiError = CulqiError;
}
public HttpStatusCode HttpStatusCode { get; set; }
public CulqiError CulqiError { get; set; }
public CulqiResponse CulqiResponse { get; set; }
}
}
| 22.282051 | 99 | 0.605293 | [
"MIT"
] | wilsonvargas/culqi-net | src/Culqi.net/Exceptions/CulqiException.cs | 871 | C# |
using Microsoft.SqlServer.Server;
using System;
using System.Data.SqlTypes;
using System.Globalization;
namespace MySQLCLRFunctions
{
public static class Adaptors
{
// Converts a hex string to a VARBINARY string, I think.
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, IsPrecise = true)]
public static string VarBin2Hex(SqlBytes InputAsHex)
{
if (InputAsHex == null) return null;
return BitConverter.ToString(InputAsHex.Buffer);
}
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, IsPrecise = true)]
public static DateTime? ADDateTimeString2DateTime(string InputAsStringDateTime)
{
if (InputAsStringDateTime == null) return null;
if (string.IsNullOrWhiteSpace(InputAsStringDateTime)) return null;
// 20021111182004.0Z
// 20021031003422
try
{
return DateTime.ParseExact(InputAsStringDateTime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
}
catch (FormatException)
{
return null;
}
}
private static string[][] formats = new string[][]
{
new string [] {"yyyyMMddHHmmssfffffff", "21" }
, new string [] { "yyyyMMddHHmmssfff", "17" }
, new string [] {"yyyyMMddHHmmss", "14" }
, new string [] {"yyyyMMdd", "8" }
, new string [] { "yyMMdd", "6" }
, new string [] { "MMddyyyy", "8" }
, new string [] { "MMddyy", "6" }
, new string [] {"MM/dd/yy", "8" }
, new string [] {"MM/dd/yyyy", "10" }
, new string [] {"ddd dd MMM yyyy h:mm tt zzz", "0" }
, new string [] {"MMddyyyyHHmmss", "14" }
, new string [] {"dd/MM/yyyy HH:mm:ss.ffffff", "0"}
, new string [] {"d", "0" }
};
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, IsPrecise = true)]
public static DateTime? ToDate(string InputAsStringDateTime)
{
if (InputAsStringDateTime == null) return null;
if (string.IsNullOrWhiteSpace(InputAsStringDateTime)) return null;
// 20021111182004.0Z
// 20021031003422
foreach (string[] _format in formats)
{
try
{
if (_format[1] == "0")
return DateTime.ParseExact(InputAsStringDateTime, _format[0], CultureInfo.InvariantCulture);
else
{
return DateTime.ParseExact(InputAsStringDateTime, _format[0], CultureInfo.InvariantCulture);
}
}
catch (FormatException)
{
}
}
return null;
}
}
}
| 35.686747 | 116 | 0.524983 | [
"MIT"
] | jeffshumphreys/MySQLCLRFunctions | Adaptors.cs | 2,964 | C# |
/*******************************************************************************
* Copyright (c) 2013 IBM Corporation.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Steve Pitschke - initial API and implementation
*******************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.NetworkInformation;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.ChannelElements;
using DotNetOpenAuth.OAuth.Messages;
using OSLC4Net.Client.Exceptions;
namespace OSLC4Net.Client.Oslc.Jazz
{
public class JazzOAuthClient : OslcClient
{
/// <summary>
/// Initialize an OAuthClient with the required OAuth URLs
/// </summary>
/// <param name="requestTokenURL"></param>
/// <param name="authorizationTokenURL"></param>
/// <param name="accessTokenURL"></param>
/// <param name="consumerKey"></param>
/// <param name="consumerSecret"></param>\
/// <param name="authUrl"></param>
public JazzOAuthClient(string requestTokenURL,
string authorizationTokenURL,
string accessTokenURL,
string consumerKey,
string consumerSecret,
string user,
string passwd,
string authUrl) :
base(null, OAuthHandler(requestTokenURL, authorizationTokenURL, accessTokenURL, consumerKey, consumerSecret,
user, passwd, authUrl))
{
}
/// <summary>
/// Initialize an OAuthClient with the required OAuth URLs
/// </summary>
/// <param name="requestTokenURL"></param>
/// <param name="authorizationTokenURL"></param>
/// <param name="accessTokenURL"></param>
/// <param name="consumerKey"></param>
/// <param name="consumerSecret"></param>
/// <param name="oauthRealmName"></param>
/// <param name="authUrl"></param>
public JazzOAuthClient(string requestTokenURL,
string authorizationTokenURL,
string accessTokenURL,
string consumerKey,
string consumerSecret,
string oauthRealmName,
string user,
string passwd,
string authUrl) :
base(null, OAuthHandler(requestTokenURL, authorizationTokenURL, accessTokenURL, consumerKey, consumerSecret,
user, passwd, authUrl))
{
}
private class TokenManager : IConsumerTokenManager
{
public TokenManager(string consumerKey, string consumerSecret)
{
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
}
public string ConsumerKey
{
get { return consumerKey; }
}
public string ConsumerSecret
{
get { return consumerSecret; }
}
public string GetTokenSecret(string token)
{
return tokensAndSecrets[token];
}
public void StoreNewRequestToken(UnauthorizedTokenRequest request,
ITokenSecretContainingMessage response)
{
tokensAndSecrets[response.Token] = response.TokenSecret;
}
public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey,
string requestToken,
string accessToken,
string accessTokenSecret)
{
tokensAndSecrets.Remove(requestToken);
tokensAndSecrets[accessToken] = accessTokenSecret;
}
public TokenType GetTokenType(string token)
{
throw new NotImplementedException();
}
public string GetRequestToken()
{
return tokensAndSecrets.First().Key;
}
private readonly IDictionary<string, string> tokensAndSecrets =
new Dictionary<string, string>();
private readonly string consumerKey;
private readonly string consumerSecret;
}
private static HttpMessageHandler OAuthHandler(string requestTokenURL,
string authorizationTokenURL,
string accessTokenURL,
string consumerKey,
string consumerSecret,
string user,
string passwd,
string authUrl)
{
ServiceProviderDescription serviceDescription = new ServiceProviderDescription();
serviceDescription.AccessTokenEndpoint = new MessageReceivingEndpoint(new Uri(accessTokenURL), HttpDeliveryMethods.PostRequest);
serviceDescription.ProtocolVersion = ProtocolVersion.V10a;
serviceDescription.RequestTokenEndpoint = new MessageReceivingEndpoint(new Uri(requestTokenURL), HttpDeliveryMethods.PostRequest);
serviceDescription.TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() };
serviceDescription.UserAuthorizationEndpoint = new MessageReceivingEndpoint(new Uri(authorizationTokenURL), HttpDeliveryMethods.PostRequest);
TokenManager tokenManager = new TokenManager(consumerKey, consumerSecret);
WebConsumer consumer = new WebConsumer(serviceDescription, tokenManager);
// callback is never called by CLM, but needed to do OAuth based forms login
// XXX - Dns.GetHostName() alway seems to return simple, uppercased hostname
string callback = "https://" + Dns.GetHostName() + '.' + IPGlobalProperties.GetIPGlobalProperties().DomainName + ":9443/cb";
callback = callback.ToLower();
consumer.PrepareRequestUserAuthorization(new Uri(callback), null, null);
OslcClient oslcClient = new OslcClient();
HttpClient client = oslcClient.GetHttpClient();
HttpStatusCode statusCode = HttpStatusCode.Unused;
string location = null;
HttpResponseMessage resp;
try
{
client.DefaultRequestHeaders.Clear();
resp = client.GetAsync(authorizationTokenURL + "?oauth_token=" + tokenManager.GetRequestToken() +
"&oauth_callback=" + Uri.EscapeUriString(callback).Replace("#", "%23").Replace("/", "%2F").Replace(":", "%3A")).Result;
statusCode = resp.StatusCode;
if (statusCode == HttpStatusCode.Found)
{
location = resp.Headers.Location.AbsoluteUri;
resp.ConsumeContent();
statusCode = FollowRedirects(client, statusCode, location);
}
string securityCheckUrl = "j_username=" + user + "&j_password=" + passwd;
StringContent content = new StringContent(securityCheckUrl, System.Text.Encoding.UTF8);
MediaTypeHeaderValue mediaTypeValue = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
mediaTypeValue.CharSet = "utf-8";
content.Headers.ContentType = mediaTypeValue;
resp = client.PostAsync(authUrl + "/j_security_check", content).Result;
statusCode = resp.StatusCode;
string jazzAuthMessage = null;
IEnumerable<string> values = new List<string>();
if (resp.Headers.TryGetValues(JAZZ_AUTH_MESSAGE_HEADER, out values)) {
jazzAuthMessage = values.Last();
}
if (jazzAuthMessage != null && string.Compare(jazzAuthMessage, JAZZ_AUTH_FAILED, true) == 0)
{
resp.ConsumeContent();
throw new JazzAuthFailedException(user, authUrl);
}
else if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Found)
{
resp.ConsumeContent();
throw new JazzAuthErrorException(statusCode, authUrl);
}
else //success
{
Uri callbackUrl = resp.Headers.Location;
resp = client.GetAsync(callbackUrl.AbsoluteUri).Result;
callbackUrl = resp.Headers.Location;
resp = client.GetAsync(callbackUrl.AbsoluteUri).Result;
callbackUrl = resp.Headers.Location;
NameValueCollection qscoll = callbackUrl.ParseQueryString();
if (callbackUrl.OriginalString.StartsWith(callback + '?') && qscoll["oauth_verifier"] != null)
{
DesktopConsumer desktopConsumer = new DesktopConsumer(serviceDescription, tokenManager);
AuthorizedTokenResponse authorizedTokenResponse = desktopConsumer.ProcessUserAuthorization(tokenManager.GetRequestToken(), qscoll["oauth_verifier"]);
return consumer.CreateAuthorizingHandler(authorizedTokenResponse.AccessToken, CreateSSLHandler());
}
throw new JazzAuthErrorException(statusCode, authUrl);
}
} catch (JazzAuthFailedException jfe) {
throw jfe;
} catch (JazzAuthErrorException jee) {
throw jee;
} catch (Exception e) {
Console.WriteLine(e.StackTrace);
}
// return consumer.CreateAuthorizingHandler(accessToken);
return null;
}
private static HttpStatusCode FollowRedirects(HttpClient client, HttpStatusCode statusCode, string location)
{
while ((statusCode == HttpStatusCode.Found) && (location != null))
{
try {
HttpResponseMessage newResp = client.GetAsync(location).Result;
statusCode = newResp.StatusCode;
location = (newResp.Headers.Location != null) ? newResp.Headers.Location.AbsoluteUri : null;
newResp.ConsumeContent();
} catch (Exception e) {
Console.WriteLine(e.StackTrace);
}
}
return statusCode;
}
private const string JAZZ_AUTH_MESSAGE_HEADER = "X-com-ibm-team-repository-web-auth-msg";
private const string JAZZ_AUTH_FAILED = "authfailed";
}
}
| 43.838951 | 179 | 0.561555 | [
"EPL-1.0"
] | nenaaki/oslc4net | OSLC4Net_SDK/OSLC4Net.Client/Oslc/Jazz/JazzOAuthClient.cs | 11,707 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace IG.Repository
{
public interface IRepository<TEntity>
where TEntity : class
{
IQueryable<TEntity> GetQuery(Expression<Func<TEntity, bool>> predicate = null);
IEnumerable<TEntity> GetRecords(Expression<Func<TEntity, bool>> predicate = null);
TEntity GetFirstOrDefault(Expression<Func<TEntity, bool>> predicate = null);
int Count(Expression<Func<TEntity, bool>> predicate = null);
bool Any(Expression<Func<TEntity, bool>> predicate = null);
}
}
| 28.045455 | 90 | 0.703404 | [
"MIT"
] | igambin/Experiments | IG.Repository/IRepository.cs | 619 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Point_Of_Sales.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("server=Localhost;user id=root;database=pointofsales;allowuservariables=True;passw" +
"ord=abc123abc")]
public string pointofsalesConnectionString {
get {
return ((string)(this["pointofsalesConnectionString"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("server=Localhost;user id=root;database=pointofsales")]
public string pointofsalesConnectionString1 {
get {
return ((string)(this["pointofsalesConnectionString1"]));
}
}
}
}
| 48.208333 | 153 | 0.630078 | [
"MIT"
] | junkiesdevstudio/Point-Of-Sales | Point Of Sales/Properties/Settings.Designer.cs | 2,316 | C# |
namespace _03.Introduction_to_Entity_Framework.GringottsContext
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class GringottsContext : DbContext
{
public GringottsContext()
: base("name=GringottsContext")
{
}
public virtual DbSet<WizzardDeposit> WizzardDeposits { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<WizzardDeposit>()
.Property(e => e.FirstName)
.IsUnicode(false);
modelBuilder.Entity<WizzardDeposit>()
.Property(e => e.LastName)
.IsUnicode(false);
modelBuilder.Entity<WizzardDeposit>()
.Property(e => e.Notes)
.IsUnicode(false);
modelBuilder.Entity<WizzardDeposit>()
.Property(e => e.MagicWandCreator)
.IsUnicode(false);
modelBuilder.Entity<WizzardDeposit>()
.Property(e => e.DepositGroup)
.IsUnicode(false);
modelBuilder.Entity<WizzardDeposit>()
.Property(e => e.DepositAmount)
.HasPrecision(8, 2);
modelBuilder.Entity<WizzardDeposit>()
.Property(e => e.DepositInterest)
.HasPrecision(5, 2);
modelBuilder.Entity<WizzardDeposit>()
.Property(e => e.DepositCharge)
.HasPrecision(8, 2);
}
}
}
| 23.811321 | 70 | 0.709984 | [
"MIT"
] | HouseBreaker/SoftUni-Databases-Advanced | 03. Introduction to Entity Framework/03. Introduction to Entity Framework/GringottsContext/GringottsContext.cs | 1,262 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UseYourChaninsBuddy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UseYourChaninsBuddy")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("62b83e9b-4c03-4e45-a39d-6aea6f7a5374")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135 | 84 | 0.747697 | [
"MIT"
] | sholev/SoftUni | C#-WebDeveloper-3.0/Advanced-C#-May-2016/Exercises/RegularExpressions/UseYourChaninsBuddy/Properties/AssemblyInfo.cs | 1,414 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Charlotte.GameCommons;
namespace Charlotte.Games
{
public class Logo : IDisposable
{
// <---- prm
public static Logo I;
public Logo()
{
I = this;
}
public void Dispose()
{
I = null;
}
public void Perform()
{
// 開発中_暫定
{
int endFrame = DDEngine.ProcFrame + 300;
DDGround.EL.Add(() =>
{
int sec = endFrame - DDEngine.ProcFrame;
DDPrint.SetPrint(180, DDConsts.Screen_H - 32);
DDPrint.Print("これはクローズドテスト版です。仮リソース・実装されていない機能を含みます。(あと " + (sec / 60.0).ToString("F1") + " 秒で消えます)");
return 0 < sec;
});
}
foreach (DDScene scene in DDSceneUtils.Create(30))
{
DDCurtain.DrawCurtain();
DDEngine.EachFrame();
}
foreach (DDScene scene in DDSceneUtils.Create(60))
{
DDCurtain.DrawCurtain();
DDDraw.SetAlpha(scene.Rate);
DDDraw.DrawCenter(Ground.I.Picture.Copyright, DDConsts.Screen_W / 2, DDConsts.Screen_H / 2);
DDDraw.Reset();
DDEngine.EachFrame();
}
{
long endLoopTime = long.MaxValue;
for (int frame = 0; ; frame++)
{
if (endLoopTime < DDEngine.FrameStartTime)
break;
if (frame == 1)
{
endLoopTime = DDEngine.FrameStartTime + 1500;
DDTouch.Touch();
}
DDCurtain.DrawCurtain();
DDDraw.DrawCenter(Ground.I.Picture.Copyright, DDConsts.Screen_W / 2, DDConsts.Screen_H / 2);
DDEngine.EachFrame();
}
}
foreach (DDScene scene in DDSceneUtils.Create(60))
{
DDCurtain.DrawCurtain();
DDDraw.SetAlpha(1.0 - scene.Rate);
DDDraw.DrawCenter(Ground.I.Picture.Copyright, DDConsts.Screen_W / 2, DDConsts.Screen_H / 2);
DDDraw.Reset();
DDEngine.EachFrame();
}
}
}
}
| 19.505495 | 107 | 0.628732 | [
"MIT"
] | soleil-taruto/Elsa | e20210109_Nekomimi_old/Elsa20200001/Elsa20200001/Games/Logo.cs | 1,877 | C# |
using System;
using EasyNetQ.HostedService.Abstractions;
namespace EasyNetQ.HostedService.Models
{
/// <summary>
/// <inheritdoc cref="INackWithRequeueException"/>
/// </summary>
public class NackWithRequeueException : Exception, INackWithRequeueException
{
/// <summary>
/// <inheritdoc/>
/// </summary>
/// <param name="message"/>
public NackWithRequeueException(string message = "") : base(message)
{
}
/// <summary>
/// <inheritdoc/>
/// </summary>
/// <param name="message"/>
/// <param name="innerException"/>
public NackWithRequeueException(Exception innerException, string message = "") :
base(message, innerException)
{
}
}
}
| 26.433333 | 88 | 0.57377 | [
"MIT"
] | harry-detsis/EasyNetQ.HostedService | src/EasyNetQ.HostedService/Models/NackWithRequeueException.cs | 793 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
namespace Azure.AI.MetricsAdvisor.Models
{
/// <summary> The AzureTableDataFeed. </summary>
internal partial class AzureTableDataFeed : DataFeedDetail
{
/// <summary> Initializes a new instance of AzureTableDataFeed. </summary>
/// <param name="dataFeedName"> data feed name. </param>
/// <param name="granularityName"> granularity of the time series. </param>
/// <param name="metrics"> measure list. </param>
/// <param name="dataStartFrom"> ingestion start time. </param>
/// <param name="dataSourceParameter"> . </param>
/// <exception cref="ArgumentNullException"> <paramref name="dataFeedName"/>, <paramref name="metrics"/>, or <paramref name="dataSourceParameter"/> is null. </exception>
public AzureTableDataFeed(string dataFeedName, DataFeedGranularityType granularityName, IEnumerable<DataFeedMetric> metrics, DateTimeOffset dataStartFrom, AzureTableParameter dataSourceParameter) : base(dataFeedName, granularityName, metrics, dataStartFrom)
{
if (dataFeedName == null)
{
throw new ArgumentNullException(nameof(dataFeedName));
}
if (metrics == null)
{
throw new ArgumentNullException(nameof(metrics));
}
if (dataSourceParameter == null)
{
throw new ArgumentNullException(nameof(dataSourceParameter));
}
DataSourceParameter = dataSourceParameter;
DataSourceType = DataFeedSourceType.AzureTable;
}
/// <summary> Initializes a new instance of AzureTableDataFeed. </summary>
/// <param name="dataSourceType"> data source type. </param>
/// <param name="dataFeedId"> data feed unique id. </param>
/// <param name="dataFeedName"> data feed name. </param>
/// <param name="dataFeedDescription"> data feed description. </param>
/// <param name="granularityName"> granularity of the time series. </param>
/// <param name="granularityAmount"> if granularity is custom,it is required. </param>
/// <param name="metrics"> measure list. </param>
/// <param name="dimension"> dimension list. </param>
/// <param name="timestampColumn"> user-defined timestamp column. if timestampColumn is null, start time of every time slice will be used as default value. </param>
/// <param name="dataStartFrom"> ingestion start time. </param>
/// <param name="startOffsetInSeconds"> the time that the beginning of data ingestion task will delay for every data slice according to this offset. </param>
/// <param name="maxConcurrency"> the max concurrency of data ingestion queries against user data source. 0 means no limitation. </param>
/// <param name="minRetryIntervalInSeconds"> the min retry interval for failed data ingestion tasks. </param>
/// <param name="stopRetryAfterInSeconds"> stop retry data ingestion after the data slice first schedule time in seconds. </param>
/// <param name="needRollup"> mark if the data feed need rollup. </param>
/// <param name="rollUpMethod"> roll up method. </param>
/// <param name="rollUpColumns"> roll up columns. </param>
/// <param name="allUpIdentification"> the identification value for the row of calculated all-up value. </param>
/// <param name="fillMissingPointType"> the type of fill missing point for anomaly detection. </param>
/// <param name="fillMissingPointValue"> the value of fill missing point for anomaly detection. </param>
/// <param name="viewMode"> data feed access mode, default is Private. </param>
/// <param name="admins"> data feed administrator. </param>
/// <param name="viewers"> data feed viewer. </param>
/// <param name="isAdmin"> the query user is one of data feed administrator or not. </param>
/// <param name="creator"> data feed creator. </param>
/// <param name="status"> data feed status. </param>
/// <param name="createdTime"> data feed created time. </param>
/// <param name="actionLinkTemplate"> action link for alert. </param>
/// <param name="dataSourceParameter"> . </param>
internal AzureTableDataFeed(DataFeedSourceType dataSourceType, string dataFeedId, string dataFeedName, string dataFeedDescription, DataFeedGranularityType granularityName, int? granularityAmount, IList<DataFeedMetric> metrics, IList<DataFeedDimension> dimension, string timestampColumn, DateTimeOffset dataStartFrom, long? startOffsetInSeconds, int? maxConcurrency, long? minRetryIntervalInSeconds, long? stopRetryAfterInSeconds, DataFeedRollupType? needRollup, DataFeedAutoRollupMethod? rollUpMethod, IList<string> rollUpColumns, string allUpIdentification, DataFeedMissingDataPointFillType? fillMissingPointType, double? fillMissingPointValue, DataFeedAccessMode? viewMode, IList<string> admins, IList<string> viewers, bool? isAdmin, string creator, DataFeedStatus? status, DateTimeOffset? createdTime, string actionLinkTemplate, AzureTableParameter dataSourceParameter) : base(dataSourceType, dataFeedId, dataFeedName, dataFeedDescription, granularityName, granularityAmount, metrics, dimension, timestampColumn, dataStartFrom, startOffsetInSeconds, maxConcurrency, minRetryIntervalInSeconds, stopRetryAfterInSeconds, needRollup, rollUpMethod, rollUpColumns, allUpIdentification, fillMissingPointType, fillMissingPointValue, viewMode, admins, viewers, isAdmin, creator, status, createdTime, actionLinkTemplate)
{
DataSourceParameter = dataSourceParameter;
DataSourceType = dataSourceType;
}
public AzureTableParameter DataSourceParameter { get; set; }
}
}
| 73.765432 | 1,321 | 0.700753 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Generated/Models/AzureTableDataFeed.cs | 5,975 | C# |
namespace DNNDataTables.Modules.Models
{
public class Criteria
{
public string cField { get; set; }
public string cType { get; set; }
public string cOperator { get; set; }
public string cValue { get; set; }
}
} | 25.5 | 45 | 0.596078 | [
"MIT"
] | cartersolutions/DNNDataTables | Models/Criteria.cs | 257 | 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/ShObjIdl_core.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='AHTYPE.xml' path='doc/member[@name="AHTYPE"]/*' />
public enum AHTYPE
{
/// <include file='AHTYPE.xml' path='doc/member[@name="AHTYPE.AHTYPE_UNDEFINED"]/*' />
AHTYPE_UNDEFINED = 0,
/// <include file='AHTYPE.xml' path='doc/member[@name="AHTYPE.AHTYPE_USER_APPLICATION"]/*' />
AHTYPE_USER_APPLICATION = 0x8,
/// <include file='AHTYPE.xml' path='doc/member[@name="AHTYPE.AHTYPE_ANY_APPLICATION"]/*' />
AHTYPE_ANY_APPLICATION = 0x10,
/// <include file='AHTYPE.xml' path='doc/member[@name="AHTYPE.AHTYPE_MACHINEDEFAULT"]/*' />
AHTYPE_MACHINEDEFAULT = 0x20,
/// <include file='AHTYPE.xml' path='doc/member[@name="AHTYPE.AHTYPE_PROGID"]/*' />
AHTYPE_PROGID = 0x40,
/// <include file='AHTYPE.xml' path='doc/member[@name="AHTYPE.AHTYPE_APPLICATION"]/*' />
AHTYPE_APPLICATION = 0x80,
/// <include file='AHTYPE.xml' path='doc/member[@name="AHTYPE.AHTYPE_CLASS_APPLICATION"]/*' />
AHTYPE_CLASS_APPLICATION = 0x100,
/// <include file='AHTYPE.xml' path='doc/member[@name="AHTYPE.AHTYPE_ANY_PROGID"]/*' />
AHTYPE_ANY_PROGID = 0x200,
}
| 41.085714 | 145 | 0.693324 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/ShObjIdl_core/AHTYPE.cs | 1,440 | C# |
using CaffeDemo.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaffeDemo.Entities
{
public class Customer:IEntity
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string NationalatyId { get; set; }
}
}
| 23.684211 | 49 | 0.668889 | [
"MIT"
] | YasinBulut/Object-Oriented-Programming | Interface-Abstract/InterfaceAndAbstract/CaffeDemo/Entities/Customer.cs | 452 | C# |
using OrpheusInterfaces.Interfaces.Attributes;
namespace OrpheusAttributes
{
/// <summary>
/// Composite key attribute, to decorate models that have primary or unique keys that are comprised from than one field.
/// </summary>
/// <seealso cref="OrpheusAttributes.OrpheusBaseAttribute" />
/// <seealso cref="OrpheusInterfaces.Interfaces.Attributes.IOrpheusBaseCompositeKeyAttribute" />
public class OrpheusCompositeKeyBaseAttribute : OrpheusBaseAttribute, IOrpheusBaseCompositeKeyAttribute
{
/// <value>
/// List of fields that are the key.
/// </value>
public string[] Fields { get; private set; }
/// <value>
/// Sort for the key.
/// </value>
public string Sort { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="OrpheusCompositeKeyBaseAttribute"/> class.
/// </summary>
/// <param name="fields">The fields.</param>
/// <param name="sort">The sort direction.</param>
public OrpheusCompositeKeyBaseAttribute(string[] fields,string sort = null):base()
{
this.Fields = fields;
this.Sort = sort;
}
}
}
| 35.970588 | 124 | 0.626329 | [
"MPL-2.0"
] | gtrifidis/OrpheusORM | OrpheusAttributes/OrpheusCompositeKeyBaseAttribute.cs | 1,225 | C# |
using Gum.CompileTime;
namespace Gum.Runtime
{
public interface IGlobalVarRepo
{
Value GetValue(ItemId varId);
void SetValue(ItemId varId, Value value);
}
} | 19.5 | 50 | 0.635897 | [
"MIT"
] | ioklo/gum | Src/Gum.Runtime/Runtime/IGlobalVarRepo.cs | 197 | C# |
using CarinaStudio.Collections;
using System;
using System.Collections.Generic;
namespace CarinaStudio.ULogViewer.Logs.DataSources
{
/// <summary>
/// <see cref="ILogDataSourceProvider"/> for <see cref="HttpLogDataSource"/>.
/// </summary>
class HttpLogDataSourceProvider : BaseLogDataSourceProvider
{
/// <summary>
/// Initialize new <see cref="HttpLogDataSourceProvider"/> instance.
/// </summary>
/// <param name="app">Application.</param>
public HttpLogDataSourceProvider(IApplication app) : base(app)
{ }
// Update display name.
protected override string OnUpdateDisplayName() => "HTTP/HTTPS";
// Implementations.
protected override ILogDataSource CreateSourceCore(LogDataSourceOptions options) => new HttpLogDataSource(this, options);
public override string Name => "Http";
public override ISet<string> RequiredSourceOptions => new HashSet<string>()
{
nameof(LogDataSourceOptions.Uri),
}.AsReadOnly();
public override ISet<string> SupportedSourceOptions => new HashSet<string>()
{
nameof(LogDataSourceOptions.Password),
nameof(LogDataSourceOptions.Uri),
nameof(LogDataSourceOptions.UserName),
}.AsReadOnly();
}
}
| 30.179487 | 123 | 0.740867 | [
"MIT"
] | ylchu/ULogViewer | ULogViewer/Logs/DataSources/HttpLogDataSourceProvider.cs | 1,179 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace CSharpScriptSerialization
{
public class EnumCSScriptSerializer : CSScriptSerializer
{
public EnumCSScriptSerializer(Type type)
: base(type)
{
}
public override ExpressionSyntax GetCreation(object obj)
{
var name = Enum.GetName(Type, obj);
return name == null
? GetCompositeValue((Enum)obj)
: GetSimpleValue(name);
}
protected virtual ExpressionSyntax GetCompositeValue(Enum flags)
{
var simpleValues = new HashSet<Enum>(flags.GetFlags());
foreach (var currentValue in simpleValues.ToList())
{
var decomposedValues = currentValue.GetFlags();
if (decomposedValues.Count > 1)
{
simpleValues.ExceptWith(decomposedValues.Where(v => !Equals(v, currentValue)));
}
}
return simpleValues.Aggregate((ExpressionSyntax)null,
(previous, current) =>
previous == null
? GetSimpleValue(Enum.GetName(Type, current))
: SyntaxFactory.BinaryExpression(
SyntaxKind.BitwiseOrExpression, previous, GetSimpleValue(Enum.GetName(Type, current))));
}
protected virtual ExpressionSyntax GetSimpleValue(string name)
=> SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
GetTypeSyntax(Type),
SyntaxFactory.IdentifierName(name));
}
} | 35.4 | 116 | 0.588701 | [
"Apache-2.0"
] | AndriySvyryd/CSharpScriptSerializer | src/CSharpScriptSerializer/EnumCSScriptSerializer.cs | 1,770 | C# |
namespace Machete.X12Schema.V5010
{
using X12;
public interface LoopFA1_861 :
X12Layout
{
Segment<FA1> TypeOfFinancialAccountingData { get; }
SegmentList<FA2> AccountingData { get; }
}
} | 18.230769 | 59 | 0.616034 | [
"Apache-2.0"
] | ahives/Machete | src/Machete.X12Schema/V5010/Layouts/LoopFA1_861.cs | 237 | C# |
using RX_Explorer.Class;
using System;
using Windows.Storage;
using Windows.System;
namespace RX_Explorer.Dialog
{
public sealed partial class WhatIsNew : QueueContentDialog
{
public WhatIsNew()
{
InitializeComponent();
Init();
}
private void Init()
{
switch (Globalization.CurrentLanguage)
{
case LanguageEnum.Chinese_Simplified:
{
StorageFile UpdateFile = StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/UpdateLog-Chinese_S.txt")).AsTask().Result;
MarkDown.Text = FileIO.ReadTextAsync(UpdateFile).AsTask().Result;
break;
}
case LanguageEnum.Chinese_Traditional:
{
StorageFile UpdateFile = StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/UpdateLog-Chinese_T.txt")).AsTask().Result;
MarkDown.Text = FileIO.ReadTextAsync(UpdateFile).AsTask().Result;
break;
}
case LanguageEnum.English:
{
StorageFile UpdateFile = StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/UpdateLog-English.txt")).AsTask().Result;
MarkDown.Text = FileIO.ReadTextAsync(UpdateFile).AsTask().Result;
break;
}
case LanguageEnum.French:
{
StorageFile UpdateFile = StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/UpdateLog-French.txt")).AsTask().Result;
MarkDown.Text = FileIO.ReadTextAsync(UpdateFile).AsTask().Result;
break;
}
case LanguageEnum.Spanish:
{
StorageFile UpdateFile = StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/UpdateLog-Spanish.txt")).AsTask().Result;
MarkDown.Text = FileIO.ReadTextAsync(UpdateFile).AsTask().Result;
break;
}
}
}
private async void MarkDown_LinkClicked(object sender, Microsoft.Toolkit.Uwp.UI.Controls.LinkClickedEventArgs e)
{
await Launcher.LaunchUriAsync(new Uri(e.Link));
}
}
}
| 42.305085 | 162 | 0.542468 | [
"Apache-2.0"
] | Ajohnie/RX-Explorer | RX_Explorer/Dialog/WhatIsNew.xaml.cs | 2,498 | C# |
// _ __ __
// ___ ___ ___ _ __ __| | __ _ | \/ |
// / __|/ __| / _ \| '_ \ / _` | / _` || |\/| |
// \__ \\__ \| __/| | | || (_| || (_| || | | |
// |___/|___/ \___||_| |_| \__,_| \__,_||_| |_|
// |
// Copyright 2021-2022 Łukasz "JustArchi" Domeradzki
// Contact: JustArchi@JustArchi.net
// |
// 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 JetBrains.Annotations;
using JustArchiNET.Madness.Helpers;
namespace JustArchiNET.Madness.ConvertMadness;
[MadnessType(EMadnessType.Replacement)]
[PublicAPI]
public static class Convert {
[MadnessType(EMadnessType.Proxy)]
[Pure]
public static object ChangeType(object? value, Type conversionType, IFormatProvider? provider) => System.Convert.ChangeType(value, conversionType, provider);
[MadnessType(EMadnessType.Proxy)]
[Pure]
public static byte[] FromBase64String(string s) => System.Convert.FromBase64String(s);
[MadnessType(EMadnessType.Proxy)]
[Pure]
public static string ToBase64String(byte[] inArray) => System.Convert.ToBase64String(inArray);
[MadnessType(EMadnessType.Implementation)]
[Pure]
public static string ToHexString(byte[] inArray) {
if (inArray == null) {
throw new ArgumentNullException(nameof(inArray));
}
return BitConverter.ToString(inArray).Replace("-", "", StringComparison.Ordinal);
}
}
| 35.09434 | 158 | 0.693548 | [
"Apache-2.0"
] | Abrynos/Madness | JustArchiNET.Madness/ConvertMadness/Convert.cs | 1,861 | 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 comprehend-2017-11-27.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.Comprehend.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Comprehend.Model.Internal.MarshallTransformations
{
/// <summary>
/// StopDominantLanguageDetectionJob Request Marshaller
/// </summary>
public class StopDominantLanguageDetectionJobRequestMarshaller : IMarshaller<IRequest, StopDominantLanguageDetectionJobRequest> , 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((StopDominantLanguageDetectionJobRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(StopDominantLanguageDetectionJobRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Comprehend");
string target = "Comprehend_20171127.StopDominantLanguageDetectionJob";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-11-27";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetJobId())
{
context.Writer.WritePropertyName("JobId");
context.Writer.Write(publicRequest.JobId);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static StopDominantLanguageDetectionJobRequestMarshaller _instance = new StopDominantLanguageDetectionJobRequestMarshaller();
internal static StopDominantLanguageDetectionJobRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static StopDominantLanguageDetectionJobRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.666667 | 180 | 0.628571 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Comprehend/Generated/Model/Internal/MarshallTransformations/StopDominantLanguageDetectionJobRequestMarshaller.cs | 3,955 | C# |
using System.Web.Mvc;
using System.Web.Routing;
namespace DbLocalizationProvider.MvcSample
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
}
} | 26.052632 | 87 | 0.557576 | [
"MIT"
] | ShadowLaurus/LocalizationProvider | Tests/DbLocalizationProvider.MvcSample/App_Start/RouteConfig.cs | 497 | C# |
/*****************************************************************************
* Copyright 2016 Aurora Solutions
*
* http://www.aurorasolutions.io
*
* Aurora Solutions is an innovative services and product company at
* the forefront of the software industry, with processes and practices
* involving Domain Driven Design(DDD), Agile methodologies to build
* scalable, secure, reliable and high performance products.
*
* TradeSharp is a C# based data feed and broker neutral Algorithmic
* Trading Platform that lets trading firms or individuals automate
* any rules based trading strategies in stocks, forex and ETFs.
* TradeSharp allows users to connect to providers like Tradier Brokerage,
* IQFeed, FXCM, Blackwood, Forexware, Integral, HotSpot, Currenex,
* Interactive Brokers and more.
* Key features: Place and Manage Orders, Risk Management,
* Generate Customized Reports etc
*
* 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.Text;
namespace TradeHub.Common.Core.DomainModels
{
/// <summary>
/// Snapshot of the market at a particular point in time, containing information like
/// last price, last time, bid, ask, volume, etc.
/// </summary>
[Serializable()]
public class Tick : MarketDataEvent, ICloneable
{
private decimal _lastSize;
private decimal _lastPrice;
private string _lastExchange;
private int _depth;
private decimal _bidPrice;
private decimal _bidSize;
private string _bidExchange;
private decimal _askPrice;
private string _askExchange;
private decimal _askSize;
#region Properties
/// <summary>
/// Last size of tick
/// </summary>
public decimal LastSize
{
get { return this._lastSize; }
set { this._lastSize = value; }
}
/// <summary>
/// Last price of tick
/// </summary>
public decimal LastPrice
{
get { return this._lastPrice; }
set { this._lastPrice = value; }
}
/// <summary>
/// Exchange of las tick
/// </summary>
public string LastExchange
{
get { return this._lastExchange; }
set { this._lastExchange = value; }
}
/// <summary>
/// Depth in market book
/// </summary>
public int Depth
{
get { return this._depth; }
set { this._depth = value; }
}
/// <summary>
/// Bid price of tick
/// </summary>
public decimal BidPrice
{
get { return this._bidPrice; }
set { this._bidPrice = value; }
}
/// <summary>
/// Bid size of tick
/// </summary>
public decimal BidSize
{
get { return this._bidSize; }
set { this._bidSize = value; }
}
/// <summary>
/// Bid exchange of tick
/// </summary>
public string BidExchange
{
get { return this._bidExchange; }
set { this._bidExchange = value; }
}
/// <summary>
/// Ask price of tick
/// </summary>
public decimal AskPrice
{
get { return this._askPrice; }
set { this._askPrice = value; }
}
/// <summary>
/// Ask size of tick
/// </summary>
public decimal AskSize
{
get { return this._askSize; }
set { this._askSize = value; }
}
/// <summary>
/// Ask exchange of tick
/// </summary>
public string AskExchange
{
get { return this._askExchange; }
set { this._askExchange = value; }
}
#endregion
#region Constructors
/// <summary>
/// Default Constructor
/// </summary>
public Tick() : base()
{
InitializeFields();
}
/// <summary>
/// Argument Constructor
/// </summary>
/// <param name="security">TradeHub Security</param>
/// <param name="marketDataProvider">Name of Market Data provider</param>
public Tick(Security security, string marketDataProvider)
: base(security, marketDataProvider)
{
InitializeFields();
}
/// <summary>
/// Argument Constructor
/// </summary>
/// <param name="security">TradeHub Security</param>
/// <param name="marketDataProvider">Name of Market Data provider</param>
/// <param name="dateTime">DataTime</param>
public Tick(Security security, string marketDataProvider, DateTime dateTime)
: base(security, marketDataProvider, dateTime)
{
InitializeFields();
}
#endregion
/// <summary>
/// Initializes private fields
/// </summary>
private void InitializeFields()
{
_lastSize = default(decimal);
_lastPrice = default(decimal);
_lastExchange = string.Empty;
_depth = default(int);
_bidPrice = default(decimal);
_bidSize = default(decimal);
_bidExchange = string.Empty;
_askPrice = default(decimal);
_askExchange = string.Empty;
_askSize = default(decimal);
}
/// <summary>
/// Does this tick has trade?
/// </summary>
public bool HasTrade
{
get { return (this._lastPrice != 0M) && (this._lastSize != 0M); }
}
/// <summary>
/// Does this tick has bid?
/// </summary>
public bool HasBid
{
get { return (this._bidPrice != 0M) && (this._bidSize != 0M); }
}
/// <summary>
/// Does this tick has ask?
/// </summary>
public bool HasAsk
{
get { return (this._askPrice != 0M) && (this._askSize != 0M); }
}
/// <summary>
/// Overrides default ToString() method
/// </summary>
/// <returns></returns>
public override string ToString()
{
var str = new StringBuilder();
str.Append("Tick :: ");
str.Append("Market Data Provider : " + MarketDataProvider);
str.Append(" | " + Security);
str.Append(" | ");
str.Append("DateTime : " + DateTime.ToString("yyyyMMdd HH:mm:ss.fff"));
if (HasAsk)
{
str.Append(" | ");
str.Append("AskPrice : " + this._askPrice);
str.Append(" | ");
str.Append("AskSize : " + this._askSize);
str.Append(" | ");
str.Append("AskExchange : " + this._askExchange);
}
if (HasBid)
{
str.Append(" | ");
str.Append("BidPrice : " + this._bidPrice);
str.Append(" | ");
str.Append("BidSize : " + this._bidSize);
str.Append(" | ");
str.Append("BidExchange : " + this._bidExchange);
}
if (HasTrade)
{
str.Append(" | ");
str.Append("LastPrice : " + this._lastPrice);
str.Append(" | ");
str.Append("LastSize : " + this._lastSize);
str.Append(" | ");
str.Append("LastExchange : " + this._lastExchange);
}
return str.ToString();
}
/// <summary>
/// Creates a string which is to be published and converted back to Tick on receiver end
/// </summary>
public String DataToPublish()
{
//var str = new StringBuilder();
//str.Append("TICK");
//str.Append("," + _bidPrice);
//str.Append("," + _bidSize);
//str.Append("," + _askPrice);
//str.Append("," + _askSize);
//str.Append("," + _lastPrice);
//str.Append("," + _lastSize);
//str.Append("," + Security.Symbol);
//str.Append("," + DateTime.ToString("M/d/yyyy h:mm:ss.fff tt"));
//str.Append("," + MarketDataProvider);
//return str.ToString();
return "TICK" +
"," + _bidPrice +
"," + _bidSize +
"," + _askPrice +
"," + _askSize +
"," + _lastPrice +
"," + _lastSize +
"," + Security.Symbol +
"," + DateTime.ToString("M/d/yyyy h:mm:ss.fff tt") +
"," + MarketDataProvider +
"," + _depth;
}
/// <summary>
/// Clone Object
/// </summary>
/// <returns>Copy of object</returns>
public object Clone()
{
return MemberwiseClone();
}
}
}
| 30.802548 | 96 | 0.502171 | [
"Apache-2.0"
] | TradeNexus/tradesharp-core | Backend/Common/TradeHub.Common.Core/DomainModels/Tick.cs | 9,674 | C# |
#region Copyright
//=======================================================================================
// Microsoft Azure Customer Advisory Team
//
// This sample is supplemental to the technical guidance published on my personal
// blog at http://blogs.msdn.com/b/paolos/.
//
// Author: Paolo Salvatori
//=======================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE
// FILES EXCEPT IN COMPLIANCE WITH THE LICENSE. YOU MAY OBTAIN A COPY OF THE LICENSE AT
// http://www.apache.org/licenses/LICENSE-2.0
// UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, SOFTWARE DISTRIBUTED UNDER THE
// LICENSE IS DISTRIBUTED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED. SEE THE LICENSE FOR THE SPECIFIC LANGUAGE GOVERNING
// PERMISSIONS AND LIMITATIONS UNDER THE LICENSE.
//=======================================================================================
#endregion
#region Using Directives
using System;
#endregion
namespace ServiceBusExplorer.Relay.Helpers
{
/// <summary>
/// This class contains the information of a Relay
/// </summary>
public class RelayWrapper
{
#region Public Constructors
/// <summary>
/// Initializes a new instance of the RelayWrapper class.
/// </summary>
/// <param name="name">The service name.</param>
/// <param name="uri">The service uri.</param>
public RelayWrapper(string name, Uri uri)
{
Name = name;
Uri = uri;
}
#endregion
#region Public Properties
public string Name { get; set; }
public Uri Uri { get; set; }
#endregion
}
}
| 34.777778 | 93 | 0.56869 | [
"Apache-2.0"
] | 0be1/ServiceBusExplorer | src/Relay/Helpers/RelayWrapper.cs | 1,880 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DataMonitoring.Business;
using DataMonitoring.Model;
using DataMonitoring.ViewModel;
using Sodevlog.Tools;
using Sodevlog.CoreServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace DataMonitoring.Controllers
{
[Route("api/[controller]")]
[ApiController]
[AllowAnonymous]
[SecurityHeaders]
public class TimeManagementController : ControllerBase
{
private static readonly ILogger Logger = ApplicationLogging.LoggerFactory.CreateLogger<TimeManagementController>();
private readonly ITimeManagementBusiness _timeManagementBusiness;
private readonly ILocalizationService _localizationService;
public TimeManagementController(ITimeManagementBusiness timeManagementBusiness, ILocalizationService localizationService)
{
_timeManagementBusiness = timeManagementBusiness;
_localizationService = localizationService;
}
// GET: api/TimeManagement
[HttpGet]
public async Task<IEnumerable<TimeManagementViewModel>> Get()
{
try
{
var timeManagements = await _timeManagementBusiness.GetAllTimeManagementsAsync();
return timeManagements.Select(ViewModelConverter.GetTimeManagement);
}
catch (Exception e)
{
Logger.LogError(e, "Error during get all TimeManagement");
return null;
}
}
// GET: api/TimeManagement/5
[HttpGet("{id}")]
public async Task<ActionResult<TimeManagementViewModel>> Get(long id)
{
try
{
var timeManagement = await _timeManagementBusiness.GetTimeManagementAsync(id);
if (timeManagement == null)
{
Logger.LogError($"TimeManagement id {id} NotFound");
var messageResult = _localizationService.GetLocalizedHtmlString("NotFoundError");
return NotFound(messageResult);
}
return Ok(ViewModelConverter.GetTimeManagement(timeManagement));
}
catch (Exception e)
{
Logger.LogError(e.Message, $"Error during get TimeManagement id {id}");
var messageResult = _localizationService.GetLocalizedHtmlString("GetError");
return StatusCode(500, messageResult);
}
}
// POST: api/TimeManagement
[HttpPost]
public ActionResult Post([FromBody] TimeManagementViewModel value)
{
try
{
var timeManagement = BusinessConverter.GetTimeManagement(value);
_timeManagementBusiness.CreateOrUpdateTimeManagement(timeManagement);
return Ok();
}
catch (Exception e)
{
Logger.LogError(e.Message, "Error during Post Operation TimeManagement");
var messageResult = _localizationService.GetLocalizedHtmlString("CreateOrUpdateError");
return StatusCode(500, messageResult);
}
}
// DELETE: api/TimeManagement/5
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(int id)
{
try
{
var timeManagement = await _timeManagementBusiness.Repository<TimeManagement>().GetAsync(id);
if (timeManagement == null)
{
Logger.LogError($"TimeManagement id {id} NotFound");
var messageResult = _localizationService.GetLocalizedHtmlString("NotFoundError");
return NotFound(messageResult);
}
_timeManagementBusiness.DeleteTimeManagement(id);
return Ok();
}
catch (InvalidOperationException)
{
Logger.LogError($"TimeManagement id {id} Delete impossible due to relationship");
var messageResult = _localizationService.GetLocalizedHtmlString("DeleteImpossibleBecauseRelationship");
return StatusCode(500, messageResult);
}
catch (Exception e)
{
Logger.LogError(e, $"Error during delete TimeManagement id {id}");
var messageResult = _localizationService.GetLocalizedHtmlString("DeleteError");
return StatusCode(500, messageResult);
}
}
// GET: api/TimeManagement/timeManagementTypes
[HttpGet("timeManagementTypes")]
public List<EnumValue> GetTimeManagementTypes()
{
List<EnumValue> result = EnumExtension.GetValues<TimeManagementType>( _localizationService );
return result;
}
// GET: api/TimeManagement/unitOfTimes
[HttpGet("unitOfTimes")]
public List<EnumValue> GetUnitOfTimes()
{
List<EnumValue> result = EnumExtension.GetValues<UnitOfTime>( _localizationService );
return result;
}
}
}
| 37.683453 | 129 | 0.611493 | [
"MIT"
] | SoDevLog/DataMonitoring | DataMonitoring/Controllers/TimeManagementController.cs | 5,240 | C# |
using System;
namespace PizzaCalories
{
public class Dough
{
private const double BaseCaloriesPerGram = 2.0;
private const int MinWeight = 1;
private const int MaxWeight = 200;
private string flourType;
private string bakingTechnique;
private double weight;
public Dough(string flourType, string bakingTechnique, double weight)
{
this.FlourType = flourType;
this.BakingTechnique = bakingTechnique;
this.Weight = weight;
}
public string FlourType
{
get => this.flourType;
private set
{
this.ValidateFlourType(value);
this.flourType = value;
}
}
public string BakingTechnique
{
get => this.bakingTechnique;
private set
{
this.ValidateBakingTechniques(value);
this.bakingTechnique = value;
}
}
public double Weight
{
get => this.weight;
private set
{
this.ValidateWeight(value);
this.weight = value;
}
}
public double GetCalories()
=> this.Weight * BaseCaloriesPerGram * this.GetFlourTypeModifier() * this.GetBakingTechniqueModifier();
private double GetFlourTypeModifier()
{
switch (this.FlourType.ToLower())
{
case "white":
return 1.5;
case "wholegrain":
return 1.0;
default:
return 0;
}
}
private double GetBakingTechniqueModifier()
{
switch (this.BakingTechnique.ToLower())
{
case "crispy":
return 0.9;
case "chewy":
return 1.1;
case "homemade":
return 1.0;
default:
return 0;
}
}
private void ValidateFlourType(string flourType)
{
if (flourType.ToLower() != "white" && flourType.ToLower() != "wholegrain")
{
throw new ArgumentException("Invalid type of dough.");
}
}
private void ValidateBakingTechniques(string bakingTechniques)
{
if (bakingTechniques.ToLower() != "crispy"
&& bakingTechniques.ToLower() != "chewy"
&& bakingTechniques.ToLower() != "homemade")
{
throw new ArgumentException("Invalid type of dough.");
}
}
private void ValidateWeight(double value)
{
if (value < MinWeight || value > MaxWeight)
{
throw new ArgumentException("Dough weight should be in the range [1..200].");
}
}
}
}
| 26.359649 | 115 | 0.476872 | [
"MIT"
] | ivanov-mi/SoftUni-Training | 03CSharpOOP/03Encapsulation/04PizzaCalories/Dough.cs | 3,007 | C# |
using System;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Util.Datas.Transactions;
namespace Util.Events.Cap {
/// <summary>
/// Cap消息事件总线
/// </summary>
public class MessageEventBus : IMessageEventBus {
/// <summary>
/// 初始化Cap消息事件总线
/// </summary>
/// <param name="publisher">事件发布器</param>
/// <param name="transactionActionManager">事务操作管理器</param>
public MessageEventBus( ICapPublisher publisher, ITransactionActionManager transactionActionManager ) {
Publisher = publisher ?? throw new ArgumentNullException( nameof( publisher ) );
TransactionActionManager = transactionActionManager ?? throw new ArgumentNullException( nameof( transactionActionManager ) );
}
/// <summary>
/// 事件发布器
/// </summary>
public ICapPublisher Publisher { get; set; }
/// <summary>
/// 事务操作管理器
/// </summary>
public ITransactionActionManager TransactionActionManager { get; set; }
/// <summary>
/// 发布事件
/// </summary>
/// <typeparam name="TEvent">事件类型</typeparam>
/// <param name="event">事件</param>
public Task PublishAsync<TEvent>( TEvent @event ) where TEvent : IMessageEvent {
return PublishAsync( @event.Name, @event.Data, @event.Callback );
}
/// <summary>
/// 发布事件
/// </summary>
/// <param name="name">消息名称</param>
/// <param name="data">事件数据</param>
/// <param name="callback">回调名称</param>
public Task PublishAsync( string name, object data, string callback ) {
TransactionActionManager.Register( async transaction => {
Publisher.Transaction.DbTransaction = transaction;
Publisher.Transaction.AutoCommit = false;
await Publisher.PublishAsync( name, data, callback );
} );
return Task.CompletedTask;
}
}
}
| 36.236364 | 137 | 0.592574 | [
"MIT"
] | LuciferJun1227/Util | src/Util.Events/Cap/MessageEventBus.cs | 2,125 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using lm.Comol.Core.Authentication;
using lm.Comol.Core.DomainModel;
using lm.Comol.Core.DomainModel.Helpers;
namespace lm.Comol.Core.BaseModules.ProfileManagement.Presentation
{
public interface IViewImportAgencies : lm.Comol.Core.DomainModel.Common.iDomainView
{
Boolean AllowManagement { set; }
System.Guid ImportIdentifier { get; set; }
AgencyImportStep CurrentStep { get; set; }
List<AgencyImportStep> AvailableSteps { get; set; }
List<AgencyImportStep> SkipSteps { get; set; }
Boolean IsInitialized(AgencyImportStep pStep);
void GotoStep(AgencyImportStep pStep);
void GotoStep(AgencyImportStep pStep, Boolean initialize);
void InitializeStep(AgencyImportStep pStep);
// ' STEP CSV
CsvFile RetrieveFile();
ExternalResource GetFileContent(List<ExternalColumnComparer<String, Int32>> columns);
List<ExternalColumnComparer<String, Int32>> AvailableColumns();
// 'SETP
List<ExternalColumnComparer<String, Int32>> Fields { get; }
Boolean ValidDestinationFields { get; }
void InitializeFieldsMatcher(List<ExternalColumnComparer<String, Int32>> sourceColumns);
//Step select Items
ExternalResource SelectedItems{ get;}
Boolean HasSelectedItems{ get;}
Int32 ItemsToSelect{ get;}
void UpdateSourceItems();
//Step select Organizations
Boolean AvailableForAll { get; }
Dictionary<Int32, String> SelectedOrganizations { get; }
Boolean HasAvailableOrganizations { get; }
// 'STEP SUMMARY
Boolean isCompleted { get; set; }
void SetupProgressInfo(Int32 agencyCount);
void UpdateAgencyCreation(Int32 agencyCount, Int32 agencyIndex, Boolean created, String displayName);
// '''/STEP SUMMARY
void DisplayImportedAgencies(Int32 importedItems,Int32 itemsToImport);
void DisplayError(AgencyImportStep currentStep);
void DisplayImportError(Int32 importedItems, List<String> notCreatedItems);
AgencyImportStep PreviousStep { get; set; }
void DisplaySessionTimeout();
void DisplayNoPermission();
}
} | 37.213115 | 109 | 0.704846 | [
"MIT"
] | EdutechSRL/Adevico | 3-Business/3-Modules/lm.Comol.Core.BaseModules/ProfileManagement/Presentation/Import/View/IViewImportAgencies.cs | 2,272 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Logging.ExceptionSender
{
public class ExceptionSenderTelegramOptions : ExceptionSenderOptions
{
/// <summary>
/// Chat ID to send reports to.
/// </summary>
public string ChatId { get; set; }
/// <summary>
/// Telegram Bot token (like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11).
/// </summary>
public string BotToken { get; set; }
}
}
| 24.590909 | 80 | 0.639556 | [
"MIT"
] | justdmitry/Logger.ExceptionSender | src/Logging.ExceptionSender/ExceptionSenderTelegramOptions.cs | 543 | C# |
using System;
public class UserInfo {
public UserInfo() {
}
public bool inGame;
public bool inCurrentGame;
public bool inLobby;
public bool inMyLobby;
public SteamUserState state;
public FriendRelationship relationship;
}
| 13.789474 | 43 | 0.687023 | [
"MIT"
] | 0x0ade/DuckGame-Linux | Steam/src/UserInfo.cs | 264 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("C1_BT3_Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("C1_BT3_Client")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7a41b268-b860-4c56-99f0-3ebd85ee45a5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.745533 | [
"Unlicense"
] | phuccoder/Network-Program | 3_1_SimpleUdpClient/Properties/AssemblyInfo.cs | 1,402 | 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.Cdn.V20200901.Inputs
{
/// <summary>
/// Round-Robin load balancing settings for a backend pool
/// </summary>
public sealed class LoadBalancingSettingsParametersArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The additional latency in milliseconds for probes to fall into the lowest latency bucket
/// </summary>
[Input("additionalLatencyInMilliseconds")]
public Input<int>? AdditionalLatencyInMilliseconds { get; set; }
/// <summary>
/// The number of samples to consider for load balancing decisions
/// </summary>
[Input("sampleSize")]
public Input<int>? SampleSize { get; set; }
/// <summary>
/// The number of samples within the sample period that must succeed
/// </summary>
[Input("successfulSamplesRequired")]
public Input<int>? SuccessfulSamplesRequired { get; set; }
public LoadBalancingSettingsParametersArgs()
{
}
}
}
| 32.463415 | 100 | 0.655147 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Cdn/V20200901/Inputs/LoadBalancingSettingsParametersArgs.cs | 1,331 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
/*LCPI*/using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
//LCPI: using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
using CA = System.Diagnostics.CodeAnalysis;
/*LCPI*/ using Microsoft.EntityFrameworkCore;
/*LCPI*/ using Microsoft.EntityFrameworkCore.Query;
/*LCPI*/ using Microsoft.EntityFrameworkCore.Query.Internal;
#nullable enable
namespace Lcpi.EXT.Microsoft.EntityFrameworkCore.Query
{
/// <summary>
/// <para>
/// A class that processes a SQL tree based on nullability of nodes to apply null semantics in use and
/// optimize it based on parameter values.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
/*LCPI: public*/ class SqlNullabilityProcessor
{
private readonly List<ColumnExpression> _nonNullableColumns;
private readonly List<ColumnExpression> _nullValueColumns;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
private bool _canCache;
//----------------------------------------------------------------
private readonly RelationalTypeMapping _lcpi_typeMappingForBool;
private readonly SqlExpression _lcpi_expr_BOOL_FALSE;
private readonly SqlExpression _lcpi_expr_BOOL_TRUE;
//----------------------------------------------------------------
protected enum LCPI__TransformationRule
{
AddNullConcatenationProtection =100,
};//enum LCPI__TransformationRule
//----------------------------------------------------------------
protected virtual bool LCPI__GetPermissionForTransformation(LCPI__TransformationRule optRule)
{
return true;
}//LCPI__GetPermissionForTransformation
//----------------------------------------------------------------
/// <summary>
/// Creates a new instance of the <see cref="SqlNullabilityProcessor" /> class.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this class. </param>
/// <param name="useRelationalNulls"> A bool value indicating whether relational null semantics are in use. </param>
public SqlNullabilityProcessor(
/*LCPI: [NotNull]*/ RelationalParameterBasedSqlProcessorDependencies dependencies,
bool useRelationalNulls)
{
Check.NotNull(dependencies, nameof(dependencies));
_sqlExpressionFactory = dependencies.SqlExpressionFactory;
UseRelationalNulls = useRelationalNulls;
_nonNullableColumns = new List<ColumnExpression>();
_nullValueColumns = new List<ColumnExpression>();
ParameterValues = null!;
_lcpi_typeMappingForBool
=Check.NotNull
(dependencies.TypeMappingSource.FindMapping(typeof(bool)),
nameof(_lcpi_typeMappingForBool));
_lcpi_expr_BOOL_FALSE
=Check.NotNull
(LCPI__Helper__SqlENodeFactory__Constant(false,_lcpi_typeMappingForBool),
nameof(_lcpi_expr_BOOL_FALSE));
_lcpi_expr_BOOL_TRUE
=Check.NotNull
(LCPI__Helper__SqlENodeFactory__Constant(true,_lcpi_typeMappingForBool),
nameof(_lcpi_expr_BOOL_TRUE));
}
/// <summary>
/// A bool value indicating whether relational null semantics are in use.
/// </summary>
protected virtual bool UseRelationalNulls { get; }
/// <summary>
/// Dictionary of current parameter values in use.
/// </summary>
protected virtual IReadOnlyDictionary<string, object?> ParameterValues { get; private set; }
/// <summary>
/// Processes a <see cref="SelectExpression" /> to apply null semantics and optimize it.
/// </summary>
/// <param name="selectExpression"> A select expression to process. </param>
/// <param name="parameterValues"> A dictionary of parameter values in use. </param>
/// <param name="canCache"> A bool value indicating whether the select expression can be cached. </param>
/// <returns> An optimized select expression. </returns>
public virtual SelectExpression Process(
/*LCPI: [NotNull]*/ SelectExpression selectExpression,
/*LCPI: [NotNull]*/ IReadOnlyDictionary<string, object?> parameterValues,
out bool canCache)
{
Check.NotNull(selectExpression, nameof(selectExpression));
Check.NotNull(parameterValues, nameof(parameterValues));
_canCache = true;
_nonNullableColumns.Clear();
_nullValueColumns.Clear();
ParameterValues = parameterValues;
var result = Visit(selectExpression);
canCache = _canCache;
return result;
}
/// <summary>
/// Marks the select expression being processed as cannot be cached.
/// </summary>
protected virtual void DoNotCache()
=> _canCache = false;
/// <summary>
/// Adds a column to non nullable columns list to further optimizations can take the column as non-nullable.
/// </summary>
/// <param name="columnExpression"> A column expression to add. </param>
protected virtual void AddNonNullableColumn(/*LCPI: [NotNull]*/ ColumnExpression columnExpression)
=> _nonNullableColumns.Add(Check.NotNull(columnExpression, nameof(columnExpression)));
/// <summary>
/// Visits a <see cref="TableExpressionBase" />.
/// </summary>
/// <param name="tableExpressionBase"> A table expression base to visit. </param>
/// <returns> An optimized table expression base. </returns>
protected virtual TableExpressionBase Visit(/*LCPI: [NotNull]*/ TableExpressionBase tableExpressionBase)
{
Check.NotNull(tableExpressionBase, nameof(tableExpressionBase));
switch (tableExpressionBase)
{
case CrossApplyExpression crossApplyExpression:
return crossApplyExpression.Update(Visit(crossApplyExpression.Table));
case CrossJoinExpression crossJoinExpression:
return crossJoinExpression.Update(Visit(crossJoinExpression.Table));
case ExceptExpression exceptExpression:
{
var source1 = Visit(exceptExpression.Source1);
var source2 = Visit(exceptExpression.Source2);
return exceptExpression.Update(source1, source2);
}
case FromSqlExpression fromSqlExpression:
return fromSqlExpression;
case InnerJoinExpression innerJoinExpression:
{
var newTable = Visit(innerJoinExpression.Table);
var newJoinPredicate = ProcessJoinPredicate(innerJoinExpression.JoinPredicate);
return TryGetBoolConstantValue(newJoinPredicate) == true
? (TableExpressionBase)new CrossJoinExpression(newTable)
: innerJoinExpression.Update(newTable, newJoinPredicate);
}
case IntersectExpression intersectExpression:
{
var source1 = Visit(intersectExpression.Source1);
var source2 = Visit(intersectExpression.Source2);
return intersectExpression.Update(source1, source2);
}
case LeftJoinExpression leftJoinExpression:
{
var newTable = Visit(leftJoinExpression.Table);
var newJoinPredicate = ProcessJoinPredicate(leftJoinExpression.JoinPredicate);
return leftJoinExpression.Update(newTable, newJoinPredicate);
}
case OuterApplyExpression outerApplyExpression:
return outerApplyExpression.Update(Visit(outerApplyExpression.Table));
case SelectExpression selectExpression:
return Visit(selectExpression);
case TableValuedFunctionExpression tableValuedFunctionExpression:
{
var arguments = new List<SqlExpression>();
foreach (var argument in tableValuedFunctionExpression.Arguments)
{
arguments.Add(Visit(argument, out _));
}
return tableValuedFunctionExpression.Update(arguments);
}
case TableExpression tableExpression:
return tableExpression;
case UnionExpression unionExpression:
{
var source1 = Visit(unionExpression.Source1);
var source2 = Visit(unionExpression.Source2);
return unionExpression.Update(source1, source2);
}
default:
throw new InvalidOperationException(
RelationalStrings.UnhandledExpressionInVisitor(
tableExpressionBase, tableExpressionBase.GetType(), nameof(SqlNullabilityProcessor)));
}
}
/// <summary>
/// Visits a <see cref="SelectExpression" />.
/// </summary>
/// <param name="selectExpression"> A select expression to visit. </param>
/// <returns> An optimized select expression. </returns>
protected virtual SelectExpression Visit(/*LCPI: [NotNull]*/ SelectExpression selectExpression)
{
Check.NotNull(selectExpression, nameof(selectExpression));
var changed = false;
var projections = (List<ProjectionExpression>)selectExpression.Projection;
for (var i = 0; i < selectExpression.Projection.Count; i++)
{
var item = selectExpression.Projection[i];
var projection = item.Update(Visit(item.Expression, out _));
if (projection != item
&& projections == selectExpression.Projection)
{
projections = new List<ProjectionExpression>();
for (var j = 0; j < i; j++)
{
projections.Add(selectExpression.Projection[j]);
}
changed = true;
}
if (projections != selectExpression.Projection)
{
projections.Add(projection);
}
}
var tables = (List<TableExpressionBase>)selectExpression.Tables;
for (var i = 0; i < selectExpression.Tables.Count; i++)
{
var item = selectExpression.Tables[i];
var table = Visit(item);
if (table != item
&& tables == selectExpression.Tables)
{
tables = new List<TableExpressionBase>();
for (var j = 0; j < i; j++)
{
tables.Add(selectExpression.Tables[j]);
}
changed = true;
}
if (tables != selectExpression.Tables)
{
tables.Add(table);
}
}
var predicate = Visit(selectExpression.Predicate, allowOptimizedExpansion: true, out _);
changed |= predicate != selectExpression.Predicate;
if (TryGetBoolConstantValue(predicate) == true)
{
predicate = null;
changed = true;
}
var groupBy = (List<SqlExpression>)selectExpression.GroupBy;
for (var i = 0; i < selectExpression.GroupBy.Count; i++)
{
var item = selectExpression.GroupBy[i];
var groupingKey = Visit(item, out _);
if (groupingKey != item
&& groupBy == selectExpression.GroupBy)
{
groupBy = new List<SqlExpression>();
for (var j = 0; j < i; j++)
{
groupBy.Add(selectExpression.GroupBy[j]);
}
changed = true;
}
if (groupBy != selectExpression.GroupBy)
{
groupBy.Add(groupingKey);
}
}
var having = Visit(selectExpression.Having, allowOptimizedExpansion: true, out _);
changed |= having != selectExpression.Having;
if (TryGetBoolConstantValue(having) == true)
{
having = null;
changed = true;
}
var orderings = (List<OrderingExpression>)selectExpression.Orderings;
for (var i = 0; i < selectExpression.Orderings.Count; i++)
{
var item = selectExpression.Orderings[i];
var ordering = item.Update(Visit(item.Expression, out _));
if (ordering != item
&& orderings == selectExpression.Orderings)
{
orderings = new List<OrderingExpression>();
for (var j = 0; j < i; j++)
{
orderings.Add(selectExpression.Orderings[j]);
}
changed = true;
}
if (orderings != selectExpression.Orderings)
{
orderings.Add(ordering);
}
}
var offset = Visit(selectExpression.Offset, out _);
changed |= offset != selectExpression.Offset;
var limit = Visit(selectExpression.Limit, out _);
changed |= limit != selectExpression.Limit;
return changed
? selectExpression.Update(
projections, tables, predicate, groupBy, having, orderings, limit, offset)
: selectExpression;
}
/// <summary>
/// Visits a <see cref="SqlExpression" /> and computes its nullability.
/// </summary>
/// <param name="sqlExpression"> A sql expression to visit. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
[return: CA.NotNullIfNotNull("sqlExpression")]
protected virtual SqlExpression? Visit(/*LCPI: [CanBeNull]*/ SqlExpression? sqlExpression, out bool nullable)
=> Visit(sqlExpression, allowOptimizedExpansion: false, out nullable);
/// <summary>
/// Visits a <see cref="SqlExpression" /> and computes its nullability.
/// </summary>
/// <param name="sqlExpression"> A sql expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
[return: CA.NotNullIfNotNull("sqlExpression")]
protected virtual SqlExpression? Visit(/*LCPI: [CanBeNull]*/ SqlExpression? sqlExpression, bool allowOptimizedExpansion, out bool nullable)
=> Visit(sqlExpression, allowOptimizedExpansion, preserveColumnNullabilityInformation: false, out nullable);
[return: CA.NotNullIfNotNull("sqlExpression")]
private SqlExpression? Visit(
/*LCPI: [CanBeNull]*/ SqlExpression? sqlExpression,
bool allowOptimizedExpansion,
bool preserveColumnNullabilityInformation,
out bool nullable)
{
if (sqlExpression == null)
{
nullable = false;
return sqlExpression;
}
var nonNullableColumnsCount = _nonNullableColumns.Count;
var nullValueColumnsCount = _nullValueColumns.Count;
var result = sqlExpression switch
{
CaseExpression caseExpression
=> VisitCase(caseExpression, allowOptimizedExpansion, out nullable),
CollateExpression collateExpression
=> VisitCollate(collateExpression, allowOptimizedExpansion, out nullable),
ColumnExpression columnExpression
=> VisitColumn(columnExpression, allowOptimizedExpansion, out nullable),
DistinctExpression distinctExpression
=> VisitDistinct(distinctExpression, allowOptimizedExpansion, out nullable),
ExistsExpression existsExpression
=> VisitExists(existsExpression, allowOptimizedExpansion, out nullable),
InExpression inExpression
=> VisitIn(inExpression, allowOptimizedExpansion, out nullable),
LikeExpression likeExpression
=> VisitLike(likeExpression, allowOptimizedExpansion, out nullable),
RowNumberExpression rowNumberExpression
=> VisitRowNumber(rowNumberExpression, allowOptimizedExpansion, out nullable),
ScalarSubqueryExpression scalarSubqueryExpression
=> VisitScalarSubquery(scalarSubqueryExpression, allowOptimizedExpansion, out nullable),
SqlBinaryExpression sqlBinaryExpression
=> VisitSqlBinary(sqlBinaryExpression, allowOptimizedExpansion, out nullable),
SqlConstantExpression sqlConstantExpression
=> VisitSqlConstant(sqlConstantExpression, allowOptimizedExpansion, out nullable),
SqlFragmentExpression sqlFragmentExpression
=> VisitSqlFragment(sqlFragmentExpression, allowOptimizedExpansion, out nullable),
SqlFunctionExpression sqlFunctionExpression
=> VisitSqlFunction(sqlFunctionExpression, allowOptimizedExpansion, out nullable),
SqlParameterExpression sqlParameterExpression
=> VisitSqlParameter(sqlParameterExpression, allowOptimizedExpansion, out nullable),
SqlUnaryExpression sqlUnaryExpression
=> VisitSqlUnary(sqlUnaryExpression, allowOptimizedExpansion, out nullable),
_ => VisitCustomSqlExpression(sqlExpression, allowOptimizedExpansion, out nullable)
};
if (!preserveColumnNullabilityInformation)
{
RestoreNonNullableColumnsList(nonNullableColumnsCount);
RestoreNullValueColumnsList(nullValueColumnsCount);
}
return result;
}
/// <summary>
/// Visits a custom <see cref="SqlExpression" /> added by providers and computes its nullability.
/// </summary>
/// <param name="sqlExpression"> A sql expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitCustomSqlExpression(
/*LCPI: [NotNull]*/ SqlExpression sqlExpression,
bool allowOptimizedExpansion,
out bool nullable)
=> throw new InvalidOperationException(
RelationalStrings.UnhandledExpressionInVisitor(sqlExpression, sqlExpression.GetType(), nameof(SqlNullabilityProcessor)));
/// <summary>
/// Visits a <see cref="CaseExpression" /> and computes its nullability.
/// </summary>
/// <param name="caseExpression"> A case expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitCase(/*LCPI: [NotNull]*/ CaseExpression caseExpression, bool allowOptimizedExpansion, out bool nullable)
{
Check.NotNull(caseExpression, nameof(caseExpression));
// if there is no 'else' there is a possibility of null, when none of the conditions are met
// otherwise the result is nullable if any of the WhenClause results OR ElseResult is nullable
nullable = caseExpression.ElseResult == null;
var currentNonNullableColumnsCount = _nonNullableColumns.Count;
var currentNullValueColumnsCount = _nullValueColumns.Count;
var operand = Visit(caseExpression.Operand, out _);
var whenClauses = new List<CaseWhenClause>();
var testIsCondition = caseExpression.Operand == null;
var testEvaluatesToTrue = false;
foreach (var whenClause in caseExpression.WhenClauses)
{
// we can use column nullability information we got from visiting Test, in the Result
var test = Visit(whenClause.Test, allowOptimizedExpansion: testIsCondition, preserveColumnNullabilityInformation: true, out _);
if (TryGetBoolConstantValue(test) is bool testConstantBool)
{
if (testConstantBool)
{
testEvaluatesToTrue = true;
}
else
{
// if test evaluates to 'false' we can remove the WhenClause
RestoreNonNullableColumnsList(currentNonNullableColumnsCount);
RestoreNullValueColumnsList(currentNullValueColumnsCount);
continue;
}
}
var newResult = Visit(whenClause.Result, out var resultNullable);
nullable |= resultNullable;
whenClauses.Add(new CaseWhenClause(test, newResult));
RestoreNonNullableColumnsList(currentNonNullableColumnsCount);
RestoreNullValueColumnsList(currentNonNullableColumnsCount);
// if test evaluates to 'true' we can remove every condition that comes after, including ElseResult
if (testEvaluatesToTrue)
{
break;
}
}
SqlExpression? elseResult = null;
if (!testEvaluatesToTrue)
{
elseResult = Visit(caseExpression.ElseResult, out var elseResultNullable);
nullable |= elseResultNullable;
}
RestoreNonNullableColumnsList(currentNonNullableColumnsCount);
RestoreNullValueColumnsList(currentNullValueColumnsCount);
// if there are no whenClauses left (e.g. their tests evaluated to false):
// - if there is Else block, return it
// - if there is no Else block, return null
if (whenClauses.Count == 0)
{
return elseResult ?? LCPI__Helper__SqlENodeFactory__Constant(null, caseExpression.TypeMapping);
}
// if there is only one When clause and it's test evaluates to 'true' AND there is no else block, simply return the result
return elseResult == null
&& whenClauses.Count == 1
&& TryGetBoolConstantValue(whenClauses[0].Test) == true
? whenClauses[0].Result
: caseExpression.Update(operand, whenClauses, elseResult);
}
/// <summary>
/// Visits a <see cref="CollateExpression" /> and computes its nullability.
/// </summary>
/// <param name="collateExpression"> A collate expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitCollate(
/*LCPI: [NotNull]*/ CollateExpression collateExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(collateExpression, nameof(collateExpression));
return collateExpression.Update(Visit(collateExpression.Operand, out nullable));
}
/// <summary>
/// Visits a <see cref="ColumnExpression" /> and computes its nullability.
/// </summary>
/// <param name="columnExpression"> A column expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitColumn(
/*LCPI: [NotNull]*/ ColumnExpression columnExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(columnExpression, nameof(columnExpression));
nullable = columnExpression.IsNullable && !_nonNullableColumns.Contains(columnExpression);
return columnExpression;
}
/// <summary>
/// Visits a <see cref="DistinctExpression" /> and computes its nullability.
/// </summary>
/// <param name="distinctExpression"> A collate expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitDistinct(
/*LCPI: [NotNull]*/ DistinctExpression distinctExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(distinctExpression, nameof(distinctExpression));
return distinctExpression.Update(Visit(distinctExpression.Operand, out nullable));
}
/// <summary>
/// Visits an <see cref="ExistsExpression" /> and computes its nullability.
/// </summary>
/// <param name="existsExpression"> An exists expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitExists(
/*LCPI: [NotNull]*/ ExistsExpression existsExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(existsExpression, nameof(existsExpression));
var subquery = Visit(existsExpression.Subquery);
nullable = false;
// if subquery has predicate which evaluates to false, we can simply return false
// if the exisits is negated we need to return true instead
return TryGetBoolConstantValue(subquery.Predicate) == false
? LCPI__Helper__SqlENodeFactory__BoolConstant(existsExpression.IsNegated)
: existsExpression.Update(subquery);
}
/// <summary>
/// Visits an <see cref="InExpression" /> and computes its nullability.
/// </summary>
/// <param name="inExpression"> An in expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitIn(/*LCPI: [NotNull]*/ InExpression inExpression, bool allowOptimizedExpansion, out bool nullable)
{
Check.NotNull(inExpression, nameof(inExpression));
var item = Visit(inExpression.Item, out var itemNullable);
if (inExpression.Subquery != null)
{
var subquery = Visit(inExpression.Subquery);
// a IN (SELECT * FROM table WHERE false) => false
if (TryGetBoolConstantValue(subquery.Predicate) == false)
{
nullable = false;
return subquery.Predicate!;
}
// if item is not nullable, and subquery contains a non-nullable column we know the result can never be null
// note: in this case we could broaden the optimization if we knew the nullability of the projection
// but we don't keep that information and we want to avoid double visitation
nullable = !(!itemNullable
&& subquery.Projection.Count == 1
&& subquery.Projection[0].Expression is ColumnExpression columnProjection
&& !columnProjection.IsNullable);
return inExpression.Update(item, values: null, subquery);
}
// for relational null semantics we don't need to extract null values from the array
if (UseRelationalNulls
|| !(inExpression.Values is SqlConstantExpression || inExpression.Values is SqlParameterExpression))
{
var (valuesExpression, valuesList, _) = ProcessInExpressionValues(inExpression.Values!, extractNullValues: false);
nullable = false;
return valuesList.Count == 0
? LCPI__Helper__SqlENodeFactory__BoolConstant(false)
: SimplifyInExpression(
inExpression.Update(item, valuesExpression, subquery: null),
valuesExpression,
valuesList);
}
// for c# null semantics we need to remove nulls from Values and add IsNull/IsNotNull when necessary
var (inValuesExpression, inValuesList, hasNullValue) = ProcessInExpressionValues(inExpression.Values, extractNullValues: true);
// either values array is empty or only contains null
if (inValuesList.Count == 0)
{
nullable = false;
// a IN () -> false
// non_nullable IN (NULL) -> false
// a NOT IN () -> true
// non_nullable NOT IN (NULL) -> true
// nullable IN (NULL) -> nullable IS NULL
// nullable NOT IN (NULL) -> nullable IS NOT NULL
return !hasNullValue || !itemNullable
? LCPI__Helper__SqlENodeFactory__BoolConstant(inExpression.IsNegated)
: inExpression.IsNegated
? LCPI__Helper__SqlENodeFactory__IsNotNull(item)
: LCPI__Helper__SqlENodeFactory__IsNull(item);
}
var simplifiedInExpression = SimplifyInExpression(
inExpression.Update(item, inValuesExpression, subquery: null),
inValuesExpression,
inValuesList);
if (!itemNullable
|| (allowOptimizedExpansion && !inExpression.IsNegated && !hasNullValue))
{
nullable = false;
// non_nullable IN (1, 2) -> non_nullable IN (1, 2)
// non_nullable IN (1, 2, NULL) -> non_nullable IN (1, 2)
// non_nullable NOT IN (1, 2) -> non_nullable NOT IN (1, 2)
// non_nullable NOT IN (1, 2, NULL) -> non_nullable NOT IN (1, 2)
// nullable IN (1, 2) -> nullable IN (1, 2) (optimized)
return simplifiedInExpression;
}
nullable = false;
// nullable IN (1, 2) -> nullable IN (1, 2) AND nullable IS NOT NULL (full)
// nullable IN (1, 2, NULL) -> nullable IN (1, 2) OR nullable IS NULL (full)
// nullable NOT IN (1, 2) -> nullable NOT IN (1, 2) OR nullable IS NULL (full)
// nullable NOT IN (1, 2, NULL) -> nullable NOT IN (1, 2) AND nullable IS NOT NULL (full)
if(inExpression.IsNegated == hasNullValue)
{
return LCPI__Helper__SqlENodeFactory__AndAlso(
simplifiedInExpression,
LCPI__Helper__SqlENodeFactory__IsNotNull(item));
}
return LCPI__Helper__SqlENodeFactory__OrElse(
simplifiedInExpression,
LCPI__Helper__SqlENodeFactory__IsNull(item));
(SqlConstantExpression ProcessedValuesExpression, List<object?> ProcessedValuesList, bool HasNullValue)
ProcessInExpressionValues(SqlExpression valuesExpression, bool extractNullValues)
{
var inValues = new List<object?>();
var hasNullValue = false;
RelationalTypeMapping? typeMapping = null;
IEnumerable? values = null;
if (valuesExpression is SqlConstantExpression sqlConstant)
{
typeMapping = sqlConstant.TypeMapping;
values = (IEnumerable)sqlConstant.Value!;
}
else if (valuesExpression is SqlParameterExpression sqlParameter)
{
DoNotCache();
typeMapping = sqlParameter.TypeMapping;
values = (IEnumerable?)ParameterValues[sqlParameter.Name];
if (values == null)
{
throw new NullReferenceException();
}
}
foreach (var value in values!)
{
if (value == null && extractNullValues)
{
hasNullValue = true;
continue;
}
inValues.Add(value);
}
var processedValuesExpression = LCPI__Helper__SqlENodeFactory__Constant(inValues, typeMapping);
return (processedValuesExpression, inValues, hasNullValue);
}
SqlExpression SimplifyInExpression(
InExpression inExpression,
SqlConstantExpression inValuesExpression,
List<object?> inValuesList)
{
return inValuesList.Count == 1
? inExpression.IsNegated
? LCPI__Helper__SqlENodeFactory__NotEqual(
inExpression.Item,
LCPI__Helper__SqlENodeFactory__Constant(inValuesList[0], inValuesExpression.TypeMapping))
: LCPI__Helper__SqlENodeFactory__Equal(
inExpression.Item,
LCPI__Helper__SqlENodeFactory__Constant(inValuesList[0], inExpression.Values!.TypeMapping))
: inExpression;
}
}
/// <summary>
/// Visits a <see cref="LikeExpression" /> and computes its nullability.
/// </summary>
/// <param name="likeExpression"> A like expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitLike(/*LCPI: [NotNull]*/ LikeExpression likeExpression, bool allowOptimizedExpansion, out bool nullable)
{
Check.NotNull(likeExpression, nameof(likeExpression));
var match = Visit(likeExpression.Match, out var matchNullable);
var pattern = Visit(likeExpression.Pattern, out var patternNullable);
var escapeChar = Visit(likeExpression.EscapeChar, out var escapeCharNullable);
nullable = matchNullable || patternNullable || escapeCharNullable;
return likeExpression.Update(match, pattern, escapeChar);
}
/// <summary>
/// Visits a <see cref="RowNumberExpression" /> and computes its nullability.
/// </summary>
/// <param name="rowNumberExpression"> A row number expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitRowNumber(
/*LCPI: [NotNull]*/ RowNumberExpression rowNumberExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(rowNumberExpression, nameof(rowNumberExpression));
var changed = false;
var partitions = new List<SqlExpression>();
foreach (var partition in rowNumberExpression.Partitions)
{
var newPartition = Visit(partition, out _);
changed |= newPartition != partition;
partitions.Add(newPartition);
}
var orderings = new List<OrderingExpression>();
foreach (var ordering in rowNumberExpression.Orderings)
{
var newOrdering = ordering.Update(Visit(ordering.Expression, out _));
changed |= newOrdering != ordering;
orderings.Add(newOrdering);
}
nullable = false;
return changed
? rowNumberExpression.Update(partitions, orderings)
: rowNumberExpression;
}
/// <summary>
/// Visits a <see cref="ScalarSubqueryExpression" /> and computes its nullability.
/// </summary>
/// <param name="scalarSubqueryExpression"> A scalar subquery expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitScalarSubquery(
/*LCPI: [NotNull]*/ ScalarSubqueryExpression scalarSubqueryExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(scalarSubqueryExpression, nameof(scalarSubqueryExpression));
nullable = true;
return scalarSubqueryExpression.Update(Visit(scalarSubqueryExpression.Subquery));
}
/// <summary>
/// Visits a <see cref="SqlBinaryExpression" /> and computes its nullability.
/// </summary>
/// <param name="sqlBinaryExpression"> A sql binary expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitSqlBinary(
/*LCPI: [NotNull]*/ SqlBinaryExpression sqlBinaryExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(sqlBinaryExpression, nameof(sqlBinaryExpression));
var optimize = allowOptimizedExpansion;
allowOptimizedExpansion = allowOptimizedExpansion
&& (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso
|| sqlBinaryExpression.OperatorType == ExpressionType.OrElse);
var currentNonNullableColumnsCount = _nonNullableColumns.Count;
var currentNullValueColumnsCount = _nullValueColumns.Count;
var left = Visit(sqlBinaryExpression.Left, allowOptimizedExpansion, preserveColumnNullabilityInformation: true, out var leftNullable);
var leftNonNullableColumns = _nonNullableColumns.Skip(currentNonNullableColumnsCount).ToList();
var leftNullValueColumns = _nullValueColumns.Skip(currentNullValueColumnsCount).ToList();
if (sqlBinaryExpression.OperatorType != ExpressionType.AndAlso)
{
RestoreNonNullableColumnsList(currentNonNullableColumnsCount);
}
if (sqlBinaryExpression.OperatorType == ExpressionType.OrElse)
{
// in case of OrElse, we can assume all null value columns on the left side can be treated as non-nullable on the right
// e.g. (a == null || b == null) || f(a, b)
// f(a, b) will only be executed if a != null and b != null
_nonNullableColumns.AddRange(_nullValueColumns.Skip(currentNullValueColumnsCount).ToList());
}
else
{
RestoreNullValueColumnsList(currentNullValueColumnsCount);
}
var right = Visit(sqlBinaryExpression.Right, allowOptimizedExpansion, preserveColumnNullabilityInformation: true, out var rightNullable);
if (sqlBinaryExpression.OperatorType == ExpressionType.OrElse)
{
var intersect = leftNonNullableColumns.Intersect(_nonNullableColumns.Skip(currentNonNullableColumnsCount)).ToList();
RestoreNonNullableColumnsList(currentNonNullableColumnsCount);
_nonNullableColumns.AddRange(intersect);
}
else if (sqlBinaryExpression.OperatorType != ExpressionType.AndAlso)
{
// in case of AndAlso we already have what we need as the column information propagates from left to right
RestoreNonNullableColumnsList(currentNonNullableColumnsCount);
}
if (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso)
{
var intersect = leftNullValueColumns.Intersect(_nullValueColumns.Skip(currentNullValueColumnsCount)).ToList();
RestoreNullValueColumnsList(currentNullValueColumnsCount);
_nullValueColumns.AddRange(intersect);
}
else if (sqlBinaryExpression.OperatorType != ExpressionType.OrElse)
{
RestoreNullValueColumnsList(currentNullValueColumnsCount);
}
// nullableStringColumn + a -> COALESCE(nullableStringColumn, "") + a
if (sqlBinaryExpression.OperatorType == ExpressionType.Add
&& sqlBinaryExpression.Type == typeof(string))
{
/*LCPI CODE:*/ if (!this.LCPI__GetPermissionForTransformation(LCPI__TransformationRule.AddNullConcatenationProtection))
/*LCPI CODE:*/ {
/*LCPI CODE:*/ nullable = true;
/*LCPI CODE:*/
/*LCPI CODE:*/ return sqlBinaryExpression.Update(left, right);
/*LCPI CODE:*/ }//if
if (leftNullable)
{
left = AddNullConcatenationProtection(left, sqlBinaryExpression.TypeMapping!);
}
if (rightNullable)
{
right = AddNullConcatenationProtection(right, sqlBinaryExpression.TypeMapping!);
}
nullable = false;
return sqlBinaryExpression.Update(left, right);
}
if (sqlBinaryExpression.OperatorType == ExpressionType.Equal
|| sqlBinaryExpression.OperatorType == ExpressionType.NotEqual)
{
var updated = sqlBinaryExpression.Update(left, right);
var optimized = OptimizeComparison(
updated,
left,
right,
leftNullable,
rightNullable,
out nullable);
if (optimized is SqlUnaryExpression optimizedUnary
&& optimizedUnary.Operand is ColumnExpression optimizedUnaryColumnOperand)
{
if (optimizedUnary.OperatorType == ExpressionType.NotEqual)
{
_nonNullableColumns.Add(optimizedUnaryColumnOperand);
}
else if (optimizedUnary.OperatorType == ExpressionType.Equal)
{
_nullValueColumns.Add(optimizedUnaryColumnOperand);
}
}
// we assume that NullSemantics rewrite is only needed (on the current level)
// if the optimization didn't make any changes.
// Reason is that optimization can/will change the nullability of the resulting expression
// and that inforation is not tracked/stored anywhere
// so we can no longer rely on nullabilities that we computed earlier (leftNullable, rightNullable)
// when performing null semantics rewrite.
// It should be fine because current optimizations *radically* change the expression
// (e.g. binary -> unary, or binary -> constant)
// but we need to pay attention in the future if we introduce more subtle transformations here
if (optimized.Equals(updated)
&& (leftNullable || rightNullable)
&& !UseRelationalNulls)
{
var rewriteNullSemanticsResult = RewriteNullSemantics(
updated,
updated.Left,
updated.Right,
leftNullable,
rightNullable,
optimize,
out nullable);
return rewriteNullSemanticsResult;
}
return optimized;
}
nullable = leftNullable || rightNullable;
var result = sqlBinaryExpression.Update(left, right);
// LCPI: return result is SqlBinaryExpression sqlBinaryResult
// LCPI: && (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso
// LCPI: || sqlBinaryExpression.OperatorType == ExpressionType.OrElse)
// LCPI: ? SimplifyLogicalSqlBinaryExpression(sqlBinaryResult)
// LCPI: : result;
/*LCPI*/ if (result is SqlBinaryExpression sqlBinaryResult)
/*LCPI*/ {
/*LCPI*/ if(sqlBinaryExpression.OperatorType == ExpressionType.AndAlso)
/*LCPI*/ {
/*LCPI*/ return LCPI__Make_LogicalAnd
/*LCPI*/ (sqlBinaryResult.Left,
/*LCPI*/ sqlBinaryResult.Right,
/*LCPI*/ new LCPI__tagPreparedResult(sqlBinaryResult));
/*LCPI*/ }
/*LCPI*/
/*LCPI*/ if(sqlBinaryExpression.OperatorType == ExpressionType.OrElse)
/*LCPI*/ {
/*LCPI*/ return LCPI__Make_LogicalOr
/*LCPI*/ (sqlBinaryResult.Left,
/*LCPI*/ sqlBinaryResult.Right,
/*LCPI*/ new LCPI__tagPreparedResult(sqlBinaryResult));
/*LCPI*/ }
/*LCPI*/
/*LCPI*/ return sqlBinaryResult;
/*LCPI*/ }//if
/*LCPI*/
/*LCPI*/ return result;
SqlExpression AddNullConcatenationProtection(SqlExpression argument, RelationalTypeMapping typeMapping)
=> argument is SqlConstantExpression || argument is SqlParameterExpression
? LCPI__Helper__SqlENodeFactory__Constant(string.Empty, typeMapping)
: LCPI__Helper__SqlENodeFactory__Coalesce(argument, LCPI__Helper__SqlENodeFactory__Constant(string.Empty, typeMapping));
}
/// <summary>
/// Visits a <see cref="SqlConstantExpression" /> and computes its nullability.
/// </summary>
/// <param name="sqlConstantExpression"> A sql constant expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitSqlConstant(
/*LCPI: [NotNull]*/ SqlConstantExpression sqlConstantExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(sqlConstantExpression, nameof(sqlConstantExpression));
nullable = sqlConstantExpression.Value == null;
return sqlConstantExpression;
}
/// <summary>
/// Visits a <see cref="SqlFragmentExpression" /> and computes its nullability.
/// </summary>
/// <param name="sqlFragmentExpression"> A sql fragment expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitSqlFragment(
/*LCPI: [NotNull]*/ SqlFragmentExpression sqlFragmentExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(sqlFragmentExpression, nameof(sqlFragmentExpression));
nullable = false;
return sqlFragmentExpression;
}
/// <summary>
/// Visits a <see cref="SqlFunctionExpression" /> and computes its nullability.
/// </summary>
/// <param name="sqlFunctionExpression"> A sql function expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitSqlFunction(
/*LCPI: [NotNull]*/ SqlFunctionExpression sqlFunctionExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
/*LCPI*/ Check.NotNull(sqlFunctionExpression, nameof(sqlFunctionExpression));
/*LCPI*/
/*LCPI*/ var instance = Visit(sqlFunctionExpression.Instance, out _);
/*LCPI*/
/*LCPI*/ SqlExpression resultExpression;
/*LCPI*/
/*LCPI*/ if (sqlFunctionExpression.IsNiladic)
/*LCPI*/ {
/*LCPI*/ resultExpression = sqlFunctionExpression.Update(instance, sqlFunctionExpression.Arguments);
/*LCPI*/ }
/*LCPI*/ else
/*LCPI*/ {
/*LCPI*/ var arguments = new SqlExpression[sqlFunctionExpression.Arguments.Count];
/*LCPI*/ for (var i = 0; i < arguments.Length; i++)
/*LCPI*/ {
/*LCPI*/ arguments[i] = Visit(sqlFunctionExpression.Arguments[i], out _);
/*LCPI*/ }
/*LCPI*/
/*LCPI*/ resultExpression = sqlFunctionExpression.Update(instance, arguments);
/*LCPI*/ }
/*LCPI*/
/*LCPI*/ if (resultExpression is SqlFunctionExpression updatedFunctionExpresion)
/*LCPI*/ {
/*LCPI*/ if (LCPI__Helper__TestBuiltInFunctionName(updatedFunctionExpresion, "SUM"))
/*LCPI*/ {
/*LCPI*/ resultExpression = LCPI__Helper__MakeCoalesceForValueAndZero
/*LCPI*/ (updatedFunctionExpresion);
/*LCPI*/ }//if - SUM
/*LCPI*/ }//if - updatedFunctionExpresion
/*LCPI*/
/*LCPI*/ Check.NotNull(resultExpression, nameof(resultExpression));
/*LCPI*/
/*LCPI*/ nullable = Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Core.SQL.Core_SQL__TestNullable.TestNullable
/*LCPI*/ (resultExpression);
/*LCPI*/
/*LCPI*/ return resultExpression;
}
private static bool LCPI__Helper__TestBuiltInFunctionName(SqlFunctionExpression sqlFunctionExpression,
string functionName)
{
Debug.Assert(!Object.ReferenceEquals(sqlFunctionExpression, null));
Debug.Assert(!Object.ReferenceEquals(functionName, null));
Debug.Assert(functionName.Length > 0);
if (!sqlFunctionExpression.IsBuiltIn)
return false;
if (!string.Equals(sqlFunctionExpression.Name, functionName, StringComparison.OrdinalIgnoreCase))
return false;
return true;
}//LCPI__Helper__TestBuiltInFunctionName
private static System.Type LCPI__Helper__GetClrType(SqlExpression sqlExpression)
{
Debug.Assert(!Object.ReferenceEquals(sqlExpression,null));
const string c_bugcheck_src
= "SqlNullabilityProcessor::LCPI__Helper__GetClrType";
if (Object.ReferenceEquals(sqlExpression.TypeMapping, null))
{
Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.ThrowBugCheck.No_TypeMapping
(Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.ErrSourceID.EXT,
c_bugcheck_src,
"#001");
}
if (Object.ReferenceEquals(sqlExpression.TypeMapping!.ClrType, null))
{
Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.ThrowBugCheck.No_TypeMapping_ClrType
(Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.ErrSourceID.EXT,
c_bugcheck_src,
"#002");
}
return sqlExpression.TypeMapping!.ClrType!;
}//LCPI__Helper__GetClrType
private SqlExpression LCPI__Helper__MakeCoalesceForValueAndZero(SqlExpression sqlValue)
{
var clrType
= LCPI__Helper__GetClrType(sqlValue); //throw
System.Diagnostics.Debug.Assert(!Object.ReferenceEquals(clrType, null));
var zeroValue
= System.Convert.ChangeType(0,clrType);
var sqlConstantZero
= LCPI__Helper__SqlENodeFactory__Constant
(zeroValue,
sqlValue.TypeMapping);
System.Diagnostics.Debug.Assert(!Object.ReferenceEquals(sqlConstantZero, null));
return LCPI__Helper__SqlENodeFactory__Coalesce(
sqlValue,
sqlConstantZero,
sqlValue.TypeMapping);
}
/// <summary>
/// Visits a <see cref="SqlParameterExpression" /> and computes its nullability.
/// </summary>
/// <param name="sqlParameterExpression"> A sql parameter expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitSqlParameter(
/*LCPI: [NotNull]*/ SqlParameterExpression sqlParameterExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(sqlParameterExpression, nameof(sqlParameterExpression));
nullable = ParameterValues[sqlParameterExpression.Name] == null;
return nullable
? LCPI__Helper__SqlENodeFactory__Constant(null, sqlParameterExpression.TypeMapping)
: sqlParameterExpression;
}
/// <summary>
/// Visits a <see cref="SqlUnaryExpression" /> and computes its nullability.
/// </summary>
/// <param name="sqlUnaryExpression"> A sql unary expression to visit. </param>
/// <param name="allowOptimizedExpansion"> A bool value indicating if optimized expansion which considers null value as false value is allowed. </param>
/// <param name="nullable"> A bool value indicating whether the sql expression is nullable. </param>
/// <returns> An optimized sql expression. </returns>
protected virtual SqlExpression VisitSqlUnary(
/*LCPI: [NotNull]*/ SqlUnaryExpression sqlUnaryExpression,
bool allowOptimizedExpansion,
out bool nullable)
{
Check.NotNull(sqlUnaryExpression, nameof(sqlUnaryExpression));
var operand = Visit(sqlUnaryExpression.Operand, out var operandNullable);
var updated = sqlUnaryExpression.Update(operand);
if (sqlUnaryExpression.OperatorType == ExpressionType.Equal
|| sqlUnaryExpression.OperatorType == ExpressionType.NotEqual)
{
//LCPI: var result = ProcessNullNotNull(updated, operandNullable);
/*LCPI*/var result = LCPI__Make_NullNotNull
/*LCPI*/ (updated.OperatorType,
/*LCPI*/ updated.Operand,
/*LCPI*/ operandNullable,
/*LCPI*/ new LCPI__tagPreparedResult(updated));
// result of IsNull/IsNotNull can never be null
nullable = false;
if (result is SqlUnaryExpression resultUnary
&& resultUnary.Operand is ColumnExpression resultColumnOperand)
{
if (resultUnary.OperatorType == ExpressionType.NotEqual)
{
_nonNullableColumns.Add(resultColumnOperand);
}
else if (resultUnary.OperatorType == ExpressionType.Equal)
{
_nullValueColumns.Add(resultColumnOperand);
}
}
return result;
}
nullable = operandNullable;
return !operandNullable && sqlUnaryExpression.OperatorType == ExpressionType.Not
? LCPI__Make_NonNullableNot(updated.Operand,new LCPI__tagPreparedResult(updated))
: updated;
}
private static bool? TryGetBoolConstantValue(SqlExpression? expression)
=> expression is SqlConstantExpression constantExpression
&& constantExpression.Value is bool boolValue
? boolValue
: (bool?)null;
private void RestoreNonNullableColumnsList(int counter)
{
if (counter < _nonNullableColumns.Count)
{
_nonNullableColumns.RemoveRange(counter, _nonNullableColumns.Count - counter);
}
}
private void RestoreNullValueColumnsList(int counter)
{
if (counter < _nullValueColumns.Count)
{
_nullValueColumns.RemoveRange(counter, _nullValueColumns.Count - counter);
}
}
private SqlExpression ProcessJoinPredicate(SqlExpression predicate)
{
if (predicate is SqlBinaryExpression sqlBinaryExpression)
{
if (sqlBinaryExpression.OperatorType == ExpressionType.Equal)
{
var left = Visit(sqlBinaryExpression.Left, allowOptimizedExpansion: true, out var leftNullable);
var right = Visit(sqlBinaryExpression.Right, allowOptimizedExpansion: true, out var rightNullable);
var result = OptimizeComparison(
sqlBinaryExpression.Update(left, right),
left,
right,
leftNullable,
rightNullable,
out _);
return result;
}
if (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso
|| sqlBinaryExpression.OperatorType == ExpressionType.NotEqual
|| sqlBinaryExpression.OperatorType == ExpressionType.GreaterThan
|| sqlBinaryExpression.OperatorType == ExpressionType.GreaterThanOrEqual
|| sqlBinaryExpression.OperatorType == ExpressionType.LessThan
|| sqlBinaryExpression.OperatorType == ExpressionType.LessThanOrEqual)
{
return Visit(sqlBinaryExpression, allowOptimizedExpansion: true, out _);
}
}
throw new InvalidOperationException(
RelationalStrings.UnhandledExpressionInVisitor(predicate, predicate.GetType(), nameof(SqlNullabilityProcessor)));
}
private SqlExpression OptimizeComparison(
SqlBinaryExpression sqlBinaryExpression,
SqlExpression left,
SqlExpression right,
bool leftNullable,
bool rightNullable,
out bool nullable)
{
/*LCPI*/ Debug.Assert(!Object.ReferenceEquals(sqlBinaryExpression,null));
/*LCPI*/ Debug.Assert(!Object.ReferenceEquals(left,null));
/*LCPI*/ Debug.Assert(!Object.ReferenceEquals(right,null));
/*LCPI*/
/*LCPI*/ Debug.Assert(sqlBinaryExpression.OperatorType == ExpressionType.Equal ||
/*LCPI*/ sqlBinaryExpression.OperatorType == ExpressionType.NotEqual);
var leftNullValue = leftNullable && (left is SqlConstantExpression || left is SqlParameterExpression);
var rightNullValue = rightNullable && (right is SqlConstantExpression || right is SqlParameterExpression);
// a == null -> a IS NULL
// a != null -> a IS NOT NULL
if (rightNullValue)
{
//LCPI: var result = sqlBinaryExpression.OperatorType == ExpressionType.Equal
//LCPI: ? ProcessNullNotNull(_sqlExpressionFactory.IsNull(left), leftNullable)
//LCPI: : ProcessNullNotNull(_sqlExpressionFactory.IsNotNull(left), leftNullable);
/*LCPI*/ var result = LCPI__Make_NullNotNull
/*LCPI*/ (sqlBinaryExpression.OperatorType,
/*LCPI*/ left,
/*LCPI*/ leftNullable);
/*LCPI*/ Debug.Assert(!Object.ReferenceEquals(result, null));
nullable = false;
return result;
}
// null == a -> a IS NULL
// null != a -> a IS NOT NULL
if (leftNullValue)
{
//LCPI: var result = sqlBinaryExpression.OperatorType == ExpressionType.Equal
//LCPI: ? ProcessNullNotNull(_sqlExpressionFactory.IsNull(right), rightNullable)
//LCPI: : ProcessNullNotNull(_sqlExpressionFactory.IsNotNull(right), rightNullable);
/*LCPI*/ var result = LCPI__Make_NullNotNull
/*LCPI*/ (sqlBinaryExpression.OperatorType,
/*LCPI*/ right,
/*LCPI*/ rightNullable);
/*LCPI*/ Debug.Assert(!Object.ReferenceEquals(result, null));
nullable = false;
return result;
}
if (TryGetBoolConstantValue(right) is bool rightBoolValue
&& !leftNullable
&& left.TypeMapping!.Converter == null)
{
nullable = leftNullable;
// only correct in 2-value logic
// a == true -> a
// a == false -> !a
// a != true -> !a
// a != false -> a
return sqlBinaryExpression.OperatorType == ExpressionType.Equal ^ rightBoolValue
? LCPI__Make_NonNullableNot(left)
: left;
}
if (TryGetBoolConstantValue(left) is bool leftBoolValue
&& !rightNullable
&& right.TypeMapping!.Converter == null)
{
nullable = rightNullable;
// only correct in 2-value logic
// true == a -> a
// false == a -> !a
// true != a -> !a
// false != a -> a
return sqlBinaryExpression.OperatorType == ExpressionType.Equal ^ leftBoolValue
? LCPI__Make_NonNullableNot(right)
: right;
}
// only correct in 2-value logic
// a == a -> true
// a != a -> false
if (!leftNullable
&& left.Equals(right))
{
nullable = false;
return LCPI__Helper__SqlENodeFactory__BoolConstant(
sqlBinaryExpression.OperatorType == ExpressionType.Equal);
}
if (!leftNullable
&& !rightNullable
&& (sqlBinaryExpression.OperatorType == ExpressionType.Equal
|| sqlBinaryExpression.OperatorType == ExpressionType.NotEqual))
{
var leftUnary = left as SqlUnaryExpression;
var rightUnary = right as SqlUnaryExpression;
var leftNegated = IsLogicalNot(leftUnary);
var rightNegated = IsLogicalNot(rightUnary);
if (leftNegated)
{
left = leftUnary!.Operand;
}
if (rightNegated)
{
right = rightUnary!.Operand;
}
// a == b <=> !a == !b -> a == b
// !a == b <=> a == !b -> a != b
// a != b <=> !a != !b -> a != b
// !a != b <=> a != !b -> a == b
nullable = false;
return sqlBinaryExpression.OperatorType == ExpressionType.Equal ^ leftNegated == rightNegated
? LCPI__Helper__SqlENodeFactory__NotEqual(left, right)
: LCPI__Helper__SqlENodeFactory__Equal(left, right);
}
nullable = false;
return sqlBinaryExpression.Update(left, right);
}
private SqlExpression RewriteNullSemantics(
SqlBinaryExpression sqlBinaryExpression,
SqlExpression left,
SqlExpression right,
bool leftNullable,
bool rightNullable,
bool optimize,
out bool nullable)
{
var leftUnary = left as SqlUnaryExpression;
var rightUnary = right as SqlUnaryExpression;
var leftNegated = IsLogicalNot(leftUnary);
var rightNegated = IsLogicalNot(rightUnary);
if (leftNegated)
{
left = leftUnary!.Operand;
}
if (rightNegated)
{
right = rightUnary!.Operand;
}
//LCPI: var leftIsNull = ProcessNullNotNull(_sqlExpressionFactory.IsNull(left), leftNullable);
var leftIsNull = LCPI__Make_NullNotNull(ExpressionType.Equal, left, leftNullable);
var leftIsNotNull = LCPI__Make_NonNullableNot(leftIsNull);
//var rightIsNull = ProcessNullNotNull(_sqlExpressionFactory.IsNull(right), rightNullable);
var rightIsNull = LCPI__Make_NullNotNull(ExpressionType.Equal, right, rightNullable);
var rightIsNotNull = LCPI__Make_NonNullableNot(rightIsNull);
// optimized expansion which doesn't distinguish between null and false
if (optimize
&& sqlBinaryExpression.OperatorType == ExpressionType.Equal
&& !leftNegated
&& !rightNegated)
{
// when we use optimized form, the result can still be nullable
if (leftNullable && rightNullable)
{
nullable = true;
//LCPI: return SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(
//LCPI: _sqlExpressionFactory.Equal(left, right),
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(leftIsNull, rightIsNull))));
/*LCPI*/ return LCPI__Make_LogicalOr
/*LCPI*/ (LCPI__Helper__SqlENodeFactory__Equal(left, right),
/*LCPI*/ LCPI__Make_LogicalAnd
/*LCPI*/ (leftIsNull,
/*LCPI*/ rightIsNull));
}
if ((leftNullable && !rightNullable)
|| (!leftNullable && rightNullable))
{
nullable = true;
return LCPI__Helper__SqlENodeFactory__Equal(left, right);
}
}
// doing a full null semantics rewrite - removing all nulls from truth table
nullable = false;
if (sqlBinaryExpression.OperatorType == ExpressionType.Equal)
{
if (leftNullable && rightNullable)
{
// ?a == ?b <=> !(?a) == !(?b) -> [(a == b) && (a != null && b != null)] || (a == null && b == null))
// !(?a) == ?b <=> ?a == !(?b) -> [(a != b) && (a != null && b != null)] || (a == null && b == null)
return leftNegated == rightNegated
? ExpandNullableEqualNullable(left, right, leftIsNull, leftIsNotNull, rightIsNull, rightIsNotNull)
: ExpandNegatedNullableEqualNullable(left, right, leftIsNull, leftIsNotNull, rightIsNull, rightIsNotNull);
}
if (leftNullable && !rightNullable)
{
// ?a == b <=> !(?a) == !b -> (a == b) && (a != null)
// !(?a) == b <=> ?a == !b -> (a != b) && (a != null)
return leftNegated == rightNegated
? ExpandNullableEqualNonNullable(left, right, leftIsNotNull)
: ExpandNegatedNullableEqualNonNullable(left, right, leftIsNotNull);
}
if (rightNullable && !leftNullable)
{
// a == ?b <=> !a == !(?b) -> (a == b) && (b != null)
// !a == ?b <=> a == !(?b) -> (a != b) && (b != null)
return leftNegated == rightNegated
? ExpandNullableEqualNonNullable(left, right, rightIsNotNull)
: ExpandNegatedNullableEqualNonNullable(left, right, rightIsNotNull);
}
}
if (sqlBinaryExpression.OperatorType == ExpressionType.NotEqual)
{
if (leftNullable && rightNullable)
{
// ?a != ?b <=> !(?a) != !(?b) -> [(a != b) || (a == null || b == null)] && (a != null || b != null)
// !(?a) != ?b <=> ?a != !(?b) -> [(a == b) || (a == null || b == null)] && (a != null || b != null)
return leftNegated == rightNegated
? ExpandNullableNotEqualNullable(left, right, leftIsNull, leftIsNotNull, rightIsNull, rightIsNotNull)
: ExpandNegatedNullableNotEqualNullable(left, right, leftIsNull, leftIsNotNull, rightIsNull, rightIsNotNull);
}
if (leftNullable && !rightNullable)
{
// ?a != b <=> !(?a) != !b -> (a != b) || (a == null)
// !(?a) != b <=> ?a != !b -> (a == b) || (a == null)
return leftNegated == rightNegated
? ExpandNullableNotEqualNonNullable(left, right, leftIsNull)
: ExpandNegatedNullableNotEqualNonNullable(left, right, leftIsNull);
}
if (rightNullable && !leftNullable)
{
// a != ?b <=> !a != !(?b) -> (a != b) || (b == null)
// !a != ?b <=> a != !(?b) -> (a == b) || (b == null)
return leftNegated == rightNegated
? ExpandNullableNotEqualNonNullable(left, right, rightIsNull)
: ExpandNegatedNullableNotEqualNonNullable(left, right, rightIsNull);
}
}
return sqlBinaryExpression.Update(left, right);
}
//LCPI: private SqlExpression SimplifyLogicalSqlBinaryExpression(SqlBinaryExpression sqlBinaryExpression)
//LCPI: {
//LCPI: if (sqlBinaryExpression.Left is SqlUnaryExpression leftUnary
//LCPI: && sqlBinaryExpression.Right is SqlUnaryExpression rightUnary
//LCPI: && (leftUnary.OperatorType == ExpressionType.Equal || leftUnary.OperatorType == ExpressionType.NotEqual)
//LCPI: && (rightUnary.OperatorType == ExpressionType.Equal || rightUnary.OperatorType == ExpressionType.NotEqual)
//LCPI: && leftUnary.Operand.Equals(rightUnary.Operand))
//LCPI: {
//LCPI: // a is null || a is null -> a is null
//LCPI: // a is not null || a is not null -> a is not null
//LCPI: // a is null && a is null -> a is null
//LCPI: // a is not null && a is not null -> a is not null
//LCPI: // a is null || a is not null -> true
//LCPI: // a is null && a is not null -> false
//LCPI: return leftUnary.OperatorType == rightUnary.OperatorType
//LCPI: ? (SqlExpression)leftUnary
//LCPI: : _sqlExpressionFactory.Constant(
//LCPI: sqlBinaryExpression.OperatorType == ExpressionType.OrElse, sqlBinaryExpression.TypeMapping);
//LCPI: }
//LCPI:
//LCPI: // true && a -> a
//LCPI: // true || a -> true
//LCPI: // false && a -> false
//LCPI: // false || a -> a
//LCPI: if (sqlBinaryExpression.Left is SqlConstantExpression newLeftConstant
//LCPI: && newLeftConstant.Value is bool leftBoolValue)
//LCPI: {
//LCPI: return sqlBinaryExpression.OperatorType == ExpressionType.AndAlso
//LCPI: ? leftBoolValue
//LCPI: ? sqlBinaryExpression.Right
//LCPI: : newLeftConstant
//LCPI: : leftBoolValue
//LCPI: ? newLeftConstant
//LCPI: : sqlBinaryExpression.Right;
//LCPI: }
//LCPI:
//LCPI: if (sqlBinaryExpression.Right is SqlConstantExpression newRightConstant
//LCPI: && newRightConstant.Value is bool rightBoolValue)
//LCPI: {
//LCPI: // a && true -> a
//LCPI: // a || true -> true
//LCPI: // a && false -> false
//LCPI: // a || false -> a
//LCPI: return sqlBinaryExpression.OperatorType == ExpressionType.AndAlso
//LCPI: ? rightBoolValue
//LCPI: ? sqlBinaryExpression.Left
//LCPI: : newRightConstant
//LCPI: : rightBoolValue
//LCPI: ? newRightConstant
//LCPI: : sqlBinaryExpression.Left;
//LCPI: }
//LCPI:
//LCPI: return sqlBinaryExpression;
//LCPI: }
private struct LCPI__tagPreparedResult
{
public readonly SqlExpression? Value;
public LCPI__tagPreparedResult(SqlExpression v)
{
this.Value=v;
}
};//struct LCPI__tagPreparedResult
private SqlExpression LCPI__Make_LogicalAnd
(SqlExpression sourceLeft,
SqlExpression sourceRight,
LCPI__tagPreparedResult preparedResult=default)
{
// RETURNS AndAlso
if (sourceLeft is SqlUnaryExpression leftUnary
&& sourceRight is SqlUnaryExpression rightUnary
&& (leftUnary.OperatorType == ExpressionType.Equal || leftUnary.OperatorType == ExpressionType.NotEqual)
&& (rightUnary.OperatorType == ExpressionType.Equal || rightUnary.OperatorType == ExpressionType.NotEqual)
&& leftUnary.Operand.Equals(rightUnary.Operand))
{
// a is null || a is null -> a is null
// a is not null || a is not null -> a is not null
// a is null && a is null -> a is null
// a is not null && a is not null -> a is not null
// a is null || a is not null -> true
// a is null && a is not null -> false
return leftUnary.OperatorType == rightUnary.OperatorType
? (SqlExpression)leftUnary
: LCPI__Helper__SqlENodeFactory__BoolConstant(false /*sqlBinaryExpression.OperatorType == ExpressionType.OrElse*/);
}
// true && a -> a
// true || a -> true
// false && a -> false
// false || a -> a
if (sourceLeft is SqlConstantExpression newLeftConstant
&& newLeftConstant.Value is bool leftBoolValue)
{
return leftBoolValue
? sourceRight
: newLeftConstant;
}
if (sourceRight is SqlConstantExpression newRightConstant
&& newRightConstant.Value is bool rightBoolValue)
{
// a && true -> a
// a || true -> true
// a && false -> false
// a || false -> a
return rightBoolValue
? sourceLeft
: newRightConstant;
}
if (!Object.ReferenceEquals(preparedResult.Value, null))
return preparedResult.Value;
return LCPI__Helper__SqlENodeFactory__AndAlso
(sourceLeft,
sourceRight);
}//LCPI__Make_LogicalAnd
private SqlExpression LCPI__Make_LogicalOr
(SqlExpression sourceLeft,
SqlExpression sourceRight,
LCPI__tagPreparedResult preparedResult=default)
{
// RETURNS OrElse
if (sourceLeft is SqlUnaryExpression leftUnary
&& sourceRight is SqlUnaryExpression rightUnary
&& (leftUnary.OperatorType == ExpressionType.Equal || leftUnary.OperatorType == ExpressionType.NotEqual)
&& (rightUnary.OperatorType == ExpressionType.Equal || rightUnary.OperatorType == ExpressionType.NotEqual)
&& leftUnary.Operand.Equals(rightUnary.Operand))
{
// a is null || a is null -> a is null
// a is not null || a is not null -> a is not null
// a is null && a is null -> a is null
// a is not null && a is not null -> a is not null
// a is null || a is not null -> true
// a is null && a is not null -> false
return leftUnary.OperatorType == rightUnary.OperatorType
? (SqlExpression)leftUnary
: LCPI__Helper__SqlENodeFactory__BoolConstant(true /*sqlBinaryExpression.OperatorType == ExpressionType.OrElse*/);
}
// true && a -> a
// true || a -> true
// false && a -> false
// false || a -> a
if (sourceLeft is SqlConstantExpression newLeftConstant
&& newLeftConstant.Value is bool leftBoolValue)
{
return leftBoolValue
? newLeftConstant
: sourceRight;
}
if (sourceRight is SqlConstantExpression newRightConstant
&& newRightConstant.Value is bool rightBoolValue)
{
// a && true -> a
// a || true -> true
// a && false -> false
// a || false -> a
return rightBoolValue
? newRightConstant
: sourceLeft;
}
if (!Object.ReferenceEquals(preparedResult.Value, null))
return preparedResult.Value;
return LCPI__Helper__SqlENodeFactory__OrElse
(sourceLeft,
sourceRight);
}//LCPI__Make_LogicalOr
private SqlExpression LCPI__Make_NonNullableNot(SqlExpression sqlOperandExpression,
LCPI__tagPreparedResult preparedResult=default)
{
switch (sqlOperandExpression)
{
// !(true) -> false
// !(false) -> true
case SqlConstantExpression constantOperand
when constantOperand.Value is bool value:
{
return LCPI__Helper__SqlENodeFactory__BoolConstant(!value);
}
case InExpression inOperand:
return inOperand.Negate();
case SqlUnaryExpression sqlUnaryOperand:
{
switch (sqlUnaryOperand.OperatorType)
{
// !(!a) -> a
case ExpressionType.Not:
return sqlUnaryOperand.Operand;
//!(a IS NULL) -> a IS NOT NULL
case ExpressionType.Equal:
return LCPI__Helper__SqlENodeFactory__IsNotNull(sqlUnaryOperand.Operand);
//!(a IS NOT NULL) -> a IS NULL
case ExpressionType.NotEqual:
return LCPI__Helper__SqlENodeFactory__IsNull(sqlUnaryOperand.Operand);
}
break;
}
case SqlBinaryExpression sqlBinaryOperand:
{
// optimizations below are only correct in 2-value logic
// De Morgan's
//LCPI: if (sqlBinaryOperand.OperatorType == ExpressionType.AndAlso
//LCPI: || sqlBinaryOperand.OperatorType == ExpressionType.OrElse)
//LCPI: {
//LCPI: // since entire AndAlso/OrElse expression is non-nullable, both sides of it (left and right) must also be non-nullable
//LCPI: // so it's safe to perform recursive optimization here
//LCPI: var left = LCPI__MakeNonNullableNotExpression(sqlBinaryOperand.Left);
//LCPI: var right = LCPI__MakeNonNullableNotExpression(sqlBinaryOperand.Right);
//LCPI:
//LCPI: return SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.MakeBinary(
//LCPI: sqlBinaryOperand.OperatorType == ExpressionType.AndAlso
//LCPI: ? ExpressionType.OrElse
//LCPI: : ExpressionType.AndAlso,
//LCPI: left,
//LCPI: right,
//LCPI: sqlBinaryOperand.TypeMapping)!);
//LCPI: }
/*LCPI*/ if (sqlBinaryOperand.OperatorType == ExpressionType.AndAlso)
/*LCPI*/ {
/*LCPI*/ // since entire AndAlso/OrElse expression is non-nullable, both sides of it (left and right) must also be non-nullable
/*LCPI*/ // so it's safe to perform recursive optimization here
/*LCPI*/ var left = LCPI__Make_NonNullableNot(sqlBinaryOperand.Left);
/*LCPI*/ var right = LCPI__Make_NonNullableNot(sqlBinaryOperand.Right);
/*LCPI*/
/*LCPI*/ return LCPI__Make_LogicalOr
/*LCPI*/ (left,
/*LCPI*/ right);
/*LCPI*/ }
/*LCPI*/ if (sqlBinaryOperand.OperatorType == ExpressionType.OrElse)
/*LCPI*/ {
/*LCPI*/ // since entire AndAlso/OrElse expression is non-nullable, both sides of it (left and right) must also be non-nullable
/*LCPI*/ // so it's safe to perform recursive optimization here
/*LCPI*/ var left = LCPI__Make_NonNullableNot(sqlBinaryOperand.Left);
/*LCPI*/ var right = LCPI__Make_NonNullableNot(sqlBinaryOperand.Right);
/*LCPI*/
/*LCPI*/ return LCPI__Make_LogicalAnd
/*LCPI*/ (left,
/*LCPI*/ right);
/*LCPI*/ }
// use equality where possible
// !(a == true) -> a == false
// !(a == false) -> a == true
// !(true == a) -> false == a
// !(false == a) -> true == a
if (sqlBinaryOperand.OperatorType == ExpressionType.Equal)
{
if (sqlBinaryOperand.Left is SqlConstantExpression leftConstant
&& leftConstant.Type == typeof(bool))
{
return LCPI__Helper__SqlENodeFactory__Equal(
LCPI__Helper__SqlENodeFactory__BoolConstant(!(bool)leftConstant.Value!),
sqlBinaryOperand.Right);
}
if (sqlBinaryOperand.Right is SqlConstantExpression rightConstant
&& rightConstant.Type == typeof(bool))
{
return LCPI__Helper__SqlENodeFactory__Equal(
sqlBinaryOperand.Left,
LCPI__Helper__SqlENodeFactory__BoolConstant(!(bool)rightConstant.Value!));
}
}
// !(a == b) -> a != b
// !(a != b) -> a == b
// !(a > b) -> a <= b
// !(a >= b) -> a < b
// !(a < b) -> a >= b
// !(a <= b) -> a > b
if (TryNegate(sqlBinaryOperand.OperatorType, out var negated))
{
return LCPI__Helper__SqlENodeFactory__MakeBinary(
negated,
sqlBinaryOperand.Left,
sqlBinaryOperand.Right,
sqlBinaryOperand.TypeMapping);
}
}
break;
}
if (!Object.ReferenceEquals(preparedResult.Value,null))
return preparedResult.Value;
return LCPI__Helper__SqlENodeFactory__Not(sqlOperandExpression);
static bool TryNegate(ExpressionType expressionType, out ExpressionType result)
{
var negated = expressionType switch
{
ExpressionType.Equal => ExpressionType.NotEqual,
ExpressionType.NotEqual => ExpressionType.Equal,
ExpressionType.GreaterThan => ExpressionType.LessThanOrEqual,
ExpressionType.GreaterThanOrEqual => ExpressionType.LessThan,
ExpressionType.LessThan => ExpressionType.GreaterThanOrEqual,
ExpressionType.LessThanOrEqual => ExpressionType.GreaterThan,
_ => (ExpressionType?)null
};
result = negated ?? default;
return negated.HasValue;
}
}//LCPI__Make_NonNullableNot
private SqlExpression LCPI__Make_NullNotNull
(ExpressionType sourceOperatorType,
SqlExpression sourceOperand,
bool sourceOperandIsNullable,
LCPI__tagPreparedResult preparedResult=default)
{
Debug.Assert(sourceOperatorType == ExpressionType.Equal ||
sourceOperatorType == ExpressionType.NotEqual);
if (!sourceOperandIsNullable)
{
// when we know that operand is non-nullable:
// not_null_operand is null-> false
// not_null_operand is not null -> true
return LCPI__Helper__SqlENodeFactory__BoolConstant(
sourceOperatorType == ExpressionType.NotEqual);
}
switch (sourceOperand)
{
case SqlConstantExpression sqlConstantOperand:
// null_value_constant is null -> true
// null_value_constant is not null -> false
// not_null_value_constant is null -> false
// not_null_value_constant is not null -> true
return LCPI__Helper__SqlENodeFactory__BoolConstant(
sqlConstantOperand.Value == null ^ sourceOperatorType == ExpressionType.NotEqual);
case SqlParameterExpression sqlParameterOperand:
// null_value_parameter is null -> true
// null_value_parameter is not null -> false
// not_null_value_parameter is null -> false
// not_null_value_parameter is not null -> true
return LCPI__Helper__SqlENodeFactory__BoolConstant(
ParameterValues[sqlParameterOperand.Name] == null ^ sourceOperatorType == ExpressionType.NotEqual);
case ColumnExpression columnOperand
when !columnOperand.IsNullable || _nonNullableColumns.Contains(columnOperand):
{
// IsNull(non_nullable_column) -> false
// IsNotNull(non_nullable_column) -> true
return LCPI__Helper__SqlENodeFactory__BoolConstant(
sourceOperatorType == ExpressionType.NotEqual);
}
case SqlUnaryExpression sqlUnaryOperand:
switch (sqlUnaryOperand.OperatorType)
{
case ExpressionType.Convert:
case ExpressionType.Not:
case ExpressionType.Negate:
// op(a) is null -> a is null
// op(a) is not null -> a is not null
return LCPI__Make_NullNotNull(
sourceOperatorType,
sqlUnaryOperand.Operand,
sourceOperandIsNullable);
case ExpressionType.Equal:
case ExpressionType.NotEqual:
// (a is null) is null -> false
// (a is not null) is null -> false
// (a is null) is not null -> true
// (a is not null) is not null -> true
return LCPI__Helper__SqlENodeFactory__BoolConstant(
sourceOperatorType == ExpressionType.NotEqual);
}
break;
case SqlBinaryExpression sqlBinaryOperand
when sqlBinaryOperand.OperatorType != ExpressionType.AndAlso
&& sqlBinaryOperand.OperatorType != ExpressionType.OrElse:
{
// in general:
// binaryOp(a, b) == null -> a == null || b == null
// binaryOp(a, b) != null -> a != null && b != null
// for AndAlso, OrElse we can't do this optimization
// we could do something like this, but it seems too complicated:
// (a && b) == null -> a == null && b != 0 || a != 0 && b == null
// NOTE: we don't preserve nullabilities of left/right individually so we are using nullability binary expression as a whole
// this may lead to missing some optimizations, where one of the operands (left or right) is not nullable and the other one is
var left = LCPI__Make_NullNotNull(
sourceOperatorType,
sqlBinaryOperand.Left,
sourceOperandIsNullable);
var right = LCPI__Make_NullNotNull(
sourceOperatorType,
sqlBinaryOperand.Right,
sourceOperandIsNullable);
//LCPI: return SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.MakeBinary(
//LCPI: sourceOperatorType == ExpressionType.Equal
//LCPI: ? ExpressionType.OrElse
//LCPI: : ExpressionType.AndAlso,
//LCPI: left,
//LCPI: right,
//LCPI: /*sqlUnaryExpression.TypeMapping*/_lcpi_typeMappingForBool)!);
/*LCPI*/ if (sourceOperatorType == ExpressionType.Equal)
/*LCPI*/ {
/*LCPI*/ return LCPI__Make_LogicalOr
/*LCPI*/ (left,
/*LCPI*/ right);
/*LCPI*/ }
/*LCPI*/
/*LCPI*/ Debug.Assert(sourceOperatorType == ExpressionType.NotEqual);
/*LCPI*/
/*LCPI*/ return LCPI__Make_LogicalAnd
/*LCPI*/ (left,
/*LCPI*/ right);
}
case SqlFunctionExpression sqlFunctionExpression:
{
if (LCPI__Helper__TestBuiltInFunctionName(sqlFunctionExpression,"COALESCE"))
{
/*LCPI*/ Debug.Assert(!Object.ReferenceEquals(sqlFunctionExpression.Arguments,null));
/*LCPI*/ Debug.Assert(sqlFunctionExpression.Arguments.Count>=2);
// for coalesce:
// (a ?? b) == null -> a == null && b == null
// (a ?? b) != null -> a != null || b != null
/*LCPI*/ var newArguments
/*LCPI*/ = sqlFunctionExpression.Arguments!
/*LCPI*/ .Select(
/*LCPI*/ e => LCPI__Make_NullNotNull(
/*LCPI*/ sourceOperatorType,
/*LCPI*/ e,
/*LCPI*/ sourceOperandIsNullable));
//LCPI: return SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.MakeBinary(
//LCPI: sourceOperatorType == ExpressionType.Equal
//LCPI: ? ExpressionType.AndAlso
//LCPI: : ExpressionType.OrElse,
//LCPI: left,
//LCPI: right,
//LCPI: /*sqlUnaryExpression.TypeMapping*/_lcpi_typeMappingForBool)!);
/*LCPI*/ if (sourceOperatorType == ExpressionType.Equal)
/*LCPI*/ {
/*LCPI*/ return newArguments.Aggregate((r, e) => LCPI__Make_LogicalAnd(r, e));
/*LCPI*/ }
/*LCPI*/
/*LCPI*/ Debug.Assert(sourceOperatorType == ExpressionType.NotEqual);
/*LCPI*/
/*LCPI*/ return newArguments.Aggregate((r, e) => LCPI__Make_LogicalOr(r, e));
}
if (!sqlFunctionExpression.IsNullable)
{
// when we know that function can't be nullable:
// non_nullable_function() is null-> false
// non_nullable_function() is not null -> true
return LCPI__Helper__SqlENodeFactory__BoolConstant(
sourceOperatorType == ExpressionType.NotEqual);
}
// see if we can derive function nullability from it's instance and/or arguments
// rather than evaluating nullability of the entire function
var nullabilityPropagationElements = new List<SqlExpression>();
if (sqlFunctionExpression.Instance != null
&& sqlFunctionExpression.InstancePropagatesNullability == true)
{
nullabilityPropagationElements.Add(sqlFunctionExpression.Instance);
}
if (!sqlFunctionExpression.IsNiladic)
{
for (var i = 0; i < sqlFunctionExpression.Arguments.Count; i++)
{
if (sqlFunctionExpression.ArgumentsPropagateNullability[i])
{
nullabilityPropagationElements.Add(sqlFunctionExpression.Arguments[i]);
}
}
}
// function(a, b) IS NULL -> a IS NULL || b IS NULL
// function(a, b) IS NOT NULL -> a IS NOT NULL && b IS NOT NULL
if (nullabilityPropagationElements.Count > 0)
{
var result = nullabilityPropagationElements
.Select(
e => LCPI__Make_NullNotNull(
sourceOperatorType,
e,
sourceOperandIsNullable))
.Aggregate(
(r, e) => sourceOperatorType == ExpressionType.Equal
? LCPI__Make_LogicalOr(r, e)
: LCPI__Make_LogicalAnd(r, e));
return result;
}
}
break;
}
if (!Object.ReferenceEquals(preparedResult.Value,null))
{
return preparedResult.Value;
}
if (sourceOperatorType == ExpressionType.Equal)
{
return LCPI__Helper__SqlENodeFactory__IsNull(sourceOperand);
}
Debug.Assert(sourceOperatorType == ExpressionType.NotEqual);
return LCPI__Helper__SqlENodeFactory__IsNotNull(sourceOperand);
}//LCPI__Make_NullNotNull
private static bool IsLogicalNot(SqlUnaryExpression? sqlUnaryExpression)
=> sqlUnaryExpression != null
&& sqlUnaryExpression.OperatorType == ExpressionType.Not
&& sqlUnaryExpression.Type == typeof(bool);
// ?a == ?b -> [(a == b) && (a != null && b != null)] || (a == null && b == null))
//
// a | b | F1 = a == b | F2 = (a != null && b != null) | F3 = F1 && F2 |
// | | | | |
// 0 | 0 | 1 | 1 | 1 |
// 0 | 1 | 0 | 1 | 0 |
// 0 | N | N | 0 | 0 |
// 1 | 0 | 0 | 1 | 0 |
// 1 | 1 | 1 | 1 | 1 |
// 1 | N | N | 0 | 0 |
// N | 0 | N | 0 | 0 |
// N | 1 | N | 0 | 0 |
// N | N | N | 0 | 0 |
//
// a | b | F4 = (a == null && b == null) | Final = F3 OR F4 |
// | | | |
// 0 | 0 | 0 | 1 OR 0 = 1 |
// 0 | 1 | 0 | 0 OR 0 = 0 |
// 0 | N | 0 | 0 OR 0 = 0 |
// 1 | 0 | 0 | 0 OR 0 = 0 |
// 1 | 1 | 0 | 1 OR 0 = 1 |
// 1 | N | 0 | 0 OR 0 = 0 |
// N | 0 | 0 | 0 OR 0 = 0 |
// N | 1 | 0 | 0 OR 0 = 0 |
// N | N | 1 | 0 OR 1 = 1 |
private SqlExpression ExpandNullableEqualNullable(
SqlExpression left,
SqlExpression right,
SqlExpression leftIsNull,
SqlExpression leftIsNotNull,
SqlExpression rightIsNull,
SqlExpression rightIsNotNull)
//LCPI: => SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(
//LCPI: _sqlExpressionFactory.Equal(left, right),
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(leftIsNotNull, rightIsNotNull)))),
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(leftIsNull, rightIsNull))));
/*LCPI*/=> LCPI__Make_LogicalOr(
/*LCPI*/ LCPI__Make_LogicalAnd(
/*LCPI*/ LCPI__Helper__SqlENodeFactory__Equal(left, right),
/*LCPI*/ LCPI__Make_LogicalAnd(leftIsNotNull, rightIsNotNull)),
/*LCPI*/ LCPI__Make_LogicalAnd(leftIsNull, rightIsNull));
// !(?a) == ?b -> [(a != b) && (a != null && b != null)] || (a == null && b == null)
//
// a | b | F1 = a != b | F2 = (a != null && b != null) | F3 = F1 && F2 |
// | | | | |
// 0 | 0 | 0 | 1 | 0 |
// 0 | 1 | 1 | 1 | 1 |
// 0 | N | N | 0 | 0 |
// 1 | 0 | 1 | 1 | 1 |
// 1 | 1 | 0 | 1 | 0 |
// 1 | N | N | 0 | 0 |
// N | 0 | N | 0 | 0 |
// N | 1 | N | 0 | 0 |
// N | N | N | 0 | 0 |
//
// a | b | F4 = (a == null && b == null) | Final = F3 OR F4 |
// | | | |
// 0 | 0 | 0 | 0 OR 0 = 0 |
// 0 | 1 | 0 | 1 OR 0 = 1 |
// 0 | N | 0 | 0 OR 0 = 0 |
// 1 | 0 | 0 | 1 OR 0 = 1 |
// 1 | 1 | 0 | 0 OR 0 = 0 |
// 1 | N | 0 | 0 OR 0 = 0 |
// N | 0 | 0 | 0 OR 0 = 0 |
// N | 1 | 0 | 0 OR 0 = 0 |
// N | N | 1 | 0 OR 1 = 1 |
private SqlExpression ExpandNegatedNullableEqualNullable(
SqlExpression left,
SqlExpression right,
SqlExpression leftIsNull,
SqlExpression leftIsNotNull,
SqlExpression rightIsNull,
SqlExpression rightIsNotNull)
//LCPI: => SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(
//LCPI: _sqlExpressionFactory.NotEqual(left, right),
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(leftIsNotNull, rightIsNotNull)))),
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(leftIsNull, rightIsNull))));
/*LCPI*/=> LCPI__Make_LogicalOr(
/*LCPI*/ LCPI__Make_LogicalAnd(
/*LCPI*/ LCPI__Helper__SqlENodeFactory__NotEqual(left, right),
/*LCPI*/ LCPI__Make_LogicalAnd(leftIsNotNull, rightIsNotNull)),
/*LCPI*/ LCPI__Make_LogicalAnd(leftIsNull, rightIsNull));
// ?a == b -> (a == b) && (a != null)
//
// a | b | F1 = a == b | F2 = (a != null) | Final = F1 && F2 |
// | | | | |
// 0 | 0 | 1 | 1 | 1 |
// 0 | 1 | 0 | 1 | 0 |
// 1 | 0 | 0 | 1 | 0 |
// 1 | 1 | 1 | 1 | 1 |
// N | 0 | N | 0 | 0 |
// N | 1 | N | 0 | 0 |
private SqlExpression ExpandNullableEqualNonNullable(
SqlExpression left,
SqlExpression right,
SqlExpression leftIsNotNull)
//LCPI: => SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(
//LCPI: _sqlExpressionFactory.Equal(left, right),
//LCPI: leftIsNotNull));
/*LCPI*/=> LCPI__Make_LogicalAnd(
/*LCPI*/ LCPI__Helper__SqlENodeFactory__Equal(left, right),
/*LCPI*/ leftIsNotNull);
// !(?a) == b -> (a != b) && (a != null)
//
// a | b | F1 = a != b | F2 = (a != null) | Final = F1 && F2 |
// | | | | |
// 0 | 0 | 0 | 1 | 0 |
// 0 | 1 | 1 | 1 | 1 |
// 1 | 0 | 1 | 1 | 1 |
// 1 | 1 | 0 | 1 | 0 |
// N | 0 | N | 0 | 0 |
// N | 1 | N | 0 | 0 |
private SqlExpression ExpandNegatedNullableEqualNonNullable(
SqlExpression left,
SqlExpression right,
SqlExpression leftIsNotNull)
//LCPI: => SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(
//LCPI: _sqlExpressionFactory.NotEqual(left, right),
//LCPI: leftIsNotNull));
/*LCPI*/=> LCPI__Make_LogicalAnd(
/*LCPI*/ LCPI__Helper__SqlENodeFactory__NotEqual(left, right),
/*LCPI*/ leftIsNotNull);
// ?a != ?b -> [(a != b) || (a == null || b == null)] && (a != null || b != null)
//
// a | b | F1 = a != b | F2 = (a == null || b == null) | F3 = F1 || F2 |
// | | | | |
// 0 | 0 | 0 | 0 | 0 |
// 0 | 1 | 1 | 0 | 1 |
// 0 | N | N | 1 | 1 |
// 1 | 0 | 1 | 0 | 1 |
// 1 | 1 | 0 | 0 | 0 |
// 1 | N | N | 1 | 1 |
// N | 0 | N | 1 | 1 |
// N | 1 | N | 1 | 1 |
// N | N | N | 1 | 1 |
//
// a | b | F4 = (a != null || b != null) | Final = F3 && F4 |
// | | | |
// 0 | 0 | 1 | 0 && 1 = 0 |
// 0 | 1 | 1 | 1 && 1 = 1 |
// 0 | N | 1 | 1 && 1 = 1 |
// 1 | 0 | 1 | 1 && 1 = 1 |
// 1 | 1 | 1 | 0 && 1 = 0 |
// 1 | N | 1 | 1 && 1 = 1 |
// N | 0 | 1 | 1 && 1 = 1 |
// N | 1 | 1 | 1 && 1 = 1 |
// N | N | 0 | 1 && 0 = 0 |
private SqlExpression ExpandNullableNotEqualNullable(
SqlExpression left,
SqlExpression right,
SqlExpression leftIsNull,
SqlExpression leftIsNotNull,
SqlExpression rightIsNull,
SqlExpression rightIsNotNull)
//LCPI:=> SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(
//LCPI: _sqlExpressionFactory.NotEqual(left, right),
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(leftIsNull, rightIsNull)))),
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(leftIsNotNull, rightIsNotNull))));
/*LCPI*/=> LCPI__Make_LogicalAnd(
/*LCPI*/ LCPI__Make_LogicalOr(
/*LCPI*/ LCPI__Helper__SqlENodeFactory__NotEqual(left, right),
/*LCPI*/ LCPI__Make_LogicalOr(leftIsNull, rightIsNull)),
/*LCPI*/ LCPI__Make_LogicalOr(leftIsNotNull, rightIsNotNull));
// !(?a) != ?b -> [(a == b) || (a == null || b == null)] && (a != null || b != null)
//
// a | b | F1 = a == b | F2 = (a == null || b == null) | F3 = F1 || F2 |
// | | | | |
// 0 | 0 | 1 | 0 | 1 |
// 0 | 1 | 0 | 0 | 0 |
// 0 | N | N | 1 | 1 |
// 1 | 0 | 0 | 0 | 0 |
// 1 | 1 | 1 | 0 | 1 |
// 1 | N | N | 1 | 1 |
// N | 0 | N | 1 | 1 |
// N | 1 | N | 1 | 1 |
// N | N | N | 1 | 1 |
//
// a | b | F4 = (a != null || b != null) | Final = F3 && F4 |
// | | | |
// 0 | 0 | 1 | 1 && 1 = 1 |
// 0 | 1 | 1 | 0 && 1 = 0 |
// 0 | N | 1 | 1 && 1 = 1 |
// 1 | 0 | 1 | 0 && 1 = 0 |
// 1 | 1 | 1 | 1 && 1 = 1 |
// 1 | N | 1 | 1 && 1 = 1 |
// N | 0 | 1 | 1 && 1 = 1 |
// N | 1 | 1 | 1 && 1 = 1 |
// N | N | 0 | 1 && 0 = 0 |
private SqlExpression ExpandNegatedNullableNotEqualNullable(
SqlExpression left,
SqlExpression right,
SqlExpression leftIsNull,
SqlExpression leftIsNotNull,
SqlExpression rightIsNull,
SqlExpression rightIsNotNull)
//LCPI:=> SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.AndAlso(
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(
//LCPI: _sqlExpressionFactory.Equal(left, right),
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(leftIsNull, rightIsNull)))),
//LCPI: SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(leftIsNotNull, rightIsNotNull))));
/*LCPI*/=> LCPI__Make_LogicalAnd(
/*LCPI*/ LCPI__Make_LogicalOr(
/*LCPI*/ LCPI__Helper__SqlENodeFactory__Equal(left, right),
/*LCPI*/ LCPI__Make_LogicalOr(leftIsNull, rightIsNull)),
/*LCPI*/ LCPI__Make_LogicalOr(leftIsNotNull, rightIsNotNull));
// ?a != b -> (a != b) || (a == null)
//
// a | b | F1 = a != b | F2 = (a == null) | Final = F1 OR F2 |
// | | | | |
// 0 | 0 | 0 | 0 | 0 |
// 0 | 1 | 1 | 0 | 1 |
// 1 | 0 | 1 | 0 | 1 |
// 1 | 1 | 0 | 0 | 0 |
// N | 0 | N | 1 | 1 |
// N | 1 | N | 1 | 1 |
private SqlExpression ExpandNullableNotEqualNonNullable(
SqlExpression left,
SqlExpression right,
SqlExpression leftIsNull)
//LCPI:=> SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(
//LCPI: _sqlExpressionFactory.NotEqual(left, right),
//LCPI: leftIsNull));
/*LCPI*/=> LCPI__Make_LogicalOr(
/*LCPI*/ LCPI__Helper__SqlENodeFactory__NotEqual(left, right),
/*LCPI*/ leftIsNull);
// !(?a) != b -> (a == b) || (a == null)
//
// a | b | F1 = a == b | F2 = (a == null) | F3 = F1 OR F2 |
// | | | | |
// 0 | 0 | 1 | 0 | 1 |
// 0 | 1 | 0 | 0 | 0 |
// 1 | 0 | 0 | 0 | 0 |
// 1 | 1 | 1 | 0 | 1 |
// N | 0 | N | 1 | 1 |
// N | 1 | N | 1 | 1 |
private SqlExpression ExpandNegatedNullableNotEqualNonNullable(
SqlExpression left,
SqlExpression right,
SqlExpression leftIsNull)
//LCPI:=> SimplifyLogicalSqlBinaryExpression(
//LCPI: _sqlExpressionFactory.OrElse(
//LCPI: _sqlExpressionFactory.Equal(left, right),
//LCPI: leftIsNull));
/*LCPI*/=> LCPI__Make_LogicalOr(
/*LCPI*/ LCPI__Helper__SqlENodeFactory__Equal(left, right),
/*LCPI*/ leftIsNull);
//----------------------------------------------------------------
private SqlExpression LCPI__Helper__SqlENodeFactory__BoolConstant(bool value)
{
if(value)
return _lcpi_expr_BOOL_TRUE;
return _lcpi_expr_BOOL_FALSE;
}//LCPI__Helper__SqlENodeFactory__BoolConstant
//----------------------------------------------------------------
//
// PRIMARY TARGET:
//
// The switch to usage of SqlExpression instead typed subclasses of SqlExpression.
//
private SqlExpression LCPI__Helper__SqlENodeFactory__Not(SqlExpression sqlOperand)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
return _sqlExpressionFactory.Not
(sqlOperand);
}//LCPI__Helper__SqlENodeFactory__Not
//----------------------------------------------------------------
private SqlExpression LCPI__Helper__SqlENodeFactory__IsNotNull(SqlExpression sqlOperand)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
return _sqlExpressionFactory.IsNotNull
(sqlOperand);
}//LCPI__Helper__SqlENodeFactory__IsNotNull
//----------------------------------------------------------------
private SqlExpression LCPI__Helper__SqlENodeFactory__IsNull(SqlExpression sqlOperand)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
return _sqlExpressionFactory.IsNull
(sqlOperand);
}//LCPI__Helper__SqlENodeFactory__IsNull
//----------------------------------------------------------------
private SqlExpression LCPI__Helper__SqlENodeFactory__AndAlso
(SqlExpression sqlLeft,
SqlExpression sqlRight)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
Debug.Assert(!Object.ReferenceEquals(sqlLeft, null));
Debug.Assert(!Object.ReferenceEquals(sqlRight, null));
return _sqlExpressionFactory.AndAlso
(sqlLeft,
sqlRight);
}//LCPI__Helper__SqlENodeFactory__AndAlso
//----------------------------------------------------------------
private SqlExpression LCPI__Helper__SqlENodeFactory__OrElse
(SqlExpression sqlLeft,
SqlExpression sqlRight)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
Debug.Assert(!Object.ReferenceEquals(sqlLeft, null));
Debug.Assert(!Object.ReferenceEquals(sqlRight, null));
return _sqlExpressionFactory.OrElse
(sqlLeft,
sqlRight);
}//LCPI__Helper__SqlENodeFactory__OrElse
//----------------------------------------------------------------
private SqlExpression LCPI__Helper__SqlENodeFactory__Equal
(SqlExpression sqlLeft,
SqlExpression sqlRight)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
Debug.Assert(!Object.ReferenceEquals(sqlLeft, null));
Debug.Assert(!Object.ReferenceEquals(sqlRight, null));
return _sqlExpressionFactory.Equal
(sqlLeft,
sqlRight);
}//LCPI__Helper__SqlENodeFactory__Equal
//----------------------------------------------------------------
private SqlExpression LCPI__Helper__SqlENodeFactory__NotEqual
(SqlExpression sqlLeft,
SqlExpression sqlRight)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
Debug.Assert(!Object.ReferenceEquals(sqlLeft, null));
Debug.Assert(!Object.ReferenceEquals(sqlRight, null));
return _sqlExpressionFactory.NotEqual
(sqlLeft,
sqlRight);
}//LCPI__Helper__SqlENodeFactory__NotEqual
//----------------------------------------------------------------
private SqlExpression LCPI__Helper__SqlENodeFactory__MakeBinary
(ExpressionType operatorType,
SqlExpression sqlLeft,
SqlExpression sqlRight,
RelationalTypeMapping? resultTypeMapping)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
Debug.Assert(!Object.ReferenceEquals(sqlLeft, null));
Debug.Assert(!Object.ReferenceEquals(sqlRight, null));
var r=_sqlExpressionFactory.MakeBinary
(operatorType,
sqlLeft,
sqlRight,
resultTypeMapping);
return Check.NotNull
(r,
nameof(r));
}//LCPI__Helper__SqlENodeFactory__MakeBinary
//----------------------------------------------------------------
private SqlExpression LCPI__Helper__SqlENodeFactory__Coalesce
(SqlExpression sqlLeft,
SqlExpression sqlRight,
RelationalTypeMapping? typeMapping=null)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
Debug.Assert(!Object.ReferenceEquals(sqlLeft, null));
Debug.Assert(!Object.ReferenceEquals(sqlRight, null));
return _sqlExpressionFactory.Coalesce
(sqlLeft,
sqlRight);
}//LCPI__Helper__SqlENodeFactory__Coalesce
//----------------------------------------------------------------
private SqlConstantExpression LCPI__Helper__SqlENodeFactory__Constant
(object? value,
RelationalTypeMapping? typeMapping)
{
Debug.Assert(!Object.ReferenceEquals(_sqlExpressionFactory,null));
return _sqlExpressionFactory.Constant
(value,
typeMapping);
}//LCPI__Helper__SqlENodeFactory__Constant
}
}
| 48.693917 | 160 | 0.516459 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Code/Provider/Source-External/Microsoft/EntityFrameworkCode/EFCore.Relational/Query/SqlNullabilityProcessor.cs | 125,679 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("My Local Broadband WSS Activities")]
[assembly: AssemblyDescription("SharePoint Designer Activities for a WSS environment.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("My Local Broadband LLC")]
[assembly: AssemblyProduct("WSSActivities")]
[assembly: AssemblyCopyright("Copyright © My Local Broadband LLC 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using '*'.
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: ComVisible(false)]
//NOTE: When updating the namespaces in the project please add new or update existing the XmlnsDefinitionAttribute
//You can add additional attributes in order to map any additional namespaces you have in the project
//[assembly: System.Workflow.ComponentModel.Serialization.XmlnsDefinition("http://schemas.com/WSSActivities", "WSSActivities")]
| 42.606061 | 127 | 0.772404 | [
"MIT"
] | szysse/Codeplex | WSSActivities/WSSActivities/Properties/AssemblyInfo.cs | 1,409 | C# |
namespace InvoiceService.Repository
{
public interface IInvoiceRepository
{
Invoice Get(int salesOrderId);
}
} | 18.714286 | 39 | 0.694656 | [
"MIT"
] | nuitsjp/DioDocs.FastReportBuilder | Sample/AspNetCore/InvoiceService.Repository/IInvoiceRepository.cs | 133 | C# |
using System;
using System.Text;
using Renci.SshNet.Messages.Transport;
using Renci.SshNet.Common;
namespace Renci.SshNet.Security
{
/// <summary>
/// Represents base class for Diffie Hellman key exchange algorithm
/// </summary>
internal abstract class KeyExchangeDiffieHellman : KeyExchange
{
/// <summary>
/// Specifies key exchange group number.
/// </summary>
protected BigInteger _group;
/// <summary>
/// Specifies key exchange prime number.
/// </summary>
protected BigInteger _prime;
/// <summary>
/// Specifies client payload
/// </summary>
protected byte[] _clientPayload;
/// <summary>
/// Specifies server payload
/// </summary>
protected byte[] _serverPayload;
/// <summary>
/// Specifies client exchange number.
/// </summary>
protected byte[] _clientExchangeValue;
/// <summary>
/// Specifies server exchange number.
/// </summary>
protected byte[] _serverExchangeValue;
/// <summary>
/// Specifies random generated number.
/// </summary>
protected BigInteger _privateExponent;
/// <summary>
/// Specifies host key data.
/// </summary>
protected byte[] _hostKey;
/// <summary>
/// Specifies signature data.
/// </summary>
protected byte[] _signature;
/// <summary>
/// Gets the size, in bits, of the computed hash code.
/// </summary>
/// <value>
/// The size, in bits, of the computed hash code.
/// </value>
protected abstract int HashSize { get; }
/// <summary>
/// Validates the exchange hash.
/// </summary>
/// <returns>
/// true if exchange hash is valid; otherwise false.
/// </returns>
protected override bool ValidateExchangeHash()
{
byte[] exchangeHash = CalculateHash();
var length = Pack.BigEndianToUInt32(_hostKey);
var algorithmName = Encoding.UTF8.GetString(_hostKey, 4, (int)length);
var key = Session.ConnectionInfo.HostKeyAlgorithms[algorithmName](_hostKey);
Session.ConnectionInfo.CurrentHostKeyAlgorithm = algorithmName;
if (CanTrustHostKey(key))
{
return key.VerifySignature(exchangeHash, _signature);
}
return false;
}
/// <summary>
/// Starts key exchange algorithm
/// </summary>
/// <param name="session">The session.</param>
/// <param name="message">Key exchange init message.</param>
public override void Start(Session session, KeyExchangeInitMessage message)
{
base.Start(session, message);
_serverPayload = message.GetBytes();
_clientPayload = Session.ClientInitMessage.GetBytes();
}
/// <summary>
/// Populates the client exchange value.
/// </summary>
protected void PopulateClientExchangeValue()
{
if (_group.IsZero)
throw new ArgumentNullException("_group");
if (_prime.IsZero)
throw new ArgumentNullException("_prime");
// generate private exponent that is twice the hash size (RFC 4419) with a minimum
// of 1024 bits (whatever is less)
var privateExponentSize = Math.Max(HashSize * 2, 1024);
BigInteger clientExchangeValue;
do
{
// create private component
_privateExponent = BigInteger.Random(privateExponentSize);
// generate public component
clientExchangeValue = BigInteger.ModPow(_group, _privateExponent, _prime);
} while (clientExchangeValue < 1 || clientExchangeValue > _prime - 1);
_clientExchangeValue = clientExchangeValue.ToByteArray().Reverse();
}
/// <summary>
/// Handles the server DH reply message.
/// </summary>
/// <param name="hostKey">The host key.</param>
/// <param name="serverExchangeValue">The server exchange value.</param>
/// <param name="signature">The signature.</param>
protected virtual void HandleServerDhReply(byte[] hostKey, byte[] serverExchangeValue, byte[] signature)
{
_serverExchangeValue = serverExchangeValue;
_hostKey = hostKey;
SharedKey = BigInteger.ModPow(serverExchangeValue.ToBigInteger(), _privateExponent, _prime).ToByteArray().Reverse();
_signature = signature;
}
}
}
| 32.520548 | 128 | 0.575821 | [
"MIT"
] | iodes/SSH.NET | src/Renci.SshNet/Security/KeyExchangeDiffieHellman.cs | 4,750 | C# |
// <auto-generated />
using AmazingTODOApp.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace AmazingTODOApp.Migrations
{
[DbContext(typeof(AmazingTodoEFContext))]
[Migration("20201021023912_DefaultUserNowWithTodoItemList")]
partial class DefaultUserNowWithTodoItemList
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.9")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("AmazingTODOApp.Domain.TodoItem", b =>
{
b.Property<int>("TodoItemId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsCompleted")
.HasColumnType("bit");
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.HasKey("TodoItemId");
b.HasIndex("UserId");
b.ToTable("TodoItems");
});
modelBuilder.Entity("AmazingTODOApp.Domain.User", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Password")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId");
b.ToTable("Users");
b.HasData(
new
{
UserId = "1",
Password = "mario",
UserName = "mario"
});
});
modelBuilder.Entity("AmazingTODOApp.Domain.TodoItem", b =>
{
b.HasOne("AmazingTODOApp.Domain.User", null)
.WithMany("TodoItems")
.HasForeignKey("UserId");
});
#pragma warning restore 612, 618
}
}
}
| 35.175 | 125 | 0.521322 | [
"MIT"
] | Lesthad/MariosTODO | AmazingTODOApp/Migrations/20201021023912_DefaultUserNowWithTodoItemList.Designer.cs | 2,816 | C# |
using System;
using Copren.Net.Hosting.Hosting;
namespace Copren.Net.Hosting.Context
{
public class HostContext
{
public Host Host { get; }
public Uri ClientUri { get; }
public Guid? ClientId { get; }
public HostContext(Host host, Uri clientUri, Guid? clientId = null)
{
Host = host;
ClientUri = clientUri;
ClientId = clientId;
}
}
} | 22.684211 | 75 | 0.573086 | [
"MIT"
] | copren/Copren.Net | Copren.Net.Hosting/Context/HostContext.cs | 431 | C# |
// MIT License
//
// Copyright (c) 2018 Tim Koopman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
// OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using Koopman.CheckPoint;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
namespace Tests
{
[TestClass]
public class ServiceOtherTests : StandardTestsBase
{
#region Fields
private static readonly string Name = "TestServiceOther.NET";
#endregion Fields
#region Methods
[TestMethod]
public async Task FindAll()
{
var a = await Session.FindServicesOther(limit: 5, order: ServiceOther.Order.NameAsc);
Assert.IsNotNull(a);
a = await a.NextPage();
}
[TestMethod]
public async Task FindAllFiltered()
{
var a = await Session.FindServicesOther(filter: "dhcp", limit: 5, order: ServiceOther.Order.NameAsc);
Assert.IsNotNull(a);
a = await a.NextPage();
}
[TestMethod]
public async Task ServiceOtherTest()
{
// Create
var a = new ServiceOther(Session)
{
Name = Name,
Color = Colors.Red,
IPProtocol = 17,
Match = "dhcp-rep-match",
AggressiveAging = new Koopman.CheckPoint.Common.AggressiveAging()
{
Enable = true
}
};
await a.AcceptChanges(Ignore.Warnings);
Assert.IsFalse(a.IsNew);
Assert.IsNotNull(a.UID);
// Find
a = await Session.FindServiceOther(Name);
a.Comments = "Blah";
await a.AcceptChanges();
// Delete
await a.Delete();
}
#endregion Methods
}
} | 33.963855 | 113 | 0.622561 | [
"MIT"
] | tkoopman/CheckPoint.NET | Tests/ServiceOtherTests.cs | 2,821 | C# |
using AElf.Types;
using Google.Protobuf;
namespace AElf.CrossChain.Indexing.Infrastructure
{
public interface ITransactionInputForBlockMiningDataProvider
{
void AddTransactionInputForBlockMining(Hash blockHash, CrossChainTransactionInput crossChainTransactionInput);
CrossChainTransactionInput GetTransactionInputForBlockMining(Hash blockHash);
void ClearExpiredTransactionInput(long blockHeight);
}
public class CrossChainTransactionInput
{
public long PreviousBlockHeight { get; set; }
public string MethodName { get; set; }
public ByteString Value { get; set; }
}
} | 31.238095 | 118 | 0.737805 | [
"MIT"
] | 380086154/AElf | src/AElf.CrossChain.Core/Indexing/Infrastructure/TranactionInputForBlockMiningDataProvider.cs | 656 | C# |
namespace TraktNet.Requests.Tests.Recommendations.OAuth
{
using FluentAssertions;
using System.Collections.Generic;
using Trakt.NET.Tests.Utility.Traits;
using TraktNet.Requests.Base;
using TraktNet.Requests.Parameters;
using TraktNet.Requests.Recommendations.OAuth;
using Xunit;
[Category("Requests.Recommendations.OAuth")]
public class UserShowRecommendationsRequest_Tests
{
[Fact]
public void Test_UserShowRecommendationsRequest_Has_AuthorizationRequirement_Required()
{
var request = new UserShowRecommendationsRequest();
request.AuthorizationRequirement.Should().Be(AuthorizationRequirement.Required);
}
[Fact]
public void Test_UserShowRecommendationsRequest_Has_Valid_UriTemplate()
{
var request = new UserShowRecommendationsRequest();
request.UriTemplate.Should().Be("recommendations/shows{?extended,limit,ignore_collected}");
}
[Fact]
public void Test_UserShowRecommendationsRequest_Returns_Valid_UriPathParameters()
{
// no parameters
var requestMock = new UserShowRecommendationsRequest();
requestMock.GetUriPathParameters().Should().NotBeNull().And.BeEmpty().And.HaveCount(0);
// with extended info
var extendedInfo = new TraktExtendedInfo { Full = true };
requestMock = new UserShowRecommendationsRequest { ExtendedInfo = extendedInfo };
requestMock.GetUriPathParameters().Should().NotBeNull()
.And.HaveCount(1)
.And.Contain(new Dictionary<string, object>
{
["extended"] = extendedInfo.ToString()
});
// with extended info and limit
var limit = 123U;
requestMock = new UserShowRecommendationsRequest { ExtendedInfo = extendedInfo, Limit = limit };
requestMock.GetUriPathParameters().Should().NotBeNull()
.And.HaveCount(2)
.And.Contain(new Dictionary<string, object>
{
["extended"] = extendedInfo.ToString(),
["limit"] = limit.ToString()
});
// with extended info and limit and ignore_collected
bool ignoreCollected = true;
requestMock = new UserShowRecommendationsRequest { ExtendedInfo = extendedInfo, Limit = limit, IgnoreCollected = ignoreCollected };
requestMock.GetUriPathParameters().Should().NotBeNull()
.And.HaveCount(3)
.And.Contain(new Dictionary<string, object>
{
["extended"] = extendedInfo.ToString(),
["limit"] = limit.ToString(),
["ignore_collected"] = ignoreCollected.ToString().ToLower()
});
}
}
}
| 48.918919 | 143 | 0.492541 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Tests/Trakt.NET.Requests.Tests/Recommendations/OAuth/UserShowRecommendationsRequest_Tests.cs | 3,622 | C# |
using System;
using System.Reflection;
// Delegate Cache
class C<T>
{
static Func<T> XX ()
{
System.Func<T> t = () => default (T);
return t;
}
}
// Delegate Cache
class C2<T>
{
static Func<C<T>> XX ()
{
System.Func<C<T>> t = () => default (C<T>);
return t;
}
}
// No delegate cache
class N1
{
static Func<T> XX<T> ()
{
System.Func<T> t = () => default (T);
return t;
}
}
public class Test
{
public static int Main ()
{
var t = typeof (C<>);
if (t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).Length != 1)
return 1;
t = typeof (C2<>);
if (t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).Length != 1)
return 1;
t = typeof (N1);
if (t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).Length != 0)
return 1;
Console.WriteLine ("OK");
return 0;
}
}
| 18.055556 | 123 | 0.631795 | [
"Apache-2.0"
] | 121468615/mono | mcs/tests/test-anon-135.cs | 975 | C# |
using UnityEngine;
using System.Collections;
public class FishSpawnBox : MonoBehaviour
{
public GameObject fishObject;
[SerializeField]
private bool spawnedOnLeft;
// Use this for initialization
void Start ()
{
InvokeRepeating("spawnFish", 0, 1f);
// spawnFish();
// spawnFish();
// spawnFish();
}
// Update is called once per frame
void Update () {
}
private void spawnFish()
{
Vector3 pos = transform.position;
pos.y = UnityEngine.Random.value * 10 - 5;
transform.position = pos;
GameObject obj = GameObject.Instantiate(fishObject,transform.position, Quaternion.identity) as GameObject;
obj.GetComponent<Fish>().spawnedOnLeft(spawnedOnLeft);
}
}
| 22.361111 | 115 | 0.612422 | [
"MIT"
] | Seth-W/SmallMarlin | Assets/Scripts/FishSpawnBox.cs | 807 | C# |
#pragma checksum "C:\Users\DTige.000\Documents\GitHub\AspNetCoreToDo\AspNetCoreToDo\Views\Home\Privacy.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d8ddb6bffa5a9b264bf8f89038bf03c234083fd3"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Privacy), @"mvc.1.0.view", @"/Views/Home/Privacy.cshtml")]
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;
#nullable restore
#line 1 "C:\Users\DTige.000\Documents\GitHub\AspNetCoreToDo\AspNetCoreToDo\Views\_ViewImports.cshtml"
using AspNetCoreTodo;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\DTige.000\Documents\GitHub\AspNetCoreToDo\AspNetCoreToDo\Views\_ViewImports.cshtml"
using AspNetCoreTodo.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d8ddb6bffa5a9b264bf8f89038bf03c234083fd3", @"/Views/Home/Privacy.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"63823eaa5b73e495aebe7447edc96790f50c299d", @"/Views/_ViewImports.cshtml")]
public class Views_Home_Privacy : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 1 "C:\Users\DTige.000\Documents\GitHub\AspNetCoreToDo\AspNetCoreToDo\Views\Home\Privacy.cshtml"
ViewData["Title"] = "Privacy Policy";
#line default
#line hidden
#nullable disable
WriteLiteral("<h1>");
#nullable restore
#line 4 "C:\Users\DTige.000\Documents\GitHub\AspNetCoreToDo\AspNetCoreToDo\Views\Home\Privacy.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral("</h1>\r\n\r\n<p>Use this page to detail your site\'s privacy policy.</p>\r\n");
}
#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<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 46.764706 | 194 | 0.762893 | [
"Apache-2.0"
] | DuanShaolong/AspNetCoreToDo | AspNetCoreTodo/obj/Debug/netcoreapp3.0/Razor/Views/Home/Privacy.cshtml.g.cs | 3,180 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UES_Sensor_Scale : UES_BaseModule
{
List<GameObject> touchingObjects = new List<GameObject>();
public float targetWeight = 1;
public float currentWdight = 0;
public UES_WaypointPositioner leftTrack, rightTrack;
public UES_IndicatorLight indicator;
bool bIsWeightedDown = false;
float GetTotalWeight
{
get
{
float f = 0;
foreach (GameObject obj in touchingObjects)
{
Rigidbody r = obj.GetComponent<Rigidbody>();
if (r == null)
continue;
f += r.mass;
}
return f;
}
}
private void OnTriggerEnter(Collider other)
{
touchingObjects.Add(other.gameObject);
}
public override void OnFixedUpdate()
{
base.OnFixedUpdate();
touchingObjects.Clear();
}
private void OnTriggerExit(Collider other)
{
touchingObjects.Remove(other.gameObject);
}
private void OnTriggerStay(Collider other)
{
touchingObjects.Add(other.gameObject);
}
public override void OnInactive()
{
//indicator.Off();
}
public override void OnUpdate()
{
currentWdight = GetTotalWeight;
base.OnUpdate();
if (currentWdight >= targetWeight)
{
//isUESModuleActive = true;
bIsWeightedDown = true;
indicator.On();
}
else
{
//isUESModuleActive = false;
bIsWeightedDown = false;
indicator.Off();
}
}
public override void OnPowered()
{
base.OnPowered();
float weightFactor = GetTotalWeight / targetWeight;
leftTrack.percent = weightFactor;
rightTrack.percent = weightFactor;
}
public override void SendPowerToModules(UES_Signal signal)
{
if (bIsWeightedDown == false)
return;
base.SendPowerToModules(signal);
}
}
| 22.473118 | 62 | 0.577033 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | DeathCharm/Unity-Electric-Systems | Assets/UES/Scripts/UES_Sensor_Scale.cs | 2,090 | C# |
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System;
using Microsoft.Practices.Prism.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using StockTraderRI.Infrastructure;
using StockTraderRI.Modules.Market.Tests.Mocks;
using StockTraderRI.Modules.Market.TrendLine;
namespace StockTraderRI.Modules.Market.Tests.TrendLine
{
/// <summary>
/// Unit tests for TrendLineViewModel
/// </summary>
[TestClass]
public class TrendLineViewModelFixture
{
[TestMethod]
public void CanInitPresenter()
{
var historyService = new MockMarketHistoryService();
var eventAggregator = new Mock<IEventAggregator>();
eventAggregator.Setup(x => x.GetEvent<TickerSymbolSelectedEvent>()).Returns(
new MockTickerSymbolSelectedEvent());
TrendLineViewModel presentationModel = new TrendLineViewModel(historyService, eventAggregator.Object);
Assert.IsNotNull(presentationModel);
}
[TestMethod]
public void ShouldUpdateModelWithDataFromServiceOnTickerSymbolSelected()
{
var historyService = new MockMarketHistoryService();
var tickerSymbolSelected = new MockTickerSymbolSelectedEvent();
var eventAggregator = new Mock<IEventAggregator>();
eventAggregator.Setup(x => x.GetEvent<TickerSymbolSelectedEvent>()).Returns(
tickerSymbolSelected);
TrendLineViewModel presentationModel = new TrendLineViewModel(historyService, eventAggregator.Object);
tickerSymbolSelected.SubscribeArgumentAction("MyTickerSymbol");
Assert.IsTrue(historyService.GetPriceHistoryCalled);
Assert.AreEqual("MyTickerSymbol", historyService.GetPriceHistoryArgument);
Assert.IsNotNull(presentationModel.HistoryCollection);
Assert.AreEqual(historyService.Data.Count, presentationModel.HistoryCollection.Count);
Assert.AreEqual(historyService.Data[0], presentationModel.HistoryCollection[0]);
Assert.AreEqual("MyTickerSymbol", presentationModel.TickerSymbol);
}
}
internal class MockTickerSymbolSelectedEvent : TickerSymbolSelectedEvent
{
public Action<string> SubscribeArgumentAction;
public Predicate<string> SubscribeArgumentFilter;
public override SubscriptionToken Subscribe(Action<string> action, ThreadOption threadOption, bool keepSubscriberReferenceAlive, Predicate<string> filter)
{
SubscribeArgumentAction = action;
SubscribeArgumentFilter = filter;
return null;
}
}
}
| 47.658228 | 163 | 0.642231 | [
"MIT"
] | cointoss1973/Prism4.1-WPF | StockTrader RI/Desktop/StockTraderRI.Modules.Market.Tests/TrendLineView/TrendLineViewModelFixture.cs | 3,765 | C# |
using System;
using System.IO;
namespace ExcelTrans.Commands
{
public struct PopSet : IExcelCommand
{
public When When { get; }
void IExcelCommand.Read(BinaryReader r) { }
void IExcelCommand.Write(BinaryWriter w) { }
void IExcelCommand.Execute(IExcelContext ctx, ref Action after) => ctx.Sets.Pop().Execute(ctx);
internal static void Flush(IExcelContext ctx, int idx)
{
while (ctx.Sets.Count > idx)
ctx.Sets.Pop().Execute(ctx);
}
void IExcelCommand.Describe(StringWriter w, int pad) { w.WriteLine($"{new string(' ', pad)}PopSet"); }
}
} | 31.619048 | 111 | 0.600904 | [
"MIT"
] | smorey2/ExcelTrans | ExcelTrans/Commands/PopSet.cs | 666 | C# |
using System;
using Abp.Zero.SampleApp.BookStore;
using Shouldly;
using Xunit;
namespace Abp.Zero.SampleApp.Tests
{
public class PrimaryKey_Guid_Generation_Tests : SampleAppTestBase
{
[Fact]
public void Guid_Id_Should_Not_Be_Generated_By_GuidGenerator_When_DatabaseGeneratedOption_Identity_Is_Used()
{
var guid = Guid.NewGuid();
UsingDbContext(context =>
{
var testGuidGenerator = new TestGuidGenerator(guid);
context.GuidGenerator = testGuidGenerator;
var book = context.Set<Book>().Add(new Book
{
Name = "Hitchhiker's Guide to the Galaxy"
});
context.SaveChanges();
testGuidGenerator.CreateCalled.ShouldBeFalse();
guid.ShouldNotBe(book.Id);
});
}
[Fact]
public void Guid_Id_Should_Not_Be_Generated_By_GuidGenerator_When_DatabaseGenerated_Identity_Attribute_Is_Used()
{
var guid = Guid.NewGuid();
UsingDbContext(context =>
{
var testGuidGenerator = new TestGuidGenerator(guid);
context.GuidGenerator = testGuidGenerator;
var author = context.Set<Author>().Add(new Author
{
Name = "Douglas Adams"
});
context.SaveChanges();
testGuidGenerator.CreateCalled.ShouldBeFalse();
guid.ShouldNotBe(author.Id);
});
}
internal class TestGuidGenerator : IGuidGenerator
{
private readonly Guid _guid;
public TestGuidGenerator(Guid guid)
{
_guid = guid;
}
public Guid Create()
{
CreateCalled = true;
return _guid;
}
public bool CreateCalled { get; private set; }
}
}
}
| 26.773333 | 120 | 0.537351 | [
"MIT"
] | CAH-FlyChen/aspnetboilerplate | test/Abp.Zero.SampleApp.Tests/PrimaryKey_Guid_Generation_Tests.cs | 2,010 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Rocket.Surgery.LaunchPad.Foundation;
namespace Rocket.Surgery.LaunchPad.AspNetCore.Filters;
/// <summary>
/// Not authorized exception that catches not authorized messages that might have been thrown by calling code.
/// </summary>
internal class NotAuthorizedExceptionFilter : ProblemDetailsExceptionFilter<NotAuthorizedException>
{
/// <summary>
/// Not authorized exception that catches not authorized messages that might have been thrown by calling code.
/// </summary>
public NotAuthorizedExceptionFilter(ProblemDetailsFactory problemDetailsFactory) : base(StatusCodes.Status403Forbidden, problemDetailsFactory)
{
}
}
| 39.105263 | 146 | 0.786003 | [
"MIT"
] | RocketSurgeonsGuild/SpaceShuttle | src/AspNetCore/Filters/NotAuthorizedExceptionFilter.cs | 743 | C# |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// WorkerResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Taskrouter.V1.Workspace
{
public class WorkerResource : Resource
{
private static Request BuildReadRequest(ReadWorkerOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Taskrouter,
"/v1/Workspaces/" + options.PathWorkspaceSid + "/Workers",
client.Region,
queryParams: options.GetParams()
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static ResourceSet<WorkerResource> Read(ReadWorkerOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<WorkerResource>.FromJson("workers", response.Content);
return new ResourceSet<WorkerResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WorkerResource>> ReadAsync(ReadWorkerOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<WorkerResource>.FromJson("workers", response.Content);
return new ResourceSet<WorkerResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="activityName"> Filter by workers that are in a particular Activity by Friendly Name </param>
/// <param name="activitySid"> Filter by workers that are in a particular Activity by SID </param>
/// <param name="available"> Filter by workers that are available or unavailable. </param>
/// <param name="friendlyName"> Filter by a worker's friendly name </param>
/// <param name="targetWorkersExpression"> Filter by workers that would match an expression on a TaskQueue. </param>
/// <param name="taskQueueName"> Filter by workers that are eligible for a TaskQueue by Friendly Name </param>
/// <param name="taskQueueSid"> Filter by workers that are eligible for a TaskQueue by SID </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static ResourceSet<WorkerResource> Read(string pathWorkspaceSid,
string activityName = null,
string activitySid = null,
string available = null,
string friendlyName = null,
string targetWorkersExpression = null,
string taskQueueName = null,
string taskQueueSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWorkerOptions(pathWorkspaceSid){ActivityName = activityName, ActivitySid = activitySid, Available = available, FriendlyName = friendlyName, TargetWorkersExpression = targetWorkersExpression, TaskQueueName = taskQueueName, TaskQueueSid = taskQueueSid, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="activityName"> Filter by workers that are in a particular Activity by Friendly Name </param>
/// <param name="activitySid"> Filter by workers that are in a particular Activity by SID </param>
/// <param name="available"> Filter by workers that are available or unavailable. </param>
/// <param name="friendlyName"> Filter by a worker's friendly name </param>
/// <param name="targetWorkersExpression"> Filter by workers that would match an expression on a TaskQueue. </param>
/// <param name="taskQueueName"> Filter by workers that are eligible for a TaskQueue by Friendly Name </param>
/// <param name="taskQueueSid"> Filter by workers that are eligible for a TaskQueue by SID </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<ResourceSet<WorkerResource>> ReadAsync(string pathWorkspaceSid,
string activityName = null,
string activitySid = null,
string available = null,
string friendlyName = null,
string targetWorkersExpression = null,
string taskQueueName = null,
string taskQueueSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadWorkerOptions(pathWorkspaceSid){ActivityName = activityName, ActivitySid = activitySid, Available = available, FriendlyName = friendlyName, TargetWorkersExpression = targetWorkersExpression, TaskQueueName = taskQueueName, TaskQueueSid = taskQueueSid, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<WorkerResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<WorkerResource>.FromJson("workers", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<WorkerResource> NextPage(Page<WorkerResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(
Rest.Domain.Taskrouter,
client.Region
)
);
var response = client.Request(request);
return Page<WorkerResource>.FromJson("workers", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<WorkerResource> PreviousPage(Page<WorkerResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(
Rest.Domain.Taskrouter,
client.Region
)
);
var response = client.Request(request);
return Page<WorkerResource>.FromJson("workers", response.Content);
}
private static Request BuildCreateRequest(CreateWorkerOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Taskrouter,
"/v1/Workspaces/" + options.PathWorkspaceSid + "/Workers",
client.Region,
postParams: options.GetParams()
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static WorkerResource Create(CreateWorkerOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<WorkerResource> CreateAsync(CreateWorkerOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="friendlyName"> String representing user-friendly name for the Worker. </param>
/// <param name="activitySid"> A valid Activity describing the worker's initial state. </param>
/// <param name="attributes"> JSON object describing this worker. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static WorkerResource Create(string pathWorkspaceSid,
string friendlyName,
string activitySid = null,
string attributes = null,
ITwilioRestClient client = null)
{
var options = new CreateWorkerOptions(pathWorkspaceSid, friendlyName){ActivitySid = activitySid, Attributes = attributes};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="friendlyName"> String representing user-friendly name for the Worker. </param>
/// <param name="activitySid"> A valid Activity describing the worker's initial state. </param>
/// <param name="attributes"> JSON object describing this worker. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<WorkerResource> CreateAsync(string pathWorkspaceSid,
string friendlyName,
string activitySid = null,
string attributes = null,
ITwilioRestClient client = null)
{
var options = new CreateWorkerOptions(pathWorkspaceSid, friendlyName){ActivitySid = activitySid, Attributes = attributes};
return await CreateAsync(options, client);
}
#endif
private static Request BuildFetchRequest(FetchWorkerOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Taskrouter,
"/v1/Workspaces/" + options.PathWorkspaceSid + "/Workers/" + options.PathSid + "",
client.Region,
queryParams: options.GetParams()
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static WorkerResource Fetch(FetchWorkerOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<WorkerResource> FetchAsync(FetchWorkerOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static WorkerResource Fetch(string pathWorkspaceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchWorkerOptions(pathWorkspaceSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<WorkerResource> FetchAsync(string pathWorkspaceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchWorkerOptions(pathWorkspaceSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateWorkerOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Taskrouter,
"/v1/Workspaces/" + options.PathWorkspaceSid + "/Workers/" + options.PathSid + "",
client.Region,
postParams: options.GetParams()
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static WorkerResource Update(UpdateWorkerOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<WorkerResource> UpdateAsync(UpdateWorkerOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="activitySid"> The activity_sid </param>
/// <param name="attributes"> The attributes </param>
/// <param name="friendlyName"> The friendly_name </param>
/// <param name="rejectPendingReservations"> The reject_pending_reservations </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static WorkerResource Update(string pathWorkspaceSid,
string pathSid,
string activitySid = null,
string attributes = null,
string friendlyName = null,
bool? rejectPendingReservations = null,
ITwilioRestClient client = null)
{
var options = new UpdateWorkerOptions(pathWorkspaceSid, pathSid){ActivitySid = activitySid, Attributes = attributes, FriendlyName = friendlyName, RejectPendingReservations = rejectPendingReservations};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="activitySid"> The activity_sid </param>
/// <param name="attributes"> The attributes </param>
/// <param name="friendlyName"> The friendly_name </param>
/// <param name="rejectPendingReservations"> The reject_pending_reservations </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<WorkerResource> UpdateAsync(string pathWorkspaceSid,
string pathSid,
string activitySid = null,
string attributes = null,
string friendlyName = null,
bool? rejectPendingReservations = null,
ITwilioRestClient client = null)
{
var options = new UpdateWorkerOptions(pathWorkspaceSid, pathSid){ActivitySid = activitySid, Attributes = attributes, FriendlyName = friendlyName, RejectPendingReservations = rejectPendingReservations};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteWorkerOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Taskrouter,
"/v1/Workspaces/" + options.PathWorkspaceSid + "/Workers/" + options.PathSid + "",
client.Region,
queryParams: options.GetParams()
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static bool Delete(DeleteWorkerOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Worker parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteWorkerOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Worker </returns>
public static bool Delete(string pathWorkspaceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteWorkerOptions(pathWorkspaceSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathWorkspaceSid"> The workspace_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Worker </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathWorkspaceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteWorkerOptions(pathWorkspaceSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a WorkerResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> WorkerResource object represented by the provided JSON </returns>
public static WorkerResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<WorkerResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The ID of the account that owns this worker
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// Filter by workers that are in a particular Activity by Friendly Name
/// </summary>
[JsonProperty("activity_name")]
public string ActivityName { get; private set; }
/// <summary>
/// Filter by workers that are in a particular Activity by SID
/// </summary>
[JsonProperty("activity_sid")]
public string ActivitySid { get; private set; }
/// <summary>
/// JSON object describing this worker.
/// </summary>
[JsonProperty("attributes")]
public string Attributes { get; private set; }
/// <summary>
/// Filter by workers that are available or unavailable.
/// </summary>
[JsonProperty("available")]
public bool? Available { get; private set; }
/// <summary>
/// DateTime this worker was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// DateTime of the last change to the Worker's activity.
/// </summary>
[JsonProperty("date_status_changed")]
public DateTime? DateStatusChanged { get; private set; }
/// <summary>
/// DateTime of the last update
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// Filter by a worker's friendly name
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The unique ID of the worker
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The ID of the Workflow this worker is associated with
/// </summary>
[JsonProperty("workspace_sid")]
public string WorkspaceSid { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The links
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private WorkerResource()
{
}
}
} | 49.153061 | 321 | 0.537852 | [
"MIT"
] | FMV1491/twilio-csharp | src/Twilio/Rest/Taskrouter/V1/Workspace/WorkerResource.cs | 28,902 | C# |
/*
* FactSet SCIM API
*
* FactSet's SCIM API implementation.
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = FactSet.SDK.ProcuretoPayAPISCIM.Client.OpenAPIDateConverter;
namespace FactSet.SDK.ProcuretoPayAPISCIM.Model
{
/// <summary>
/// A complex type that specifies FILTER options.
/// </summary>
[DataContract(Name = "ServiceProviderConfig_filter")]
public partial class ServiceProviderConfigFilter : IEquatable<ServiceProviderConfigFilter>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ServiceProviderConfigFilter" /> class.
/// </summary>
[JsonConstructorAttribute]
public ServiceProviderConfigFilter()
{
}
/// <summary>
/// A Boolean value specifying whether or not the operation is supported.
/// </summary>
/// <value>A Boolean value specifying whether or not the operation is supported.</value>
[DataMember(Name = "supported", IsRequired = true, EmitDefaultValue = true)]
public bool Supported { get; private set; }
/// <summary>
/// Returns false as Supported should not be serialized given that it's read-only.
/// </summary>
/// <returns>false (boolean)</returns>
public bool ShouldSerializeSupported()
{
return false;
}
/// <summary>
/// An integer value specifying the maximum number of resources returned in a response.
/// </summary>
/// <value>An integer value specifying the maximum number of resources returned in a response.</value>
[DataMember(Name = "maxResults", IsRequired = true, EmitDefaultValue = false)]
public int MaxResults { get; private set; }
/// <summary>
/// Returns false as MaxResults should not be serialized given that it's read-only.
/// </summary>
/// <returns>false (boolean)</returns>
public bool ShouldSerializeMaxResults()
{
return false;
}
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class ServiceProviderConfigFilter {\n");
sb.Append(" Supported: ").Append(Supported).Append("\n");
sb.Append(" MaxResults: ").Append(MaxResults).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ServiceProviderConfigFilter);
}
/// <summary>
/// Returns true if ServiceProviderConfigFilter instances are equal
/// </summary>
/// <param name="input">Instance of ServiceProviderConfigFilter to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ServiceProviderConfigFilter input)
{
if (input == null)
{
return false;
}
return
(
this.Supported == input.Supported ||
this.Supported.Equals(input.Supported)
) &&
(
this.MaxResults == input.MaxResults ||
this.MaxResults.Equals(input.MaxResults)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = (hashCode * 59) + this.Supported.GetHashCode();
hashCode = (hashCode * 59) + this.MaxResults.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 35.051948 | 128 | 0.59522 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/ProcuretoPayAPISCIM/v1/src/FactSet.SDK.ProcuretoPayAPISCIM/Model/ServiceProviderConfigFilter.cs | 5,398 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 29.03.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int32.Single{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Int32;
using T_DATA2 =System.Single;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_R504ABB002__param
public static class TestSet_R504ABB002__param
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
string vv1="1";
T_DATA2 vv2=2;
var recs=db.testTable.Where(r => (string)(object)(((T_DATA1)vv1.Length)*vv2*vv2)=="4.000000000000000");
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
[Test]
public static void Test_002()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
string vv1="1";
T_DATA2 vv2=2;
var recs=db.testTable.Where(r => (string)(object)((((T_DATA1)vv1.Length)*vv2)*vv2)=="4.000000000000000");
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002
//-----------------------------------------------------------------------
[Test]
public static void Test_003()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
string vv1="1";
T_DATA2 vv2=2;
var recs=db.testTable.Where(r => (string)(object)(((T_DATA1)vv1.Length)*(vv2*vv2))=="4.000000000000000");
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003
};//class TestSet_R504ABB002__param
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int32.Single
| 23.73301 | 136 | 0.523215 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_002__AS_STR/Multiply/Complete/Int32/Single/TestSet_R504ABB002__param.cs | 4,891 | C# |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace EventStore.Core.Tests {
public static class TaskExtensions {
public static Task WithTimeout(this Task task, TimeSpan timeout, [CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
=> task.WithTimeout(Convert.ToInt32(timeout.TotalMilliseconds), memberName, sourceFilePath, sourceLineNumber);
public static async Task WithTimeout(this Task task, int timeoutMs = 10000,
[CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0) {
if (Debugger.IsAttached) {
timeoutMs = -1;
}
if (await Task.WhenAny(task, Task.Delay(timeoutMs)) != task)
throw new TimeoutException($"Timed out waiting for task at: {memberName} {sourceFilePath}:{sourceLineNumber}");
await task;
}
public static Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout, [CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
=> task.WithTimeout(Convert.ToInt32(timeout.TotalMilliseconds), memberName, sourceFilePath, sourceLineNumber);
public static async Task<T> WithTimeout<T>(this Task<T> task, int timeoutMs = 10000,
[CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0) {
if (Debugger.IsAttached) {
timeoutMs = -1;
}
if (await Task.WhenAny(task, Task.Delay(timeoutMs)) == task)
return await task;
throw new TimeoutException($"Timed out waiting for task at: {memberName} {sourceFilePath}:{sourceLineNumber}");
}
}
}
| 41.136364 | 118 | 0.734254 | [
"Apache-2.0",
"CC0-1.0"
] | BearerPipelineTest/EventStore | src/EventStore.Core.Tests/TaskExtensions.cs | 1,810 | 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 test fragments the heap with ~50 byte holes, then allocates ~50 byte objects to plug them
*/
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
public class Test
{
public static List<GCHandle> gchList = new List<GCHandle>();
public static List<byte[]> bList = new List<byte[]>();
public static int Main()
{
Console.WriteLine("Beginning phase 1");
GCUtil.AllocWithGaps();
Console.WriteLine("phase 1 complete");
// losing all live references to the unpinned byte arrays
// this will fragment the heap with ~50 byte holes
GCUtil.FreeNonPins();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Console.WriteLine("Beginning phase 2");
bList = new List<byte[]>();
for (int i=0; i<1024*1024; i++)
{
byte[] unpinned = new byte[50];
bList.Add(unpinned);
}
Console.WriteLine("phase 2 complete");
GC.KeepAlive(gchList);
GC.KeepAlive(bList);
return 100;
}
} | 25.54902 | 94 | 0.629317 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/GC/Features/HeapExpansion/pluggaps.cs | 1,303 | C# |
#region Using directives
#endregion
namespace Blazorise
{
/// <summary>
/// Defines the heading size.
/// </summary>
public enum HeadingSize
{
/// <summary>
/// Main title.
/// </summary>
Is1,
Is2,
Is3,
Is4,
Is5,
Is6,
}
}
| 12.037037 | 33 | 0.446154 | [
"MIT"
] | CPlusPlus17/Blazorise | Source/Blazorise/Enums/HeadingSize.cs | 327 | C# |
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Zeds.Graphics.Background;
namespace Zeds.Engine
{
public static class Textures
{
#region Terrain
//Terrain
public static Texture2D BackgroundTexture;
public static Texture2D GrassTuftTexture;
public static Texture2D GrassTuft2Texture;
public static Texture2D GrassTuft3Texture;
public static Texture2D GrassTuft4Texture;
public static Texture2D Bush1Texture;
public static Texture2D Bush2Texture;
public static Texture2D Bush3Texture;
public static Texture2D Bush4Texture;
public static Texture2D Tree1Texture;
public static Texture2D Tree2Texture;
public static Texture2D Tree3Texture;
public static Texture2D Tree4Texture;
public static Texture2D TreeFoliage1;
#endregion
#region Pawns
//Pawns
public static Texture2D HumanMale1Texture;
public static Texture2D HumanFemale1Texture;
public static Texture2D ZedTexture;
#endregion
#region Structures
//Structures
public static Texture2D HqTexture;
public static Texture2D SmallTentTexture;
public static Texture2D LargeTentTexture;
public static Texture2D CabinTexture;
//Ruined Structures
public static Texture2D RuinedSmallTent;
public static Texture2D RuinedLargeTent;
public static Texture2D RuinedCabin;
public static Texture2D RuinedHQ;
#endregion
#region Interface
public static Texture2D CloseMenu;
//Build Menus
public static Texture2D BlankWindowPane;
public static Texture2D BuildMenuPane;
public static Texture2D BuildMenuIcon;
public static Texture2D DemolishIcon;
public static Texture2D TempMenuIcon;
public static Texture2D SmallTentBuildIcon;
public static Texture2D LargeTentBuildIcon;
public static Texture2D GatherIcon;
//Debug
public static Texture2D DebugSquareSmall;
public static Texture2D DebugSquareLarge;
public static Texture2D OnePixel;
//DetailsPane
public static Texture2D DetailsWindowPane;
public static Texture2D HealthBarOuter;
public static Texture2D HealthBarInner;
//InfoPane
public static Texture2D PawnInfoPane;
public static Texture2D InfoPawnOutline;
public static Texture2D SelectedEntity;
public static Texture2D InfoHead;
public static Texture2D InfoChest;
public static Texture2D InfoHand;
public static Texture2D InfoMisc;
//Cursors
public static Texture2D CursorTexture;
public static Texture2D DozerTexture;
public static Texture2D DozerDeniedTexture;
//Misc
public static Texture2D ExtendArrow;
public static Texture2D RedCross;
#endregion
#region Items
// Weapons
public static Texture2D KitchenKnife;
public static Texture2D CombatKnife;
#endregion
public static void LoadTextures(ContentManager Content)
{
#region Terrain
//Maps
BackgroundTexture = Content.Load<Texture2D>("Terrain/background");
GrassTuftTexture = Content.Load<Texture2D>("Terrain/Grass/grasstuft");
GrassTuft2Texture = Content.Load<Texture2D>("Terrain/Grass/grasstufttwo");
GrassTuft3Texture = Content.Load<Texture2D>("Terrain/Grass/grasstuftthree");
GrassTuft4Texture = Content.Load<Texture2D>("Terrain/Grass/grasstuftfour");
Bush1Texture = Content.Load<Texture2D>("Terrain/Bushes/bush1");
Bush2Texture = Content.Load<Texture2D>("Terrain/Bushes/bush2");
Bush3Texture = Content.Load<Texture2D>("Terrain/Bushes/bush3");
Bush4Texture = Content.Load<Texture2D>("Terrain/Bushes/bush4");
Tree1Texture = Content.Load<Texture2D>("Terrain/Tree/tree1");
Tree2Texture = Content.Load<Texture2D>("Terrain/Tree/tree2");
Tree3Texture = Content.Load<Texture2D>("Terrain/Tree/tree3");
Tree4Texture = Content.Load<Texture2D>("Terrain/Tree/tree4");
TreeFoliage1 = Content.Load<Texture2D>("Terrain/Tree/Tree1Folliage");
#endregion
#region Pawns
//Pawns
HumanMale1Texture = Content.Load<Texture2D>("Pawns/Human/HumanMale1");
HumanFemale1Texture = Content.Load<Texture2D>("Pawns/Human/HumanFemale1");
ZedTexture = Content.Load<Texture2D>("Pawns/Zed/BasicZed");
#endregion
#region Structures
//Structures
HqTexture = Content.Load<Texture2D>("Buildings/HQTexture");
SmallTentTexture = Content.Load<Texture2D>("Buildings/SmallTent");
LargeTentTexture = Content.Load<Texture2D>("Buildings/LargeTent");
CabinTexture = Content.Load<Texture2D>("Buildings/CabinTexture");
//Ruined Structures
RuinedSmallTent = Content.Load<Texture2D>("Buildings/RuinedSmallTent");
RuinedLargeTent = Content.Load<Texture2D>("Buildings/RuinedLargeTent");
RuinedCabin = Content.Load<Texture2D>("Buildings/RuinedCabin");
RuinedHQ = Content.Load<Texture2D>("Buildings/RuinedHQTexture");
#endregion
#region Interface
CloseMenu = Content.Load<Texture2D>("Interface/CloseMenu");
//Cursors
CursorTexture = Content.Load<Texture2D>("Interface/Cursors/cursor");
DozerTexture = Content.Load<Texture2D>("Interface/Cursors/DozerIcon");
DozerDeniedTexture = Content.Load<Texture2D>("Interface/Cursors/DozerDeniedIcon");
//Menu Panes
BlankWindowPane = Content.Load<Texture2D>("Interface/Menus/BlankWindowPane");
DetailsWindowPane = Content.Load<Texture2D>("Interface/Menus/DetailsWindowPane");
BuildMenuPane = Content.Load<Texture2D>("Interface/Menus/BuildMenuPane");
//Pawn Info Panel
PawnInfoPane = Content.Load<Texture2D>("Interface/Menus/PawnInfoPane");
InfoPawnOutline = Content.Load<Texture2D>("Interface/Menus/PawnOutline");
SelectedEntity = Content.Load<Texture2D>("Interface/Menus/SelectedEntity");
InfoHead = Content.Load<Texture2D>("Interface/Menus/InfoHead");
InfoChest = Content.Load<Texture2D>("Interface/Menus/InfoChest");
InfoHand = Content.Load<Texture2D>("Interface/Menus/InfoHand");
InfoMisc = Content.Load<Texture2D>("Interface/Menus/InfoMisc");
//Menu Icons
BuildMenuIcon = Content.Load<Texture2D>("Interface/Menus/BuildMenuIcon");
DemolishIcon = Content.Load<Texture2D>("Interface/Menus/Bulldozer");
TempMenuIcon = Content.Load<Texture2D>("Interface/Menus/tempIcon");
SmallTentBuildIcon = Content.Load<Texture2D>("Interface/Menus/SmallTentBuildIcon");
LargeTentBuildIcon = Content.Load<Texture2D>("Interface/Menus/LargeTentBuildIcon");
GatherIcon = Content.Load<Texture2D>("Interface/Menus/pickaxe");
DebugSquareSmall = Content.Load<Texture2D>("Interface/Debug/DebugSquareSmall");
DebugSquareLarge = Content.Load<Texture2D>("Interface/Debug/DebugSquareLarge");
OnePixel = Content.Load<Texture2D>("Interface/Debug/1px");
HealthBarOuter = Content.Load<Texture2D>("Interface/HealthBar");
HealthBarInner = Content.Load<Texture2D>("Interface/HealthBarInner");
//Misc
ExtendArrow = Content.Load<Texture2D>("Interface/ExtendArrow");
RedCross = Content.Load<Texture2D>("Interface/redcross");
#endregion
#region Items
//Weapons
KitchenKnife = Content.Load<Texture2D>("Item/Weapon/KitchenKnife");
CombatKnife = Content.Load<Texture2D>("Item/Weapon/CombatKnife");
#endregion
}
}
} | 40.745 | 95 | 0.663762 | [
"MIT"
] | Ratstool/Zeds | Graphics/Textures.cs | 8,151 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContestsApi.Data
{
public interface IDbContext : IDisposable, IObjectContextAdapter
{
int SaveChanges();
DbContextConfiguration Configuration { get; }
}
}
| 20.705882 | 68 | 0.747159 | [
"MIT"
] | QuinntyneBrown/contest-api | ContestsApi/Data/IDbContext.cs | 352 | C# |
using ETModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// 提供一个可供寻找到BUFF对应的Handler的组件
/// </summary>
public class BuffHandlerComponent : ETModel.Component
{
public static BuffHandlerComponent Instance;
public Dictionary<string, BaseBuffHandler> BuffHandlerDic;
public override void Dispose()
{
base.Dispose();
Instance = null;
BuffHandlerDic.Clear();
}
}
| 19.76 | 62 | 0.712551 | [
"MIT"
] | shadowcking/ET-RPG-DEMO | Server/Model/GamePlay/Battle/Buff/BuffHandlerComponent.cs | 526 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Lib.MVVM;
using Wpf.GridView.Types;
namespace Wpf.GridView.Models
{
public partial class NewItemModel : PropertyChangedNotification
{
public ItemType NewItem
{
get => GetValue(() => NewItem);
set => SetValue(() => NewItem, value);
}
}
}
| 21.095238 | 67 | 0.656885 | [
"MIT"
] | KohrAhr/XTask | Wpf.MainApp/Models/NewItemModel.cs | 445 | C# |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using Newtonsoft.Json;
namespace Microsoft.WindowsAzure.MobileServices.Test
{
public class DerivedDuplicateKeyType : PocoType
{
[JsonProperty(PropertyName = "PublicProperty")]
public string OtherThanPublicProperty { get; set; }
}
}
| 32.266667 | 80 | 0.485537 | [
"Apache-2.0"
] | AndreyMitsyk/azure-mobile-apps-net-client | unittest/Microsoft.WindowsAzure.MobileServices.Test/SerializationTypes/DerivedDuplicateKeyType.cs | 486 | 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 elasticmapreduce-2009-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticMapReduce.Model
{
/// <summary>
///
/// </summary>
public partial class NotebookExecutionSummary
{
private string _editorId;
private DateTime? _endTime;
private string _notebookExecutionId;
private string _notebookExecutionName;
private DateTime? _startTime;
private NotebookExecutionStatus _status;
/// <summary>
/// Gets and sets the property EditorId.
/// <para>
/// The unique identifier of the editor associated with the notebook execution.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=256)]
public string EditorId
{
get { return this._editorId; }
set { this._editorId = value; }
}
// Check to see if EditorId property is set
internal bool IsSetEditorId()
{
return this._editorId != null;
}
/// <summary>
/// Gets and sets the property EndTime.
/// <para>
/// The timestamp when notebook execution started.
/// </para>
/// </summary>
public DateTime EndTime
{
get { return this._endTime.GetValueOrDefault(); }
set { this._endTime = value; }
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this._endTime.HasValue;
}
/// <summary>
/// Gets and sets the property NotebookExecutionId.
/// <para>
/// The unique identifier of the notebook execution.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=256)]
public string NotebookExecutionId
{
get { return this._notebookExecutionId; }
set { this._notebookExecutionId = value; }
}
// Check to see if NotebookExecutionId property is set
internal bool IsSetNotebookExecutionId()
{
return this._notebookExecutionId != null;
}
/// <summary>
/// Gets and sets the property NotebookExecutionName.
/// <para>
/// The name of the notebook execution.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=256)]
public string NotebookExecutionName
{
get { return this._notebookExecutionName; }
set { this._notebookExecutionName = value; }
}
// Check to see if NotebookExecutionName property is set
internal bool IsSetNotebookExecutionName()
{
return this._notebookExecutionName != null;
}
/// <summary>
/// Gets and sets the property StartTime.
/// <para>
/// The timestamp when notebook execution started.
/// </para>
/// </summary>
public DateTime StartTime
{
get { return this._startTime.GetValueOrDefault(); }
set { this._startTime = value; }
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this._startTime.HasValue;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The status of the notebook execution.
/// </para>
/// <ul> <li>
/// <para>
/// <code>START_PENDING</code> indicates that the cluster has received the execution
/// request but execution has not begun.
/// </para>
/// </li> <li>
/// <para>
/// <code>STARTING</code> indicates that the execution is starting on the cluster.
/// </para>
/// </li> <li>
/// <para>
/// <code>RUNNING</code> indicates that the execution is being processed by the cluster.
/// </para>
/// </li> <li>
/// <para>
/// <code>FINISHING</code> indicates that execution processing is in the final stages.
/// </para>
/// </li> <li>
/// <para>
/// <code>FINISHED</code> indicates that the execution has completed without error.
/// </para>
/// </li> <li>
/// <para>
/// <code>FAILING</code> indicates that the execution is failing and will not finish
/// successfully.
/// </para>
/// </li> <li>
/// <para>
/// <code>FAILED</code> indicates that the execution failed.
/// </para>
/// </li> <li>
/// <para>
/// <code>STOP_PENDING</code> indicates that the cluster has received a <code>StopNotebookExecution</code>
/// request and the stop is pending.
/// </para>
/// </li> <li>
/// <para>
/// <code>STOPPING</code> indicates that the cluster is in the process of stopping the
/// execution as a result of a <code>StopNotebookExecution</code> request.
/// </para>
/// </li> <li>
/// <para>
/// <code>STOPPED</code> indicates that the execution stopped because of a <code>StopNotebookExecution</code>
/// request.
/// </para>
/// </li> </ul>
/// </summary>
public NotebookExecutionStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
}
} | 32.870647 | 119 | 0.539579 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ElasticMapReduce/Generated/Model/NotebookExecutionSummary.cs | 6,607 | 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;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.vod.Model.V20170321;
namespace Aliyun.Acs.vod.Transform.V20170321
{
public class ListAppInfoResponseUnmarshaller
{
public static ListAppInfoResponse Unmarshall(UnmarshallerContext context)
{
ListAppInfoResponse listAppInfoResponse = new ListAppInfoResponse();
listAppInfoResponse.HttpResponse = context.HttpResponse;
listAppInfoResponse.RequestId = context.StringValue("ListAppInfo.RequestId");
List<ListAppInfoResponse.ListAppInfo_AppInfo> listAppInfoResponse_appInfoList = new List<ListAppInfoResponse.ListAppInfo_AppInfo>();
for (int i = 0; i < context.Length("ListAppInfo.AppInfoList.Length"); i++) {
ListAppInfoResponse.ListAppInfo_AppInfo appInfo = new ListAppInfoResponse.ListAppInfo_AppInfo();
appInfo.AppId = context.StringValue("ListAppInfo.AppInfoList["+ i +"].AppId");
appInfo.AppName = context.StringValue("ListAppInfo.AppInfoList["+ i +"].AppName");
appInfo.Type = context.StringValue("ListAppInfo.AppInfoList["+ i +"].Type");
appInfo.Description = context.StringValue("ListAppInfo.AppInfoList["+ i +"].Description");
appInfo.Status = context.StringValue("ListAppInfo.AppInfoList["+ i +"].Status");
appInfo.CreationTime = context.StringValue("ListAppInfo.AppInfoList["+ i +"].CreationTime");
appInfo.ModificationTime = context.StringValue("ListAppInfo.AppInfoList["+ i +"].ModificationTime");
listAppInfoResponse_appInfoList.Add(appInfo);
}
listAppInfoResponse.AppInfoList = listAppInfoResponse_appInfoList;
return listAppInfoResponse;
}
}
}
| 45.963636 | 136 | 0.73932 | [
"Apache-2.0"
] | fossabot/aliyun-openapi-net-sdk | aliyun-net-sdk-vod/Vod/Transform/V20170321/ListAppInfoResponseUnmarshaller.cs | 2,528 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace PMCommonEntities.Models
{
public class PseudoFunds
{
public int Id { get; set; }
public string FundName { get; set; }
public string FundTicker { get; set; }
public string FundDescription { get; set; }
public double InitialInvestment { get; set; }
public int SharesOutstanding { get; set; }
public RDSEnums.EnvironmentId EnvironmentId { get; set; }
}
}
| 26.315789 | 65 | 0.65 | [
"MIT"
] | pseudomarkets/PMCommonEntities | PMCommonEntities/Models/PseudoFunds.cs | 502 | C# |
using System;
using TitaniumAS.Opc.Client.Common;
using TitaniumAS.Opc.Client.Interop.Da;
using TitaniumAS.Opc.Client.Interop.System;
namespace TitaniumAS.Opc.Client.Da.Wrappers
{
public class OpcAsyncIO2 : ComWrapper
{
public OpcAsyncIO2(object comObject, object userData) : base(userData)
{
if (comObject == null) throw new ArgumentNullException("comObject");
ComObject = DoComCall(comObject, "IUnknown::QueryInterface<IOpcAsyncIO2>",
() => comObject.QueryInterface<IOPCAsyncIO2>());
}
private IOPCAsyncIO2 ComObject { get; set; }
public bool Enable
{
get
{
return DoComCall(ComObject, "IOpcAsyncIO2::GetEnable", () =>
{
bool enable;
ComObject.GetEnable(out enable);
return enable;
});
}
set { DoComCall(ComObject, "IOpcAsyncIO2::SetEnable", () => ComObject.SetEnable(value), value); }
}
public int Read(int[] serverHandles, int transactionId, out HRESULT[] errors)
{
var _errors = new HRESULT[serverHandles.Length];
int result = DoComCall(ComObject, "IOpcAsyncIO2::Read", () =>
{
int dwCancelId;
ComObject.Read(serverHandles.Length, serverHandles, transactionId, out dwCancelId, out _errors);
return dwCancelId;
}, serverHandles, transactionId);
errors = _errors;
return result;
}
public int Write(int[] serverHandles, object[] values, int transactionId, out HRESULT[] errors)
{
var _errors = new HRESULT[serverHandles.Length];
int result = DoComCall(ComObject, "IOpcAsyncIO2::Write", () =>
{
int dwCancelId;
ComObject.Write(serverHandles.Length, serverHandles, values, transactionId, out dwCancelId, out _errors);
return dwCancelId;
}, serverHandles, values, transactionId);
errors = _errors;
return result;
}
public int Refresh2(OPCDATASOURCE dataSource, int transactionID)
{
return DoComCall(ComObject, "IOpcAsyncIO2::Refresh2", () =>
{
int dwCancelId;
ComObject.Refresh2(dataSource, transactionID, out dwCancelId);
return dwCancelId;
}, dataSource, transactionID);
}
public void Cancel2(int cancelId)
{
DoComCall(ComObject, "IOpcAsyncIO2::Cancel2", () => ComObject.Cancel2(cancelId), cancelId);
}
}
} | 36.635135 | 121 | 0.568794 | [
"MIT"
] | FaperCommon/TitaniumAS.Opc.Client | TitaniumAS.Opc.Client/Da/Wrappers/OpcAsyncIO2.cs | 2,713 | C# |
using OilChange.Dto;
using OilChange.Services;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using static OilChange.Util.CsvParser;
using static OilChange.Util.Toggler;
namespace OilChange
{
public partial class Form1 : Form
{
const double laborCost = 15.00;
const double salesTax = 0.7;
//Fields
string fileTarget = Global.FileTargetPath;
IEnumerable<string> eLines; //String array when file is read
VehicleService fileData = new VehicleService(); //methods for accessing the data in the file
//Constructor
public Form1()
{
InitializeComponent();
Global.FilePathChanged += new EventHandler<string>(OnFilePathChanged);
}
//Event-handler when form Load
private void Form1_Load(object sender, EventArgs e)
{
try
{
folderPathLabel.Text = "Data path: " + fileTarget;
eLines = File.ReadLines(fileTarget);
updateCarList(ParseFile(eLines));
} catch
{
}
}
//Event-handler when file path changed
private void OnFilePathChanged(object sender, string e)
{
fileTarget = e;
folderPathLabel.Text = "Data Path: " + e;
}
//Event-Handler when add button is clicked
//New Vehicle
private void addCarBtn_Click(object sender, EventArgs e)
{
//Execute Add button
if (!makeTextBox.ReadOnly)
{
try
{
//Parse the data from textboxes/////
//Car Textboxes
string make = makeTextBox.Text;
string model = modelTextBox.Text;
int year = Int32.Parse(yearTextBox.Text);
Vehicle carObj = new Vehicle(make, model, year);
//Oil Textboxes
string w = weightTextBox.Text;
string b = brandTextBox.Text;
double qty = Double.Parse(qtyTextBox.Text);
double oprice = Double.Parse(oPriceTextBox.Text);
string fb = fBrandTextBox.Text;
double fp = Double.Parse(fPriceTextBox.Text);
Oil oilObj = new Oil(w, b, qty, oprice, fb, fp);
//Service info
double labor = Double.Parse(laborHourTextBox.Text);
DateTime sDate = DateTime.Parse(dateTimePicker1.Text);
int sMileage = Int32.Parse(sMileageTxtbox.Text);
DateTime ns = dateTimePicker2.Value;
int nm = Int32.Parse(nextSMileageTxtbox.Text);
//Add new vehicle to the file
fileData.AddVehicleService(carObj, oilObj, labor, sDate, sMileage, ns, nm);
//Read the file
eLines = File.ReadLines(fileTarget);
//Update main source
updateCarList(ParseFile(eLines));
//Display the added data in a message box//
string msg = carObj.ToString() + oilObj.ToString();
MessageBox.Show("Car has been successfully added: \n" + msg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
gridCarSelect.ClearSelection();
ToggleReadOnly(makeTextBox, modelTextBox, yearTextBox, weightTextBox, brandTextBox, qtyTextBox, oPriceTextBox, fBrandTextBox, fPriceTextBox, laborHourTextBox, sMileageTxtbox, nextSMileageTxtbox);
dateTimePicker1.Enabled = false;
dateTimePicker2.Enabled = false;
gridCarSelect.Enabled = true;
return;
}
//Unlock textboxes for user input
ToggleReadOnly(makeTextBox, modelTextBox, yearTextBox, weightTextBox, brandTextBox, qtyTextBox, oPriceTextBox, fBrandTextBox, fPriceTextBox, laborHourTextBox, sMileageTxtbox, nextSMileageTxtbox);
dateTimePicker1.Enabled = true;
dateTimePicker2.Enabled = true;
//Clears out everything
newForm();
}
//Event-Handler: When user click a vehicle
private void gridCarSelect_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (gridCarSelect.SelectedRows.Count > 0)
{
OilChangeInfo oci = parseObjToOilChangeInfo(gridCarSelect.SelectedRows[0].DataBoundItem);
makeTextBox.Text = oci.Car.Make;
modelTextBox.Text = oci.Car.Model;
yearTextBox.Text = oci.Car.Year.ToString();
weightTextBox.Text = oci.Oil.Weight;
brandTextBox.Text = oci.Oil.Brand;
qtyTextBox.Text = oci.Oil.Quantity.ToString();
oPriceTextBox.Text = oci.Oil.OilPrice.ToString();
fPriceTextBox.Text = oci.Oil.FPrice.ToString();
fBrandTextBox.Text = oci.Oil.FBrand;
laborHourTextBox.Text = oci.LaborHours.ToString();
dateTimePicker1.Value = oci.ServicedDate;
dateTimePicker2.Value = oci.NextService;
sMileageTxtbox.Text = oci.ServicedMileage.ToString();
nextSMileageTxtbox.Text = oci.NextServiceMileage.ToString();
}
}
//Event-Handler: Reset selection when data is updated
private void gridCarSelect_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
gridCarSelect.ClearSelection();
}
//Local method for updating the Main Array
private void updateCarList(List<OilChangeInfo> s) //s is the passed List of cars from the file
{
//Updates the main source
Global.MainArraySource = s;
//Update display table
rebindGrid(s);
}
private void rebindGrid(List<OilChangeInfo> oci)
{
//Updates the displayed table
var bind = oci.Select(x => {
double subtotal = (x.LaborHours * laborCost) + (x.Oil.OilPrice * x.Oil.Quantity) + x.Oil.FPrice;
double Total = subtotal + (subtotal * salesTax);
return new
{
Id = x.Id,
Make = x.Car.Make,
Model = x.Car.Model,
Year = x.Car.Year,
Weight = x.Oil.Weight,
Brand = x.Oil.Brand,
Quantity = x.Oil.Quantity,
OilPrice = String.Format("{0:C}", x.Oil.OilPrice),
FBrand = x.Oil.FBrand,
FPrice = String.Format("{0:C}", x.Oil.FPrice),
ServicedDate = x.ServicedDate,
ServicedMileage = x.ServicedMileage,
LaborHour = x.LaborHours,
NextServiceDate = x.NextService,
NextMileage = x.NextServiceMileage,
TotalPrice = String.Format("{0:C}",Total),
};
}
).ToList();
gridCarSelect.AutoGenerateColumns = false;
gridCarSelect.DataSource = bind;
}
private OilChangeInfo parseObjToOilChangeInfo(object obj)
{
var props = obj.GetType().GetProperties();
int id = 1000000;
string make = "Unknown";
string model = "Unknown";
int year = 9999;
string weight = "Unknown";
string brand = "Unknown";
string fbrand = "Unknown";
double fprice = 0;
double qty = 0;
double oprice = 0;
double labor = 0;
DateTime sd = DateTime.Now;
int mileage = 0;
DateTime nextDate = DateTime.Now;
int nm = 0;
foreach(var prop in props)
{
if (prop.Name == "Id") id = (int) prop.GetValue(obj);
if (prop.Name == "Make") make = prop.GetValue(obj) as string;
if (prop.Name == "Model") model = prop.GetValue(obj) as string;
if (prop.Name == "Year") year = (int) prop.GetValue(obj);
if (prop.Name == "Weight") weight = prop.GetValue(obj) as string;
if (prop.Name == "Brand") brand = prop.GetValue(obj) as string;
if (prop.Name == "FBrand") fbrand = prop.GetValue(obj) as string;
if (prop.Name == "Quantity") qty = (double) prop.GetValue(obj);
if (prop.Name == "FPrice")
fprice = double.Parse(prop.GetValue(obj) as string, NumberStyles.Currency);
if (prop.Name == "OilPrice")
oprice = double.Parse(prop.GetValue(obj) as string, NumberStyles.Currency);
if (prop.Name == "LaborHour") labor = (double)prop.GetValue(obj);
if (prop.Name == "ServicedDate") sd = (DateTime) prop.GetValue(obj);
if (prop.Name == "ServicedMileage") mileage = (int) prop.GetValue(obj);
if (prop.Name == "NextMileage") nm = (int) prop.GetValue(obj);
if (prop.Name == "NextServiceDate") nextDate = (DateTime) prop.GetValue(obj);
}
OilChangeInfo oci = new OilChangeInfo(id, make, model, year, weight, brand, qty, oprice, fbrand, fprice, labor, sd, mileage, nextDate, nm);
return oci;
}
private void newForm()
{
gridCarSelect.ClearSelection();
gridCarSelect.Enabled = false;
makeTextBox.Text = "";
modelTextBox.Text = "";
yearTextBox.Text = "";
weightTextBox.Text = "";
brandTextBox.Text = "";
qtyTextBox.Text = "";
oPriceTextBox.Text = "";
fPriceTextBox.Text = "";
fBrandTextBox.Text = "";
laborHourTextBox.Text = "";
dateTimePicker1.Value = DateTime.Now;
dateTimePicker2.Value = DateTime.Now.AddMonths(3);
sMileageTxtbox.Text = "";
nextSMileageTxtbox.Text = "";
}
private void searchButton_Click(object sender, EventArgs e)
{
List<OilChangeInfo> lists = Global.MainArraySource;
List<OilChangeInfo> searchedCars = new List<OilChangeInfo>();
DateTime a = DateTime.Today;
DateTime reference = new DateTime(1, 1, 1);
for (int x = 0; x < lists.Count; x++)
{
DateTime b = lists[x].NextService;
TimeSpan span = b - a;
int months = (reference + span).Month - 1;
if (months <= 1)
{
searchedCars.Add(lists[x]);
}
}
rebindGrid(searchedCars);
searchButton.Enabled = false;
addCarBtn.Enabled = false;
clearFilterBtn.Enabled = true;
if (!makeTextBox.ReadOnly)
{
ToggleReadOnly(makeTextBox, modelTextBox, yearTextBox, weightTextBox, brandTextBox, qtyTextBox, oPriceTextBox, fBrandTextBox, fPriceTextBox, laborHourTextBox, sMileageTxtbox, nextSMileageTxtbox);
}
MessageBox.Show("Number of cars due within one month: " + searchedCars.Count);
}
private void clearFilterBtn_Click(object sender, EventArgs e)
{
if (!searchButton.Enabled)
{
searchButton.Enabled = true;
addCarBtn.Enabled = true;
rebindGrid(Global.MainArraySource);
clearFilterBtn.Enabled = false;
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dateTimePicker2.MinDate = dateTimePicker1.Value;
}
}
}
| 37.296636 | 211 | 0.535995 | [
"MIT"
] | csp91/OilChange | OilChange/Form1.cs | 12,198 | C# |
using System.Collections.Generic;
using System.Linq;
using VXDesign.Store.DevTools.Common.Core.Entities.NoteFolder;
using VXDesign.Store.DevTools.Modules.SimpleNoteService.Server.Models.NoteFolder;
namespace VXDesign.Store.DevTools.Modules.SimpleNoteService.Server.Extensions
{
internal static class NoteProjectModelExtensions
{
internal static IEnumerable<NoteProjectModel> ToModel(this IEnumerable<NoteProjectEntity> entities) => entities.Select(entity => new NoteProjectModel
{
Id = entity.Id,
NoteId = entity.NoteId,
ProjectId = entity.ProjectId,
ProjectName = entity.ProjectName,
ProjectAlias = entity.ProjectAlias
});
}
} | 38.105263 | 157 | 0.720994 | [
"MIT"
] | GUSAR1T0/VXDS-DEV-TOOLS | DevTools/Modules/SimpleNoteService/Server/Extensions/NoteProjectModelExtensions.cs | 724 | C# |
//
// DO NOT MODIFY! THIS IS AUTOGENERATED FILE!
//
namespace Xilium.CefGlue.Interop
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
[StructLayout(LayoutKind.Sequential, Pack = libcef.ALIGN)]
[SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")]
internal unsafe struct cef_v8handler_t
{
internal cef_base_ref_counted_t _base;
internal IntPtr _execute;
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
internal delegate void add_ref_delegate(cef_v8handler_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
internal delegate int release_delegate(cef_v8handler_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
internal delegate int has_one_ref_delegate(cef_v8handler_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
internal delegate int has_at_least_one_ref_delegate(cef_v8handler_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
internal delegate int execute_delegate(cef_v8handler_t* self, cef_string_t* name, cef_v8value_t* @object, UIntPtr argumentsCount, cef_v8value_t** arguments, cef_v8value_t** retval, cef_string_t* exception);
private static int _sizeof;
static cef_v8handler_t()
{
_sizeof = Marshal.SizeOf(typeof(cef_v8handler_t));
}
internal static cef_v8handler_t* Alloc()
{
var ptr = (cef_v8handler_t*)Marshal.AllocHGlobal(_sizeof);
*ptr = new cef_v8handler_t();
ptr->_base._size = (UIntPtr)_sizeof;
return ptr;
}
internal static void Free(cef_v8handler_t* ptr)
{
Marshal.FreeHGlobal((IntPtr)ptr);
}
}
}
| 32.957143 | 214 | 0.646294 | [
"MIT"
] | OutSystems/CefGlue | CefGlue/Interop/Classes.g/cef_v8handler_t.g.cs | 2,307 | C# |
using System;
using NetOffice;
namespace NetOffice.VisioApi.Enums
{
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum VisWindowScrollX
{
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>9</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visScrollNoneX = 9,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visScrollLeft = 0,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visScrollLeftPage = 2,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visScrollRight = 1,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>3</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visScrollRightPage = 3,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>6</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visScrollToLeft = 6,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>7</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visScrollToRight = 7
}
} | 26.770492 | 55 | 0.622168 | [
"MIT"
] | Engineerumair/NetOffice | Source/Visio/Enums/VisWindowScrollX.cs | 1,633 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api.Test.Helpers;
using Mozu.Api.Test.Factories;
using System.Threading;
namespace Mozu.Api.Test.MsTestCases
{
[TestClass]
public class ProductPublishingTests : MozuApiTestBase
{
#region NonTestCaseCode
public ProductPublishingTests()
{
}
private static List<string> productCode1 = new List<string>();
private static List<int> productTypeId1 = new List<int>();
private static List<int> cateIds1 = new List<int>();
#region Initializers
/// <summary>
/// This will run once before each test.
/// </summary>
[TestInitialize]
public void TestMethodInit()
{
tenantId = Convert.ToInt32(Mozu.Api.Test.Helpers.Environment.GetConfigValueByEnvironment("TenantId"));
ApiMsgHandler = ServiceClientMessageFactory.GetTestClientMessage();
TestBaseTenant = TenantFactory.GetTenant(handler: ApiMsgHandler, tenantId: tenantId);
masterCatalogId = TestBaseTenant.MasterCatalogs.First().Id;
catalogId = TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id;
ApiMsgHandler = ServiceClientMessageFactory.GetTestClientMessage(tenantId, masterCatalogId: masterCatalogId,
catalogId: catalogId);
ShopperMsgHandler = ServiceClientMessageFactory.GetTestShopperMessage(tenantId,
siteId: TestBaseTenant.Sites.First().Id);
}
/// <summary>
/// Runs once before any test is run.
/// </summary>
/// <param name="testContext"></param>
[ClassInitialize]
public static void InitializeBeforeRun(TestContext testContext)
{
//Call the base class's static initializer.
MozuApiTestBase.TestClassInitialize(testContext);
}
#endregion
#region CleanupMethods
/// <summary>
/// This will run once after each test.
/// </summary>
[TestCleanup]
public void TestMethodCleanup()
{
//Calls the base class's Test Cleanup
base.TestCleanup();
}
/// <summary>
/// Runs once after all of the tests have run.
/// </summary>
[ClassCleanup]
public static void TestsCleanup()
{
//Calls the Base class's static cleanup.
MozuApiTestBase.TestClassCleanup();
}
#endregion
#endregion
/// <summary>
/// PublishDrafts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("AllPending is true, should ignore productcode in the list")]
public void ProductPublishingTests_PublishDrafts1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(3000);
var getPro1 = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
var getPro2 = ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
getPro1 = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.OK);
getPro2 = ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.OK);
//AllPending is true
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(false, new List<string>() { createdPro1.ProductCode }));
getPro1 = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.OK);
getPro2 = ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
getPro1 = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.OK);
getPro2 = ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.OK);
}
/// <summary>
/// PublishDrafts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("AllPending is false")]
public void ProductPublishingTests_PublishDrafts2()
{
var masterCatalog = Generator.SetMasterCatalogLiveMode(ApiMsgHandler, masterCatalogId);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(3000);
//Validation Error: Cannot publish drafts for masterCatalog in Live publishingMode
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(false, new List<string>() { createdPro1.ProductCode }), expectedCode: HttpStatusCode.Conflict);
MasterCatalogFactory.UpdateMasterCatalog(ApiMsgHandler, masterCatalog: masterCatalog, masterCatalogId: masterCatalogId );
createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(5300);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(false, new List<string>() { createdPro1.ProductCode }));
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.OK);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.OK);
}
/// <summary>
/// PublishDrafts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("AllPending is null")]
public void ProductPublishingTests_PublishDrafts3()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(3000);
//AllPending is false
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.OK);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.OK);
}
/// <summary>
/// PublishDrafts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductCodes: not found ProductCode")] //bug 21199
public void ProductPublishingTests_PublishDrafts5()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(3000);
//Nonexisting product code //
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(false, new List<string>() { Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly) }), expectedCode: HttpStatusCode.NotFound);
//publish all
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(true, null));
//publish a product already published before
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(false, new List<string>() { createdPro1.ProductCode }), expectedCode: HttpStatusCode.NotFound);
}
/// <summary>
/// DiscardDrafts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("AllPending is true, should ignore productcode in the list")]
public void ProductPublishingTests_DiscardDrafts1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
//AllPending is true
PublishingScopeFactory.DiscardDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(true, new List<string>() { createdPro1.ProductCode }));
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.DeleteProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.DeleteProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
}
/// <summary>
/// DiscardDrafts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("AllPending is false")]
public void ProductPublishingTests_DiscardDrafts2()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(3000);
//AllPending is false
PublishingScopeFactory.DiscardDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(false, new List<string>() { createdPro1.ProductCode }));
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.OK);
}
/// <summary>
/// DiscardDrafts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("AllPending is null")]
public void ProductPublishingTests_DiscardDrafts3()
{
var masterCatalog = MasterCatalogFactory.GetMasterCatalog(ApiMsgHandler, masterCatalogId);
if (masterCatalog.ProductPublishingMode.Equals("Live"))
{
MasterCatalogFactory.UpdateMasterCatalog(ApiMsgHandler, masterCatalog: masterCatalog, masterCatalogId: masterCatalogId);
}
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(5000);
//AllPending is null
PublishingScopeFactory.DiscardDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.OK);
//ProductFactory.DeleteProduct(ApiMsgHandler, createdPro1.ProductCode);
//ProductFactory.DeleteProduct(ApiMsgHandler, createdPro2.ProductCode);
}
/// <summary>
/// DiscardDrafts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductCodes: not found ProductCode")] //bug 17977
public void ProductPublishingTests_DiscardDrafts5()
{
var masterCatalog = MasterCatalogFactory.GetMasterCatalog(ApiMsgHandler, masterCatalogId);
if (masterCatalog.ProductPublishingMode.Equals("Live"))
{
MasterCatalogFactory.UpdateMasterCatalog(ApiMsgHandler, masterCatalog: masterCatalog, masterCatalogId: masterCatalogId);
}
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(3000);
//Nonexistent product code //bug id 21078
var prodScope =
Generator.GeneratePublishingScope(null, new List<string>(){Generator.RandomString(3,
Generator.RandomCharacterGroup.AlphaOnly)});
PublishingScopeFactory.DiscardDrafts(ApiMsgHandler, prodScope, expectedCode: HttpStatusCode.NotFound);
//discard all
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(true, null));
//discard a product already discarded before
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(false, new List<string>() { createdPro1.ProductCode }), expectedCode: HttpStatusCode.NotFound);
}
/// <summary>
/// UpdateMasterCatalog
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode, Live to Pending")]
public void ProductPublishingTests_UpdateSiteGroup1()
{
var masterCatalog = MasterCatalogFactory.GetMasterCatalog(ApiMsgHandler, masterCatalogId);
if (masterCatalog.ProductPublishingMode.Equals("Pending"))
{
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(true, null));
var mode = MasterCatalogFactory.GetMasterCatalog(ApiMsgHandler, masterCatalogId);
if (mode.ProductPublishingMode.Equals("Pending"))
{
MasterCatalogFactory.UpdateMasterCatalog(ApiMsgHandler, masterCatalog: masterCatalog, masterCatalogId: masterCatalogId);
}
}
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
var mode1 = MasterCatalogFactory.GetMasterCatalog(ApiMsgHandler, masterCatalogId);
if (mode1.ProductPublishingMode.Equals("Live"))
{
MasterCatalogFactory.UpdateMasterCatalog(ApiMsgHandler, masterCatalog: masterCatalog, masterCatalogId: masterCatalogId);
}
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
productCode1.Add(createdPro2.ProductCode);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
}
/// <summary>
/// UpdateMasterCatalog
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode, Pending to Live")]
public void ProductPublishingTests_UpdateSiteGroup2()
{
var masterCatalog = MasterCatalogFactory.GetMasterCatalog(ApiMsgHandler, masterCatalogId);
if (masterCatalog.ProductPublishingMode.Equals("Live"))
{
Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
}
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(5000);
productCode1.Add(createdPro1.ProductCode);
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
MasterCatalogFactory.UpdateMasterCatalog(ApiMsgHandler, masterCatalog: masterCatalog, masterCatalogId: masterCatalogId, expectedCode: HttpStatusCode.Conflict);
//PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(false, null));
}
/// <summary>
/// UpdateProduct
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, Update a product, productinsite, add a site")]
public void ProductPublishingTests_UpdateProduct5()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
//cat1 at in first site
var catObj1 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat1 = CategoryFactory.AddCategory(ApiMsgHandler, catObj1);
cateIds1.Add(createdCat1.Id.Value);
//cat2 is in second site
var msgHandler = ServiceClientMessageFactory.GetTestClientMessage(tenantId, masterCatalogId, TestBaseTenant.MasterCatalogs.First().Catalogs.Last().Id, siteId);
var catObj2 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat2 = CategoryFactory.AddCategory(msgHandler, catObj2);
cateIds1.Add(createdCat2.Id.Value);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
var proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, createdCat1.Id);
//add product to first site
ProductFactory.AddProductInCatalog(msgHandler, proInfo, createdPro1.ProductCode);
Thread.Sleep(3000);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
// add product to second site also
var getPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.Last().Id, createdCat2.Id);
getPro.ProductInCatalogs.Add(proInfo);
ProductFactory.UpdateProduct(ApiMsgHandler, getPro, createdPro1.ProductCode);
getPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual(1, getPro.ProductInCatalogs.Count);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
getPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual(2, getPro.ProductInCatalogs.Count);
}
/// <summary>
/// UpdateProduct
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, Update a product's content")]
public void ProductPublishingTests_UpdateProduct7()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
string originalContent = createdPro1.Content.ProductName;
createdPro1.Content = Generator.GenerateProductLocalizedContent(Generator.RandomString(5, Generator.RandomCharacterGroup.AlphaOnly));
ProductFactory.UpdateProduct(ApiMsgHandler, createdPro1, createdPro1.ProductCode);
var getPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual(originalContent, getPro.Content.ProductName);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
getPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual(createdPro1.Content.ProductName, getPro.Content.ProductName);
}
/// <summary>
/// UpdateProduct
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, Update a product, stock")]
public void ProductPublishingTests_UpdateProductStock1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var product = Generator.GenerateProduct();
//product.InventoryInfo.ManageStock = true;
//product.InventoryInfo.OutOfStockBehavior = "AllowBackorder";
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
/* var loc = LocationFactory.GetLocations(ApiMsgHandler);
var locCode = loc.Items[0].Code;
var stockOnHand = Generator.RandomInt(200, 300);
//StockAvailable - (StockOnHand minus Reserved.) Products are reserved using the ProductReservation resource
//var stockBackOrder = Generator.RandomInt(10, 60);
var locInv = Generator.GenerateLocationInventory(locCode, createdPro1.ProductCode,
null, null, stockOnHand);
//locInv.StockOnBackOrder = stockBackOrder;
var locInvs = Generator.GenerateLocationInventoryList();
locInvs.Add(locInv);
LocationInventoryFactory.AddLocationInventory(ApiMsgHandler, locInvs, locCode);
var getLocInv = LocationInventoryFactory.GetLocationInventory(ApiMsgHandler, locCode,
createdPro1.ProductCode);
Assert.AreEqual(stockOnHand, getLocInv.StockOnHand);
Assert.AreEqual(stockOnHand, getLocInv.StockAvailable);
*/
}
/// <summary>
/// GetProducts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("viewmode = live")]
public void ProductPublishingTests_GetProducts1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
//Add Category
var catObj1 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat1 = CategoryFactory.AddCategory(ApiMsgHandler, catObj1);
cateIds1.Add(createdCat1.Id.Value);
var catObj2 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat2 = CategoryFactory.AddCategory(ApiMsgHandler, catObj2);
cateIds1.Add(createdCat2.Id.Value);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(3000);
var createdPro3 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro3.ProductCode);
Thread.Sleep(3000);
var proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, createdCat1.Id);
ProductFactory.AddProductInCatalog(ApiMsgHandler, proInfo, createdPro1.ProductCode);
Thread.Sleep(2000);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode, createdPro2.ProductCode }));
var prodInCatalog = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
var originalPrice = createdPro1.Price;
prodInCatalog.Price = Generator.GenerateProductPrice(price: Generator.RandomDecimal(10, 50));
ProductFactory.UpdateProduct(ApiMsgHandler, prodInCatalog, createdPro1.ProductCode);
Thread.Sleep(3000);
var products = ProductFactory.GetProducts(ApiMsgHandler, pageSize: 230);
bool found1 = false;
foreach (var pro in products.Items)
{
if (createdPro1.ProductCode == pro.ProductCode)
{
found1 = true;
Assert.AreEqual(originalPrice.Price.Value, pro.Price.Price.Value);
Assert.AreEqual("Draft", pro.PublishingInfo.PublishedState);
}
}
Assert.IsTrue(found1);
}
/// <summary>
/// GetProducts
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("viewmode = pending")]
public void ProductPublishingTests_GetProducts2()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
//Add Category
var catObj1 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat1 = CategoryFactory.AddCategory(ApiMsgHandler, catObj1);
cateIds1.Add(createdCat1.Id.Value);
var catObj2 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat2 = CategoryFactory.AddCategory(ApiMsgHandler, catObj2);
cateIds1.Add(createdCat2.Id.Value);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, createdCat1.Id);
ProductFactory.AddProductInCatalog(ApiMsgHandler, proInfo, createdPro1.ProductCode);
Thread.Sleep(3000);
//Publish drafts
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
var prodInCatalog = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
var originalPrice = createdPro1.Price;
prodInCatalog.Price = Generator.GenerateProductPrice(price: Generator.RandomDecimal(10, 50));
ProductFactory.UpdateProduct(ApiMsgHandler, prodInCatalog, createdPro1.ProductCode);
var products = ProductFactory.GetProducts(ApiMsgHandler, pageSize: 200);
bool found1 = false;
foreach (var pro in products.Items)
{
if (createdPro1.ProductCode == pro.ProductCode)
{
found1 = true;
Assert.AreEqual(prodInCatalog.Price.Price.Value, pro.Price.Price.Value);
Assert.AreEqual("Draft", pro.PublishingInfo.PublishedState);
}
}
Assert.IsTrue(found1);
}
/// <summary>
/// AddProduct
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true")]
public void ProductPublishingTests_AddProduct1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro1.ProductCode);
Thread.Sleep(3000);
var createdPro2 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
productCode1.Add(createdPro2.ProductCode);
Thread.Sleep(3000);
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.OK);
var getPro2 = ProductFactory.GetProduct(ApiMsgHandler, createdPro2.ProductCode, expectedCode: HttpStatusCode.OK);
Assert.AreEqual("New", getPro2.PublishingInfo.PublishedState);
}
/// <summary>
/// UpdateProductInCatalog
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, UpdatepProductInsite:category")]
public void ProductPublishingTests_UpdateProductInsite1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var catObj1 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat1 = CategoryFactory.AddCategory(ApiMsgHandler, catObj1);
cateIds1.Add(createdCat1.Id.Value);
var catObj2 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat2 = CategoryFactory.AddCategory(ApiMsgHandler, catObj2);
cateIds1.Add(createdCat2.Id.Value);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
var proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, createdCat1.Id);
ProductFactory.AddProductInCatalog(ApiMsgHandler, proInfo, createdPro1.ProductCode);
Thread.Sleep(3000);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
var readPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual(createdCat1.Id, readPro.ProductInCatalogs.First().ProductCategories.First().CategoryId);
//change product category from 1 to 2
proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, createdCat2.Id);
ProductFactory.UpdateProductInCatalog(ApiMsgHandler, proInfo, createdPro1.ProductCode, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id);
readPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual(createdCat1.Id, readPro.ProductInCatalogs.First().ProductCategories.First().CategoryId);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
readPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual(createdCat2.Id, readPro.ProductInCatalogs.First().ProductCategories.First().CategoryId);
}
/// <summary>
/// UpdateProductInCatalog
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, UpdatepProductInsite:price, content, seocontent")]
public void ProductPublishingTests_UpdateProductInsite2()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var catObj1 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat1 = CategoryFactory.AddCategory(ApiMsgHandler, catObj1);
cateIds1.Add(createdCat1.Id.Value);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
var proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, createdCat1.Id);
ProductFactory.AddProductInCatalog(ApiMsgHandler, proInfo, createdPro1.ProductCode);
Thread.Sleep(3000);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
var getPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
var originalInfo = getPro.ProductInCatalogs.First();
var info = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, originalInfo.ProductCategories, Generator.RandomString(6, Generator.RandomCharacterGroup.AlphaOnly), Generator.RandomDecimal(10, 100), true, true, true, true);
ProductFactory.UpdateProductInCatalog(ApiMsgHandler, info, createdPro1.ProductCode, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id);
var readInfo = ProductFactory.GetProductInCatalog(ApiMsgHandler, createdPro1.ProductCode, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id);
Assert.AreEqual(originalInfo.Content.ProductName, readInfo.Content.ProductName);
Assert.AreEqual(originalInfo.Price.Price.Value, readInfo.Price.Price.Value);
readInfo = ProductFactory.GetProductInCatalog(ApiMsgHandler, createdPro1.ProductCode, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id);
Assert.AreEqual(info.Content.ProductName, readInfo.Content.ProductName);
Assert.AreEqual(info.Price.Price.Value, readInfo.Price.Price.Value);
}
/// <summary>
/// DeleteProductInCatalog
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, DeleteProductInsite")]
public void ProductPublishingTests_DeleteProductInsite1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var ApiMsgHandler1 = ServiceClientMessageFactory.GetTestClientMessage(TestBaseTenant.Id, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id,
TestBaseTenant.MasterCatalogs.First().Id);
var catObj1 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat1 = CategoryFactory.AddCategory(ApiMsgHandler1, catObj1);
cateIds1.Add(createdCat1.Id.Value);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
var proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, createdCat1.Id);
ProductFactory.AddProductInCatalog(ApiMsgHandler1, proInfo, createdPro1.ProductCode);
Thread.Sleep(3000);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
ProductFactory.DeleteProductInCatalog(ApiMsgHandler1, createdPro1.ProductCode, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id);
ProductFactory.GetProductInCatalog(ApiMsgHandler1, createdPro1.ProductCode, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
ProductFactory.GetProductInCatalog(ApiMsgHandler1, createdPro1.ProductCode, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProductInCatalog(ApiMsgHandler1, createdPro1.ProductCode, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, expectedCode: HttpStatusCode.NotFound);
}
/// <summary>
/// DeleteProduct
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, DeleteProduct")]
public void ProductPublishingTests_DeleteProduct1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var ApiMsgHandler1 = ServiceClientMessageFactory.GetTestClientMessage(TestBaseTenant.Id, TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id,
TestBaseTenant.MasterCatalogs.First().Id);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
ProductFactory.DeleteProduct(ApiMsgHandler1, createdPro1.ProductCode);
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode, expectedCode: HttpStatusCode.NotFound);
}
/// <summary>
/// GetProductInCatalog
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("viewmode = pending or live, GetProductInCatalogs")]
public void ProductPublishingTests_GetProductInCatalogs1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
// add to site 1 and publish
var catObj1 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat1 = CategoryFactory.AddCategory(ApiMsgHandler, catObj1);
cateIds1.Add(createdCat1.Id.Value);
var attrObj = Generator.GenerateAttribute(isProperty: true);
var createdAttr = AttributeFactory.AddAttribute(ApiMsgHandler, attrObj);
var attributeFQN1 = new List<string>();
attributeFQN1.Add(createdAttr.AttributeFQN);
var prodType = Generator.GenerateProductType(createdAttr, Generator.RandomString(5,
Generator.RandomCharacterGroup.AlphaOnly));
var myPT = ProductTypeFactory.AddProductType(ApiMsgHandler, prodType);
Thread.Sleep(3000);
productTypeId1.Add(myPT.Id.Value);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, Generator.GenerateProduct(myPT));
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
var proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.First().Id, createdCat1.Id);
ProductFactory.AddProductInCatalog(ApiMsgHandler, proInfo, createdPro1.ProductCode);
Thread.Sleep(3000);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
//add to site 2
var ApiMsgHandler1 = ServiceClientMessageFactory.GetTestClientMessage(TestBaseTenant.Id, masterCatalogId,
TestBaseTenant.MasterCatalogs[0].Catalogs.Last().Id);
var catObj2 = Generator.GenerateCategory(Generator.RandomString(4, Generator.RandomCharacterGroup.AlphaOnly));
var createdCat2 = CategoryFactory.AddCategory(ApiMsgHandler1, catObj2);
cateIds1.Add(createdCat2.Id.Value);
proInfo = Generator.GenerateProductInCatalogInfo(TestBaseTenant.MasterCatalogs.First().Catalogs.Last().Id, createdCat2.Id);
ProductFactory.AddProductInCatalog(ApiMsgHandler1, proInfo, createdPro1.ProductCode);
Thread.Sleep(3000);
//verify when mode=live
var readPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual(1, readPro.ProductInCatalogs.Count);
//verify when mode=pending
readPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual(2, readPro.ProductInCatalogs.Count);
}
/// <summary>
/// GetProductVariations
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, GetProductVariations")]
public void ProductPublishingTests_GetProductVariations1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrs = Generator.PrepareProductType(ApiMsgHandler);
var shirtType = ProductTypeFactory.AddProductType(ApiMsgHandler, attrs);
productTypeId1.Add(shirtType.Id.Value);
Thread.Sleep(3000);
var po = Generator.GenerateProductOptionList();
po.Add(Generator.GenerateProductOption(shirtType.Options[0], 2));
po.Add(Generator.GenerateProductOption(shirtType.Options[1], 2));
po.Add(Generator.GenerateProductOption(shirtType.Options[2], 2));
var pt = Generator.GenerateProduct(shirtType.Id, null, po, null);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, pt);
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
var vars = ProductTypeVariationFactory.GenerateProductVariations(ApiMsgHandler, createdPro1.Options,
(int)createdPro1.ProductTypeId, startIndex: 0, pageSize: 20);
var variation = vars.Items.First();
variation.IsActive = true;
ProductVariationFactory.UpdateProductVariation(ApiMsgHandler, variation, createdPro1.ProductCode,
variation.Variationkey);
var variations = ProductVariationFactory.GetProductVariations(ApiMsgHandler, createdPro1.ProductCode, filter: "isactive eq true");
Assert.AreEqual(0, variations.TotalCount);
variations = ProductVariationFactory.GetProductVariations(ApiMsgHandler, createdPro1.ProductCode, filter: "isactive eq true");
Assert.AreEqual(1, variations.TotalCount);
foreach (var p in po)
{
ProductOptionFactory.DeleteOption(ApiMsgHandler, createdPro1.ProductCode, p.AttributeFQN);
}
foreach (var v in variations.Items)
{
ProductVariationFactory.DeleteProductVariation(ApiMsgHandler, createdPro1.ProductCode, v.Variationkey);
}
}
/// <summary>
/// GetProductVariation
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, GetProductVariation")]
public void ProductPublishingTests_GetProductVariation1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrs = Generator.PrepareProductType(ApiMsgHandler);
var shirtType = ProductTypeFactory.AddProductType(ApiMsgHandler, attrs);
Thread.Sleep(5000);
productTypeId1.Add(shirtType.Id.Value);
var po = Generator.GenerateProductOptionList();;
po.Add(Generator.GenerateProductOption(shirtType.Options[0], 2));
po.Add(Generator.GenerateProductOption(shirtType.Options[1], 2));
po.Add(Generator.GenerateProductOption(shirtType.Options[2], 2));
var pt = Generator.GenerateProduct(shirtType.Id, null, po, null);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, pt);
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
var vars = ProductTypeVariationFactory.GenerateProductVariations(ApiMsgHandler, createdPro1.Options,
(int)createdPro1.ProductTypeId, startIndex: 0, pageSize: 20);
var variation = vars.Items.First();
variation.IsActive = true;
ProductVariationFactory.UpdateProductVariation(ApiMsgHandler, variation, createdPro1.ProductCode,
variation.Variationkey);
var getVar = ProductVariationFactory.GetProductVariation(ApiMsgHandler, createdPro1.ProductCode, variation.Variationkey);
Assert.AreEqual(false, getVar.IsActive);
getVar = ProductVariationFactory.GetProductVariation(ApiMsgHandler, createdPro1.ProductCode, variation.Variationkey);
Assert.AreEqual(true, getVar.IsActive);
foreach (var p in po)
{
ProductOptionFactory.DeleteOption(ApiMsgHandler, createdPro1.ProductCode, p.AttributeFQN);
}
ProductVariationFactory.DeleteProductVariation(ApiMsgHandler, createdPro1.ProductCode, getVar.Variationkey);
}
/// <summary>
/// UpdateProductVariations
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, UpdateProductVariations")]
public void ProductPublishingTests_UpdateProductVariations1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrs = Generator.PrepareProductType(ApiMsgHandler);
var shirtType = ProductTypeFactory.AddProductType(ApiMsgHandler, attrs);
productTypeId1.Add(shirtType.Id.Value);
var po = Generator.GenerateProductOptionList();;
po.Add(Generator.GenerateProductOption(shirtType.Options[0], 2));
po.Add(Generator.GenerateProductOption(shirtType.Options[1], 2));
po.Add(Generator.GenerateProductOption(shirtType.Options[2], 2));
var pt = Generator.GenerateProduct(shirtType.Id, null, po, null);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, pt);
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
var vars = ProductTypeVariationFactory.GenerateProductVariations(ApiMsgHandler, createdPro1.Options,
(int)createdPro1.ProductTypeId, startIndex: 0, pageSize: 20);
var variation1 = vars.Items.First();
variation1.IsActive = true;
var variation2 = vars.Items.Last();
variation2.IsActive = true;
var productVariationList = Generator.GenerateProductVariationList();
productVariationList.Add(variation1);
productVariationList.Add(variation2);
var variationCollection = Generator.GenerateProductVariationCollection(productVariationList, 2);
ProductVariationFactory.UpdateProductVariations(ApiMsgHandler, variationCollection, createdPro1.ProductCode);
var getVar = ProductVariationFactory.GetProductVariations(ApiMsgHandler, createdPro1.ProductCode, filter: "isactive eq true");
Assert.AreEqual(0, getVar.TotalCount);
getVar = ProductVariationFactory.GetProductVariations(ApiMsgHandler, createdPro1.ProductCode, filter: "isactive eq true");
Assert.AreEqual(2, getVar.TotalCount);
var getPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual("Draft", getPro.PublishingInfo.PublishedState);
//publish
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
getVar = ProductVariationFactory.GetProductVariations(ApiMsgHandler, createdPro1.ProductCode, filter: "isactive eq true");
Assert.AreEqual(2, getVar.TotalCount);
getPro = ProductFactory.GetProduct(ApiMsgHandler, createdPro1.ProductCode);
Assert.AreEqual("Live", getPro.PublishingInfo.PublishedState);
foreach (var p in po)
{
//bug id 21072
ProductOptionFactory.DeleteOption(ApiMsgHandler, createdPro1.ProductCode, p.AttributeFQN);
}
foreach (var v in vars.Items)
{
if (v.IsActive.Value)
{
ProductVariationFactory.DeleteProductVariation(ApiMsgHandler, createdPro1.ProductCode, v.Variationkey);
}
}
}
/// <summary>
/// DeleteProductVariation
/// </summary>
[TestMethod]
[TestCategory("ProductPublishing")]
[TestCategory("SDK")]
[Timeout(TestTimeout.Infinite)]
[Priority(2)]
[Description("ProductPublishingMode is true, DeleteProductVariation")]
public void ProductPublishingTests_DeleteProductVariation1()
{
var masterCatalog = Generator.SetMasterCatalogPendingMode(ApiMsgHandler, masterCatalogId);
var attrs = Generator.PrepareProductType(ApiMsgHandler);
var shirtType = ProductTypeFactory.AddProductType(ApiMsgHandler, attrs);
Thread.Sleep(3000);
productTypeId1.Add(shirtType.Id.Value);
var po = Generator.GenerateProductOptionList();;
po.Add(Generator.GenerateProductOption(shirtType.Options[0], 2));
po.Add(Generator.GenerateProductOption(shirtType.Options[1], 2));
po.Add(Generator.GenerateProductOption(shirtType.Options[2], 2));
var pt = Generator.GenerateProduct(shirtType.Id, null, po, null);
var createdPro1 = ProductFactory.AddProduct(ApiMsgHandler, pt);
Thread.Sleep(3000);
productCode1.Add(createdPro1.ProductCode);
var vars = ProductTypeVariationFactory.GenerateProductVariations(ApiMsgHandler, createdPro1.Options,
(int)createdPro1.ProductTypeId, startIndex: 0, pageSize: 20);
var variation = vars.Items.First();
variation.IsActive = true;
ProductVariationFactory.UpdateProductVariation(ApiMsgHandler, variation, createdPro1.ProductCode,
variation.Variationkey);
PublishingScopeFactory.PublishDrafts(ApiMsgHandler, Generator.GeneratePublishingScope(null, new List<string>() { createdPro1.ProductCode }));
ProductVariationFactory.DeleteProductVariation(ApiMsgHandler, createdPro1.ProductCode, variation.Variationkey);
var getVar = ProductVariationFactory.GetProductVariation(ApiMsgHandler, createdPro1.ProductCode, variation.Variationkey);
Assert.AreEqual(false, getVar.VariationExists);
foreach (var p in po)
{
ProductOptionFactory.DeleteOption(ApiMsgHandler, createdPro1.ProductCode, p.AttributeFQN);
}
}
}
}
| 59.846088 | 280 | 0.667605 | [
"MIT"
] | thomsumit/mozu-dotnet | Mozu.Api.Test/MsTestCases/ProductPublishingTests.cs | 69,603 | C# |
#region Licence
/* The MIT License (MIT)
Copyright © 2014 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#endregion
using System;
using paramore.brighter.commandprocessor;
namespace Orders_Core.Ports.Commands
{
public class AddOrderCommand : Command, ICanBeValidated
{
public string OrderDescription { get; private set; }
public DateTime? OrderDueDate { get; private set; }
public int OrderId { get; set; }
public string CustomerName { get; private set; }
public AddOrderCommand(string customerName, string orderDescription, DateTime? dueDate = null)
: base(Guid.NewGuid())
{
CustomerName = customerName;
OrderDescription = orderDescription;
OrderDueDate = dueDate;
}
public bool IsValid()
{
if ((OrderDescription == null) || (CustomerName == null))
{
return false;
}
return true;
}
}
} | 36.745455 | 102 | 0.706086 | [
"MIT"
] | claudiosteuernagel/Microservices-Tutorial | Orders-Core/Ports/Commands/AddOrderCommand.cs | 2,032 | C# |
namespace DaHo.MyStrom.Models
{
public class WifiSignal
{
/// <summary>
/// SSID of the Wifi
/// </summary>
public string WifiName { get; set; }
/// <summary>
/// Wireless signal strength measured in dBm (decibel milliwatts)
/// </summary>
public int SignalStrength { get; set; }
}
}
| 22.6875 | 74 | 0.53719 | [
"MIT"
] | Davee02/DaHo.MyStrom | src/DaHo.MyStrom/Models/WifiSignal.cs | 365 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace GraphApplications.Web.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 25.892857 | 88 | 0.666207 | [
"MIT"
] | foppenm/Microsoft-Graph-Applications | GraphApplications.Web/Pages/Error.cshtml.cs | 725 | C# |
using System;
using System.Collections.Generic;
using Rhino.Mocks;
namespace JustEat.Testing
{
public class MockManager
{
private readonly IDictionary<Type, object> _mockDictionary;
private readonly MockRepository _mockRepository;
public MockManager()
{
_mockRepository = new MockRepository();
_mockDictionary = new Dictionary<Type, object>();
}
public T Mock<T>() where T : class
{
return (T)Mock(typeof (T));
}
public void Inject(object value)
{
_mockDictionary.Add(value.GetType(), value);
}
public object Mock(Type type)
{
var mock = _mockRepository.DynamicMock(type);
_mockRepository.Replay(mock);
if (!_mockDictionary.ContainsKey(type))
_mockDictionary.Add(type, mock);
return _mockDictionary[type];
}
}
} | 22.075 | 62 | 0.627407 | [
"Apache-2.0"
] | ILikePies/JustSaying | JustSaying.UnitTests/MockManager.cs | 883 | C# |
namespace Altinn.Common.PEP.Configuration
{
/// <summary>
/// General configuration settings
/// </summary>
public class PepSettings
{
/// <summary>
/// The timout on pdp decions
/// </summary>
public int PdpDecisionCachingTimeout { get; set; }
}
}
| 21.785714 | 58 | 0.577049 | [
"BSD-3-Clause"
] | Altinn/altinn-studio | src/Altinn.Common/Altinn.Common.PEP/Altinn.Common.PEP/Configuration/PepSettings.cs | 305 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Scripts.Menu.Main
{
public class GraphicsSectionController : UIController
{
public OptionsMenuController OptionsMenuController;
private MainMenuManager MainMenuManager => OptionsMenuController.MainMenuManager;
public Dropdown ResolutionDropdown;
public Dropdown AspectRatioDropdown;
public Dropdown ScreenTypeDropdown;
public Dropdown QualityDropdown;
/*public Button LowResButton;
public Button MediumResButton;
public Button HighResButton;*/
public Button ApplyButton;
void Start()
{
ResolutionDropdown.AddOptions(
MainMenuManager.GetSupportedResolutions()
);
ResolutionDropdown.value = MainMenuManager.GetSupportedResolutions().IndexOf(MainMenuManager.GetResolution());
AspectRatioDropdown.AddOptions(
MainMenuManager.GetSupportedAspectRatios()
);
AspectRatioDropdown.value = MainMenuManager.GetSupportedAspectRatios().IndexOf(MainMenuManager.GetAspectRatio());
ScreenTypeDropdown.AddOptions(
MainMenuManager.GetSupportedScreenTypes()
);
ScreenTypeDropdown.value = MainMenuManager.GetSupportedScreenTypes().IndexOf(MainMenuManager.GetScreenType());
QualityDropdown.AddOptions(new List<string>()
{
"Low",
"Medium",
"High"
}
);
QualityDropdown.value = 0;
ApplyButton.onClick.AddListener(ApplySettings);
}
public override void Open()
{
base.Open();
}
public override void Close()
{
base.Close();
}
private void ApplySettings()
{
int resolutionIndex = ResolutionDropdown.value;
int aspectRatioIndex = AspectRatioDropdown.value;
int screenTypeIndex = ScreenTypeDropdown.value;
string aspectRatio = MainMenuManager.GetSupportedAspectRatios()[aspectRatioIndex];
string resolution = MainMenuManager.GetSupportedResolutions(aspectRatio)[resolutionIndex];
string screenType = MainMenuManager.GetSupportedScreenTypes()[screenTypeIndex];
MainMenuManager.SetAspectRatio(aspectRatio);
MainMenuManager.SetResolution(resolution, screenTypeIndex == 0);
MainMenuManager.SetScreenType(screenType);
int qualityIndex = QualityDropdown.value;
switch (qualityIndex)
{
case 0:
MainMenuManager.SetLowQuality();
break;
case 1:
MainMenuManager.SetMediumQuality();
break;
case 2:
MainMenuManager.SetHighQuality();
break;
}
}
}
} | 33.901099 | 125 | 0.60389 | [
"MIT"
] | Freezer-Games/Frozen-Out | FrozenOut/Assets/Scripts/Menu/Main/GraphicsSectionController.cs | 3,085 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.