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 Newtonsoft.Json;
using System;
namespace SimilarWeb.Api.Connector.Models.SegmentAnalysis
{
/// <summary>
/// Метаданные ответа.
/// </summary>
public class Meta
{
#region Свойства
[JsonProperty("request")]
public Request Request { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("last_updated")]
public DateTime LastUpdated { get; set; }
[JsonProperty("device")]
public string Device { get; set; }
#endregion
}
}
| 20.285714 | 57 | 0.588028 | [
"MIT"
] | wm-russia-software/SimilarWeb.Api.Connector | SimilarWeb.Api.Connector/SimilarWeb.Api.Connector/Models/SegmentAnalysis/Meta.cs | 594 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql.Models
{
/// <summary>
/// Represents a response to the get request.
/// </summary>
public partial class DatabaseCopyGetResponse : OperationResponse
{
private DatabaseCopy _databaseCopy;
/// <summary>
/// Optional. Gets or sets the returned database copy.
/// </summary>
public DatabaseCopy DatabaseCopy
{
get { return this._databaseCopy; }
set { this._databaseCopy = value; }
}
/// <summary>
/// Initializes a new instance of the DatabaseCopyGetResponse class.
/// </summary>
public DatabaseCopyGetResponse()
{
}
}
}
| 30.943396 | 76 | 0.668902 | [
"Apache-2.0"
] | achal3754/azure-sdk-for-net | src/SqlManagement/Generated/Models/DatabaseCopyGetResponse.cs | 1,640 | C# |
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Views;
using PhotoStationFrame.Api;
using PhotoStationFrame.Api.Models;
using PhotoStationFrame.Uwp.Extensions;
using PhotoStationFrame.Uwp.Settings;
using PhotoStationFrame.Uwp.ViewObjects;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
namespace PhotoStationFrame.Uwp.ViewModels
{
public class MainViewModel : ViewModelBase
{
private PhotoStationClient photoClient;
private readonly INavigationService navigationService;
private readonly ISettingsHelper settingsHelper;
private ObservableCollection<ImageModel> _thumbnailUrls;
private bool _showNoSettingsNotification;
private bool _isLoading;
private string _message;
private const int pageSize = 100;
private const bool randomOrder = true;
public MainViewModel(PhotoStationClient photoStationClient, INavigationService navigationService, ISettingsHelper settingsHelper)
{
this.photoClient = photoStationClient;
this.navigationService = navigationService;
this.settingsHelper = settingsHelper;
GoToSettingsCommand = new RelayCommand(HandleGoToSettingsCommand);
}
private void HandleGoToSettingsCommand()
{
navigationService?.NavigateTo(ViewModelLocator.SettingsPageKey);
}
public async Task LoadData()
{
try
{
IsLoading = true;
ShowNoSettingsNotification = false;
Message = string.Empty;
var settings = await settingsHelper.LoadAsync();
#if DEBUG
/* When debugging or deploying to IoT device use some "predefined" settings. Not included in git
public class PhotoApiSettings : PhotoFrameSettings
{
public PhotoApiSettings() : base("diskstation", "user", "password")
...
*/
//settings = new PhotoApiSettings();
#endif
if(settings == null)
{
IsLoading = false;
ShowNoSettingsNotification = true;
return;
}
photoClient.Initialize(settings);
var loginResult = await photoClient.LoginAsync();
if (!loginResult)
{
Message = $"Login with user {settings.Username} to {settings.Url} not successfull. Ples got to settings or check your network connection.";
return;
}
Message = $"Loading images from {settings.Address}.";
ListItemResponse listResponse = null;
// ToDo: if smells like duplicate code
string albumId = null;
if (settings.UseSmartAlbum)
{
// Known bug when album contains videos
var albums = await photoClient.ListSmartAlbumsAsync();
var album = albums.data.smart_albums.FirstOrDefault(x => x.name == settings.AlbumName);
if (album == null)
{
return;
}
albumId = album.id;
listResponse = await photoClient.ListSmartAlbumItemsAsync(albumId, 0, pageSize);
}
else
{
var albums = await photoClient.ListAlbumsAsync();
var album = albums.data.items.FirstOrDefault(x => x.info.name == settings.AlbumName);
if (album == null)
{
return;
}
albumId = album.id;
listResponse = await photoClient.ListPhotosAsync(albumId, 0, pageSize);
}
var images = listResponse.data?.items?.Select(p => new ImageModel(photoClient.GetBiglUrl(p), p, photoClient)).ToList();
if (randomOrder)
{
images.Shuffle();
}
var tempimages = images.ToList();
Message = string.Empty;
Images = new ObservableCollection<ImageModel>(images);
for (int i = images.Count; i < listResponse.data.total; i += pageSize)
{
var pagingListResponse = settings.UseSmartAlbum ? (await photoClient.ListSmartAlbumItemsAsync(albumId, i, pageSize)) : (await photoClient.ListPhotosAsync(albumId, i, pageSize));
images = pagingListResponse.data?.items?.Select(p => new ImageModel(photoClient.GetBiglUrl(p), p, photoClient)).ToList();
tempimages.AddRange(images);
}
if (randomOrder)
{
tempimages.Shuffle();
}
Images = new ObservableCollection<ImageModel>(tempimages);
}
catch (Exception e)
{
Message = $"Ooops something went wrong. Sorry! \r\nInfo: {e.Message}";
Debug.WriteLine(e.Message);
}
}
public ICommand GoToSettingsCommand { get; set; }
public ObservableCollection<ImageModel> Images { get => _thumbnailUrls; set => Set(ref _thumbnailUrls, value); }
public bool ShowNoSettingsNotification { get => _showNoSettingsNotification; set => Set(ref _showNoSettingsNotification, value); }
public bool IsLoading { get => _isLoading; set => Set(ref _isLoading, value); }
public string Message { get => _message; set => Set(ref _message, value); }
}
}
| 39.530201 | 197 | 0.565874 | [
"MIT"
] | Alex-Witkowski/PhotoStationFrame | PhotoStationFrame.Uwp/ViewModels/MainViewModel.cs | 5,892 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using StrawberryShake;
namespace CoolStore.WebUI.Host
{
[System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")]
public partial class GetProducts
: IGetProducts
{
public GetProducts(
global::CoolStore.WebUI.Host.IOffsetPagingOfCatalogProductDto products)
{
Products = products;
}
public global::CoolStore.WebUI.Host.IOffsetPagingOfCatalogProductDto Products { get; }
}
}
| 25.714286 | 94 | 0.690741 | [
"MIT"
] | ANgajasinghe/practical-dapr | src/WebUI/CoolStore.WebUI.Host/GraphQL/Generated/GetProducts.cs | 542 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Psy.Migrations
{
public partial class Remove_IsActive_From_Role : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsActive",
table: "AbpRoles");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsActive",
table: "AbpRoles",
nullable: false,
defaultValue: false);
}
}
}
| 26.416667 | 71 | 0.574132 | [
"MIT"
] | gnios/psy | aspnet-core/src/Psy.EntityFrameworkCore/Migrations/20170703134115_Remove_IsActive_From_Role.cs | 636 | C# |
/////////////////////////////////////////////////////////////////////////////////
//
// vp_AngleBob.cs
// © Opsive. All Rights Reserved.
// https://twitter.com/Opsive
// http://www.opsive.com
//
// description: this script will rotate its gameobject in a wavy (sinus / bob)
// motion. NOTE: this script currently can not be used on items
// that spawn from vp_SpawnPoints
//
/////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class vp_AngleBob : MonoBehaviour
{
public Vector3 BobAmp = new Vector3(0.0f, 0.1f, 0.0f); // wave motion strength
public Vector3 BobRate = new Vector3(0.0f, 4.0f, 0.0f); // wave motion speed
public float YOffset = 0.0f; // TIP: increase this to avoid ground intersection
public bool RandomizeBobOffset = false;
public bool LocalMotion = false;
public bool FadeToTarget = false; // NOTE: not available with local motion
protected Transform m_Transform;
protected Vector3 m_InitialRotation;
protected Vector3 m_Offset;
/// <summary>
///
/// </summary>
protected virtual void Awake()
{
m_Transform = transform;
m_InitialRotation = m_Transform.eulerAngles;
}
/// <summary>
///
/// </summary>
protected virtual void OnEnable()
{
m_Transform.eulerAngles = m_InitialRotation;
if (RandomizeBobOffset)
YOffset = Random.value;
}
/// <summary>
///
/// </summary>
protected virtual void Update()
{
if ((BobRate.x != 0.0f) && (BobAmp.x != 0.0f))
m_Offset.x = vp_MathUtility.Sinus(BobRate.x, BobAmp.x, 0);
if ((BobRate.y != 0.0f) && (BobAmp.y != 0.0f))
m_Offset.y = vp_MathUtility.Sinus(BobRate.y, BobAmp.y, 0);
if ((BobRate.z != 0.0f) && (BobAmp.z != 0.0f))
m_Offset.z = vp_MathUtility.Sinus(BobRate.z, BobAmp.z, 0);
if (!LocalMotion)
{
if (FadeToTarget)
m_Transform.rotation = Quaternion.Lerp(m_Transform.rotation, Quaternion.Euler((m_InitialRotation + m_Offset) + (Vector3.up * YOffset)), Time.deltaTime);
else
m_Transform.eulerAngles = (m_InitialRotation + m_Offset) + (Vector3.up * YOffset);
}
else
{
m_Transform.eulerAngles = m_InitialRotation + (Vector3.up * YOffset);
m_Transform.localEulerAngles += m_Transform.TransformDirection(m_Offset);
}
}
} | 25.688889 | 156 | 0.639706 | [
"MIT"
] | PotentialGames/Cal-tEspa-l | BRGAME/Assets/UFPS/Base/Scripts/Core/Motion/vp_AngleBob.cs | 2,315 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MaeFlowers
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.62963 | 70 | 0.644509 | [
"MIT"
] | mrsantons/MaeFlowers | MaeFlowers/Program.cs | 692 | C# |
#region License
// Copyright (c) 2009, ClearCanvas Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ClearCanvas Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;
namespace ClearCanvas.Enterprise.Common.Audit
{
/// <summary>
/// Defines a service for working with the audit log.
/// </summary>
[EnterpriseCoreService]
[ServiceContract]
[Authentication(false)]
public interface IAuditService
{
/// <summary>
/// Writes an entry to the audit log.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[OperationContract]
WriteEntryResponse WriteEntry(WriteEntryRequest request);
}
}
| 40.071429 | 87 | 0.725936 | [
"Apache-2.0"
] | econmed/ImageServer20 | Enterprise/Common/Audit/IAuditService.cs | 2,246 | C# |
/**
* Copyright (c) 2020-2021 LG Electronics, Inc.
*
* This software contains code licensed as described in LICENSE.
*
*/
using System.Collections;
using SimpleJSON;
using UnityEngine;
public class WaitingPointEffector : TriggerEffector
{
public override string TypeName { get; } = "WaitingPoint";
public Vector3 ActivatorPoint;
public float PointRadius = 2.0f;
public override object Clone()
{
var clone = new WaitingPointEffector {ActivatorPoint = ActivatorPoint, PointRadius = PointRadius};
return clone;
}
public override IEnumerator Apply(ITriggerAgent agent)
{
//Make parent npc wait until any ego is closer than the max distance
var lowestDistance = float.PositiveInfinity;
do
{
var egos = SimulatorManager.Instance.AgentManager.ActiveAgents;
foreach (var ego in egos)
{
var distance = Vector3.Distance(ActivatorPoint, ego.AgentGO.transform.position);
if (distance < lowestDistance)
lowestDistance = distance;
}
yield return null;
} while (lowestDistance > PointRadius);
}
public override void SerializeProperties(JSONNode jsonData)
{
var activatorNode = new JSONObject().WriteVector3(ActivatorPoint);
jsonData.Add("activatorPoint", activatorNode);
jsonData.Add("pointRadius", new JSONNumber(PointRadius));
}
public override void DeserializeProperties(JSONNode jsonData)
{
var activatorPoint = jsonData["activatorPoint"];
if (activatorPoint == null)
activatorPoint = jsonData["activator_point"];
ActivatorPoint = activatorPoint.ReadVector3();
var pointRadius = jsonData["pointRadius"];
if (pointRadius == null)
pointRadius = jsonData["point_radius"];
PointRadius = pointRadius;
}
} | 30.587302 | 106 | 0.65179 | [
"Apache-2.0",
"BSD-3-Clause"
] | Carteav/simulator | Assets/Scripts/Controllers/Triggers/WaitingPointEffector.cs | 1,927 | C# |
namespace AnimalHierarchy
{
using System;
using System.Linq;
public abstract class Animal : ISound
{
//fields
private int age;
private string name;
private Sex gender;
//constructors
public Animal(int age, string name)
{
this.Age = age;
this.Name = name;
}
public Animal(int age, string name, Sex gender)
: this(age, name)
{
this.gender = gender;
}
//properties
public int Age
{
get
{
return this.age;
}
private set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("Age cannot be a negative number!");
}
this.age = value;
}
}
public string Name
{
get
{
return this.name;
}
private set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Name cannot be null or empty!");
}
this.name = value;
}
}
public Sex Gender
{
get
{
return this.gender;
}
}
//methods
public abstract void MakeSound();
}
}
| 21.057143 | 94 | 0.400271 | [
"MIT"
] | juvemar/OOPPrincipiles1 | 03. AnimalHierarchy/Animal.cs | 1,476 | C# |
using System.Reflection;
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.MSHTMLApi
{
/// <summary>
/// Interface ISecureUrlHost
/// SupportByVersion MSHTML, 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EntityType(EntityType.IsInterface)]
public class ISecureUrlHost : COMObject
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(ISecureUrlHost);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public ISecureUrlHost(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public ISecureUrlHost(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ISecureUrlHost(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ISecureUrlHost(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ISecureUrlHost(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ISecureUrlHost(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ISecureUrlHost() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ISecureUrlHost(string progId) : base(progId)
{
}
#endregion
#region Properties
#endregion
#region Methods
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="pfAllow">Int32 pfAllow</param>
/// <param name="pchUrlInQuestion">Int16 pchUrlInQuestion</param>
/// <param name="dwFlags">Int32 dwFlags</param>
[SupportByVersion("MSHTML", 4)]
public Int32 ValidateSecureUrl(out Int32 pfAllow, Int16 pchUrlInQuestion, Int32 dwFlags)
{
ParameterModifier[] modifiers = Invoker.CreateParamModifiers(true,false,false);
pfAllow = 0;
object[] paramsArray = Invoker.ValidateParamsArray(pfAllow, pchUrlInQuestion, dwFlags);
object returnItem = Invoker.MethodReturn(this, "ValidateSecureUrl", paramsArray, modifiers);
pfAllow = (Int32)paramsArray[0];
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
#endregion
#pragma warning restore
}
}
| 32.737226 | 169 | 0.705463 | [
"MIT"
] | DominikPalo/NetOffice | Source/MSHTML/Interfaces/ISecureUrlHost.cs | 4,487 | C# |
/*
* Copyright (c) Contributors, http://whitecore-sim.org/, http://aurora-sim.org, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 WhiteCore-Sim Project 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 DEVELOPERS ``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 CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
namespace WhiteCore.Framework.Modules
{
public interface IWindModule
{
/// <summary>
/// Current active wind model plugin or String.Empty
/// </summary>
string WindActiveModelPluginName { get; }
/// <summary>
/// Retrieves the current wind speed at the given Region Coordinates
/// </summary>
Vector3 WindSpeed(int x, int y, int z);
/// <summary>
/// Set Wind Plugin Parameter
/// </summary>
void WindParamSet(string plugin, string param, float value);
/// <summary>
/// Get Wind Plugin Parameter
/// </summary>
float WindParamGet(string plugin, string param);
}
} | 45.685185 | 107 | 0.682205 | [
"BSD-3-Clause"
] | WhiteCoreSim/WhiteCore-Dev | WhiteCore/Framework/Modules/IWindModule.cs | 2,467 | C# |
// Copyright © Microsoft Corporation. All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.TeamFoundation.Migration.Toolkit;
namespace SemaphoreFileAnalysisAddin
{
public class SubTreeLabel : ILabel
{
private string m_fileSystemPath;
private string m_name;
private string m_commment;
private string m_targetSideScope;
private List<ILabelItem> m_labelItems = new List<ILabelItem>();
public SubTreeLabel(string fileSystemPath, string targetSideScope)
{
if (string.IsNullOrEmpty(fileSystemPath))
{
throw new ArgumentException("fileSystemPath");
}
m_fileSystemPath = fileSystemPath;
if (string.IsNullOrEmpty(targetSideScope))
{
throw new ArgumentException("targetSideScope");
}
m_targetSideScope = targetSideScope;
}
// Summary:
// The comment associated with the label It may be null or empty
public string Comment
{
get
{
if (m_commment == null)
{
m_commment = String.Format(CultureInfo.InvariantCulture,
SemaphoreFileAnalysisAddinResources.LabelCommentFormat, m_fileSystemPath);
}
return m_commment;
}
set
{
m_commment = value;
}
}
//
// Summary:
// The set of items included in the label
public List<ILabelItem> LabelItems
{
get { return m_labelItems; }
}
//
// Summary:
// The name of the label (a null or empty value is invalid)
public string Name
{
get
{
if (m_name == null)
{
// Generate a label that includes an indication that the label was generated by the TFS Integration platform and the current date time
m_name = String.Format(CultureInfo.InvariantCulture,
SemaphoreFileAnalysisAddinResources.DefaultLabelNameFormat,
DateTime.Now);
}
return m_name;
}
set
{
m_name = FixupLabelName(value);
}
}
public static string FixupLabelName(string labelName)
{
char [] invalidTfsLabelChars = new char [] { '"', '/', ':', '<', '>', '\\', '|', '*', '?', '@' };
int index;
do
{
index = labelName.IndexOfAny(invalidTfsLabelChars);
if (index != -1)
{
labelName = labelName.Replace(labelName.Substring(index, 1), "-");
}
}
while (index != -1);
return labelName;
}
//
// Summary:
// The name of the owner (it may be null or empty)
public string OwnerName
{
get { return null; }
}
//
// Summary:
// The scope is a server path that defines the namespace for labels in some
// VC servers In this case, label names must be unique within the scope, but
// two or more labels with the same name may exist as long as their Scopes are
// distinct. It may be null or empty is source from a VC server that does not
// have the notion of label scopes
public string Scope
{
get { return m_targetSideScope; }
}
}
}
| 31.298387 | 154 | 0.522546 | [
"MIT"
] | adamdriscoll/TfsIntegrationPlatform | Development/Adapters/Addins/SemaphoreFileAnalysisAddin/SubTreeLabel.cs | 3,884 | C# |
using SX.WebCore.MvcControllers.Abstract;
using System.Web.Mvc;
namespace LR.WebUI.Areas.Admin.Controllers
{
[Authorize]
public abstract class BaseController : SxBaseController
{
}
} | 19 | 59 | 0.708134 | [
"MIT"
] | simlex-titul2005/leavingrussia.ru | LR.WebUI/Areas/Admin/Controllers/BaseController.cs | 211 | C# |
using UnityEngine;
using UnityEngine.UI;
using Wikitude;
public class ContinuousRecognitionController : SampleController
{
public ImageTracker Tracker;
public Text buttonText;
private bool _trackerRunning = false;
private bool _connectionInitialized = false;
private double _recognitionInterval = 1.5;
#region UI Events
public void OnToggleClicked() {
_trackerRunning = !_trackerRunning;
ToggleContinuousCloudRecognition(_trackerRunning);
}
#endregion
#region Tracker Events
public void OnInitialized() {
base.OnTargetsLoaded();
_connectionInitialized = true;
}
public void OnInitializationError(Error error) {
PrintError("Error initializing cloud connection!", error);
}
public void OnRecognitionResponse(CloudRecognitionServiceResponse response) {
if (response.Recognized) {
// If the cloud recognized a target, we stop continuous recognition and track that target locally
ToggleContinuousCloudRecognition(false);
}
}
public void OnInterruption(double suggestedInterval) {
_recognitionInterval = suggestedInterval;
StartContinuousCloudRecognition();
}
#endregion
private void ToggleContinuousCloudRecognition(bool enabled) {
if (Tracker != null && _connectionInitialized) {
if (enabled) {
buttonText.text = "Scanning";
StartContinuousCloudRecognition();
} else {
buttonText.text = "Press to start scanning";
StopContinuousCloudRecognition();
}
_trackerRunning = enabled;
}
}
private void StartContinuousCloudRecognition() {
Tracker.CloudRecognitionService.StartContinuousRecognition(_recognitionInterval);
}
private void StopContinuousCloudRecognition() {
Tracker.CloudRecognitionService.StopContinuousRecognition();
}
public void OnRecognitionError(Error error) {
PrintError("Recognition error!", error);
}
}
| 30.144928 | 109 | 0.676923 | [
"MIT"
] | EnricoSandri/AR-NavMesh | Assets/Wikitude/Samples/Scripts/ContinuousRecognitionController.cs | 2,082 | C# |
using System.Windows.Forms;
namespace Analogy.UserControls
{
partial class AnalogyColumnsMatcherUC
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AnalogyColumnsMatcherUC));
this.lstBAnalogyColumns = new System.Windows.Forms.ListBox();
this.gradientLabel2 = new Syncfusion.Windows.Forms.Tools.GradientLabel();
this.sBtnMoveUp = new Syncfusion.WinForms.Controls.SfButton();
this.sBtnMoveDown = new Syncfusion.WinForms.Controls.SfButton();
this.lstBoxItems = new System.Windows.Forms.ListBox();
this.gradientLabel1 = new Syncfusion.Windows.Forms.Tools.GradientLabel();
this.scMain = new Syncfusion.Windows.Forms.Tools.SplitContainerAdv();
this.splitContainerAdv1 = new Syncfusion.Windows.Forms.Tools.SplitContainerAdv();
((System.ComponentModel.ISupportInitialize)(this.scMain)).BeginInit();
this.splitContainerAdv1.Panel1.SuspendLayout();
this.splitContainerAdv1.Panel2.SuspendLayout();
this.scMain.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainerAdv1)).BeginInit();
this.splitContainerAdv1.Panel1.SuspendLayout();
this.splitContainerAdv1.Panel2.SuspendLayout();
this.splitContainerAdv1.SuspendLayout();
this.SuspendLayout();
//
// lstBAnalogyColumns
//
this.lstBAnalogyColumns.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstBAnalogyColumns.FormattingEnabled = true;
this.lstBAnalogyColumns.ItemHeight = 16;
this.lstBAnalogyColumns.Items.AddRange(new object[] {
"Date",
"Text",
"Source",
"Module",
"MethodName",
"FileName",
"User",
"LineNumber",
"ProcessID",
"Thread",
"Level",
"Class",
"Category",
"ID",
"__ignore__",
"__ignore__",
"__ignore__",
"__ignore__",
"__ignore__",
"__ignore__",
"__ignore__"});
this.lstBAnalogyColumns.Location = new System.Drawing.Point(77, 39);
this.lstBAnalogyColumns.Name = "lstBAnalogyColumns";
this.lstBAnalogyColumns.Size = new System.Drawing.Size(263, 444);
this.lstBAnalogyColumns.TabIndex = 12;
this.lstBAnalogyColumns.SelectedIndexChanged += new System.EventHandler(this.lstBAnalogyColumns_SelectedIndexChanged);
//
// gradientLabel2
//
this.gradientLabel2.BackgroundColor = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.Color.FromArgb(((int)(((byte)(237)))), ((int)(((byte)(240)))), ((int)(((byte)(247))))), System.Drawing.Color.LightCyan);
this.gradientLabel2.BeforeTouchSize = new System.Drawing.Size(263, 39);
this.gradientLabel2.BorderSides = ((System.Windows.Forms.Border3DSide)((((System.Windows.Forms.Border3DSide.Left | System.Windows.Forms.Border3DSide.Top)
| System.Windows.Forms.Border3DSide.Right)
| System.Windows.Forms.Border3DSide.Bottom)));
this.gradientLabel2.Dock = System.Windows.Forms.DockStyle.Top;
this.gradientLabel2.Location = new System.Drawing.Point(77, 0);
this.gradientLabel2.Name = "gradientLabel2";
this.gradientLabel2.Size = new System.Drawing.Size(263, 39);
this.gradientLabel2.TabIndex = 11;
this.gradientLabel2.Text = "Log message Columns";
this.gradientLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// sBtnMoveUp
//
this.sBtnMoveUp.AccessibleName = "Button";
this.sBtnMoveUp.Dock = System.Windows.Forms.DockStyle.Fill;
this.sBtnMoveUp.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.sBtnMoveUp.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.sBtnMoveUp.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
this.sBtnMoveUp.ImageSize = new System.Drawing.Size(30, 30);
this.sBtnMoveUp.Location = new System.Drawing.Point(0, 0);
this.sBtnMoveUp.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sBtnMoveUp.Name = "sBtnMoveUp";
this.sBtnMoveUp.Size = new System.Drawing.Size(77, 237);
this.sBtnMoveUp.Style.Image = ((System.Drawing.Image)(resources.GetObject("resource.Image")));
this.sBtnMoveUp.TabIndex = 2;
this.sBtnMoveUp.Text = "Up";
this.sBtnMoveUp.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
this.sBtnMoveUp.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage;
this.sBtnMoveUp.Click += new System.EventHandler(this.SBtnMoveUp_Click);
//
// sBtnMoveDown
//
this.sBtnMoveDown.AccessibleName = "Button";
this.sBtnMoveDown.Dock = System.Windows.Forms.DockStyle.Fill;
this.sBtnMoveDown.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.sBtnMoveDown.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.sBtnMoveDown.ImageAlign = System.Drawing.ContentAlignment.BottomCenter;
this.sBtnMoveDown.ImageSize = new System.Drawing.Size(30, 30);
this.sBtnMoveDown.Location = new System.Drawing.Point(0, 0);
this.sBtnMoveDown.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sBtnMoveDown.Name = "sBtnMoveDown";
this.sBtnMoveDown.Size = new System.Drawing.Size(77, 239);
this.sBtnMoveDown.Style.Image = ((System.Drawing.Image)(resources.GetObject("resource.Image1")));
this.sBtnMoveDown.TabIndex = 3;
this.sBtnMoveDown.Text = "Down";
this.sBtnMoveDown.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.sBtnMoveDown.Click += new System.EventHandler(this.SBtnMoveDown_Click);
//
// lstBoxItems
//
this.lstBoxItems.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstBoxItems.FormattingEnabled = true;
this.lstBoxItems.ItemHeight = 16;
this.lstBoxItems.Location = new System.Drawing.Point(0, 39);
this.lstBoxItems.Name = "lstBoxItems";
this.lstBoxItems.Size = new System.Drawing.Size(341, 444);
this.lstBoxItems.TabIndex = 9;
//
// gradientLabel1
//
this.gradientLabel1.BackgroundColor = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.Color.FromArgb(((int)(((byte)(237)))), ((int)(((byte)(240)))), ((int)(((byte)(247))))), System.Drawing.Color.LightCyan);
this.gradientLabel1.BeforeTouchSize = new System.Drawing.Size(341, 39);
this.gradientLabel1.BorderSides = ((System.Windows.Forms.Border3DSide)((((System.Windows.Forms.Border3DSide.Left | System.Windows.Forms.Border3DSide.Top)
| System.Windows.Forms.Border3DSide.Right)
| System.Windows.Forms.Border3DSide.Bottom)));
this.gradientLabel1.Dock = System.Windows.Forms.DockStyle.Top;
this.gradientLabel1.Location = new System.Drawing.Point(0, 0);
this.gradientLabel1.Name = "gradientLabel1";
this.gradientLabel1.Size = new System.Drawing.Size(341, 39);
this.gradientLabel1.TabIndex = 10;
this.gradientLabel1.Text = "Parsed columns.";
this.gradientLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// scMain
//
this.scMain.BeforeTouchSize = 7;
this.scMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.scMain.Location = new System.Drawing.Point(0, 0);
this.scMain.Name = "scMain";
//
// scMain.Panel1
//
this.splitContainerAdv1.Panel1.Controls.Add(this.lstBAnalogyColumns);
this.splitContainerAdv1.Panel1.Controls.Add(this.gradientLabel2);
this.splitContainerAdv1.Panel1.Controls.Add(this.splitContainerAdv1);
//
// scMain.Panel2
//
this.splitContainerAdv1.Panel2.Controls.Add(this.lstBoxItems);
this.splitContainerAdv1.Panel2.Controls.Add(this.gradientLabel1);
this.scMain.Size = new System.Drawing.Size(688, 483);
this.scMain.SplitterDistance = 340;
this.scMain.TabIndex = 11;
this.scMain.Text = "splitContainerAdv1";
this.scMain.ThemeName = "None";
//
// splitContainerAdv1
//
this.splitContainerAdv1.BeforeTouchSize = 7;
this.splitContainerAdv1.Dock = System.Windows.Forms.DockStyle.Left;
this.splitContainerAdv1.Location = new System.Drawing.Point(0, 0);
this.splitContainerAdv1.Name = "splitContainerAdv1";
this.splitContainerAdv1.Orientation = System.Windows.Forms.Orientation.Vertical;
//
// splitContainerAdv1.Panel1
//
this.splitContainerAdv1.Panel1.Controls.Add(this.sBtnMoveUp);
//
// splitContainerAdv1.Panel2
//
this.splitContainerAdv1.Panel2.Controls.Add(this.sBtnMoveDown);
this.splitContainerAdv1.Size = new System.Drawing.Size(77, 483);
this.splitContainerAdv1.SplitterDistance = 237;
this.splitContainerAdv1.TabIndex = 13;
this.splitContainerAdv1.Text = "splitContainerAdv1";
this.splitContainerAdv1.ThemeName = "None";
//
// AnalogyColumnsMatcherUC
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.scMain);
this.Name = "AnalogyColumnsMatcherUC";
this.Size = new System.Drawing.Size(688, 483);
this.Load += new System.EventHandler(this.AnalogyColumnsMatcherUC_Load);
this.splitContainerAdv1.Panel1.ResumeLayout(false);
this.splitContainerAdv1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.scMain)).EndInit();
this.scMain.ResumeLayout(false);
this.splitContainerAdv1.Panel1.ResumeLayout(false);
this.splitContainerAdv1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainerAdv1)).EndInit();
this.splitContainerAdv1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private Syncfusion.WinForms.Controls.SfButton sBtnMoveUp;
private Syncfusion.WinForms.Controls.SfButton sBtnMoveDown;
private ListBox lstBAnalogyColumns;
private Syncfusion.Windows.Forms.Tools.GradientLabel gradientLabel2;
private ListBox lstBoxItems;
private Syncfusion.Windows.Forms.Tools.GradientLabel gradientLabel1;
private Syncfusion.Windows.Forms.Tools.SplitContainerAdv scMain;
private Syncfusion.Windows.Forms.Tools.SplitContainerAdv splitContainerAdv1;
}
}
| 53.21519 | 261 | 0.630431 | [
"MIT"
] | Analogy-LogViewer/Analogy.LogViewer.Syncfusion | Analogy/UserControls/AnalogyColumnsMatcherUC.Designer.cs | 12,614 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes a local gateway virtual interface group.
/// </summary>
public partial class LocalGatewayVirtualInterfaceGroup
{
private string _localGatewayId;
private string _localGatewayVirtualInterfaceGroupId;
private List<string> _localGatewayVirtualInterfaceIds = new List<string>();
/// <summary>
/// Gets and sets the property LocalGatewayId.
/// <para>
/// The ID of the local gateway.
/// </para>
/// </summary>
public string LocalGatewayId
{
get { return this._localGatewayId; }
set { this._localGatewayId = value; }
}
// Check to see if LocalGatewayId property is set
internal bool IsSetLocalGatewayId()
{
return this._localGatewayId != null;
}
/// <summary>
/// Gets and sets the property LocalGatewayVirtualInterfaceGroupId.
/// <para>
/// The ID of the virtual interface group.
/// </para>
/// </summary>
public string LocalGatewayVirtualInterfaceGroupId
{
get { return this._localGatewayVirtualInterfaceGroupId; }
set { this._localGatewayVirtualInterfaceGroupId = value; }
}
// Check to see if LocalGatewayVirtualInterfaceGroupId property is set
internal bool IsSetLocalGatewayVirtualInterfaceGroupId()
{
return this._localGatewayVirtualInterfaceGroupId != null;
}
/// <summary>
/// Gets and sets the property LocalGatewayVirtualInterfaceIds.
/// <para>
/// The IDs of the virtual interfaces.
/// </para>
/// </summary>
public List<string> LocalGatewayVirtualInterfaceIds
{
get { return this._localGatewayVirtualInterfaceIds; }
set { this._localGatewayVirtualInterfaceIds = value; }
}
// Check to see if LocalGatewayVirtualInterfaceIds property is set
internal bool IsSetLocalGatewayVirtualInterfaceIds()
{
return this._localGatewayVirtualInterfaceIds != null && this._localGatewayVirtualInterfaceIds.Count > 0;
}
}
} | 33.212766 | 117 | 0.647982 | [
"Apache-2.0"
] | damianh/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/LocalGatewayVirtualInterfaceGroup.cs | 3,122 | C# |
/*******************************************************************************************
*
* raylib [core] example - Basic window
*
* Welcome to raylib!
*
* To test examples, just press F6 and execute raylib_compile_execute script
* Note that compiled executable is placed in the same folder as .c file
*
* You can find all basic examples on C:\raylib\raylib\examples folder or
*
* Enjoy using raylib. :)
*
* This example has been created using raylib-cs 3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* This example was lightly modified to provide additional 'using' directives to make
* common math types and utilities readily available, though they are not using in this sample.
*
* Copyright (c) 2019-2020 Academy of Interactive Entertainment (@aie_usa)
* Copyright (c) 2013-2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using MathForGames;
using System;
namespace raygamecsharp
{
public class Program
{
public static int Main()
{
//Create a new instance of the game class
Engine game = new Engine();
//Call run to begin the game.
game.Run();
return 0;
}
}
} | 31.139535 | 96 | 0.578043 | [
"MIT"
] | LodisAIE/MathForGames2022 | MathForGames/Program.cs | 1,341 | C# |
namespace E02.Composite
{
public interface IGiftOperations
{
void Add(GiftBase gift);
bool Remove(GiftBase gift);
}
}
| 13.545455 | 36 | 0.61745 | [
"MIT"
] | Iceto04/SoftUni | C# OOP/11. Design Patterns/DesignPatterns/E02.Composite/IGiftOperations.cs | 151 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.BigQuery.Inputs
{
public sealed class DatasetAccessViewArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The ID of the dataset containing this table.
/// </summary>
[Input("datasetId", required: true)]
public Input<string> DatasetId { get; set; } = null!;
/// <summary>
/// The ID of the project containing this table.
/// </summary>
[Input("projectId", required: true)]
public Input<string> ProjectId { get; set; } = null!;
/// <summary>
/// The ID of the table. The ID must contain only letters (a-z,
/// A-Z), numbers (0-9), or underscores (_). The maximum length
/// is 1,024 characters.
/// </summary>
[Input("tableId", required: true)]
public Input<string> TableId { get; set; } = null!;
public DatasetAccessViewArgs()
{
}
}
}
| 31.05 | 88 | 0.60306 | [
"ECL-2.0",
"Apache-2.0"
] | dimpu47/pulumi-gcp | sdk/dotnet/BigQuery/Inputs/DatasetAccessViewArgs.cs | 1,242 | C# |
using System.Reflection;
using System.Resources;
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("Gravity Tide Correction")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Geophysics Made Easier")]
[assembly: AssemblyCopyright("Copyright Adien Akhmad © 2014")]
[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("11e70129-7182-4c64-a281-09bfb224276d")]
// 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.1.3.0")]
[assembly: AssemblyFileVersion("1.1.3.0")]
[assembly: NeutralResourcesLanguage("en")]
| 38.394737 | 84 | 0.746402 | [
"MIT"
] | adienakhmad/Grav-TC | GravityTidalAcceleretaion/Properties/AssemblyInfo.cs | 1,462 | C# |
using System;
using NSubstitute;
using NUnit.Framework;
namespace Mirror.Tests
{
[TestFixture]
public class NetworkAuthenticatorTest : ClientServerSetup<MockComponent>
{
NetworkAuthenticator serverAuthenticator;
NetworkAuthenticator clientAuthenticator;
Action<INetworkConnection> serverMockMethod;
Action<INetworkConnection> clientMockMethod;
class NetworkAuthenticationImpl : NetworkAuthenticator { };
public override void ExtraSetup()
{
serverAuthenticator = serverGo.AddComponent<NetworkAuthenticationImpl>();
clientAuthenticator = clientGo.AddComponent<NetworkAuthenticationImpl>();
server.authenticator = serverAuthenticator;
client.authenticator = clientAuthenticator;
serverMockMethod = Substitute.For<Action<INetworkConnection>>();
serverAuthenticator.OnServerAuthenticated += serverMockMethod;
clientMockMethod = Substitute.For<Action<INetworkConnection>>();
clientAuthenticator.OnClientAuthenticated += clientMockMethod;
}
[Test]
public void OnServerAuthenticateTest()
{
serverAuthenticator.OnServerAuthenticate(Substitute.For<INetworkConnection>());
serverMockMethod.Received().Invoke(Arg.Any<INetworkConnection>());
}
[Test]
public void OnServerAuthenticateInternalTest()
{
serverAuthenticator.OnServerAuthenticateInternal(Substitute.For<INetworkConnection>());
serverMockMethod.Received().Invoke(Arg.Any<INetworkConnection>());
}
[Test]
public void OnClientAuthenticateTest()
{
clientAuthenticator.OnClientAuthenticate(Substitute.For<INetworkConnection>());
clientMockMethod.Received().Invoke(Arg.Any<INetworkConnection>());
}
[Test]
public void OnClientAuthenticateInternalTest()
{
clientAuthenticator.OnClientAuthenticateInternal(Substitute.For<INetworkConnection>());
clientMockMethod.Received().Invoke(Arg.Any<INetworkConnection>());
}
[Test]
public void ClientOnValidateTest()
{
Assert.That(client.authenticator, Is.EqualTo(clientAuthenticator));
}
[Test]
public void ServerOnValidateTest()
{
Assert.That(server.authenticator, Is.EqualTo(serverAuthenticator));
}
[Test]
public void NetworkClientCallsAuthenticator()
{
clientMockMethod.Received().Invoke(Arg.Any<INetworkConnection>());
}
[Test]
public void NetworkServerCallsAuthenticator()
{
clientMockMethod.Received().Invoke(Arg.Any<INetworkConnection>());
}
}
}
| 31.433333 | 99 | 0.657476 | [
"MIT"
] | Jobus0/MirrorNG | Assets/Tests/Runtime/NetworkAuthenticatorTest.cs | 2,829 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Redshift.Model
{
/// <summary>
/// Container for the parameters to the DeleteEventSubscription operation.
/// Deletes an Amazon Redshift event notification subscription.
/// </summary>
public partial class DeleteEventSubscriptionRequest : AmazonRedshiftRequest
{
private string _subscriptionName;
/// <summary>
/// Gets and sets the property SubscriptionName.
/// <para>
/// The name of the Amazon Redshift event notification subscription to be deleted.
/// </para>
/// </summary>
public string SubscriptionName
{
get { return this._subscriptionName; }
set { this._subscriptionName = value; }
}
// Check to see if SubscriptionName property is set
internal bool IsSetSubscriptionName()
{
return this._subscriptionName != null;
}
}
} | 31.614035 | 106 | 0.679245 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Redshift/Generated/Model/DeleteEventSubscriptionRequest.cs | 1,802 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
using SharedLibrary.Services;
using SharedLibrary.Models;
using Newtonsoft.Json;
using Microsoft.Extensions.Caching.Memory;
using SharedLibrary.Descriptors;
using SharedLibrary.Enums;
using SharedLibrary.Structures;
using SharedLibrary.Helpers;
using System.Net;
using Core.Helpers;
using Core.Structures;
namespace Core.Pages.Rights
{
/// <summary>
/// The GetModel class in Core.Pages.Rights namespace is used as support for Get.cshtml page.
/// The page is used to display all application rights, as well as create, edit and delete action buttons.
/// </summary>
public class GetModel : PageModel
{
/// <summary>
/// Service for RightsModel based requests to the server.
/// </summary>
private readonly IRightsService rightsService;
/// <summary>
/// Service for user account based requests to the server.
/// </summary>
private readonly IAccountService accountService;
/// <summary>
/// In-memory cache service.
/// </summary>
private IMemoryCache cache;
/// <summary>
/// Constructor for initializing services and cache.
/// </summary>
/// <param name="rightsService">Rights service to be used</param>
/// <param name="accountService">Account service to be used</param>
/// <param name="memoryCache">Cache to be used</param>
public GetModel(IRightsService rightsService, IAccountService accountService, IMemoryCache memoryCache)
{
this.rightsService = rightsService;
this.accountService = accountService;
this.cache = memoryCache;
}
/// <summary>
/// ApplicationDescriptor property contains descriptor of the signed user.
/// </summary>
/// <value>ApplicationDescriptor class</value>
public ApplicationDescriptor ApplicationDescriptor { get; set; }
/// <summary>
/// Data property contains list of RightsModel to be displayed in a data table.
/// </summary>
/// <value>List of RightsModel</value>
public List<RightsModel> Data { get; set; }
/// <summary>
/// RightsRights property conatins user's rights to the rights dataset.async
/// This value is used for displaying Create, Edit and Delete buttons.
/// </summary>
/// <value>RightsEnum value.</value>
public RightsEnum? RightsRights { get; set; }
/// <summary>
/// MenuData property contains data necessary for _LoggedMenuPartial.
/// </summary>
/// <value>LoggedMenuPartialData structure</value>
public LoggedMenuPartialData MenuData { get; set; }
/// <summary>
/// Messages property contains list of messages for user.
/// </summary>
/// <value>List of Message structure</value>
public List<Message> Messages { get; set; }
/// <summary>
/// This method is used when there is a GET request to Rights/Get.cshtml page.
/// </summary>
/// <returns>The page.</returns>
public async Task<IActionResult> OnGetAsync()
{
// Authentication
var token = AccessHelper.GetTokenFromPageModel(this);
if (token == null)
return RedirectToPage("/Index");
# region PAGE DATA PREPARATION
// Messages
Messages = new List<Message>();
// Get messages from cookie
var serializedMessages = TempData["Messages"];
TempData.Remove("Messages");
if (serializedMessages != null)
{
try
{
Messages = JsonConvert.DeserializeObject<List<Message>>((string)serializedMessages) ?? throw new JsonSerializationException();
}
catch (JsonSerializationException e)
{
Logger.LogToConsole($"Messages {serializedMessages} serialization failed for user with token {token.Value}");
Logger.LogExceptionToConsole(e);
}
}
// Application descriptor
ApplicationDescriptor = await AccessHelper.GetApplicationDescriptor(cache, accountService, token);
if (ApplicationDescriptor == null)
{
Logger.LogToConsole($"Application descriptor for user with token {token.Value} not found.");
return RedirectToPage("/Error");
}
// Rights
var rights = await AccessHelper.GetUserRights(cache, accountService, token);
RightsRights = AuthorizationHelper.GetRights(rights, (long)SystemDatasetsEnum.Rights);
// Menu data
MenuData = AccessHelper.GetMenuData(ApplicationDescriptor, rights);
if (RightsRights == null || MenuData == null)
{
Logger.LogToConsole($"RightsRights or MenuData failed loading for user with token {token.Value}.");
return RedirectToPage("/Error");
}
// Data
Data = new List<RightsModel>();
#endregion
// Authorization
if (AuthorizationHelper.IsAuthorized(rights, (long)SystemDatasetsEnum.Rights, RightsEnum.R))
{
// Data request to the server via rightsService
var response = await rightsService.GetAll(token);
try
{
// If response status code if successfull, try parse data
if (response.IsSuccessStatusCode)
Data = JsonConvert.DeserializeObject<List<RightsModel>>(await response.Content.ReadAsStringAsync());
// If user is not authenticated, redirect to login page
else if (response.StatusCode == HttpStatusCode.Unauthorized)
return RedirectToPage("/Index");
// If user is not authorized, add message
else if (response.StatusCode == HttpStatusCode.Forbidden)
Messages.Add(new Message(MessageTypeEnum.Error,
4008,
new List<string>()));
// Otherwise try parse error messages
else
Messages.AddRange(JsonConvert.DeserializeObject<List<Message>>(await response.Content.ReadAsStringAsync()));
}
catch (JsonSerializationException e)
{
// In case of JSON parsing error, create server error message
Messages.Add(MessageHepler.Create1007());
Logger.LogExceptionToConsole(e);
}
}
// If user not authorized add general unauthorized message to Messages
else
Messages.Add(new Message(MessageTypeEnum.Error,
4008,
new List<string>()));
return Page();
}
/// <summary>
/// OnPostRightsDeleteAsync method is invoked after clicking on Delete button.
/// </summary>
/// <param name="dataId">Id of data to be deleted</param>
/// <returns>Login page or a page with messages</returns>
public async Task<IActionResult> OnPostRightsDeleteAsync(long dataId)
{
// Authentication
var token = AccessHelper.GetTokenFromPageModel(this);
if (token == null)
return RedirectToPage("/Index");
// Authorization
var rights = await AccessHelper.GetUserRights(cache, accountService, token);
// If user is not authorized to delete, add message and display page again
if (!AuthorizationHelper.IsAuthorized(rights, (long)SystemDatasetsEnum.Rights, RightsEnum.CRUD))
{
// Set messages to cookie
TempData["Messages"] = JsonConvert.SerializeObject(
new List<Message>(){
new Message(MessageTypeEnum.Error,
4009,
new List<string>())
});
return await OnGetAsync();
}
// Delete request to the server via rightsService
var response = await rightsService.DeleteById(dataId, token);
var messages = new List<Message>();
try
{
// If response status code if successfull, parse messages
if (response.IsSuccessStatusCode)
messages = JsonConvert.DeserializeObject<List<Message>>(await response.Content.ReadAsStringAsync());
// If user is not authenticated, redirect to login page
else if (response.StatusCode == HttpStatusCode.Unauthorized)
return RedirectToPage("/Index");
// If user is not authorized, add message
else if (response.StatusCode == HttpStatusCode.Forbidden)
messages.Add(new Message(MessageTypeEnum.Error,
4009,
new List<string>()));
// Otherwise try parse error messages
else
messages = JsonConvert.DeserializeObject<List<Message>>(await response.Content.ReadAsStringAsync()) ?? throw new JsonSerializationException();
}
catch (JsonSerializationException e)
{
// In case of JSON parsing error, create server error message
messages.Add(MessageHepler.Create1007());
Logger.LogExceptionToConsole(e);
}
// Set messages to cookie
TempData["Messages"] = JsonConvert.SerializeObject(messages);
return await OnGetAsync();
}
/// <summary>
/// OnPostRightsCreateAsync method is invoked after clicking on Create button
/// and redirects user to create page.
/// </summary>
/// <returns>Redirect to create page.</returns>
public IActionResult OnPostRightsCreateAsync()
{
return RedirectToPage("Create", "");
}
/// <summary>
/// OnPostRightsEditAsync method is invoked after clicking on Edit button
/// and redirects user to edit page.
/// </summary>
/// <returns>Redirect to edit page.</returns>
public IActionResult OnPostRightsEditAsync(string dataId)
{
return RedirectToPage("Edit", "", new { id = dataId });
}
}
}
| 45.185185 | 162 | 0.568761 | [
"MIT"
] | sapoi/MetaRMS | Core/Pages/Rights/Get.cshtml.cs | 10,980 | C# |
using System;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Office.Interop.Excel;
using OpenRPA.Interfaces;
namespace OpenRPA.Office.Activities
{
[System.ComponentModel.Designer(typeof(CloseWorkbookDesigner), typeof(System.ComponentModel.Design.IDesigner))]
[System.Drawing.ToolboxBitmap(typeof(ResFinder2), "Resources.toolbox.closeworkbook.png")]
[LocalizedToolboxTooltip("activity_closeworkbook_tooltip", typeof(Resources.strings))]
[LocalizedDisplayName("activity_closeworkbook", typeof(Resources.strings))]
public class CloseWorkbook : CodeActivity
{
[System.ComponentModel.Category("Misc")]
public virtual InArgument<bool> RemoveReadPassword { get; set; }
[System.ComponentModel.Category("Misc")]
public virtual InArgument<string> ReadPassword { get; set; }
[System.ComponentModel.Category("Misc")]
public virtual InArgument<bool> RemoveWritePassword { get; set; }
[System.ComponentModel.Category("Misc")]
public virtual InArgument<string> WritePassword { get; set; }
// [RequiredArgument]
[Category("Input")]
[OverloadGroup("asworkbook")]
[LocalizedDisplayName("activity_closeworkbook_workbook", typeof(Resources.strings)), LocalizedDescription("activity_closeworkbook_workbook_help", typeof(Resources.strings))]
public InOutArgument<Microsoft.Office.Interop.Excel.Workbook> Workbook { get; set; }
// [RequiredArgument]
[Category("Input")]
[OverloadGroup("asfilename")]
[LocalizedDisplayName("activity_closeworkbook_filename", typeof(Resources.strings)), LocalizedDescription("activity_closeworkbook_filename_help", typeof(Resources.strings))]
public InArgument<string> Filename { get; set; }
[RequiredArgument]
[Category("Input")]
[LocalizedDisplayName("activity_closeworkbook_savechanges", typeof(Resources.strings)), LocalizedDescription("activity_closeworkbook_savechanges_help", typeof(Resources.strings))]
public InArgument<bool> SaveChanges { get; set; } = true;
protected override void Execute(CodeActivityContext context)
{
var readPassword = ReadPassword.Get(context);
if (string.IsNullOrEmpty(readPassword)) readPassword = null;
var writePassword = WritePassword.Get(context);
if (string.IsNullOrEmpty(writePassword)) writePassword = null;
var removeReadPassword = RemoveReadPassword.Get(context);
var removeWritePassword = RemoveWritePassword.Get(context);
var workbook = Workbook.Get(context);
var filename = Filename.Get(context);
var saveChanges = SaveChanges.Get(context);
if (!string.IsNullOrEmpty(filename)) filename = Environment.ExpandEnvironmentVariables(filename);
if (!string.IsNullOrEmpty(filename))
{
bool foundit = false;
foreach (Microsoft.Office.Interop.Excel.Workbook w in officewrap.application.Workbooks)
{
if (w.FullName == filename || string.IsNullOrEmpty(filename))
{
try
{
workbook = w;
foundit = true;
//worksheet = workbook.ActiveSheet;
break;
}
catch (Exception)
{
workbook = null;
}
}
}
if(!foundit)
{
Workbook tempworkbook = officewrap.application.ActiveWorkbook;
if(saveChanges && tempworkbook != null)
{
tempworkbook.SaveAs(Filename: filename, Password: readPassword, WriteResPassword: writePassword);
workbook = tempworkbook;
}
}
}
if(workbook!=null)
{
officewrap.application.DisplayAlerts = false;
if (!string.IsNullOrEmpty(readPassword)) { workbook.Password = readPassword; saveChanges = true; }
if (removeReadPassword) { workbook.Password = ""; saveChanges = true; }
if (!string.IsNullOrEmpty(writePassword)) { workbook.WritePassword = writePassword; saveChanges = true; }
if (removeWritePassword) { workbook.WritePassword = ""; saveChanges = true; }
//if (saveChanges || removeWritePassword || removeReadPassword)
//{
// //if(removeWritePassword || removeReadPassword || )
// //if (string.IsNullOrEmpty(readPassword) && !string.IsNullOrEmpty(writePassword) )
// // workbook.SaveAs(Filename: filename, Password: readPassword, WriteResPassword: writePassword);
//}
workbook.Close(saveChanges);
officewrap.application.DisplayAlerts = true;
}
if (officewrap.application.Workbooks.Count == 0)
{
officewrap.application.Quit();
}
}
public new string DisplayName
{
get
{
var displayName = base.DisplayName;
if (displayName == this.GetType().Name)
{
var displayNameAttribute = this.GetType().GetCustomAttributes(typeof(DisplayNameAttribute), true).FirstOrDefault() as DisplayNameAttribute;
if (displayNameAttribute != null) displayName = displayNameAttribute.DisplayName;
}
return displayName;
}
set
{
base.DisplayName = value;
}
}
}
} | 47.294574 | 187 | 0.597115 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | IBM/openrpa | OpenRPA.Office/Activities/CloseWorkbook.cs | 6,103 | C# |
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Unity.CompilationPipeline.Common.Diagnostics;
using Unity.CompilationPipeline.Common.ILPostProcessing;
using ILPPInterface = Unity.CompilationPipeline.Common.ILPostProcessing.ILPostProcessor;
using MethodAttributes = Mono.Cecil.MethodAttributes;
namespace Unity.Netcode.Editor.CodeGen
{
internal sealed class INetworkSerializableILPP : ILPPInterface
{
public override ILPPInterface GetInstance() => this;
public override bool WillProcess(ICompiledAssembly compiledAssembly) =>
compiledAssembly.Name == CodeGenHelpers.RuntimeAssemblyName ||
compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == CodeGenHelpers.RuntimeAssemblyName);
private readonly List<DiagnosticMessage> m_Diagnostics = new List<DiagnosticMessage>();
public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly)
{
if (!WillProcess(compiledAssembly))
{
return null;
}
m_Diagnostics.Clear();
// read
var assemblyDefinition = CodeGenHelpers.AssemblyDefinitionFor(compiledAssembly, out var resolver);
if (assemblyDefinition == null)
{
m_Diagnostics.AddError($"Cannot read assembly definition: {compiledAssembly.Name}");
return null;
}
// process
var mainModule = assemblyDefinition.MainModule;
if (mainModule != null)
{
try
{
if (ImportReferences(mainModule))
{
var types = mainModule.GetTypes()
.Where(t => t.Resolve().HasInterface(CodeGenHelpers.INetworkSerializable_FullName) && !t.Resolve().IsAbstract && t.Resolve().IsValueType)
.ToList();
// process `INetworkMessage` types
if (types.Count == 0)
{
return null;
}
CreateModuleInitializer(assemblyDefinition, types);
}
else
{
m_Diagnostics.AddError($"Cannot import references into main module: {mainModule.Name}");
}
}
catch (Exception e)
{
m_Diagnostics.AddError((e.ToString() + e.StackTrace.ToString()).Replace("\n", "|").Replace("\r", "|"));
}
}
else
{
m_Diagnostics.AddError($"Cannot get main module from assembly definition: {compiledAssembly.Name}");
}
mainModule.RemoveRecursiveReferences();
// write
var pe = new MemoryStream();
var pdb = new MemoryStream();
var writerParameters = new WriterParameters
{
SymbolWriterProvider = new PortablePdbWriterProvider(),
SymbolStream = pdb,
WriteSymbols = true
};
assemblyDefinition.Write(pe, writerParameters);
return new ILPostProcessResult(new InMemoryAssembly(pe.ToArray(), pdb.ToArray()), m_Diagnostics);
}
private MethodReference m_InitializeDelegates_MethodRef;
private const string k_InitializeMethodName = nameof(NetworkVariableHelper.InitializeDelegates);
private bool ImportReferences(ModuleDefinition moduleDefinition)
{
var helperType = typeof(NetworkVariableHelper);
foreach (var methodInfo in helperType.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
{
switch (methodInfo.Name)
{
case k_InitializeMethodName:
m_InitializeDelegates_MethodRef = moduleDefinition.ImportReference(methodInfo);
break;
}
}
return true;
}
private MethodDefinition GetOrCreateStaticConstructor(TypeDefinition typeDefinition)
{
var staticCtorMethodDef = typeDefinition.GetStaticConstructor();
if (staticCtorMethodDef == null)
{
staticCtorMethodDef = new MethodDefinition(
".cctor", // Static Constructor (constant-constructor)
MethodAttributes.HideBySig |
MethodAttributes.SpecialName |
MethodAttributes.RTSpecialName |
MethodAttributes.Static,
typeDefinition.Module.TypeSystem.Void);
staticCtorMethodDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
typeDefinition.Methods.Add(staticCtorMethodDef);
}
return staticCtorMethodDef;
}
// Creates a static module constructor (which is executed when the module is loaded) that registers all the
// message types in the assembly with MessagingSystem.
// This is the same behavior as annotating a static method with [ModuleInitializer] in standardized
// C# (that attribute doesn't exist in Unity, but the static module constructor still works)
// https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.moduleinitializerattribute?view=net-5.0
// https://web.archive.org/web/20100212140402/http://blogs.msdn.com/junfeng/archive/2005/11/19/494914.aspx
private void CreateModuleInitializer(AssemblyDefinition assembly, List<TypeDefinition> networkSerializableTypes)
{
foreach (var typeDefinition in assembly.MainModule.Types)
{
if (typeDefinition.FullName == "<Module>")
{
var staticCtorMethodDef = GetOrCreateStaticConstructor(typeDefinition);
var processor = staticCtorMethodDef.Body.GetILProcessor();
var instructions = new List<Instruction>();
foreach (var type in networkSerializableTypes)
{
var method = new GenericInstanceMethod(m_InitializeDelegates_MethodRef);
method.GenericArguments.Add(type);
instructions.Add(processor.Create(OpCodes.Call, method));
}
instructions.ForEach(instruction => processor.Body.Instructions.Insert(processor.Body.Instructions.Count - 1, instruction));
break;
}
}
}
}
}
| 40.940476 | 165 | 0.589997 | [
"MIT"
] | Kynake/com.unity.netcode.gameobjects | com.unity.netcode.gameobjects/Editor/CodeGen/INetworkSerializableILPP.cs | 6,878 | C# |
// <auto-generated />
using System;
using DataAccess.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace DataAccess.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20210201183111_AddDescriptionToTemplateSynonyms")]
partial class AddDescriptionToTemplateSynonyms
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.2");
modelBuilder.Entity("DataAccess.Models.Campaign", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<int>("CreatorId")
.HasColumnType("int");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<int>("ListId")
.HasColumnType("int");
b.Property<DateTime?>("ModifiedDate")
.HasColumnType("datetime2");
b.Property<int?>("ModifierId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("ProcessedTimestamp")
.HasColumnType("datetime2");
b.Property<DateTime>("SendDate")
.HasColumnType("datetime2");
b.Property<string>("SenderEmail")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("TemplateId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CreatorId");
b.HasIndex("ModifierId");
b.ToTable("Campaigns");
});
modelBuilder.Entity("DataAccess.Models.CampaignJobHistory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("CampaignId")
.HasColumnType("int");
b.Property<int>("EmailStatusCode")
.HasColumnType("int");
b.Property<DateTime>("ProcessedTimestamp")
.HasColumnType("datetime2");
b.Property<string>("RecipientEmail")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("CampaignJobHistory");
});
modelBuilder.Entity("DataAccess.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("nvarchar(30)");
b.Property<int>("SubscriptionLevelId")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("DataAccess.Models.EmailStatus", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("EmailStatuses");
b.HasData(
new
{
Id = 1,
Name = "Pending"
},
new
{
Id = 2,
Name = "Sent"
},
new
{
Id = 3,
Name = "Failed"
});
});
modelBuilder.Entity("DataAccess.Models.List", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<int>("CreatorId")
.HasColumnType("int");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("ModifiedDate")
.HasColumnType("datetime2");
b.Property<int?>("ModifierId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.HasIndex("CreatorId");
b.HasIndex("ModifierId");
b.ToTable("Lists");
});
modelBuilder.Entity("DataAccess.Models.ListRecipient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("ListId")
.HasColumnType("int");
b.Property<int>("RecipientId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ListId");
b.HasIndex("RecipientId");
b.ToTable("ListRecipients");
});
modelBuilder.Entity("DataAccess.Models.PasswordReset", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<DateTime>("DateCreated")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("EmailSent")
.HasColumnType("bit");
b.Property<string>("Token")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("PasswordResets");
});
modelBuilder.Entity("DataAccess.Models.Recipient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Notes")
.HasColumnType("nvarchar(max)");
b.Property<string>("SchemaValues")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Recipients");
});
modelBuilder.Entity("DataAccess.Models.RecipientSchema", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<string>("Schema")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("RecipientSchemas");
});
modelBuilder.Entity("DataAccess.Models.SubscriptionLevel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<decimal>("Cost")
.HasColumnType("decimal(5,2)");
b.Property<int>("MaxUsers")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("nvarchar(20)");
b.HasKey("Id");
b.ToTable("SubscriptionLevels");
});
modelBuilder.Entity("DataAccess.Models.Template", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<int>("CreatorId")
.HasColumnType("int");
b.Property<DateTime?>("ModifiedDate")
.HasColumnType("datetime2");
b.Property<int?>("ModifierId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("Protected")
.HasColumnType("bit");
b.Property<int>("Version")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CreatorId");
b.HasIndex("ModifierId");
b.ToTable("Templates");
});
modelBuilder.Entity("DataAccess.Models.TemplateHistory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("ModifiedDate")
.HasColumnType("datetime2");
b.Property<int?>("ModifierId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("Protected")
.HasColumnType("bit");
b.Property<int>("TemplateId")
.HasColumnType("int");
b.Property<int>("Version")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ModifierId");
b.HasIndex("TemplateId");
b.ToTable("TemplateHistory");
});
modelBuilder.Entity("DataAccess.Models.TemplateSynonym", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("TemplateSynonyms");
});
modelBuilder.Entity("DataAccess.Models.Timestep", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("Hours")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Timesteps");
b.HasData(
new
{
Id = 1,
Hours = 0,
Name = "ASAP"
},
new
{
Id = 2,
Hours = 1,
Name = "Hourly"
},
new
{
Id = 3,
Hours = 24,
Name = "Daily"
},
new
{
Id = 4,
Hours = 168,
Name = "Weekly"
},
new
{
Id = 5,
Hours = 336,
Name = "Bi-Weekly"
},
new
{
Id = 6,
Hours = 672,
Name = "4 Weekly"
},
new
{
Id = 7,
Hours = 730,
Name = "Monthly"
});
});
modelBuilder.Entity("DataAccess.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<bool>("Admin")
.HasColumnType("bit");
b.Property<bool>("Archived")
.HasColumnType("bit");
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("DataAccess.Models.UserInvite", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("InviteSent")
.HasColumnType("bit");
b.Property<int>("InvitingUserId")
.HasColumnType("int");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("UserInvites");
});
modelBuilder.Entity("DataAccess.Models.Campaign", b =>
{
b.HasOne("DataAccess.Models.User", "CreatingUser")
.WithMany()
.HasForeignKey("CreatorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DataAccess.Models.User", "ModifyingUser")
.WithMany()
.HasForeignKey("ModifierId");
b.Navigation("CreatingUser");
b.Navigation("ModifyingUser");
});
modelBuilder.Entity("DataAccess.Models.List", b =>
{
b.HasOne("DataAccess.Models.User", "CreatingUser")
.WithMany()
.HasForeignKey("CreatorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DataAccess.Models.User", "ModifyingUser")
.WithMany()
.HasForeignKey("ModifierId");
b.Navigation("CreatingUser");
b.Navigation("ModifyingUser");
});
modelBuilder.Entity("DataAccess.Models.ListRecipient", b =>
{
b.HasOne("DataAccess.Models.List", null)
.WithMany("ListRecipients")
.HasForeignKey("ListId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DataAccess.Models.Recipient", "Recipient")
.WithMany()
.HasForeignKey("RecipientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Recipient");
});
modelBuilder.Entity("DataAccess.Models.PasswordReset", b =>
{
b.HasOne("DataAccess.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("DataAccess.Models.Template", b =>
{
b.HasOne("DataAccess.Models.User", "CreatingUser")
.WithMany()
.HasForeignKey("CreatorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DataAccess.Models.User", "ModifyingUser")
.WithMany()
.HasForeignKey("ModifierId");
b.Navigation("CreatingUser");
b.Navigation("ModifyingUser");
});
modelBuilder.Entity("DataAccess.Models.TemplateHistory", b =>
{
b.HasOne("DataAccess.Models.User", "ModifyingUser")
.WithMany()
.HasForeignKey("ModifierId");
b.HasOne("DataAccess.Models.Template", "Template")
.WithMany()
.HasForeignKey("TemplateId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ModifyingUser");
b.Navigation("Template");
});
modelBuilder.Entity("DataAccess.Models.List", b =>
{
b.Navigation("ListRecipients");
});
#pragma warning restore 612, 618
}
}
}
| 33.473684 | 76 | 0.383423 | [
"Apache-2.0"
] | alex-coupe/MarketingTool | source/MarketingTool/DataAccess/Migrations/20210201183111_AddDescriptionToTemplateSynonyms.Designer.cs | 22,262 | C# |
#region Usings
using System;
using System.Collections.Generic;
using System.ComponentModel;
using ModInstallation.Annotations;
#endregion
namespace ModInstallation.Interfaces.Mods
{
public interface IFileInformation : INotifyPropertyChanged
{
[CanBeNull]
string FileName { get; }
[CanBeNull]
IEnumerable<IFileVerifier> FileVerifiers { get; }
[CanBeNull]
string Destination { get; }
long Filesize { get; }
[CanBeNull]
IDictionary<string, IEnumerable<IFileVerifier>> ContentVerifiers { get; }
[NotNull]
IEnumerable<Uri> DownloadUris { get; }
}
}
| 20.40625 | 81 | 0.661562 | [
"MIT"
] | asarium/FSOLauncher | Libraries/ModInstallation/Interfaces/Mods/IFileInformation.cs | 655 | C# |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet;
using NtObjectManager.Utils;
using System;
using System.Management.Automation;
namespace NtObjectManager.Cmdlets.Object
{
/// <summary>
/// <para type="synopsis">Convert a specific object access to an AccessMask or GenericAccess.</para>
/// <para type="description">This cmdlet allows you to convert a specific object access to an
/// AccessMask or GenericAccess for use in general functions.</para>
/// </summary>
/// <example>
/// <code>Get-NtAccessMask -ProcessAccess DupHandle</code>
/// <para>Get the Process DupHandle access right as an AccessMask</para>
/// </example>
/// <example>
/// <code>Get-NtAccessMask -ProcessAccess DupHandle -ToGenericAccess</code>
/// <para>Get the Process DupHandle access right as a GenericAccess value</para>
/// </example>
/// <example>
/// <code>Get-NtAccessMask -AccessMask 0xFF -ToSpecificAccess Process</code>
/// <para>Convert a raw access mask to a process access mask.</para>
/// </example>
/// <example>
/// <code>Get-NtAccessMask -AccessControlEntry $sd.Dacl[0] -ToSpecificAccess Thread</code>
/// <para>Get the access mask from a security descriptor ACE and map to thread access.</para>
/// </example>
/// <example>
/// <code>$sd.Dacl | Get-NtAccessMask -ToSpecificAccess Thread</code>
/// <para>Get the access mask from a list of security descriptor ACEs and map to thread access.</para>
/// </example>
[Cmdlet(VerbsCommon.Get, "NtAccessMask", DefaultParameterSetName = "FromMask")]
public class GetNtAccessMaskCmdlet : PSCmdlet
{
private static NtType GetTypeObject(SpecificAccessType type)
{
switch (type)
{
case SpecificAccessType.Transaction:
return NtType.GetTypeByType<NtTransaction>();
case SpecificAccessType.TransactionManager:
return NtType.GetTypeByType<NtTransactionManager>();
case SpecificAccessType.ResourceManager:
return NtType.GetTypeByType<NtResourceManager>();
case SpecificAccessType.Enlistment:
return NtType.GetTypeByType<NtEnlistment>();
case SpecificAccessType.ALPCPort:
return NtType.GetTypeByType<NtAlpc>();
}
return NtType.GetTypeByName(type.ToString(), false);
}
private AccessMask MapGeneric(SpecificAccessType specific_type, AccessMask access_mask)
{
if (!MapGenericRights)
{
return access_mask;
}
NtType type = GetTypeObject(specific_type);
System.Diagnostics.Debug.Assert(type != null);
return type.MapGenericRights(access_mask);
}
/// <summary>
/// <para type="description">Specify a raw access mask.</para>
/// </summary>
[Parameter(Position = 0, ParameterSetName = "FromMask", Mandatory = true)]
public AccessMask AccessMask { get; set; }
/// <summary>
/// <para type="description">Specify File access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromFile", Mandatory = true)]
public FileAccessRights FileAccess { get; set; }
/// <summary>
/// <para type="description">Specify File Directory access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromFileDir", Mandatory = true)]
public FileDirectoryAccessRights FileDirectoryAccess { get; set; }
/// <summary>
/// <para type="description">Specify IO Completion access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromIoCompletion", Mandatory = true)]
public IoCompletionAccessRights IoCompletionAccess { get; set; }
/// <summary>
/// <para type="description">Specify Mutant access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromMutant", Mandatory = true)]
public MutantAccessRights MutantAccess { get; set; }
/// <summary>
/// <para type="description">Specify Semaphore access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromSemaphore", Mandatory = true)]
public SemaphoreAccessRights SemaphoreAccess { get; set; }
/// <summary>
/// <para type="description">Specify Registry Transaction access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromRegTrans", Mandatory = true)]
public RegistryTransactionAccessRights RegistryTransactionAccess { get; set; }
/// <summary>
/// <para type="description">Specify ALPC Port access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromAlpc", Mandatory = true)]
public AlpcAccessRights AlpcPortAccess { get; set; }
/// <summary>
/// <para type="description">Specify Section access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromSection", Mandatory = true)]
public SectionAccessRights SectionAccess { get; set; }
/// <summary>
/// <para type="description">Specify Key access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromKey", Mandatory = true)]
public KeyAccessRights KeyAccess { get; set; }
/// <summary>
/// <para type="description">Specify Event access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromEvent", Mandatory = true)]
public EventAccessRights EventAccess { get; set; }
/// <summary>
/// <para type="description">Specify Symbolic Link access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromSymbolicLink", Mandatory = true)]
public SymbolicLinkAccessRights SymbolicLinkAccess { get; set; }
/// <summary>
/// <para type="description">Specify Token access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromToken", Mandatory = true)]
public TokenAccessRights TokenAccess { get; set; }
/// <summary>
/// <para type="description">Specify Generic access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromGeneric", Mandatory = true)]
public GenericAccessRights GenericAccess { get; set; }
/// <summary>
/// <para type="description">Specify Directory access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromDirectory", Mandatory = true)]
public DirectoryAccessRights DirectoryAccess { get; set; }
/// <summary>
/// <para type="description">Specify Thread access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromThread", Mandatory = true)]
public ThreadAccessRights ThreadAccess { get; set; }
/// <summary>
/// <para type="description">Specify Debug Object access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromDebugObject", Mandatory = true)]
public DebugAccessRights DebugObjectAccess { get; set; }
/// <summary>
/// <para type="description">Specify Job access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromJob", Mandatory = true)]
public JobAccessRights JobAccess { get; set; }
/// <summary>
/// <para type="description">Specify Process access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromProcess", Mandatory = true)]
public ProcessAccessRights ProcessAccess { get; set; }
/// <summary>
/// <para type="description">Specify transaction access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromTransaction", Mandatory = true)]
public TransactionAccessRights TransactionAccess { get; set; }
/// <summary>
/// <para type="description">Specify transaction manager access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromTransactionManager", Mandatory = true)]
public TransactionManagerAccessRights TransactionManagerAccess { get; set; }
/// <summary>
/// <para type="description">Specify resource manager access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromResourceManager", Mandatory = true)]
public ResourceManagerAccessRights ResourceManagerAccess { get; set; }
/// <summary>
/// <para type="description">Specify enlistment access rights.</para>
/// </summary>
[Parameter(ParameterSetName = "FromEnlistment", Mandatory = true)]
public EnlistmentAccessRights EnlistmentAccess { get; set; }
/// <summary>
/// <para type="description">Specify mandatory label policy.</para>
/// </summary>
[Parameter(ParameterSetName = "FromMandatoryLabel", Mandatory = true)]
public MandatoryLabelPolicy ManadatoryLabelPolicy { get; set; }
/// <summary>
/// <para type="description">Specify an ACE to extract the mask to map.</para>
/// </summary>
[Parameter(ParameterSetName = "FromAce", Mandatory = true, ValueFromPipeline = true, Position = 0)]
[Alias("Ace")]
public Ace AccessControlEntry { get; set; }
/// <summary>
/// <para type="description">Specify a security information to get the access mask.</para>
/// </summary>
[Parameter(ParameterSetName = "FromSecurityInformation", Mandatory = true)]
public SecurityInformation SecurityInformation { get; set; }
/// <summary>
/// <para type="description">Specify to get the set security mask rather than the query.</para>
/// </summary>
[Parameter(ParameterSetName = "FromSecurityInformation")]
public SwitchParameter SetSecurity { get; set; }
/// <summary>
/// <para type="description">Return access as GenericAccess.</para>
/// </summary>
[Parameter]
public SwitchParameter ToGenericAccess { get; set; }
/// <summary>
/// <para type="description">Return access as ManadatoryLabelPolicy.</para>
/// </summary>
[Parameter]
public SwitchParameter ToMandatoryLabelPolicy { get; set; }
/// <summary>
/// <para type="description">Return access as specific access type based on the type enumeration.</para>
/// </summary>
[Parameter]
public SpecificAccessType ToSpecificAccess { get; set; }
/// <summary>
/// <para type="description">Return access as specific access type based on the NtType object.</para>
/// </summary>
[Parameter, ArgumentCompleter(typeof(NtTypeArgumentCompleter))]
public NtType ToTypeAccess { get; set; }
/// <summary>
/// <para type="description">Specify that any generic rights should be mapped to type specific rights.</para>
/// </summary>
[Parameter]
public SwitchParameter MapGenericRights { get; set; }
/// <summary>
/// <para type="description">When specifying a Mandatory Label Policy specify GenericMapping to get the mandatory access.</para>
/// </summary>
[Parameter]
public GenericMapping? GenericMapping { get; set; }
/// <summary>
/// Constructor.
/// </summary>
public GetNtAccessMaskCmdlet()
{
ToSpecificAccess = SpecificAccessType.None;
}
/// <summary>
/// Overridden ProcessRecord
/// </summary>
protected override void ProcessRecord()
{
AccessMask mask;
switch (ParameterSetName)
{
case "FromAce":
mask = AccessControlEntry.Mask;
break;
case "FromSecurityInformation":
if (SetSecurity)
{
mask = NtSecurity.SetSecurityAccessMask(SecurityInformation);
}
else
{
mask = NtSecurity.QuerySecurityAccessMask(SecurityInformation);
}
break;
default:
mask = AccessMask;
mask |= MapGeneric(SpecificAccessType.File, FileAccess);
mask |= MapGeneric(SpecificAccessType.File, FileDirectoryAccess);
mask |= MapGeneric(SpecificAccessType.IoCompletion, IoCompletionAccess);
mask |= MapGeneric(SpecificAccessType.Mutant, MutantAccess);
mask |= MapGeneric(SpecificAccessType.Semaphore, SemaphoreAccess);
mask |= MapGeneric(SpecificAccessType.RegistryTransaction, RegistryTransactionAccess);
mask |= MapGeneric(SpecificAccessType.ALPCPort, AlpcPortAccess);
mask |= MapGeneric(SpecificAccessType.Section, SectionAccess);
mask |= MapGeneric(SpecificAccessType.Key, KeyAccess);
mask |= MapGeneric(SpecificAccessType.Event, EventAccess);
mask |= MapGeneric(SpecificAccessType.SymbolicLink, SymbolicLinkAccess);
mask |= MapGeneric(SpecificAccessType.Token, TokenAccess);
mask |= GenericAccess;
mask |= MapGeneric(SpecificAccessType.Directory, DirectoryAccess);
mask |= MapGeneric(SpecificAccessType.Thread, ThreadAccess);
mask |= MapGeneric(SpecificAccessType.DebugObject, DebugObjectAccess);
mask |= MapGeneric(SpecificAccessType.Job, JobAccess);
mask |= MapGeneric(SpecificAccessType.Process, ProcessAccess);
mask |= MapGeneric(SpecificAccessType.Transaction, TransactionAccess);
mask |= MapGeneric(SpecificAccessType.TransactionManager, TransactionManagerAccess);
mask |= MapGeneric(SpecificAccessType.ResourceManager, ResourceManagerAccess);
mask |= MapGeneric(SpecificAccessType.Enlistment, EnlistmentAccess);
mask |= (uint)ManadatoryLabelPolicy;
break;
}
if (GenericMapping.HasValue)
{
mask = GenericMapping.Value.GetAllowedMandatoryAccess(mask.ToMandatoryLabelPolicy());
}
if (ToGenericAccess)
{
WriteObject(mask.ToGenericAccess());
}
else if (ToMandatoryLabelPolicy)
{
WriteObject(mask.ToMandatoryLabelPolicy());
}
else if (ToSpecificAccess == SpecificAccessType.None && ToTypeAccess == null)
{
WriteObject(mask);
}
else
{
NtType type = ToTypeAccess ?? GetTypeObject(ToSpecificAccess);
WriteObject(mask.ToSpecificAccess(type.AccessRightsType));
}
}
}
}
| 48.06079 | 136 | 0.609094 | [
"Apache-2.0"
] | InitRoot/sandbox-attacksurface-analysis-tools | NtObjectManager/Cmdlets/Object/GetNtAccessMaskCmdlet.cs | 15,814 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using EventStore.Client;
using EventStore.Client.Streams;
using EventStore.Common.Utils;
using EventStore.Core.Bus;
using EventStore.Core.Data;
using EventStore.Core.Messages;
using EventStore.Core.Messaging;
using EventStore.Plugins.Authorization;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Serilog;
using Empty = Google.Protobuf.WellKnownTypes.Empty;
using Status = Google.Rpc.Status;
using static EventStore.Client.Streams.BatchAppendReq.Types;
using static EventStore.Client.Streams.BatchAppendReq.Types.Options;
using OperationResult = EventStore.Core.Messages.OperationResult;
namespace EventStore.Core.Services.Transport.Grpc {
partial class Streams<TStreamId> {
public override async Task BatchAppend(IAsyncStreamReader<BatchAppendReq> requestStream,
IServerStreamWriter<BatchAppendResp> responseStream, ServerCallContext context) {
var worker = new BatchAppendWorker(_publisher, _provider, requestStream, responseStream,
context.GetHttpContext().User, _maxAppendSize, _writeTimeout,
GetRequiresLeader(context.RequestHeaders));
await worker.Work(context.CancellationToken).ConfigureAwait(false);
}
private class BatchAppendWorker {
private readonly IPublisher _publisher;
private readonly IAuthorizationProvider _authorizationProvider;
private readonly IAsyncStreamReader<BatchAppendReq> _requestStream;
private readonly IServerStreamWriter<BatchAppendResp> _responseStream;
private readonly ClaimsPrincipal _user;
private readonly int _maxAppendSize;
private readonly TimeSpan _writeTimeout;
private readonly bool _requiresLeader;
private readonly Channel<BatchAppendResp> _channel;
private long _pending;
public BatchAppendWorker(IPublisher publisher, IAuthorizationProvider authorizationProvider,
IAsyncStreamReader<BatchAppendReq> requestStream, IServerStreamWriter<BatchAppendResp> responseStream,
ClaimsPrincipal user, int maxAppendSize, TimeSpan writeTimeout, bool requiresLeader) {
_publisher = publisher;
_authorizationProvider = authorizationProvider;
_requestStream = requestStream;
_responseStream = responseStream;
_user = user;
_maxAppendSize = maxAppendSize;
_writeTimeout = writeTimeout;
_requiresLeader = requiresLeader;
_channel = Channel.CreateUnbounded<BatchAppendResp>(new() {
AllowSynchronousContinuations = false,
SingleReader = false,
SingleWriter = false
});
}
public Task Work(CancellationToken cancellationToken) {
var remaining = 2;
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
#if DEBUG
var sendTask =
#endif
Send(_channel.Reader, cancellationToken)
.ContinueWith(HandleCompletion, CancellationToken.None);
#if DEBUG
var receiveTask =
#endif
Receive(_channel.Writer, _user, _requiresLeader, cancellationToken)
.ContinueWith(HandleCompletion, CancellationToken.None);
return tcs.Task;
async void HandleCompletion(Task task) {
try {
await task.ConfigureAwait(false);
if (Interlocked.Decrement(ref remaining) == 0) {
tcs.TrySetResult();
}
} catch (OperationCanceledException) {
tcs.TrySetCanceled(cancellationToken);
} catch (IOException ex) {
Log.Information("Closing gRPC client connection: {message}", ex.GetBaseException().Message);
tcs.TrySetException(ex);
}
catch (Exception ex) {
tcs.TrySetException(ex);
}
}
}
private async Task Send(ChannelReader<BatchAppendResp> reader, CancellationToken cancellationToken) {
var isClosing = false;
await foreach (var response in reader.ReadAllAsync(cancellationToken)) {
if (!response.IsClosing) {
await _responseStream.WriteAsync(response).ConfigureAwait(false);
if (Interlocked.Decrement(ref _pending) >= 0 && isClosing) {
break;
}
} else {
isClosing = true;
}
}
}
private async Task Receive(ChannelWriter<BatchAppendResp> writer, ClaimsPrincipal user, bool requiresLeader,
CancellationToken cancellationToken) {
var pendingWrites = new ConcurrentDictionary<Guid, ClientWriteRequest>();
try {
await foreach (var request in _requestStream.ReadAllAsync(cancellationToken)) {
try {
var correlationId = Uuid.FromDto(request.CorrelationId).ToGuid();
if (request.Options != null) {
var timeout = Min(GetRequestedTimeout(request.Options), _writeTimeout);
if (!await _authorizationProvider.CheckAccessAsync(user, WriteOperation.WithParameter(
Plugins.Authorization.Operations.Streams.Parameters.StreamId(
request.Options.StreamIdentifier)), cancellationToken).ConfigureAwait(false)) {
await writer.WriteAsync(new BatchAppendResp {
CorrelationId = request.CorrelationId,
StreamIdentifier = request.Options.StreamIdentifier,
Error = Status.AccessDenied
}, cancellationToken).ConfigureAwait(false);
continue;
}
if (request.Options.StreamIdentifier == null) {
await writer.WriteAsync(new BatchAppendResp {
CorrelationId = request.CorrelationId,
StreamIdentifier = request.Options.StreamIdentifier,
Error = Status.BadRequest(
$"Required field {nameof(request.Options.StreamIdentifier)} not set.")
}, cancellationToken).ConfigureAwait(false);
continue;
}
if (Max(timeout, TimeSpan.Zero) == TimeSpan.Zero) {
await writer.WriteAsync(new BatchAppendResp {
CorrelationId = request.CorrelationId,
StreamIdentifier = request.Options.StreamIdentifier,
Error = Status.Timeout
}, cancellationToken).ConfigureAwait(false);
continue;
}
pendingWrites.AddOrUpdate(correlationId,
c => FromOptions(c, request.Options, timeout, cancellationToken),
(_, writeRequest) => writeRequest);
}
if (!pendingWrites.TryGetValue(correlationId, out var clientWriteRequest)) {
continue;
}
clientWriteRequest.AddEvents(request.ProposedMessages.Select(FromProposedMessage));
if (clientWriteRequest.Size > _maxAppendSize) {
pendingWrites.TryRemove(correlationId, out _);
await writer.WriteAsync(new BatchAppendResp {
CorrelationId = request.CorrelationId,
StreamIdentifier = clientWriteRequest.StreamId,
Error = Status.MaximumAppendSizeExceeded((uint)_maxAppendSize)
}, cancellationToken).ConfigureAwait(false);
}
if (!request.IsFinal) {
continue;
}
if (!pendingWrites.TryRemove(correlationId, out _)) {
continue;
}
Interlocked.Increment(ref _pending);
_publisher.Publish(ToInternalMessage(clientWriteRequest, new CallbackEnvelope(message => {
try {
writer.TryWrite(ConvertMessage(message));
} catch (Exception ex) {
writer.TryComplete(ex);
}
}), requiresLeader, user, cancellationToken));
BatchAppendResp ConvertMessage(Message message) {
var batchAppendResp = message switch {
ClientMessage.NotHandled notHandled => new BatchAppendResp {
Error = new Status {
Details = Any.Pack(new Empty()),
Message = (notHandled.Reason, AdditionalInfo: notHandled.LeaderInfo) switch {
(ClientMessage.NotHandled.Types.NotHandledReason.NotReady, _) => "Server Is Not Ready",
(ClientMessage.NotHandled.Types.NotHandledReason.TooBusy, _) => "Server Is Busy",
(ClientMessage.NotHandled.Types.NotHandledReason.NotLeader or ClientMessage.NotHandled.Types.NotHandledReason.IsReadOnly,
ClientMessage.NotHandled.Types.LeaderInfo leaderInfo) =>
throw RpcExceptions.LeaderInfo(leaderInfo.Http.GetHost(),
leaderInfo.Http.GetPort()),
(ClientMessage.NotHandled.Types.NotHandledReason.NotLeader or ClientMessage.NotHandled.Types.NotHandledReason.IsReadOnly, _) =>
"No leader info available in response",
_ => $"Unknown {nameof(ClientMessage.NotHandled.Types.NotHandledReason)} ({(int)notHandled.Reason})"
}
}
},
ClientMessage.WriteEventsCompleted completed => completed.Result switch {
OperationResult.Success => new BatchAppendResp {
Success = BatchAppendResp.Types.Success.Completed(completed.CommitPosition,
completed.PreparePosition, completed.LastEventNumber),
},
OperationResult.WrongExpectedVersion => new BatchAppendResp {
Error = Status.WrongExpectedVersion(
StreamRevision.FromInt64(completed.CurrentVersion),
clientWriteRequest.ExpectedVersion)
},
OperationResult.AccessDenied => new BatchAppendResp
{ Error = Status.AccessDenied },
OperationResult.StreamDeleted => new BatchAppendResp {
Error = Status.StreamDeleted(clientWriteRequest.StreamId)
},
OperationResult.CommitTimeout or
OperationResult.ForwardTimeout or
OperationResult.PrepareTimeout => new BatchAppendResp
{ Error = Status.Timeout },
_ => new BatchAppendResp { Error = Status.Unknown }
},
_ => new BatchAppendResp {
Error = Status.InternalError(
$"Envelope callback expected either {nameof(ClientMessage.WriteEventsCompleted)} or {nameof(ClientMessage.NotHandled)}, received {message.GetType().Name} instead.")
}
};
batchAppendResp.CorrelationId = request.CorrelationId;
batchAppendResp.StreamIdentifier = new StreamIdentifier {
StreamName = ByteString.CopyFromUtf8(clientWriteRequest.StreamId)
};
return batchAppendResp;
}
} catch (Exception ex) {
await writer.WriteAsync(new BatchAppendResp {
CorrelationId = request.CorrelationId,
StreamIdentifier = request.Options.StreamIdentifier,
Error = Status.BadRequest(ex.Message)
}, cancellationToken).ConfigureAwait(false);
}
}
await writer.WriteAsync(new BatchAppendResp {
IsClosing = true
}, cancellationToken).ConfigureAwait(false);
} catch (Exception ex) {
writer.TryComplete(ex);
throw;
}
ClientWriteRequest FromOptions(Guid correlationId, Options options, TimeSpan timeout,
CancellationToken cancellationToken) =>
new(correlationId, options.StreamIdentifier, options.ExpectedStreamPositionCase switch {
ExpectedStreamPositionOneofCase.StreamPosition => new StreamRevision(options.StreamPosition)
.ToInt64(),
ExpectedStreamPositionOneofCase.Any => AnyStreamRevision.Any.ToInt64(),
ExpectedStreamPositionOneofCase.StreamExists => AnyStreamRevision.StreamExists.ToInt64(),
ExpectedStreamPositionOneofCase.NoStream => AnyStreamRevision.NoStream.ToInt64(),
_ => throw RpcExceptions.InvalidArgument(options.ExpectedStreamPositionCase)
}, timeout, () =>
pendingWrites.TryRemove(correlationId, out var pendingWrite)
? writer.WriteAsync(new BatchAppendResp {
CorrelationId = Uuid.FromGuid(correlationId).ToDto(),
StreamIdentifier = new StreamIdentifier {
StreamName = ByteString.CopyFromUtf8(pendingWrite.StreamId)
},
Error = Status.Timeout
}, cancellationToken)
: new ValueTask(Task.CompletedTask), cancellationToken);
static Event FromProposedMessage(ProposedMessage proposedMessage) =>
new(Uuid.FromDto(proposedMessage.Id).ToGuid(),
proposedMessage.Metadata[Constants.Metadata.Type],
proposedMessage.Metadata[Constants.Metadata.ContentType] ==
Constants.Metadata.ContentTypes.ApplicationJson, proposedMessage.Data.ToByteArray(),
proposedMessage.CustomMetadata.ToByteArray());
static ClientMessage.WriteEvents ToInternalMessage(ClientWriteRequest request, IEnvelope envelope,
bool requiresLeader, ClaimsPrincipal user, CancellationToken token) =>
new(Guid.NewGuid(), request.CorrelationId, envelope, requiresLeader, request.StreamId,
request.ExpectedVersion, request.Events.ToArray(), user, cancellationToken: token);
static TimeSpan GetRequestedTimeout(Options options) => options.DeadlineOptionCase switch {
DeadlineOptionOneofCase.Deadline => options.Deadline.ToTimeSpan(),
_ => (options.Deadline21100?.ToDateTime() ?? DateTime.MaxValue) - DateTime.UtcNow,
};
static TimeSpan Min(TimeSpan a, TimeSpan b) => a > b ? b : a;
static TimeSpan Max(TimeSpan a, TimeSpan b) => a > b ? a : b;
}
}
private record ClientWriteRequest {
public Guid CorrelationId { get; }
public string StreamId { get; }
public long ExpectedVersion { get; }
private readonly List<Event> _events;
public IEnumerable<Event> Events => _events.AsEnumerable();
private int _size;
public int Size => _size;
public ClientWriteRequest(Guid correlationId, string streamId, long expectedVersion, TimeSpan timeout,
Func<ValueTask> onTimeout, CancellationToken cancellationToken) {
CorrelationId = correlationId;
StreamId = streamId;
_events = new List<Event>();
_size = 0;
ExpectedVersion = expectedVersion;
Task.Delay(timeout, cancellationToken).ContinueWith(_ => onTimeout(), cancellationToken);
}
public ClientWriteRequest AddEvents(IEnumerable<Event> events) {
foreach (var e in events) {
_size += Event.SizeOnDisk(e.EventType, e.Data, e.Metadata);
_events.Add(e);
}
return this;
}
}
}
}
| 41.00295 | 175 | 0.712374 | [
"Apache-2.0",
"CC0-1.0"
] | BearerPipelineTest/EventStore | src/EventStore.Core/Services/Transport/Grpc/Streams.BatchAppend.cs | 13,900 | C# |
// Copyright (c) Sven Groot (Ookii.org) 2009
// BSD license; see LICENSE for details.
using System;
using System.Collections.Generic;
using System.Text;
namespace Ookii.Dialogs.WinForms
{
/// <summary>
/// Represents the state of the progress bar on the task dialog.
/// </summary>
public enum ProgressBarState
{
/// <summary>
/// Normal state.
/// </summary>
Normal,
/// <summary>
/// Error state
/// </summary>
Error,
/// <summary>
/// Paused state
/// </summary>
Paused
}
}
| 21.357143 | 68 | 0.543478 | [
"BSD-3-Clause"
] | ailianyiren/ookii-dialogs-winforms | src/Ookii.Dialogs.WinForms/ProgressBarState.cs | 598 | C# |
using System;
using System.Collections.Generic;
namespace PriorityQueue
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Create a priority queue:");
PriorityQueue<Package> pq = new PriorityQueue<Package>();
Console.WriteLine(
"Add a random number (0 - 20) of random packages to queue:");
Package pack;
PackageFactory fact = new PackageFactory();
// You want a random number less than 20.
Random rand = new Random(2);
int numToCreate = rand.Next(20); // Random int from 0 - 20
Console.WriteLine("\tCreating {0} packages: ", numToCreate);
for (int i = 0; i < numToCreate; i++)
{
Console.Write("\t\tGenerating and adding random package {0}", i);
pack = fact.CreatePackage();
Console.WriteLine(" with priority {0}", pack.Priority);
pq.Enqueue(pack);
}
Console.WriteLine("See what we got:");
int total = pq.Count;
Console.WriteLine("Packages received: {0}", total);
Console.WriteLine("Remove a random number of packages (0-20): ");
int numToRemove = rand.Next(20);
Console.WriteLine("\tRemoving up to {0} packages", numToRemove);
for (int i = 0; i < numToRemove; i++)
{
pack = pq.Dequeue();
if (pack != null)
{
Console.WriteLine("\t\tShipped package with priority {0}",
pack.Priority);
}
}
Console.Read();
}
// Priority enumeration -- Defines a set of priorities
// instead of priorities like 1, 2, 3, ... these have names.
// For information on enumerations,
// see the article "Enumerating the Charms of the Enum"
// on csharp102.info.
enum Priority
{
Low, Medium, High
}
// IPrioritizable interface -- Defines ability to prioritize.
// Define a custom interface: Classes that can be added to
// PriorityQueue must implement this interface.
interface IPrioritizable
{
Priority Priority { get; } // Example of a property in an interface
}
//PriorityQueue -- A generic priority queue class
// Types to add to the queue *must* implement IPrioritizable interface.
class PriorityQueue<T> where T : IPrioritizable
{
//Queues -- the three underlying queues: all generic!
private Queue<T> _queueHigh = new Queue<T>();
private Queue<T> _queueMedium = new Queue<T>();
private Queue<T> _queueLow = new Queue<T>();
//Enqueue -- Prioritize T and add an item of type T to correct queue.
// The item must know its own priority.
public void Enqueue(T item)
{
switch (item.Priority) // Require IPrioritizable for this property.
{
case Priority.High:
_queueHigh.Enqueue(item);
break;
case Priority.Medium:
_queueMedium.Enqueue(item);
break;
case Priority.Low:
_queueLow.Enqueue(item);
break;
default:
throw new ArgumentOutOfRangeException(
item.Priority.ToString(),
"bad priority in PriorityQueue.Enqueue");
}
}
//Dequeue -- Get T from highest-priority queue available.
public T Dequeue()
{
// Find highest-priority queue with items.
Queue<T> queueTop = TopQueue();
// If a non-empty queue is found.
if (queueTop != null && queueTop.Count > 0)
{
return queueTop.Dequeue(); // Return its front item.
}
// If all queues empty, return null (you could throw exception).
return default(T); // What’s this? See discussion.
}
//TopQueue -- What’s the highest-priority underlying queue with items?
private Queue<T> TopQueue()
{
if (_queueHigh.Count > 0) // Anything in high-priority queue?
return _queueHigh;
if (_queueMedium.Count > 0) // Anything in medium-priority queue?
return _queueMedium;
if (_queueLow.Count > 0) // Anything in low-priority queue?
return _queueLow;
return null; // All empty, so return null.
}
//IsEmpty -- Check whether there’s anything to deqeue. Not implemented
//or used for this example, but provided for reference.
//public bool IsEmpty()
//{
// // True if all queues are empty
// return (_queueHigh.Count == 0) & (_queueMedium.Count == 0) &
// (_queueLow.Count == 0);
//}
//Count -- How many items are in all queues combined?
public int Count // Implement this one as a read-only property.
{
get
{
return _queueHigh.Count + _queueMedium.Count +
_queueLow.Count;
}
}
}
//Package -- An example of a prioritizable class that can be stored in
// the priority queue; any class that implements
// IPrioritizable would look something like Package.
class Package : IPrioritizable
{
private Priority _priority;
//Constructor
public Package(Priority priority) => _priority = priority;
//Priority -- Return package priority -- read-only.
public Priority Priority
{
get => _priority;
}
// Plus ToAddress, FromAddress, Insurance, etc.
}
//PackageFactory -- You need a class that knows how to create a new
// package of any desired type on demand; such a class
// is a factory class.
class PackageFactory
{
//A random-number generator
Random _randGen = new Random(2);
//CreatePackage -- The factory method selects a random priority,
// then creates a package with that priority.
// Could implement this as iterator block.
public Package CreatePackage()
{
// Return a randomly selected package priority.
// Need a 0, 1, or 2 (values less than 3).
int rand = _randGen.Next(3);
// Use that to generate a new package.
// Casting int to enum is clunky, but it saves
// having to use ifs or a switch statement.
return new Package((Priority)rand);
}
}
}
}
| 37.96875 | 83 | 0.508916 | [
"MIT"
] | robyscar/C-_10_AllInOne4Dummies_sourcecode | source/BK01/CH08/PriorityQueue/Program.cs | 7,298 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("MvcSandbox")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyDescriptionAttribute("Package Description")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("MvcSandbox")]
[assembly: System.Reflection.AssemblyTitleAttribute("MvcSandbox")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.56 | 81 | 0.663534 | [
"MIT"
] | codepic/Codepic.AspNetCore.Mvc.TagHelpers.Polymer | samples/MvcSandbox/obj/Release/netcoreapp1.1/MvcSandbox.AssemblyInfo.cs | 1,064 | C# |
using QbSync.QbXml;
using QbSync.QbXml.Objects;
using QbSync.WebConnector.Core;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace QbSync.WebConnector.Impl
{
/// <summary>
/// Helper to receive more than one response from the WebConnector.
/// </summary>
public abstract class GroupStepQueryResponseBase : IStepQueryResponse
{
/// <summary>
/// Constructs a GroupStepQueryResponseBase.
/// </summary>
public GroupStepQueryResponseBase()
{
}
/// <summary>
/// Returns the step name.
/// </summary>
/// <returns>Step name.</returns>
public abstract string Name { get; }
/// <summary>
/// Called when the Web Connector returns some data.
/// </summary>
/// <param name="authenticatedTicket">The authenticated ticket.</param>
/// <param name="response">QbXml.</param>
/// <param name="hresult">HResult.</param>
/// <param name="message">Message.</param>
/// <returns>Message to be returned to the Web Connector.</returns>
public virtual async Task<int> ReceiveXMLAsync(IAuthenticatedTicket authenticatedTicket, string response, string hresult, string message)
{
var responseObject = new QbXmlResponse();
if (!string.IsNullOrEmpty(response))
{
var objects = responseObject.GetItemsFromResponse(response, typeof(IQbResponse));
var msgResponseObject = ((IEnumerable)objects).Cast<IQbResponse>();
await ExecuteResponseAsync(authenticatedTicket, msgResponseObject);
return 0;
}
return -1;
}
/// <summary>
/// After receiving XML from the Web Connector, the step can decide to go to a specific step.
/// If you return a non null step, we will go to that step.
/// </summary>
/// <returns>Step name to go to. Null to continue.</returns>
public virtual Task<string> GotoStepAsync()
{
return Task.FromResult<string>((string)null);
}
/// <summary>
/// After receiving XML from the Web Connector, we check if we should move to the next step
/// by calling this method. Usually, you want to move to the next step unless your step
/// has other messages to send to the Web Connector. It is the case when you use an iterator.
/// </summary>
/// <returns>False stays on the current step. True goes to the next step.</returns>
public virtual Task<bool> GotoNextStepAsync()
{
return Task.FromResult<bool>(true);
}
/// <summary>
/// Called when the Web Connector detected an error.
/// You can return a message to be displayed to the user.
/// </summary>
/// <param name="authenticatedTicket">The authenticated ticket.</param>
/// <returns>Message to be displayed to the user.</returns>
public virtual Task<string> LastErrorAsync(IAuthenticatedTicket authenticatedTicket)
{
return Task.FromResult(string.Empty);
}
/// <summary>
/// Executes the response with all the QbResponse found.
/// </summary>
/// <param name="authenticatedTicket">The authenticated ticket.</param>
/// <param name="responses">The responses.</param>
/// <returns>Task.</returns>
protected internal virtual Task ExecuteResponseAsync(IAuthenticatedTicket authenticatedTicket, IEnumerable<IQbResponse> responses)
{
return Task.FromResult<object>(null);
}
}
}
| 38.536082 | 145 | 0.616372 | [
"MIT"
] | dteske25/quickbooks-sync | src/WebConnector/Impl/GroupStepQueryResponseBase.cs | 3,740 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Vokabular.ProjectParsing.Model.Entities;
using Vokabular.ProjectParsing.Model.Parsers;
namespace Vokabular.ProjectImport.Managers
{
public class FilteringManager
{
private readonly ImportedProjectMetadataManager m_importedProjectMetadataManager;
private readonly ImportHistoryManager m_importHistoryManager;
public FilteringManager(ImportedProjectMetadataManager importedProjectMetadataManager, ImportHistoryManager importHistoryManager)
{
m_importedProjectMetadataManager = importedProjectMetadataManager;
m_importHistoryManager = importHistoryManager;
}
public ImportedRecord SetFilterData(ImportedRecord importedRecord, IDictionary<string, List<string>> filteringExpressions,
IProjectParser parser)
{
if (importedRecord.IsDeleted.HasValue && importedRecord.IsDeleted.Value)
{
importedRecord.IsSuitable = false;
return importedRecord;
}
var importedRecordDb = m_importedProjectMetadataManager.GetImportedProjectMetadataByExternalId(importedRecord.ExternalId);
importedRecord.IsNew = importedRecordDb?.Project == null;
if (importedRecord.IsNew)
{
foreach (var item in parser.GetPairKeyValueList(importedRecord))
{
filteringExpressions.TryGetValue(item.Key, out var filterExpressions);
if (filterExpressions == null)
{
continue;
}
if (filterExpressions.Select(Regex.Escape).Select(expr => expr.Replace("%", ".*"))
.Any(expr => Regex.IsMatch(item.Value, expr)))
{
importedRecord.IsSuitable = true;
return importedRecord;
}
}
importedRecord.IsSuitable = false;
}
else
{
var importHistory = m_importHistoryManager.GetLastImportHistoryForImportedProjectMetadata(importedRecordDb.Id);
if (!importedRecord.TimeStamp.HasValue
|| importHistory == null
|| importHistory.Date < importedRecord.TimeStamp.Value
|| !string.IsNullOrEmpty(importedRecord.FaultedMessage))
{
importedRecord.ProjectId = importedRecordDb.Project.Id;
importedRecord.ImportedProjectMetadataId = importedRecordDb.Id;
importedRecord.IsSuitable = true;
}
else
{
importedRecord.IsSuitable = false;
}
}
return importedRecord;
}
}
} | 39.567568 | 137 | 0.597336 | [
"BSD-3-Clause"
] | RIDICS/ITJakub | UJCSystem/Vokabular.ProjectImport/Managers/FilteringManager.cs | 2,930 | C# |
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using System;
namespace ScriptForge
{
[Serializable, InDevelopment]
public class ResourcesWidget : FolderFilterWidget
{
private const string RESOURCES_FOLDER_NAME = "/Resources";
private GUIContent m_HeaderLabel = new GUIContent("Included Resource Folders");
protected ReorderableList m_SerilaizedList;
public override GUIContent label
{
get
{
return ScriptForgeLabels.resourcesWidgetTitle; ;
}
}
public override string iconString
{
get
{
return FontAwesomeIcons.PUZZLE_PIECE;
}
}
/// <summary>
/// Gets the sorting order for this widget.
/// </summary>
public override int sortOrder
{
get
{
return LayoutSettings.RESOURCES_WIDGET_SORT_ORDER;
}
}
/// <summary>
/// The default name of this script
/// </summary>
protected override string defaultName
{
get
{
return "ResourcePaths";
}
}
/// <summary>
/// Invoked when we are drawing our header.
/// </summary>
private void OnDrawHeader(Rect rect)
{
GUI.Label(rect, m_HeaderLabel);
}
/// <summary>
/// Returns back our complete list of assets inside our selected folders.
/// </summary>
/// <returns></returns>
protected string[] GetResourceAssetGUIDs()
{
return AssetDatabase.FindAssets("", folders.ToArray());
}
/// <summary>
/// When a new folder is added this will be invoked. If it returns true it will
/// be added and if false it will not be added.
/// </summary>
/// <param name="assetPath">The asset path to the folder being added.</param>
protected override bool IsValidFolder(string assetPath)
{
// Make sure it's a resources path
int resourcesIndex = assetPath.LastIndexOf(RESOURCES_FOLDER_NAME + "/");
// Get our end index
// Check to see if the index is great then -1
if (resourcesIndex >= 0 || assetPath.EndsWith(RESOURCES_FOLDER_NAME))
{
if (!folders.Contains(assetPath))
{
return true;
}
}
else
{
EditorUtility.DisplayDialog("Invalid Resource Path", "The path '" + assetPath + "' does not contain a resources folder. Please try again", "Okay");
}
// It's not a valid folder
return false;
}
/// <summary>
/// Invoked when this widget should generate it's content.
/// </summary>
public override void OnGenerate(bool forced)
{
if (ShouldRegnerate() || forced)
{
// Invoke the base.
base.OnGenerate(forced);
// Build the template
ResourcesTemplate generator = new ResourcesTemplate();
// Populate it's session
CreateSession(generator);
// Write it to disk.
WriteToDisk(generator);
}
}
/// <summary>
/// Used to send our paths for our session.
/// </summary>
/// <param name="session"></param>
protected override void PopulateSession(IDictionary<string, object> session)
{
// Create our base session
base.PopulateSession(session);
List<string> result = new List<string>();
foreach (string guid in GetResourceAssetGUIDs())
{
// Convert to our asset path
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
// Add it
if (!result.Contains(assetPath))
{
result.Add(assetPath);
}
}
// Save our paths.
session["m_ResourcePaths"] = result.ToArray();
}
/// <summary>
/// Invoked when we are required to build a new hash code for our forge. All
/// unique content should be converted to string and appending to the builder.
/// </summary>
protected override void PopulateHashBuilder(System.Text.StringBuilder hashBuilder)
{
base.PopulateHashBuilder(hashBuilder);
// Add our layer names
foreach (var guid in GetResourceAssetGUIDs())
{
// Convert to our asset path
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
// Add the path
hashBuilder.Append(assetPath);
}
}
}
} | 30.748428 | 163 | 0.538965 | [
"MIT"
] | ByronMayne/ScriptForge | proj.unity/Assets/Script Forge/Editor/Widgets/ResourcesWidget.cs | 4,891 | 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("WindowsML_IoTButton")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WindowsML_IoTButton")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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 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")]
[assembly: ComVisible(false)] | 36.37931 | 84 | 0.745024 | [
"MIT"
] | pwcasdf/WindowsML_IoTButton | WindowsML_IoTButton/Properties/AssemblyInfo.cs | 1,058 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Security;
using System.Text;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Retrieves input from the host virtual console and writes it to the pipeline output.
/// </summary>
[Cmdlet(VerbsCommunications.Read, "Host", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113371")]
[OutputType(typeof(string), typeof(SecureString))]
public sealed class ReadHostCommand : PSCmdlet
{
/// <summary>
/// Constructs a new instance.
/// </summary>
public
ReadHostCommand()
{
// empty, provided per design guidelines.
}
#region Parameters
/// <summary>
/// The objects to display on the host before collecting input.
/// </summary>
[Parameter(Position = 0, ValueFromRemainingArguments = true)]
[AllowNull]
public
object
Prompt
{
get
{
return _prompt;
}
set
{
_prompt = value;
}
}
/// <summary>
/// Set to no echo the input as is is typed.
/// </summary>
[Parameter]
public
SwitchParameter
AsSecureString
{
get
{
return _safe;
}
set
{
_safe = value;
}
}
#endregion Parameters
#region Cmdlet Overrides
/// <summary>
/// Write the prompt, then collect a line of input from the host, then output it to the output stream.
/// </summary>
protected override void BeginProcessing()
{
PSHostUserInterface ui = Host.UI;
string promptString;
if (_prompt != null)
{
IEnumerator e = LanguagePrimitives.GetEnumerator(_prompt);
if (e != null)
{
StringBuilder sb = new StringBuilder();
while (e.MoveNext())
{
// The current object might itself be a collection, like a string array, as in read/console "foo","bar","baz"
// If it is, then the PSObject ToString() will take care of it. We could go on unwrapping collections
// forever, but it's a pretty common use case to see a varags confused with an array.
string element = (string)LanguagePrimitives.ConvertTo(e.Current, typeof(string), CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(element))
{
// Prepend a space if the stringbuilder isn't empty...
// We could consider using $OFS here but that's probably more
// effort than is really needed...
if (sb.Length > 0)
sb.Append(' ');
sb.Append(element);
}
}
promptString = sb.ToString();
}
else
{
promptString = (string)LanguagePrimitives.ConvertTo(_prompt, typeof(string), CultureInfo.InvariantCulture);
}
FieldDescription fd = new FieldDescription(promptString);
if (AsSecureString)
{
fd.SetParameterType(typeof(System.Security.SecureString));
}
else
{
fd.SetParameterType(typeof(string));
}
Collection<FieldDescription> fdc = new Collection<FieldDescription>();
fdc.Add(fd);
Dictionary<string, PSObject> result = Host.UI.Prompt(string.Empty, string.Empty, fdc);
// Result can be null depending on the host implementation. One typical
// example of a null return is for a canceled dialog.
if (result != null)
{
foreach (PSObject o in result.Values)
{
WriteObject(o);
}
}
}
else
{
object result;
if (AsSecureString)
{
result = Host.UI.ReadLineAsSecureString();
}
else
{
result = Host.UI.ReadLine();
}
WriteObject(result);
}
}
#endregion Cmdlet Overrides
private object _prompt = null;
private bool _safe = false;
}
}
| 30.664671 | 135 | 0.487795 | [
"MIT"
] | Aareon/PowerShellium | src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs | 5,121 | C# |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System.Globalization;
using Amplifier.Decompiler.Semantics;
using Amplifier.Decompiler.TypeSystem;
namespace Amplifier.Decompiler.CSharp.Resolver
{
/// <summary>
/// Represents the result of an access to a member of a dynamic object.
/// </summary>
public class DynamicMemberResolveResult : ResolveResult
{
/// <summary>
/// Target of the member access (a dynamic object).
/// </summary>
public readonly ResolveResult Target;
/// <summary>
/// Name of the accessed member.
/// </summary>
public readonly string Member;
public DynamicMemberResolveResult(ResolveResult target, string member) : base(SpecialType.Dynamic) {
this.Target = target;
this.Member = member;
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[Dynamic member '{0}']", Member);
}
public override IEnumerable<ResolveResult> GetChildResults() {
return new[] { Target };
}
}
}
| 37.857143 | 102 | 0.748113 | [
"MIT"
] | Keroosha/Amplifier.NET | src/Amplifier.Net/Decompiler/CSharp/Resolver/DynamicMemberResolveResult.cs | 2,122 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
EnemyManager enemyM;
// Use this for initialization
void Start ()
{
enemyM = GetComponent<EnemyManager> ();
enemyM.commenceAttack ();
}
// Update is called once per frame
void Update ()
{
enemyM.enemyUpdates ();
}
}
| 16.409091 | 42 | 0.711911 | [
"Unlicense"
] | apetersell/GPP_AndrewPetersell | TopDownShmooter/Assets/Scripts/GameManager.cs | 363 | C# |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using IkeMtz.NRSRx.Core.Web;
namespace NRSRx_WebApi_EF
{
public class VersionDefinitions : IApiVersionDefinitions
{
public const string v1_0 = "1.0";
[ExcludeFromCodeCoverage]
public IEnumerable<string> Versions => new[] { v1_0 };
}
}
| 21.866667 | 58 | 0.746951 | [
"MIT"
] | peyoquintero/NRSRx | templates/NRSRx_WebApi_EF/VersionDefinitions.cs | 328 | C# |
using System;
using System.Configuration;
using System.Security;
using Microsoft.Dynamics365.UIAutomation.Api.UCI;
using Microsoft.Dynamics365.UIAutomation.Browser;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Dynamics365.UIAutomation.Sample.UCI
{
[TestClass]
public class Lab_TestsClass {
readonly Uri _xrmUri = new Uri(ConfigurationManager.AppSettings["OnlineCrmUrl"]);
readonly SecureString _username = ConfigurationManager.AppSettings["OnlineUsername"]?.ToSecureString();
readonly SecureString _password = ConfigurationManager.AppSettings["OnlinePassword"]?.ToSecureString();
readonly SecureString _mfaSecretKey = ConfigurationManager.AppSettings["MfaSecretKey"]?.ToSecureString();
[TestCategory("Labs - TestsBase")]
[TestMethod]
public void NotUsing_TheBaseClass()
{
var options = TestSettings.Options;
options.PrivateMode = true;
options.UCIPerformanceMode = false; // <= you can also change other settings here, for this tests only
var client = new WebClient(options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecretKey); // <= You can use different credentials here, but ensure to convert this ToSecureString
xrmApp.Navigation.OpenApp(UCIAppName.Sales); // <= change this parameters to navigate to another app
xrmApp.Navigation.OpenSubArea("Sales", "Accounts"); // <= change this parameters to navigate to another area
Assert.IsNotNull("Replace this line with your test code");
} // Note: that here get the Browser closed, xrmApp get disposed
}
[TestCategory("Labs - TestsBase")]
[TestMethod, ExpectedException(typeof(Exception), AllowDerivedTypes = true)]
public void NotUsing_TheBaseClass_GoToCases_InCustomerServicesApp()
{
var options = TestSettings.Options;
options.PrivateMode = false; // <= this test is not in private mode, ignore config
var client = new WebClient(options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, "anton@contoso.com".ToSecureString(), "2xTanTan!".ToSecureString(), "WhereIsMySecretKey?".ToSecureString()); // <= this tests use other credentials, ignore config
xrmApp.Navigation.OpenApp(UCIAppName.CustomerService); // <= navigate to another app
xrmApp.Navigation.OpenSubArea("Service", "Cases"); // <= navigate to another area
Assert.IsNotNull("Replace this line with your test code");
}
}
}
} | 47.131148 | 213 | 0.649391 | [
"MIT"
] | operep/Easy-Repro-Example | Microsoft.Dynamics365.UIAutomation.Sample/UCI/Labs/TestsBase/1_Lab_TestsClass.cs | 2,877 | C# |
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Ryujinx.Common
{
public static class BinaryReaderExtensions
{
public unsafe static T ReadStruct<T>(this BinaryReader reader)
where T : struct
{
int size = Marshal.SizeOf<T>();
byte[] data = reader.ReadBytes(size);
fixed (byte* ptr = data)
{
return Marshal.PtrToStructure<T>((IntPtr)ptr);
}
}
public unsafe static void WriteStruct<T>(this BinaryWriter writer, T value)
where T : struct
{
long size = Marshal.SizeOf<T>();
byte[] data = new byte[size];
fixed (byte* ptr = data)
{
Marshal.StructureToPtr<T>(value, (IntPtr)ptr, false);
}
writer.Write(data);
}
}
}
| 23.526316 | 83 | 0.525727 | [
"Unlicense"
] | AlexLavoie42/Ryujinx | Ryujinx.Common/Extensions/BinaryReaderExtensions.cs | 896 | C# |
using Autobot.Data.Model;
using MediatR;
using System.Collections.Generic;
namespace Autobot.Queries.Query
{
public class GetUserListQuery : IRequest<List<UserDetails>>
{
public int PageNumber { get; set; }
public int PageSize { get; set; }
public string Filter { get; set; }
public string SortColumn { get; set; }
public string SortOrder { get; set; }
}
}
| 25.6875 | 63 | 0.649635 | [
"MIT"
] | JaspreetSinghChahal/dotnetcore-entityframework-webapi | Autobot.Queries/Query/GetUserListQuery.cs | 413 | C# |
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HedgeModManager
{
public static class RegistryConfig
{
private const string ConfigPath = @"SOFTWARE\HEDGEMM";
public static string LastGameDirectory;
public static string UILanguage;
static RegistryConfig()
{
Load();
}
public static void Save()
{
var key = Registry.CurrentUser.CreateSubKey(ConfigPath);
key.SetValue("LastGame", LastGameDirectory);
key.SetValue("UILanguage", UILanguage);
key.Close();
}
public static void Load()
{
var key = Registry.CurrentUser.CreateSubKey(ConfigPath);
LastGameDirectory = (string)key.GetValue("LastGame", string.Empty);
UILanguage = (string)key.GetValue("UILanguage", App.PCCulture);
}
}
}
| 25.947368 | 79 | 0.618661 | [
"MIT"
] | DavidPires/HedgeModManager | HedgeModManager/Config/RegistryConfig.cs | 988 | 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.Vpc.Model.V20160428;
namespace Aliyun.Acs.Vpc.Transform.V20160428
{
public class AddBandwidthPackageIpsResponseUnmarshaller
{
public static AddBandwidthPackageIpsResponse Unmarshall(UnmarshallerContext context)
{
AddBandwidthPackageIpsResponse addBandwidthPackageIpsResponse = new AddBandwidthPackageIpsResponse();
addBandwidthPackageIpsResponse.HttpResponse = context.HttpResponse;
addBandwidthPackageIpsResponse.RequestId = context.StringValue("AddBandwidthPackageIps.RequestId");
return addBandwidthPackageIpsResponse;
}
}
}
| 37.5 | 105 | 0.768667 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-vpc/Vpc/Transform/V20160428/AddBandwidthPackageIpsResponseUnmarshaller.cs | 1,500 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BizHawk.Client.EmuHawk
{
public partial class ExceptionBox : Form
{
public ExceptionBox(Exception ex)
{
InitializeComponent();
txtException.Text = ex.ToString();
timer1.Start();
}
public ExceptionBox(string str)
{
InitializeComponent();
txtException.Text = str;
timer1.Start();
}
private void btnCopy_Click(object sender, EventArgs e)
{
DoCopy();
}
void DoCopy()
{
string txt = txtException.Text;
Clipboard.SetText(txt);
try
{
if (Clipboard.GetText() == txt)
{
lblDone.Text = "Done!";
lblDone.ForeColor = SystemColors.ControlText;
return;
}
}
catch
{
}
lblDone.Text = "ERROR!";
lblDone.ForeColor = SystemColors.ControlText;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.C | Keys.Control))
{
DoCopy();
return true;
}
return false;
}
private void btnOK_Click(object sender, EventArgs e)
{
Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
int a = lblDone.ForeColor.A - 16;
if (a < 0) a = 0;
lblDone.ForeColor = Color.FromArgb(a, lblDone.ForeColor);
}
//http://stackoverflow.com/questions/2636065/alpha-in-forecolor
class MyLabel : Label
{
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rc = this.ClientRectangle;
StringFormat fmt = new StringFormat(StringFormat.GenericTypographic);
using (var br = new SolidBrush(this.ForeColor))
{
e.Graphics.DrawString(this.Text, this.Font, br, rc, fmt);
}
}
}
}
}
| 19.16129 | 73 | 0.663861 | [
"MIT"
] | CognitiaAI/StreetFighterRL | emulator/Bizhawk/BizHawk-master/BizHawk.Client.EmuHawk/CustomControls/ExceptionBox.cs | 1,784 | C# |
using System;
using BACnet.Types;
using BACnet.Types.Schemas;
namespace BACnet.Ashrae
{
public partial class ObjectPropertyReference
{
public ObjectId ObjectIdentifier { get; private set; }
public PropertyIdentifier PropertyIdentifier { get; private set; }
public Option<uint> PropertyArrayIndex { get; private set; }
public ObjectPropertyReference(ObjectId objectIdentifier, PropertyIdentifier propertyIdentifier, Option<uint> propertyArrayIndex)
{
this.ObjectIdentifier = objectIdentifier;
this.PropertyIdentifier = propertyIdentifier;
this.PropertyArrayIndex = propertyArrayIndex;
}
public static readonly ISchema Schema = new SequenceSchema(false,
new FieldSchema("ObjectIdentifier", 0, Value<ObjectId>.Schema),
new FieldSchema("PropertyIdentifier", 1, Value<PropertyIdentifier>.Schema),
new FieldSchema("PropertyArrayIndex", 2, Value<Option<uint>>.Schema));
public static ObjectPropertyReference Load(IValueStream stream)
{
stream.EnterSequence();
var objectIdentifier = Value<ObjectId>.Load(stream);
var propertyIdentifier = Value<PropertyIdentifier>.Load(stream);
var propertyArrayIndex = Value<Option<uint>>.Load(stream);
stream.LeaveSequence();
return new ObjectPropertyReference(objectIdentifier, propertyIdentifier, propertyArrayIndex);
}
public static void Save(IValueSink sink, ObjectPropertyReference value)
{
sink.EnterSequence();
Value<ObjectId>.Save(sink, value.ObjectIdentifier);
Value<PropertyIdentifier>.Save(sink, value.PropertyIdentifier);
Value<Option<uint>>.Save(sink, value.PropertyArrayIndex);
sink.LeaveSequence();
}
}
}
| 34.829787 | 131 | 0.775809 | [
"MIT"
] | LorenVS/bacstack | BACnet.Ashrae/Generated/ObjectPropertyReference.cs | 1,637 | C# |
namespace Owin.Scim.Tests.Integration.Users.Create
{
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Machine.Specifications;
using Model;
public class with_null_schema : using_a_scim_server
{
Establish context = () =>
{
UserDto = new UserWithSchema()
{
Schemas = null,
UserName = "Oops"
};
};
Because of = () =>
{
Response = Server
.HttpClient
.PostAsync("v2/users", new ScimObjectContent<UserWithSchema>(UserDto))
.Result;
StatusCode = Response.StatusCode;
Error = StatusCode != HttpStatusCode.BadRequest ? null : Response.Content
.ScimReadAsAsync<ScimError>()
.Result;
};
It should_return_bad_request = () => StatusCode.ShouldEqual(HttpStatusCode.BadRequest);
It should_return_invalid_value = () => Error.ScimType.ShouldEqual(ScimErrorType.InvalidValue);
It should_return_error_schema = () => Error.Schemas.ShouldContain(ScimConstants.Messages.Error);
protected static UserWithSchema UserDto;
protected static HttpResponseMessage Response;
protected static HttpStatusCode StatusCode;
protected static ScimError Error;
public class UserWithSchema
{
public string[] Schemas { get; set; }
public string UserName { get; set; }
}
}
} | 27.508772 | 104 | 0.591837 | [
"MIT"
] | Mysonemo/Owin.Scim | source/_tests/Owin.Scim.Tests/Integration/Users/Create/with_null_schema.cs | 1,568 | C# |
using Sabio.Data.Providers;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sabio.Data
{
public sealed class DataProvider
{
private DataProvider() { }
public static IDao Instance
{
get
{
return SqlDao.Instance;
}
}
}
}
| 17.04 | 39 | 0.598592 | [
"MIT"
] | angarola/CAshowroom | Sabio.Data/DataProvider.cs | 428 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NationalParkAPI.Models;
namespace NationalParkAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ParkAPIContext>(opt =>
opt.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerDocument();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseOpenApi();
app.UseSwaggerUi3();
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
| 31.827586 | 143 | 0.663055 | [
"MIT"
] | BrevinCronk98/National-Park-API | Startup.cs | 1,848 | C# |
namespace Enyim.Caching.Memcached.Results.StatusCodes
{
public enum StatusCodeEnums
{
Success = 0,
NotFound
}
}
#region [ License information ]
/* ************************************************************
*
* © 2010 Attila Kiskó (aka Enyim), © 2016 CNBlogs, © 2020 VIEApps.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.
*
* ************************************************************/
#endregion
| 34.896552 | 79 | 0.579051 | [
"Apache-2.0"
] | shortendarragh-mt/Enyim.Caching | Memcached/Results/StatusCodes/StatusCodeEnums.cs | 990 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using EntityModeler.EntityFrameworkCore;
namespace EntityModeler.Migrations
{
[DbContext(typeof(EntityModelerDbContext))]
[Migration("20170608053244_Upgraded_To_Abp_2_1_0")]
partial class Upgraded_To_Abp_2_1_0
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration");
b.Property<DateTime>("ExecutionTime");
b.Property<int?>("ImpersonatorTenantId");
b.Property<long?>("ImpersonatorUserId");
b.Property<string>("MethodName")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasMaxLength(1024);
b.Property<string>("ServiceName")
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<bool>("IsGranted");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<long?>("UserLinkId");
b.Property<string>("UserName");
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime");
b.Property<byte>("Result");
b.Property<string>("TenancyName")
.HasMaxLength(64);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("UserNameOrEmailAddress")
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long>("OrganizationUnitId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<bool>("IsAbandoned");
b.Property<string>("JobArgs")
.IsRequired()
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime");
b.Property<DateTime>("NextTryTime");
b.Property<byte>("Priority");
b.Property<short>("TryCount");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("Value")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<string>("Icon")
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<bool>("IsDisabled");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(10);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<string>("TenantIds")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasMaxLength(96);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<int>("State");
b.Property<int?>("TenantId");
b.Property<Guid>("TenantNotificationId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(95);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<long?>("ParentId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("EntityModeler.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDefault");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsStatic");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("EntityModeler.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("AuthenticationSource")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasMaxLength(328);
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsEmailConfirmed");
b.Property<bool>("IsLockoutEnabled");
b.Property<bool>("IsPhoneNumberConfirmed");
b.Property<bool>("IsTwoFactorEnabled");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<DateTime?>("LockoutEndDateUtc");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasMaxLength(328);
b.Property<string>("PhoneNumber");
b.Property<string>("SecurityStamp");
b.Property<string>("Surname")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("EntityModeler.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConnectionString")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<int?>("EditionId");
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("TenantId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("EntityModeler.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("EntityModeler.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("EntityModeler.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("EntityModeler.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("EntityModeler.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("EntityModeler.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("EntityModeler.Authorization.Roles.Role", b =>
{
b.HasOne("EntityModeler.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("EntityModeler.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("EntityModeler.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("EntityModeler.Authorization.Users.User", b =>
{
b.HasOne("EntityModeler.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("EntityModeler.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("EntityModeler.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("EntityModeler.MultiTenancy.Tenant", b =>
{
b.HasOne("EntityModeler.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("EntityModeler.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("EntityModeler.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("EntityModeler.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("EntityModeler.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 31.812897 | 117 | 0.441643 | [
"MIT"
] | Ppiwow/EntityModeler | aspnet-core/src/EntityModeler.EntityFrameworkCore/Migrations/20170608053244_Upgraded_To_Abp_2_1_0.Designer.cs | 35,028 | C# |
using Markdig;
using Markdig.SyntaxHighlighting;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace modify
{
public partial class modifyForm : Form
{
public modifyForm()
{
InitializeComponent();
}
private string resourcePath = "";
private Markdig.MarkdownPipeline pipeline;
private void modifyForm_Load(object sender, EventArgs e)
{
menuListBox.SelectedIndex = 0;
resourcePath = Directory.GetParent(Application.StartupPath).FullName + "\\res\\";
contentTabControl.SelectedIndex = 0;
pipeline = new MarkdownPipelineBuilder()
.UseAdvancedExtensions()
.UseSyntaxHighlighting()
.Build();
webBrowser1.Url = new Uri(string.Format("file:///{0}/../res/preview.html", Application.StartupPath));
// get .md file name
DirectoryInfo di = new DirectoryInfo(resourcePath);
foreach (var item in di.GetFiles("*.md"))
{
cboFile.Items.Add(Path.GetFileNameWithoutExtension(item.Name));
}
if (cboFile.Items.Count >= 2) cboFile.SelectedIndex = 1;
// location init
string filePath = resourcePath + "data.txt";
if (File.Exists(filePath))
{
StreamReader sr = new StreamReader(new FileStream(
filePath,
FileMode.Open
)
);
string[] spstr = sr.ReadLine().Split(' ');
sr.Close();
cboStopwatchLoc.SelectedIndex = int.Parse(spstr[0]);
cboPopupLoc.SelectedIndex = int.Parse(spstr[1]);
cboPopupTime.SelectedIndex = int.Parse(spstr[2])-1;
cboSource.SelectedIndex = int.Parse(spstr[3]);
cboTarget.SelectedIndex = int.Parse(spstr[4]);
}
}
private void minimizedBtn_Click(object sender, EventArgs e)
{
lblTitle.Focus();
this.WindowState = FormWindowState.Minimized;
}
private void closedBtn_Click(object sender, EventArgs e)
{
lblTitle.Focus();
Application.Exit();
}
private Point mousePoint;
private void lblTitle_MouseDown(object sender, MouseEventArgs e)
{
mousePoint = new Point(e.X, e.Y);
}
private void lblTitle_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
Location = new Point(this.Left - (mousePoint.X - e.X),
this.Top - (mousePoint.Y - e.Y));
}
}
private void menuListBox_SelectedIndexChanged(object sender, EventArgs e)
{
contentTabControl.SelectedIndex = menuListBox.SelectedIndex;
}
private void btnChoose_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = resourcePath;
ofd.Filter = "그림 파일 (*.jpg, *.jpeg, *.gif, *.png) | *.jpg; *.jpeg; *.gif; *.png";
ofd.ShowDialog();
string source = ofd.FileName;
string fileName = ofd.SafeFileName;
string target = resourcePath + fileName;
if (source == "") return;
if (source == target)
{
// file in a resource folder
// do nothing
}
else if (File.Exists(target))
{
// overwrite
if (MessageBox.Show("덮어쓰시겠습니까?", "경고", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
File.Delete(target);
File.Copy(source, target);
}
}
else
{
File.Copy(source, target);
}
// write an image reference in a markdown editor
richTextBox1.Text += String.Format("\n![][{0}]\n\n[{0}]: {1}\n"
, Path.GetFileNameWithoutExtension(ofd.FileName)
, fileName
);
}
private void chkPreview_CheckedChanged(object sender, EventArgs e)
{
if (chkPreview.Checked)
{
editTabControl.SelectedIndex = 1;
string result = Markdown.ToHtml(richTextBox1.Text, pipeline);
string htmlPath = resourcePath + "preview.html";
string cssLink = "<link rel= \"stylesheet\" href= \"style.css\">\n";
string incoding = "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>\n";
File.WriteAllText(htmlPath, string.Empty);
StreamWriter sw = new StreamWriter(new FileStream(
htmlPath,
FileMode.Open
)
);
sw.WriteLine(cssLink + incoding + result);
sw.Close();
webBrowser1.Refresh();
}
else
{
editTabControl.SelectedIndex = 0;
}
}
private void cboFile_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboFile.SelectedItem == null) return;
string fileName = cboFile.SelectedItem.ToString();
if (fileName == "[New File]")
{
int cnt = 0;
FileInfo fi;
do
{
cnt++;
fi = new FileInfo(resourcePath + "newFile" + cnt.ToString() + ".md");
} while (fi.Exists);
File.Create(fi.FullName).Close();
cboFile.Items.Add(Path.GetFileNameWithoutExtension(fi.Name));
cboFile.SelectedIndex = cboFile.Items.Count - 1;
txtName.Text = cboFile.SelectedItem.ToString();
}
else
{
txtName.Text = fileName;
string filePath = resourcePath + fileName + ".md";
if (!File.Exists(filePath))
{
cboFile.Items.RemoveAt(cboFile.SelectedIndex);
txtName.Text = "";
return;
}
StreamReader sr = new StreamReader(new FileStream(
filePath,
FileMode.Open
)
);
string fileContent = sr.ReadToEnd();
richTextBox1.Text = fileContent;
sr.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (cboFile.SelectedIndex == -1) return;
if (MessageBox.Show("삭제하시겠습니까?", "경고", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
File.Delete(resourcePath + cboFile.SelectedItem.ToString() + ".md");
cboFile.Items.RemoveAt(cboFile.SelectedIndex);
txtName.Text = "";
richTextBox1.Text = "";
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (cboFile.SelectedIndex == -1) return;
string fileName = cboFile.SelectedItem.ToString() + ".md";
string reName = txtName.Text + ".md";
// update file content
string filePath = resourcePath + fileName;
File.WriteAllText(filePath, string.Empty);
StreamWriter sw = new StreamWriter(new FileStream(
filePath,
FileMode.Open
)
);
sw.WriteLine(richTextBox1.Text);
sw.Close();
if (txtName.Text.IndexOf(" ") != -1)
{
MessageBox.Show("파일명에 공백을 포함할 수 없습니다.");
return;
}
if (txtName.Text == "exit" || txtName.Text == "all")
{
MessageBox.Show("사용할 수 없는 파일명입니다.");
return;
}
MessageBox.Show("저장되었습니다.");
// update file name
if (fileName != reName)
{
if (File.Exists(resourcePath + reName))
{
MessageBox.Show("이미 존재하는 파일명입니다.");
return;
}
File.Move(resourcePath + fileName, resourcePath + reName);
cboFile.Items.RemoveAt(cboFile.SelectedIndex);
cboFile.Items.Add(Path.GetFileNameWithoutExtension(reName));
cboFile.SelectedIndex = cboFile.Items.Count - 1;
}
}
private void btnPopupSave_Click(object sender, EventArgs e)
{
string filePath = resourcePath + "data.txt";
if (File.Exists(filePath))
{
StreamReader sr = new StreamReader(new FileStream(
filePath,
FileMode.Open
)
);
string[] spstr = sr.ReadLine().Split(' ');
sr.Close();
File.WriteAllText(filePath, string.Empty);
StreamWriter sw = new StreamWriter(new FileStream(
filePath,
FileMode.Open
)
);
sw.WriteLine(
spstr[0]
+ " "
+ cboPopupLoc.SelectedIndex.ToString()
+ " "
+ (cboPopupTime.SelectedIndex + 1).ToString()
+ " "
+ spstr[3]
+ " "
+ spstr[4]
);
sw.Close();
}
MessageBox.Show("저장되었습니다.");
}
private void btnStopwatchSave_Click(object sender, EventArgs e)
{
string filePath = resourcePath + "data.txt";
if (File.Exists(filePath))
{
StreamReader sr = new StreamReader(new FileStream(
filePath,
FileMode.Open
)
);
string[] spstr = sr.ReadLine().Split(' ');
sr.Close();
File.WriteAllText(filePath, string.Empty);
StreamWriter sw = new StreamWriter(new FileStream(
filePath,
FileMode.Open
)
);
sw.WriteLine(
cboStopwatchLoc.SelectedIndex.ToString()
+ " "
+ spstr[1]
+ " "
+ spstr[2]
+ " "
+ spstr[3]
+ " "
+ spstr[4]
);
sw.Close();
}
MessageBox.Show("저장되었습니다.");
}
private void btnTranslateSave_Click(object sender, EventArgs e)
{
string filePath = resourcePath + "data.txt";
if (File.Exists(filePath))
{
StreamReader sr = new StreamReader(new FileStream(
filePath,
FileMode.Open
)
);
string[] spstr = sr.ReadLine().Split(' ');
sr.Close();
File.WriteAllText(filePath, string.Empty);
StreamWriter sw = new StreamWriter(new FileStream(
filePath,
FileMode.Open
)
);
sw.WriteLine(
spstr[0]
+ " "
+ spstr[1]
+ " "
+ spstr[2]
+ " "
+ cboSource.SelectedIndex.ToString()
+ " "
+ cboTarget.SelectedIndex.ToString()
);
sw.Close();
}
MessageBox.Show("저장되었습니다.");
}
private void modifyForm_FormClosing(object sender, FormClosingEventArgs e)
{
string htmlPath = resourcePath + "preview.html";
File.WriteAllText(htmlPath, string.Empty);
}
}
}
| 35.377143 | 113 | 0.463011 | [
"MIT"
] | jeong57281/ps-helper | modify/modifyForm.cs | 12,566 | C# |
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_ANDROID
using System;
using System.Runtime.InteropServices;
namespace Cloo.Bindings
{
[System.Security.SuppressUnmanagedCodeSecurity]
public class CL11 : CL10, ICL11
{
#region External
[DllImport(libName, EntryPoint = "clCreateSubBuffer")]
extern static CLMemoryHandle CreateSubBuffer(
CLMemoryHandle buffer,
ComputeMemoryFlags flags,
ComputeBufferCreateType buffer_create_type,
ref SysIntX2 buffer_create_info,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clSetMemObjectDestructorCallback")]
extern static ComputeErrorCode SetMemObjectDestructorCallback(
CLMemoryHandle memobj,
ComputeMemoryDestructorNotifer pfn_notify,
IntPtr user_data);
[DllImport(libName, EntryPoint = "clCreateUserEvent")]
extern static CLEventHandle CreateUserEvent(
CLContextHandle context,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clSetUserEventStatus")]
extern static ComputeErrorCode SetUserEventStatus(
CLEventHandle @event,
Int32 execution_status);
[DllImport(libName, EntryPoint = "clSetEventCallback")]
extern static ComputeErrorCode SetEventCallback(
CLEventHandle @event,
Int32 command_exec_callback_type,
ComputeEventCallback pfn_notify,
IntPtr user_data);
[DllImport(libName, EntryPoint = "clEnqueueReadBufferRect")]
extern static ComputeErrorCode EnqueueReadBufferRect(
CLCommandQueueHandle command_queue,
CLMemoryHandle buffer,
[MarshalAs(UnmanagedType.Bool)] bool blocking_read,
ref SysIntX3 buffer_offset,
ref SysIntX3 host_offset,
ref SysIntX3 region,
IntPtr buffer_row_pitch,
IntPtr buffer_slice_pitch,
IntPtr host_row_pitch,
IntPtr host_slice_pitch,
IntPtr ptr,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueWriteBufferRect")]
extern static ComputeErrorCode EnqueueWriteBufferRect(
CLCommandQueueHandle command_queue,
CLMemoryHandle buffer,
[MarshalAs(UnmanagedType.Bool)] bool blocking_write,
ref SysIntX3 buffer_offset,
ref SysIntX3 host_offset,
ref SysIntX3 region,
IntPtr buffer_row_pitch,
IntPtr buffer_slice_pitch,
IntPtr host_row_pitch,
IntPtr host_slice_pitch,
IntPtr ptr,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueCopyBufferRect")]
extern static ComputeErrorCode EnqueueCopyBufferRect(
CLCommandQueueHandle command_queue,
CLMemoryHandle src_buffer,
CLMemoryHandle dst_buffer,
ref SysIntX3 src_origin,
ref SysIntX3 dst_origin,
ref SysIntX3 region,
IntPtr src_row_pitch,
IntPtr src_slice_pitch,
IntPtr dst_row_pitch,
IntPtr dst_slice_pitch,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
#endregion
#region ICL11 implementation
ComputeErrorCode ICL11.SetMemObjectDestructorCallback(CLMemoryHandle memobj, ComputeMemoryDestructorNotifer pfn_notify,
IntPtr user_data)
{
return SetMemObjectDestructorCallback(memobj, pfn_notify, user_data);
}
CLEventHandle ICL11.CreateUserEvent(CLContextHandle context, out ComputeErrorCode errcode_ret)
{
return CreateUserEvent(context, out errcode_ret);
}
ComputeErrorCode ICL11.SetUserEventStatus(CLEventHandle @event, int execution_status)
{
return SetUserEventStatus(@event, execution_status);
}
ComputeErrorCode ICL11.SetEventCallback(CLEventHandle @event, int command_exec_callback_type, ComputeEventCallback pfn_notify,
IntPtr user_data)
{
return SetEventCallback(@event, command_exec_callback_type, pfn_notify, user_data);
}
ComputeErrorCode ICL11.EnqueueReadBufferRect(CLCommandQueueHandle command_queue, CLMemoryHandle buffer, bool blocking_read,
ref SysIntX3 buffer_offset, ref SysIntX3 host_offset, ref SysIntX3 region,
IntPtr buffer_row_pitch, IntPtr buffer_slice_pitch, IntPtr host_row_pitch,
IntPtr host_slice_pitch, IntPtr ptr, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueReadBufferRect(command_queue, buffer, blocking_read, ref buffer_offset, ref host_offset, ref region, buffer_row_pitch, buffer_slice_pitch, host_row_pitch, host_slice_pitch, ptr, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL11.EnqueueWriteBufferRect(CLCommandQueueHandle command_queue, CLMemoryHandle buffer, bool blocking_write,
ref SysIntX3 buffer_offset, ref SysIntX3 host_offset, ref SysIntX3 region,
IntPtr buffer_row_pitch, IntPtr buffer_slice_pitch, IntPtr host_row_pitch,
IntPtr host_slice_pitch, IntPtr ptr, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueWriteBufferRect(command_queue, buffer, blocking_write, ref buffer_offset, ref host_offset, ref region, buffer_row_pitch, buffer_slice_pitch, host_row_pitch, host_slice_pitch, ptr, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL11.EnqueueCopyBufferRect(CLCommandQueueHandle command_queue, CLMemoryHandle src_buffer,
CLMemoryHandle dst_buffer, ref SysIntX3 src_origin, ref SysIntX3 dst_origin,
ref SysIntX3 region, IntPtr src_row_pitch, IntPtr src_slice_pitch,
IntPtr dst_row_pitch, IntPtr dst_slice_pitch, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueCopyBufferRect(command_queue, src_buffer, dst_buffer, ref src_origin, ref dst_origin, ref region, src_row_pitch, src_slice_pitch, dst_row_pitch, dst_slice_pitch, num_events_in_wait_list, event_wait_list, new_event);
}
[Obsolete("Deprecated in OpenCL 1.1.")]
ComputeErrorCode ICL11.SetCommandQueueProperty(CLCommandQueueHandle command_queue, ComputeCommandQueueFlags properties,
bool enable, out ComputeCommandQueueFlags old_properties)
{
return ((ICL10)this).SetCommandQueueProperty(command_queue, properties, enable, out old_properties);
}
CLMemoryHandle ICL11.CreateSubBuffer(CLMemoryHandle buffer, ComputeMemoryFlags flags,
ComputeBufferCreateType buffer_create_type, ref SysIntX2 buffer_create_info,
out ComputeErrorCode errcode_ret)
{
return CreateSubBuffer(buffer, flags, buffer_create_type, ref buffer_create_info, out errcode_ret);
}
#endregion
}
}
#endif
| 59.117241 | 260 | 0.631241 | [
"Unlicense"
] | longleggedone/Studio2PhysicalShadow | StudioPrototype/Assets/Fluvio/_Main/PlatformSource/Cloo/Bindings/CL11.cs | 8,572 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DatingSimCharacterPortrait : MonoBehaviour {
SpriteRenderer sr;
void Start ()
{
sr = GetComponent<SpriteRenderer>();
sr.sprite = DatingSimHelper.getSelectedCharacter().defaultPortait;
}
void onResult(bool victory)
{
var character = DatingSimHelper.getSelectedCharacter();
sr.sprite = victory ? character.winPortrait : character.lossPortrait;
}
//[System.Serializable]
//public class ListWrapper {
// public List<Sprite> list;
//}
}
| 23.461538 | 77 | 0.677049 | [
"MIT"
] | Trif4/NitoriWare | Assets/Microgames/DatingSim/Scripts/DatingSimCharacterPortrait.cs | 612 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.AzureStack.Commands
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.AzureStack.Commands.Common;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
/// <summary>
/// Add Resource Provider Manifest Cmdlet
/// </summary>
[Cmdlet(VerbsCommon.Add, Nouns.ResourceProviderManifest, DefaultParameterSetName = "MultipleExtensions", SupportsShouldProcess = true)]
[OutputType(typeof(ProviderRegistrationModel))]
[Alias("Add-AzureRmResourceProviderRegistration")]
public class AddResourceProviderManifest : AdminApiCmdlet
{
/// <summary>
/// Gets or sets the namespace of the resource provider.
/// </summary>
[Parameter(Mandatory = true)]
[ValidateLength(1, 128)]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// Gets or sets the namespace of the resource provider.
/// </summary>
[Parameter(Mandatory = true)]
[ValidateLength(1, 128)]
[ValidateNotNullOrEmpty]
public string Namespace { get; set; }
/// <summary>
/// Gets or sets the resource group.
/// </summary>
[Parameter(Mandatory = true)]
[ValidateLength(1, 90)]
[ValidateNotNullOrEmpty]
[Alias("ResourceGroup")]
public string ResourceGroupName { get; set; }
// TODO - use API to get ARM location. BUG 8349643
/// <summary>
/// Gets or sets the resource manager location.
/// </summary>
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public string ArmLocation { get; set; }
/// <summary>
/// Gets or sets the routing resource manager type.
/// </summary>
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public ResourceManagerType ResourceManagerType { get; set; }
/// <summary>
/// Gets or sets the resource provider registration display name.
/// </summary>
[Parameter(Mandatory = true)]
[ValidateLength(1, 128)]
[ValidateNotNullOrEmpty]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the resource provider registration location (region).
/// </summary>
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public string ProviderLocation { get; set; }
/// <summary>
/// Optional. Gets or sets the name of the extension.
/// </summary>
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ParameterSetName = "SingleExtension")]
public string ExtensionName { get; set; }
/// <summary>
/// Gets or sets the extension endpoint.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "SingleExtension")]
[ValidateAbsoluteUri]
[ValidateNotNullOrEmpty]
public Uri ExtensionUri { get; set; }
/// <summary>
/// Gets or sets the extensions json string.
/// </summary>
[Parameter(Mandatory = false, ParameterSetName = "MultipleExtensions")]
[ValidateNotNullOrEmpty]
public string Extensions { get; set; }
/// <summary>
/// Gets or sets the resource type json string.
/// </summary>
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true)]
public string ResourceTypes { get; set; }
/// <summary>
/// Gets or sets the resource provider registration display name.
/// </summary>
[ValidateNotNullOrEmpty]
[Parameter]
public string Signature { get; set; }
/// <summary>
/// Executes the API call(s) against Azure Resource Management API(s).
/// </summary>
protected override void ExecuteCore()
{
if (ShouldProcess(this.Name, VerbsCommon.Add))
{
using (var client = this.GetAzureStackClient())
{
if (this.MyInvocation.InvocationName.Equals("Add-AzureRmResourceProviderRegistration",
StringComparison.OrdinalIgnoreCase))
{
this.WriteWarning(
"Alias Add-AzureRmResourceProviderRegistration will be deprecated in a future release. Please use the cmdlet Add-AzsResourceProviderManifest instead");
}
ProviderRegistrationCreateOrUpdateParameters registrationParams = null;
// Todo: Remove the parameter sets in the next major release
if (this.ParameterSetName.Equals("SingleExtension", StringComparison.OrdinalIgnoreCase))
{
WriteWarning(
"ExtensionName and ExtensionUri parameters will be deprecated in a future release, Use the Extensions parameter to specify the extesnions registration as a json string");
registrationParams = new ProviderRegistrationCreateOrUpdateParameters()
{
ProviderRegistration = new ProviderRegistrationModel()
{
Name = this.Name,
Location = this.ArmLocation,
Properties = new ManifestPropertiesDefinition()
{
DisplayName = this.DisplayName,
Namespace = this.Namespace,
RoutingResourceManagerType = this.ResourceManagerType,
Enabled = true,
ProviderLocation = this.ProviderLocation,
// Todo: Remove this HACK, hardcoded versions to have backward compatibility
ExtensionCollection = new ExtensionCollectionDefinition()
{
Version = "0.1.0.0",
Extensions = new ExtensionDefinition[]
{
new ExtensionDefinition()
{
Name = this.ExtensionName,
Uri = (this.ExtensionUri == null) ? null : this.ExtensionUri.AbsoluteUri
}
}
},
ResourceTypes = this.ResourceTypes.FromJson<List<ResourceType>>(),
Signature = this.Signature
}
}
};
}
else
{
registrationParams = new ProviderRegistrationCreateOrUpdateParameters()
{
ProviderRegistration = new ProviderRegistrationModel()
{
Name = this.Name,
Location = this.ArmLocation,
Properties = new ManifestPropertiesDefinition()
{
DisplayName = this.DisplayName,
Namespace = this.Namespace,
// Note: The default value is set to Admin ARM to have backward compatibility with existing deployment scripts
// The default value will get changed to User ARM in future.
RoutingResourceManagerType = this.ResourceManagerType,
Enabled = true,
ProviderLocation = this.ProviderLocation,
ExtensionCollection =
(this.Extensions == null)
? null
: this.Extensions.FromJson<ExtensionCollectionDefinition>(),
ResourceTypes = this.ResourceTypes.FromJson<List<ResourceType>>(),
Signature = this.Signature
}
}
};
}
this.WriteVerbose(
Resources.AddingResourceProviderManifest.FormatArgs(
registrationParams.ProviderRegistration.Properties.DisplayName));
this.ValidatePrerequisites(client, registrationParams);
var result = client.ProviderRegistrations
.CreateOrUpdate(this.ResourceGroupName, registrationParams)
.ProviderRegistration;
WriteObject(result);
}
}
}
/// <summary>
/// Validates the prerequisites.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="parameters">The parameters.</param>
protected virtual void ValidatePrerequisites(AzureStackClient client, ProviderRegistrationCreateOrUpdateParameters parameters)
{
ArgumentValidator.ValidateNotNull("client", client);
ArgumentValidator.ValidateNotNull("parameters", parameters);
if (!client.ResourceGroups.List().ResourceGroups.Any(r => string.Equals(r.Name, this.ResourceGroupName, StringComparison.OrdinalIgnoreCase)))
{
throw new PSInvalidOperationException(Resources.ResourceGroupDoesNotExist.FormatArgs(this.ResourceGroupName));
}
}
}
}
| 46.827004 | 199 | 0.510002 | [
"MIT"
] | AzureDataBox/azure-powershell | src/StackAdmin/AzureStackAdmin/Commands.AzureStackAdmin/Microsoft.Subscriptions/ProviderRegistrations/AddResourceProviderRegistration.cs | 10,864 | C# |
#region License
/*
MIT License
Copyright © 2006 The Mono.Xna Team
All rights reserved.
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 License
using System;
namespace MonoGameUtility {
public struct Rectangle : IEquatable<Rectangle> {
#region Private Fields
private static Rectangle emptyRectangle = new Rectangle();
#endregion Private Fields
#region Public Fields
public int X;
public int Y;
public int Width;
public int Height;
#endregion Public Fields
#region Public Properties
public static Rectangle Empty {
get { return emptyRectangle; }
}
public int Left {
get { return this.X; }
}
public int Right {
get { return (this.X + this.Width); }
}
public int Top {
get { return this.Y; }
}
public int Bottom {
get { return (this.Y + this.Height); }
}
#endregion Public Properties
#region Constructors
public Rectangle(int x, int y, int width, int height) {
this.X = x;
this.Y = y;
this.Width = width;
this.Height = height;
}
#endregion Constructors
#region Public Methods
public static bool operator ==(Rectangle a, Rectangle b) {
return ((a.X == b.X) && (a.Y == b.Y) && (a.Width == b.Width) && (a.Height == b.Height));
}
public bool Contains(int x, int y) {
return ((((this.X <= x) && (x < (this.X + this.Width))) && (this.Y <= y)) && (y < (this.Y + this.Height)));
}
public bool Contains(Point value) {
return ((((this.X <= value.X) && (value.X < (this.X + this.Width))) && (this.Y <= value.Y)) && (value.Y < (this.Y + this.Height)));
}
public bool Contains(Rectangle value) {
return ((((this.X <= value.X) && ((value.X + value.Width) <= (this.X + this.Width))) && (this.Y <= value.Y)) && ((value.Y + value.Height) <= (this.Y + this.Height)));
}
public static bool operator !=(Rectangle a, Rectangle b) {
return !(a == b);
}
public void Offset(Point offset) {
X += offset.X;
Y += offset.Y;
}
public void Offset(int offsetX, int offsetY) {
X += offsetX;
Y += offsetY;
}
public Point Location {
get {
return new Point(this.X, this.Y);
}
set {
X = value.X;
Y = value.Y;
}
}
public Point Center {
get {
// This is incorrect
//return new Point( (this.X + this.Width) / 2,(this.Y + this.Height) / 2 );
// What we want is the Center of the rectangle from the X and Y Origins
return new Point(this.X + (this.Width / 2), this.Y + (this.Height / 2));
}
}
public void Inflate(int horizontalValue, int verticalValue) {
X -= horizontalValue;
Y -= verticalValue;
Width += horizontalValue * 2;
Height += verticalValue * 2;
}
public bool IsEmpty {
get {
return ((((this.Width == 0) && (this.Height == 0)) && (this.X == 0)) && (this.Y == 0));
}
}
public bool Equals(Rectangle other) {
return this == other;
}
public override bool Equals(object obj) {
return (obj is Rectangle) ? this == ((Rectangle)obj) : false;
}
public override string ToString() {
return string.Format("{{X:{0} Y:{1} Width:{2} Height:{3}}}", X, Y, Width, Height);
}
public override int GetHashCode() {
return (this.X ^ this.Y ^ this.Width ^ this.Height);
}
public bool Intersects(Rectangle value) {
return value.Left < Right &&
Left < value.Right &&
value.Top < Bottom &&
Top < value.Bottom;
}
public void Intersects(ref Rectangle value, out bool result) {
result = value.Left < Right &&
Left < value.Right &&
value.Top < Bottom &&
Top < value.Bottom;
}
public static Rectangle Intersect(Rectangle value1, Rectangle value2) {
Rectangle rectangle;
Intersect(ref value1, ref value2, out rectangle);
return rectangle;
}
public static void Intersect(ref Rectangle value1, ref Rectangle value2, out Rectangle result) {
if (value1.Intersects(value2)) {
int right_side = Math.Min(value1.X + value1.Width, value2.X + value2.Width);
int left_side = Math.Max(value1.X, value2.X);
int top_side = Math.Max(value1.Y, value2.Y);
int bottom_side = Math.Min(value1.Y + value1.Height, value2.Y + value2.Height);
result = new Rectangle(left_side, top_side, right_side - left_side, bottom_side - top_side);
}
else {
result = new Rectangle(0, 0, 0, 0);
}
}
public static Rectangle Union(Rectangle value1, Rectangle value2) {
int x = Math.Min(value1.X, value2.X);
int y = Math.Min(value1.Y, value2.Y);
return new Rectangle(x, y,
Math.Max(value1.Right, value2.Right) - x,
Math.Max(value1.Bottom, value2.Bottom) - y);
}
public static void Union(ref Rectangle value1, ref Rectangle value2, out Rectangle result) {
result.X = Math.Min(value1.X, value2.X);
result.Y = Math.Min(value1.Y, value2.Y);
result.Width = Math.Max(value1.Right, value2.Right) - result.X;
result.Height = Math.Max(value1.Bottom, value2.Bottom) - result.Y;
}
public static implicit operator Microsoft.Xna.Framework.Rectangle(Rectangle obj) {
return new Microsoft.Xna.Framework.Rectangle(obj.X, obj.Y, obj.Width, obj.Height);
}
#endregion Public Methods
}
} | 32.035088 | 178 | 0.551205 | [
"MPL-2.0"
] | bsamuels453/With-Fire-and-Iron | MonoGameUtility/Rectangle.cs | 7,307 | C# |
/*
Copyright (C) 2008 Toyin Akin (toyin_akin@hotmail.com)
This file is part of QLNet Project https://github.com/amaggiulli/qlnet
QLNet is free software: you can redistribute it and/or modify it
under the terms of the QLNet license. You should have received a
copy of the license along with this program; if not, license is
available at <https://github.com/amaggiulli/QLNet/blob/develop/LICENSE>.
QLNet is a based on QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
The QuantLib license is available online at http://quantlib.org/license.shtml.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
namespace QLNet
{
//! %DKK %LIBOR rate
/*! Danish Krona LIBOR discontinued as of 2013.
*/
public class DKKLibor : Libor
{
public DKKLibor(Period tenor)
: base("DKKLibor", tenor, 2, new DKKCurrency(), new Denmark(), new Actual360(), new Handle<YieldTermStructure>())
{}
public DKKLibor(Period tenor, Handle<YieldTermStructure> h)
: base("DKKLibor", tenor, 2, new DKKCurrency(), new Denmark(), new Actual360(), h)
{}
}
}
| 35.078947 | 122 | 0.72093 | [
"BSD-3-Clause"
] | SalmonTie/QLNet | src/QLNet/Indexes/Ibor/Dkklibor.cs | 1,333 | C# |
using Sandbox;
using System.Collections.Generic;
namespace Frostrial
{
[GameResource( "Music", "music", "Frostrial Music", Icon = "approval" )]
public partial class Music : GameResource
{
public static IReadOnlyDictionary<string, Music> All => _all;
internal static Dictionary<string, Music> _all = new();
public string Artist { get; set; }
public string Album { get; set; }
public string Song { get; set; }
public float Length { get; set; }
public string URL { get; set; }
public string AlbumCover { get; set; }
protected override void PostLoad()
{
base.PostLoad();
if ( !_all.ContainsKey( Name ) )
_all.Add( Name, this );
}
public Sound Play(float volume = 1)
{
var s = Sound.FromScreen( Name );
s.SetVolume( volume );
return s;
}
}
}
| 21.513514 | 73 | 0.658291 | [
"MIT"
] | yuberee/Frostrial | code/assets/Music.cs | 798 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using NuGet.Client.VisualStudio.Models;
using NuGet.VisualStudio;
namespace NuGet.Client.VisualStudio
{
/// <summary>
/// Manages active source repositories using the NuGet Visual Studio settings interfaces
/// </summary>
[Export(typeof(SourceRepositoryManager))]
public class VsSourceRepositoryManager : SourceRepositoryManager
{
private static readonly PackageSource NuGetV3PreviewSource = CreateV3PreviewSource();
private readonly IVsPackageSourceProvider _sourceProvider;
private readonly IPackageRepositoryFactory _repoFactory;
private readonly ConcurrentDictionary<string, SourceRepository> _repos = new ConcurrentDictionary<string, SourceRepository>();
private static PackageSource CreateV3PreviewSource()
{
var source = new PackageSource(
Strings.VsSourceRepositoryManager_V3SourceName,
NuGetConstants.V3FeedUrl);
return source;
}
public override SourceRepository ActiveRepository
{
get
{
Debug.Assert(!_sourceProvider.ActivePackageSource.IsAggregate(), "Active source is the aggregate source! This shouldn't happen!");
if (_sourceProvider.ActivePackageSource == null)
{
return null;
}
return GetRepo(new PackageSource(
_sourceProvider.ActivePackageSource.Name,
_sourceProvider.ActivePackageSource.Source));
}
}
public override SourceRepository CreateSourceRepository(PackageSource packageSource)
{
return GetRepo(packageSource);
}
public override IEnumerable<PackageSource> AvailableSources
{
get
{
var coreSources = _sourceProvider
.GetEnabledPackageSources()
.Select(s => new PackageSource(s.Name, s.Source));
foreach (var source in coreSources)
{
yield return source;
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[ImportMany(typeof(ResourceProvider))]
public IEnumerable<Lazy<ResourceProvider, IResourceProviderMetadata>> Providers { get; set; }
[ImportingConstructor]
public VsSourceRepositoryManager(IVsPackageSourceProvider sourceProvider, IPackageRepositoryFactory repoFactory)
{
_sourceProvider = sourceProvider;
_sourceProvider.PackageSourcesSaved += (sender, e) =>
{
if (PackageSourcesChanged != null)
{
PackageSourcesChanged(this, EventArgs.Empty);
}
};
_repoFactory = repoFactory;
}
public override void ChangeActiveSource(PackageSource newSource)
{
if (newSource.Equals(NuGetV3PreviewSource))
{
return; // Can't set it as default
}
var source = _sourceProvider.GetEnabledPackageSources()
.FirstOrDefault(s => String.Equals(s.Name, newSource.Name, StringComparison.OrdinalIgnoreCase));
if (source == null)
{
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
Strings.VsPackageManagerSession_UnknownSource,
newSource.Name),
"newSource");
}
// The Urls should be equal but if they aren't, there's nothing the user can do about it :(
Debug.Assert(String.Equals(source.Source, newSource.Url, StringComparison.Ordinal));
// Update the active package source
_sourceProvider.ActivePackageSource = source;
}
public override event EventHandler PackageSourcesChanged;
private SourceRepository GetRepo(PackageSource p)
{
return _repos.GetOrAdd(p.Url, _ => CreateRepo(p));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "These objects live until end of process, at which point they will be disposed automatically")]
private SourceRepository CreateRepo(PackageSource source)
{
return new AutoDetectSourceRepository(source, VsVersionHelper.FullVsEdition, _repoFactory);
}
// TODO: A hack to get SourceRepository2. The right way is to replace SourceRepository with
// SourceRepository2
public SourceRepository2 CreateRepo2(PackageSource source)
{
var repo = new SourceRepository2(source, Providers);
return repo;
}
}
} | 38.235294 | 239 | 0.628077 | [
"ECL-2.0",
"Apache-2.0"
] | Squirrel/NuGet | src/NuGet.Client.V2.VisualStudio/VsSourceRepositoryManager.cs | 5,202 | C# |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.IO;
using System.Linq;
namespace Semmle.Extraction.CSharp.Entities
{
internal class UserOperator : Method
{
protected UserOperator(Context cx, IMethodSymbol init)
: base(cx, init) { }
public override void Populate(TextWriter trapFile)
{
PopulateMethod(trapFile);
PopulateModifiers(trapFile);
var returnType = Type.Create(Context, Symbol.ReturnType);
trapFile.operators(this,
Symbol.Name,
OperatorSymbol(Context, Symbol),
ContainingType,
returnType.TypeRef,
(UserOperator)OriginalDefinition);
foreach (var l in Locations)
trapFile.operator_location(this, l);
if (IsSourceDeclaration)
{
var declSyntaxReferences = Symbol.DeclaringSyntaxReferences.Select(s => s.GetSyntax()).ToArray();
foreach (var declaration in declSyntaxReferences.OfType<OperatorDeclarationSyntax>())
TypeMention.Create(Context, declaration.ReturnType, this, returnType);
foreach (var declaration in declSyntaxReferences.OfType<ConversionOperatorDeclarationSyntax>())
TypeMention.Create(Context, declaration.Type, this, returnType);
}
ContainingType.PopulateGenerics();
}
public override bool NeedsPopulation => Context.Defines(Symbol) || IsImplicitOperator(out _);
public override Type ContainingType
{
get
{
IsImplicitOperator(out var containingType);
return Type.Create(Context, containingType);
}
}
/// <summary>
/// For some reason, some operators are missing from the Roslyn database of mscorlib.
/// This method returns <code>true</code> for such operators.
/// </summary>
/// <param name="containingType">The type containing this operator.</param>
/// <returns></returns>
private bool IsImplicitOperator(out ITypeSymbol containingType)
{
containingType = Symbol.ContainingType;
if (containingType is not null)
{
var containingNamedType = containingType as INamedTypeSymbol;
return containingNamedType is null ||
!containingNamedType.GetMembers(Symbol.Name).Contains(Symbol);
}
var pointerType = Symbol.Parameters.Select(p => p.Type).OfType<IPointerTypeSymbol>().FirstOrDefault();
if (pointerType is not null)
{
containingType = pointerType;
return true;
}
Context.ModelError(Symbol, "Unexpected implicit operator");
return true;
}
/// <summary>
/// Convert an operator method name in to a symbolic name.
/// A return value indicates whether the conversion succeeded.
/// </summary>
/// <param name="methodName">The method name.</param>
/// <param name="operatorName">The converted operator name.</param>
public static bool OperatorSymbol(string methodName, out string operatorName)
{
var success = true;
switch (methodName)
{
case "op_LogicalNot":
operatorName = "!";
break;
case "op_BitwiseAnd":
operatorName = "&";
break;
case "op_Equality":
operatorName = "==";
break;
case "op_Inequality":
operatorName = "!=";
break;
case "op_UnaryPlus":
case "op_Addition":
operatorName = "+";
break;
case "op_UnaryNegation":
case "op_Subtraction":
operatorName = "-";
break;
case "op_Multiply":
operatorName = "*";
break;
case "op_Division":
operatorName = "/";
break;
case "op_Modulus":
operatorName = "%";
break;
case "op_GreaterThan":
operatorName = ">";
break;
case "op_GreaterThanOrEqual":
operatorName = ">=";
break;
case "op_LessThan":
operatorName = "<";
break;
case "op_LessThanOrEqual":
operatorName = "<=";
break;
case "op_Decrement":
operatorName = "--";
break;
case "op_Increment":
operatorName = "++";
break;
case "op_Implicit":
operatorName = "implicit conversion";
break;
case "op_Explicit":
operatorName = "explicit conversion";
break;
case "op_OnesComplement":
operatorName = "~";
break;
case "op_RightShift":
operatorName = ">>";
break;
case "op_LeftShift":
operatorName = "<<";
break;
case "op_BitwiseOr":
operatorName = "|";
break;
case "op_ExclusiveOr":
operatorName = "^";
break;
case "op_True":
operatorName = "true";
break;
case "op_False":
operatorName = "false";
break;
default:
operatorName = methodName;
success = false;
break;
}
return success;
}
/// <summary>
/// Converts a method name into a symbolic name.
/// Logs an error if the name is not found.
/// </summary>
/// <param name="cx">Extractor context.</param>
/// <param name="methodName">The method name.</param>
/// <returns>The converted name.</returns>
private static string OperatorSymbol(Context cx, IMethodSymbol method)
{
var methodName = method.Name;
if (!OperatorSymbol(methodName, out var result))
cx.ModelError(method, $"Unhandled operator name in OperatorSymbol(): '{methodName}'");
return result;
}
public static new UserOperator Create(Context cx, IMethodSymbol symbol) => UserOperatorFactory.Instance.CreateEntityFromSymbol(cx, symbol);
private class UserOperatorFactory : CachedEntityFactory<IMethodSymbol, UserOperator>
{
public static UserOperatorFactory Instance { get; } = new UserOperatorFactory();
public override UserOperator Create(Context cx, IMethodSymbol init) => new UserOperator(cx, init);
}
}
}
| 37.451777 | 147 | 0.502575 | [
"MIT"
] | 00mjk/codeql | csharp/extractor/Semmle.Extraction.CSharp/Entities/UserOperator.cs | 7,378 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataAccessLayer.Models
{
public class User
{
public User()
{
CreatedAt = DateTime.UtcNow;
Id = Guid.NewGuid();
Disabled = false;
}
[Key]
public Guid Id { get; set; }
[Required]
public string Email { get; set; }
[Required, DataType(DataType.Date)]
public DateTime? DateOfBirth { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
[Required]
public string PasswordHash { get; set; }
[Required]
public byte[] PasswordSalt { get; set; }
public string SecurityQ1 { get; set; }
public string SecurityQ1Answer { get; set; }
public string SecurityQ2 { get; set; }
public string SecurityQ2Answer { get; set; }
public string SecurityQ3 { get; set; }
public string SecurityQ3Answer { get; set; }
[Required]
public int IncorrectPasswordCount { get; set; } = 0;
[Required]
public bool Disabled { get; set; }
[Required, Column(TypeName = "datetime2"), DataType(DataType.DateTime)]
public DateTime UpdatedAt { get; set; }
[Column(TypeName = "datetime2"), DataType(DataType.DateTime)]
public DateTime CreatedAt { get; set; }
}
}
| 27.375 | 79 | 0.592955 | [
"MIT"
] | CECS-491A/SSO | Backend/DataAccessLayer/Models/User.cs | 1,535 | C# |
using System;
using System.Threading.Tasks;
using Rg.Plugins.Popup.Animations;
using Rg.Plugins.Popup.Enums;
using Rg.Plugins.Popup.Interfaces.Animations;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace Rg.Plugins.Popup.Pages
{
public class PopupPage : ContentPage
{
#region Private
private const string IsAnimatingObsoleteText =
nameof(IsAnimating) +
" is obsolute as of v1.1.5. Please use "
+ nameof(IsAnimationEnabled) +
" instead. See more info: "
+ Config.MigrationV1_0_xToV1_1_xUrl;
#endregion
#region Internal Properties
internal Task? AppearingTransactionTask { get; set; }
internal Task? DisappearingTransactionTask { get; set; }
#endregion
#region Events
public event EventHandler? BackgroundClicked;
#endregion
#region Bindable Properties
[Obsolete(IsAnimatingObsoleteText)]
public static readonly BindableProperty IsAnimatingProperty = BindableProperty.Create(nameof(IsAnimating), typeof(bool), typeof(PopupPage), true);
[Obsolete(IsAnimatingObsoleteText)]
public bool IsAnimating
{
get { return (bool)GetValue(IsAnimatingProperty); }
set { SetValue(IsAnimatingProperty, value); }
}
public static readonly BindableProperty IsAnimationEnabledProperty = BindableProperty.Create(nameof(IsAnimationEnabled), typeof(bool), typeof(PopupPage), true);
public bool IsAnimationEnabled
{
get { return (bool)GetValue(IsAnimationEnabledProperty); }
set { SetValue(IsAnimationEnabledProperty, value); }
}
public static readonly BindableProperty HasSystemPaddingProperty = BindableProperty.Create(nameof(HasSystemPadding), typeof(bool), typeof(PopupPage), true);
public bool HasSystemPadding
{
get { return (bool)GetValue(HasSystemPaddingProperty); }
set { SetValue(HasSystemPaddingProperty, value); }
}
public static readonly BindableProperty AnimationProperty = BindableProperty.Create(nameof(Animation), typeof(IPopupAnimation), typeof(PopupPage), new ScaleAnimation());
public IPopupAnimation Animation
{
get { return (IPopupAnimation)GetValue(AnimationProperty); }
set { SetValue(AnimationProperty, value); }
}
public static readonly BindableProperty SystemPaddingProperty = BindableProperty.Create(nameof(SystemPadding), typeof(Thickness), typeof(PopupPage), default(Thickness), BindingMode.OneWayToSource);
public Thickness SystemPadding
{
get { return (Thickness)GetValue(SystemPaddingProperty); }
internal set { SetValue(SystemPaddingProperty, value); }
}
public static readonly BindableProperty SystemPaddingSidesProperty = BindableProperty.Create(nameof(SystemPaddingSides), typeof(PaddingSide), typeof(PopupPage), PaddingSide.All);
public PaddingSide SystemPaddingSides
{
get { return (PaddingSide)GetValue(SystemPaddingSidesProperty); }
set { SetValue(SystemPaddingSidesProperty, value); }
}
public static readonly BindableProperty CloseWhenBackgroundIsClickedProperty = BindableProperty.Create(nameof(CloseWhenBackgroundIsClicked), typeof(bool), typeof(PopupPage), true);
public bool CloseWhenBackgroundIsClicked
{
get { return (bool)GetValue(CloseWhenBackgroundIsClickedProperty); }
set { SetValue(CloseWhenBackgroundIsClickedProperty, value); }
}
public static readonly BindableProperty BackgroundInputTransparentProperty = BindableProperty.Create(nameof(BackgroundInputTransparent), typeof(bool), typeof(PopupPage), false);
public bool BackgroundInputTransparent
{
get { return (bool)GetValue(BackgroundInputTransparentProperty); }
set { SetValue(BackgroundInputTransparentProperty, value); }
}
public static readonly BindableProperty HasKeyboardOffsetProperty = BindableProperty.Create(nameof(HasKeyboardOffset), typeof(bool), typeof(PopupPage), true);
public bool HasKeyboardOffset
{
get { return (bool)GetValue(HasKeyboardOffsetProperty); }
set { SetValue(HasKeyboardOffsetProperty, value); }
}
public static readonly BindableProperty KeyboardOffsetProperty = BindableProperty.Create(nameof(KeyboardOffset), typeof(double), typeof(PopupPage), 0d, BindingMode.OneWayToSource);
public double KeyboardOffset
{
get { return (double)GetValue(KeyboardOffsetProperty); }
private set { SetValue(KeyboardOffsetProperty, value); }
}
#endregion
#region Main Methods
public PopupPage()
{
BackgroundColor = Color.FromHex("#80000000");
}
protected override void OnPropertyChanged(string? propertyName = null)
{
base.OnPropertyChanged(propertyName);
switch (propertyName)
{
case nameof(HasSystemPadding):
case nameof(HasKeyboardOffset):
case nameof(SystemPaddingSides):
case nameof(SystemPadding):
ForceLayout();
break;
case nameof(IsAnimating):
IsAnimationEnabled = IsAnimating;
break;
case nameof(IsAnimationEnabled):
IsAnimating = IsAnimationEnabled;
break;
}
}
protected override bool OnBackButtonPressed()
{
return false;
}
#endregion
#region Size Methods
protected override void LayoutChildren(double x, double y, double width, double height)
{
if (HasSystemPadding)
{
var systemPadding = SystemPadding;
var systemPaddingSide = SystemPaddingSides;
var left = 0d;
var top = 0d;
var right = 0d;
var bottom = 0d;
if (systemPaddingSide.HasFlag(PaddingSide.Left))
left = systemPadding.Left;
if (systemPaddingSide.HasFlag(PaddingSide.Top))
top = systemPadding.Top;
if (systemPaddingSide.HasFlag(PaddingSide.Right))
right = systemPadding.Right;
if (systemPaddingSide.HasFlag(PaddingSide.Bottom))
bottom = systemPadding.Bottom;
x += left;
y += top;
width -= left + right;
if (HasKeyboardOffset)
height -= top + Math.Max(bottom, KeyboardOffset);
else
height -= top + bottom;
}
else if (HasKeyboardOffset)
{
height -= KeyboardOffset;
}
base.LayoutChildren(x, y, width, height);
}
#endregion
#region Animation Methods
internal void PreparingAnimation()
{
if (IsAnimationEnabled)
Animation?.Preparing(Content, this);
}
internal void DisposingAnimation()
{
if (IsAnimationEnabled)
Animation?.Disposing(Content, this);
}
internal async Task AppearingAnimation()
{
OnAppearingAnimationBegin();
await OnAppearingAnimationBeginAsync();
if (IsAnimationEnabled && Animation != null)
await Animation.Appearing(Content, this);
OnAppearingAnimationEnd();
await OnAppearingAnimationEndAsync();
}
internal async Task DisappearingAnimation()
{
OnDisappearingAnimationBegin();
await OnDisappearingAnimationBeginAsync();
if (IsAnimationEnabled && Animation != null)
await Animation.Disappearing(Content, this);
OnDisappearingAnimationEnd();
await OnDisappearingAnimationEndAsync();
}
#endregion
#region Override Animation Methods
protected virtual void OnAppearingAnimationBegin()
{
}
protected virtual void OnAppearingAnimationEnd()
{
}
protected virtual void OnDisappearingAnimationBegin()
{
}
protected virtual void OnDisappearingAnimationEnd()
{
}
protected virtual Task OnAppearingAnimationBeginAsync()
{
return Task.FromResult(0);
}
protected virtual Task OnAppearingAnimationEndAsync()
{
return Task.FromResult(0);
}
protected virtual Task OnDisappearingAnimationBeginAsync()
{
return Task.FromResult(0);
}
protected virtual Task OnDisappearingAnimationEndAsync()
{
return Task.FromResult(0);
}
#endregion
#region Background Click
protected virtual bool OnBackgroundClicked()
{
return CloseWhenBackgroundIsClicked;
}
#endregion
#region Internal Methods
internal async Task SendBackgroundClick()
{
BackgroundClicked?.Invoke(this, EventArgs.Empty);
var isClose = OnBackgroundClicked();
if (isClose)
{
await PopupNavigation.Instance.RemovePageAsync(this);
}
}
#endregion
}
}
| 31.845902 | 205 | 0.609287 | [
"MIT"
] | aliyailina/Rg.Plugins.Popup | Rg.Plugins.Popup/Pages/PopupPage.cs | 9,715 | C# |
using MigrationTool.VersionMigrationTool;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntryPoint
{
class StartUp
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("======================= VueJs MigrationTool =======================");
Console.WriteLine("To use the converter run the console with two arguments, first the");
Console.WriteLine("directory to convert, second the converter to use.");
Console.WriteLine("");
Console.WriteLine(" Existent Converters: ");
Console.WriteLine(" 1: From version 0.16.17 to 1.0.7 ");
return;
}
var path = args[0];
FileAttributes attr = File.GetAttributes(path);
if (!attr.HasFlag(FileAttributes.Directory))
{
Console.WriteLine("======================= VueJs MigrationTool =======================");
Console.WriteLine("An invalid projects was received has the first argument.");
Console.WriteLine("Please on the second argument send the project main folder");
return;
}
var versionInt = 0;
int.TryParse(args[1], out versionInt);
if (!Enum.IsDefined(typeof(VersionToConvert), versionInt))
{
Console.WriteLine("======================= VueJs MigrationTool =======================");
Console.WriteLine("An invalid converter was received has the second argument.");
Console.WriteLine("Please use one of the following:");
Console.WriteLine("");
Console.WriteLine(" Existent Converters: ");
Console.WriteLine(" 1: From version 0.16.17 to 1.0.7 ");
return;
}
VersionToConvert type = (VersionToConvert) Enum.Parse(typeof(VersionToConvert), args[1]);
MigrationTool.MigrationTool tool = new MigrationTool.MigrationTool(type, path);
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("Press any key to close...");
Console.ReadKey();
}
}
}
| 34.434783 | 105 | 0.53367 | [
"MIT"
] | joaogl/VuejsConverter | EntryPoint/StartUp.cs | 2,378 | C# |
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using MovieDB.Shared.Models.Accounts;
namespace MovieDB.Client.Blazor.Services
{
public interface IAccountService
{
AuthenticateResponse? User { get; }
bool IsAuthenticated();
Task Initialize();
Task Authenticate(AuthenticateRequest model);
Task Logout();
Task<AccountResponse> GetById(int id);
}
public class AccountService : IAccountService
{
private readonly HttpClient _client;
private readonly NavigationManager _navigationManager;
private readonly ILocalStorageService _localStorageService;
private const string _userKey = "user";
private const string _jwtKey = "jwt";
public AuthenticateResponse? User { get; private set; }
public AccountService(
HttpClient client,
NavigationManager navigationManager,
ILocalStorageService localStorageService)
{
_client = client;
_navigationManager = navigationManager;
_localStorageService = localStorageService;
}
public bool IsAuthenticated()
{
return User is not null;
}
public async Task Initialize()
{
User = await _localStorageService.GetItem<AuthenticateResponse>(_userKey);
}
public async Task Authenticate(AuthenticateRequest model)
{
var response = await _client.PostAsJsonAsync("/api/accounts/authenticate", model);
User = await response.Content.ReadFromJsonAsync<AuthenticateResponse>();
await _localStorageService.SetItem(_userKey, User);
await _localStorageService.SetItem(_jwtKey, User.JwtToken);
}
public async Task Logout()
{
User = null;
await _localStorageService.RemoveItem(_userKey);
}
public async Task<AccountResponse> GetById(int id)
{
throw new NotImplementedException();
}
}
}
| 30.471429 | 94 | 0.644163 | [
"MIT"
] | eisnstein/MovieDB | MovieDB.Client.Blazor/Services/AccountService.cs | 2,133 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
namespace Microsoft.WindowsAzure.Management.SiteRecovery.Models
{
/// <summary>
/// The definition of a ServiceError object.
/// </summary>
public partial class ServiceError
{
private string _activityId;
/// <summary>
/// Required. Activity id of the request where service error was
/// recorded.
/// </summary>
public string ActivityId
{
get { return this._activityId; }
set { this._activityId = value; }
}
private string _code;
/// <summary>
/// Required. Service error code.
/// </summary>
public string Code
{
get { return this._code; }
set { this._code = value; }
}
private string _message;
/// <summary>
/// Required. Service error message.
/// </summary>
public string Message
{
get { return this._message; }
set { this._message = value; }
}
private string _possibleCauses;
/// <summary>
/// Required. Possible causes which can lead to this error.
/// </summary>
public string PossibleCauses
{
get { return this._possibleCauses; }
set { this._possibleCauses = value; }
}
private string _recommendedAction;
/// <summary>
/// Required. Recommended action to resolve error.
/// </summary>
public string RecommendedAction
{
get { return this._recommendedAction; }
set { this._recommendedAction = value; }
}
/// <summary>
/// Initializes a new instance of the ServiceError class.
/// </summary>
public ServiceError()
{
}
}
}
| 28.322917 | 76 | 0.571166 | [
"Apache-2.0"
] | CerebralMischief/azure-sdk-for-net | src/ServiceManagement/SiteRecovery/SiteRecoveryManagement/Generated/Models/ServiceError.cs | 2,719 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace json3
{
internal class Root
{
/// <summary>
///
/// </summary>
public string id { get; set; }
/// <summary>
///
/// </summary>
public string name { get; set; }
}
}
| 15.772727 | 37 | 0.564841 | [
"MIT"
] | Baka632/SquareMinecraftLauncherCore | SquareMinecraftLauncherCore/json/json3.cs | 349 | C# |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Aop.Api.Domain
{
/// <summary>
/// Datas Data Structure.
/// </summary>
[Serializable]
public class Datas : AopObject
{
/// <summary>
/// 指标数据区
/// </summary>
[XmlArray("data")]
[XmlArrayItem("data_entry")]
public List<DataEntry> Data { get; set; }
/// <summary>
/// 数据维度
/// </summary>
[XmlArray("dimension")]
[XmlArrayItem("data_dim")]
public List<DataDim> Dimension { get; set; }
}
}
| 22.5 | 53 | 0.51746 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/Datas.cs | 648 | 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 VSServerReadyLauncher {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class PackageResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal PackageResources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("VSServerReadyLauncher.PackageResources", typeof(PackageResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to The VSServerReadyLauncher was unable to launch project '{0}'. {1}
///
///To configure launch settings, open the configuration file..
/// </summary>
internal static string Err_ProjectDebugFailed_Args2 {
get {
return ResourceManager.GetString("Err_ProjectDebugFailed_Args2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The VSServerReadyLauncher was unable to launch project '{0}'. No debuggable configuration can be found.
///
///To configure launch settings, open the configuration file..
/// </summary>
internal static string Err_ProjectNotDebuggable_Args1 {
get {
return ResourceManager.GetString("Err_ProjectNotDebuggable_Args1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The VSServerReadyLauncher was unable to parse configuration file '{0}'. Unable to find specified project '{1}' in the current solution. .
/// </summary>
internal static string Err_UnableToFindProject_Args2 {
get {
return ResourceManager.GetString("Err_UnableToFindProject_Args2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The VSServerReadyLauncher was unable to parse configuration file '{0}'. Unable to parse regular expression pattern '{1}'.
///
///{2}.
/// </summary>
internal static string Err_UnableToParsePattern_Args3 {
get {
return ResourceManager.GetString("Err_UnableToParsePattern_Args3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The VSServerReadyLauncher was unable to parse configuration file '{0}'.
///
///{1}.
/// </summary>
internal static string Err_UnableToParseSettingsFile_Args2 {
get {
return ResourceManager.GetString("Err_UnableToParseSettingsFile_Args2", resourceCulture);
}
}
}
}
| 44.273504 | 210 | 0.610425 | [
"MIT"
] | gregg-miskelly/VSServerReadyExtension | src/VSServerReadyLauncher/PackageResources.Designer.cs | 5,182 | C# |
using Miic.Base;
using Miic.Base.Setting;
using Miic.DB.Setting;
using Miic.DB.SqlObject;
using Miic.Friends.Moments;
using System;
using System.Data;
namespace Miic.Friends.Common
{
public class PersonDateView:GeneralDateView
{
/// <summary>
/// 用户ID
/// </summary>
public string UserID
{
get { return this.userID; }
set { this.userID = value; }
}
public override MiicConditionCollections visitor(PublishInfoDao publishInfoDao)
{
MiicConditionCollections condition = new MiicConditionCollections(MiicDBLogicSetting.No);
MiicCondition editStatusCondition = new MiicCondition(Config.Attribute.GetSqlColumnNameByPropertyName<AddressPublishInfo, string>(o => o.EditStatus),
((int)MiicYesNoSetting.No).ToString(),
DbType.String,
MiicDBOperatorSetting.Equal);
condition.Add(new MiicConditionLeaf(MiicDBLogicSetting.No,editStatusCondition));
MiicConditionCollections dateCondition = new MiicConditionCollections();
MiicCondition yearCondition = new MiicCondition(MiicSimpleDateTimeFunction.YearFunc<AddressPublishInfo, DateTime?>(o => o.PublishTime),
Year,
DbType.String,
MiicDBOperatorSetting.Equal);
dateCondition.Add(new MiicConditionLeaf(MiicDBLogicSetting.No, yearCondition));
if (!string.IsNullOrEmpty(Month))
{
MiicCondition monthCondition = new MiicCondition(MiicSimpleDateTimeFunction.MonthFunc<AddressPublishInfo, DateTime?>(o => o.PublishTime),
Month,
DbType.String,
MiicDBOperatorSetting.Equal);
dateCondition.Add(new MiicConditionLeaf(MiicDBLogicSetting.And, monthCondition));
}
condition.Add(dateCondition);
//发表人是用户
MiicCondition createrIDCondition = new MiicCondition(Config.Attribute.GetSqlColumnNameByPropertyName<AddressPublishInfo, string>(o => o.CreaterID),
this.UserID,
DbType.String,
MiicDBOperatorSetting.Equal);
condition.Add(new MiicConditionLeaf(createrIDCondition));
return condition;
}
}
}
| 46.833333 | 161 | 0.53274 | [
"MIT"
] | wswmjc/webfriends | MIIC_FRIENDS/DVO/Common/Date/PersonDateView.cs | 2,828 | 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.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Portal
{
public partial class WebSitesAddPointer : WebsitePanelModuleBase
{
protected void Page_Load(object sender, EventArgs e)
{
domainsSelectDomainControl.PackageId = PanelSecurity.PackageId;
if (!IsPostBack)
{
PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId);
//if (Utils.CheckQouta(Quotas.WEB_ENABLEHOSTNAMESUPPORT, cntx))
//{
txtHostName.Visible = lblTheDotInTheMiddle.Visible = true;
UserSettings settings = ES.Services.Users.GetUserSettings(PanelSecurity.LoggedUserId, UserSettings.WEB_POLICY);
txtHostName.Text = String.IsNullOrEmpty(settings["HostName"]) ? "" : settings["HostName"];
//}
//else
//txtHostName.Visible = lblTheDotInTheMiddle.Visible = false;
}
}
private void AddPointer()
{
try
{
int result = ES.Services.WebServers.AddWebSitePointer(PanelRequest.ItemID, txtHostName.Text.ToLower(), domainsSelectDomainControl.DomainId);
if (result < 0)
{
ShowResultMessage(result);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("WEB_ADD_SITE_POINTER", ex);
return;
}
RedirectBack();
}
private void RedirectBack()
{
Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "edit_item",
PortalUtils.SPACE_ID_PARAM + "=" + PanelSecurity.PackageId.ToString()));
}
protected void btnAdd_Click(object sender, EventArgs e)
{
AddPointer();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
RedirectBack();
}
}
}
| 39.342593 | 157 | 0.639209 | [
"BSD-3-Clause"
] | Key4ce/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/WebSitesAddPointer.ascx.cs | 4,249 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EndOfVideoTutorial2 : MonoBehaviour
{
private void Start()
{
GetComponent<AudioSource>().Play();
//audio.Play();
StartCoroutine(myTimer());
}
IEnumerator myTimer()
{
yield return new WaitForSeconds(5.6f);
SceneManager.LoadScene("fase1_1", LoadSceneMode.Single);
}
}
| 20.25 | 65 | 0.63786 | [
"MIT"
] | vinimussio1/comp-vr | Assets/Sample/Scripts/EndOfVideoTutorial2.cs | 488 | C# |
using System;
using UnityEngine;
[AddComponentMenu("NGUI/Examples/Item Attachment Point")]
public class InvAttachmentPoint : MonoBehaviour
{
public InvBaseItem.Slot slot;
private GameObject mPrefab;
private GameObject mChild;
public GameObject Attach(GameObject prefab)
{
if (this.mPrefab != prefab)
{
this.mPrefab = prefab;
if (this.mChild != null)
{
UnityEngine.Object.Destroy(this.mChild);
}
if (this.mPrefab != null)
{
Transform transform = base.transform;
this.mChild = (UnityEngine.Object.Instantiate(this.mPrefab, transform.position, transform.rotation) as GameObject);
Transform transform2 = this.mChild.transform;
transform2.parent = transform;
transform2.localPosition = Vector3.zero;
transform2.localRotation = Quaternion.identity;
transform2.localScale = Vector3.one;
}
}
return this.mChild;
}
}
| 24.416667 | 119 | 0.726962 | [
"MIT"
] | moto2002/superWeapon | src/InvAttachmentPoint.cs | 879 | C# |
using System;
namespace Chaos.NaCl.Internal.Ed25519Ref10
{
internal static partial class FieldOperations
{
private static Int64 load_3(byte[] data, int offset)
{
uint result;
result = (uint)data[offset + 0];
result |= (uint)data[offset + 1] << 8;
result |= (uint)data[offset + 2] << 16;
return (Int64)(UInt64)result;
}
private static Int64 load_4(byte[] data, int offset)
{
uint result;
result = (uint)data[offset + 0];
result |= (uint)data[offset + 1] << 8;
result |= (uint)data[offset + 2] << 16;
result |= (uint)data[offset + 3] << 24;
return (Int64)(UInt64)result;
}
// Ignores top bit of h.
internal static void fe_frombytes(out FieldElement h, byte[] data, int offset)
{
Int64 h0 = load_4(data, offset);
Int64 h1 = load_3(data, offset + 4) << 6;
Int64 h2 = load_3(data, offset + 7) << 5;
Int64 h3 = load_3(data, offset + 10) << 3;
Int64 h4 = load_3(data, offset + 13) << 2;
Int64 h5 = load_4(data, offset + 16);
Int64 h6 = load_3(data, offset + 20) << 7;
Int64 h7 = load_3(data, offset + 23) << 5;
Int64 h8 = load_3(data, offset + 26) << 4;
Int64 h9 = (load_3(data, offset + 29) & 8388607) << 2;
Int64 carry0;
Int64 carry1;
Int64 carry2;
Int64 carry3;
Int64 carry4;
Int64 carry5;
Int64 carry6;
Int64 carry7;
Int64 carry8;
Int64 carry9;
carry9 = (h9 + (Int64)(1 << 24)) >> 25; h0 += carry9 * 19; h9 -= carry9 << 25;
carry1 = (h1 + (Int64)(1 << 24)) >> 25; h2 += carry1; h1 -= carry1 << 25;
carry3 = (h3 + (Int64)(1 << 24)) >> 25; h4 += carry3; h3 -= carry3 << 25;
carry5 = (h5 + (Int64)(1 << 24)) >> 25; h6 += carry5; h5 -= carry5 << 25;
carry7 = (h7 + (Int64)(1 << 24)) >> 25; h8 += carry7; h7 -= carry7 << 25;
carry0 = (h0 + (Int64)(1 << 25)) >> 26; h1 += carry0; h0 -= carry0 << 26;
carry2 = (h2 + (Int64)(1 << 25)) >> 26; h3 += carry2; h2 -= carry2 << 26;
carry4 = (h4 + (Int64)(1 << 25)) >> 26; h5 += carry4; h4 -= carry4 << 26;
carry6 = (h6 + (Int64)(1 << 25)) >> 26; h7 += carry6; h6 -= carry6 << 26;
carry8 = (h8 + (Int64)(1 << 25)) >> 26; h9 += carry8; h8 -= carry8 << 26;
h.x0 = (int)h0;
h.x1 = (int)h1;
h.x2 = (int)h2;
h.x3 = (int)h3;
h.x4 = (int)h4;
h.x5 = (int)h5;
h.x6 = (int)h6;
h.x7 = (int)h7;
h.x8 = (int)h8;
h.x9 = (int)h9;
}
// does NOT ignore top bit
internal static void fe_frombytes2(out FieldElement h, byte[] data, int offset)
{
Int64 h0 = load_4(data, offset);
Int64 h1 = load_3(data, offset + 4) << 6;
Int64 h2 = load_3(data, offset + 7) << 5;
Int64 h3 = load_3(data, offset + 10) << 3;
Int64 h4 = load_3(data, offset + 13) << 2;
Int64 h5 = load_4(data, offset + 16);
Int64 h6 = load_3(data, offset + 20) << 7;
Int64 h7 = load_3(data, offset + 23) << 5;
Int64 h8 = load_3(data, offset + 26) << 4;
Int64 h9 = load_3(data, offset + 29) << 2;
Int64 carry0;
Int64 carry1;
Int64 carry2;
Int64 carry3;
Int64 carry4;
Int64 carry5;
Int64 carry6;
Int64 carry7;
Int64 carry8;
Int64 carry9;
carry9 = (h9 + (Int64)(1 << 24)) >> 25; h0 += carry9 * 19; h9 -= carry9 << 25;
carry1 = (h1 + (Int64)(1 << 24)) >> 25; h2 += carry1; h1 -= carry1 << 25;
carry3 = (h3 + (Int64)(1 << 24)) >> 25; h4 += carry3; h3 -= carry3 << 25;
carry5 = (h5 + (Int64)(1 << 24)) >> 25; h6 += carry5; h5 -= carry5 << 25;
carry7 = (h7 + (Int64)(1 << 24)) >> 25; h8 += carry7; h7 -= carry7 << 25;
carry0 = (h0 + (Int64)(1 << 25)) >> 26; h1 += carry0; h0 -= carry0 << 26;
carry2 = (h2 + (Int64)(1 << 25)) >> 26; h3 += carry2; h2 -= carry2 << 26;
carry4 = (h4 + (Int64)(1 << 25)) >> 26; h5 += carry4; h4 -= carry4 << 26;
carry6 = (h6 + (Int64)(1 << 25)) >> 26; h7 += carry6; h6 -= carry6 << 26;
carry8 = (h8 + (Int64)(1 << 25)) >> 26; h9 += carry8; h8 -= carry8 << 26;
h.x0 = (int)h0;
h.x1 = (int)h1;
h.x2 = (int)h2;
h.x3 = (int)h3;
h.x4 = (int)h4;
h.x5 = (int)h5;
h.x6 = (int)h6;
h.x7 = (int)h7;
h.x8 = (int)h8;
h.x9 = (int)h9;
}
}
}
| 32.821138 | 81 | 0.538519 | [
"Apache-2.0"
] | BlockForks/dotnetstandard-bip32 | dotnetstandard-bip32/chaos.nacl/Internal/Ed25519Ref10/fe_frombytes.cs | 4,039 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DotNet.Interactive.Telemetry
{
public static class TelemetryExtensions
{
public static void SendFiltered(this ITelemetry telemetry, ITelemetryFilter filter, object o)
{
if (o == null || !telemetry.Enabled || filter == null)
{
return;
}
foreach (ApplicationInsightsEntryFormat entry in filter.Filter(o))
{
telemetry.TrackEvent(entry.EventName, entry.Properties, entry.Measurements);
}
}
}
}
| 33.045455 | 101 | 0.628611 | [
"MIT"
] | Allyn69/try | Microsoft.DotNet.Interactive.Telemetry/TelemetryExtensions.cs | 729 | C# |
/******************************************************************************
* $Id: VSIMem.cs 25805 2013-03-26 10:46:39Z tamas $
*
* Name: VSIMem.cs
* Project: GDAL CSharp Interface
* Purpose: A sample app for demonstrating the in-memory virtual file support.
* Author: Tamas Szekeres, szekerest@gmail.com
*
******************************************************************************
* Copyright (c) 2013, Tamas Szekeres
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*****************************************************************************/
using System;
using System.IO;
using System.Runtime.InteropServices;
using OSGeo.GDAL;
/**
* <p>Title: GDAL C# VSIMem example.</p>
* <p>Description: A sample app for demonstrating the in-memory virtual file support.</p>
* @author Tamas Szekeres (szekerest@gmail.com)
* @version 1.0
*/
/// <summary>
/// A C# based sample for demonstrating the in-memory virtual file support.
/// </summary>
class VSIMem {
public static void usage()
{
Console.WriteLine("usage example: vsimem [image file]");
System.Environment.Exit(-1);
}
public static void Main(string[] args) {
if (args.Length != 1) usage();
byte[] imageBuffer;
using (FileStream fs = new FileStream(args[0], FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
long numBytes = new FileInfo(args[0]).Length;
imageBuffer = br.ReadBytes((int)numBytes);
br.Close();
fs.Close();
}
}
Gdal.AllRegister();
string memFilename = "/vsimem/inmemfile";
try
{
Gdal.FileFromMemBuffer(memFilename, imageBuffer);
Dataset ds = Gdal.Open(memFilename, Access.GA_ReadOnly);
Console.WriteLine("Raster dataset parameters:");
Console.WriteLine(" RasterCount: " + ds.RasterCount);
Console.WriteLine(" RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")");
Driver drv = Gdal.GetDriverByName("GTiff");
if (drv == null)
{
Console.WriteLine("Can't get driver.");
System.Environment.Exit(-1);
}
drv.CreateCopy("sample.tif", ds, 0, null, null, null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Gdal.Unlink(memFilename);
}
}
} | 32.504587 | 94 | 0.595823 | [
"MIT"
] | TUW-GEO/OGRSpatialRef3D | gdal-1.10.0/swig/csharp/apps/VSIMem.cs | 3,543 | C# |
using System.Text;
namespace Loretta.CodeAnalysis.Lua.Test.Utilities
{
public static class RandomSpaceInserter
{
public static IEnumerable<string> Enumerate(params string[] parts)
{
if (parts.Length is < 1 or > 64)
throw new ArgumentOutOfRangeException(nameof(parts));
var spaceLocations = parts.Length - 1;
var builder = new StringBuilder();
var lastCase = (1UL << spaceLocations) - 1;
for (var spaces = 0UL; spaces <= lastCase; spaces++)
{
builder.Clear();
for (var partIdx = 0; partIdx < parts.Length - 1; partIdx++)
{
builder.Append(parts[partIdx]);
if (((1UL << partIdx) & spaces) != 0)
builder.Append(' ');
}
builder.Append(parts[^1]);
yield return builder.ToString();
}
}
public static IEnumerable<object[]> MemberDataEnumerate(params string[] parts)
{
foreach (var result in Enumerate(parts))
{
yield return new object[] { result };
}
}
}
}
| 29.261905 | 86 | 0.497966 | [
"MIT"
] | LorettaDevs/Loretta | src/Compilers/Lua/Test/Utilities/RandomSpaceInserter.cs | 1,231 | 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("GameMemento.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GameMemento.Core")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4e7844c3-4f73-4595-88ac-12458c480580")]
// 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.837838 | 84 | 0.747857 | [
"Unlicense"
] | wilmerbz/designpatterns | GameMemento/GameMemento.Core/Properties/AssemblyInfo.cs | 1,403 | C# |
using System.ComponentModel.DataAnnotations;
namespace Equinox.Infra.CrossCutting.Identity.Models.ManageViewModels
{
public class VerifyPhoneNumberViewModel
{
[Required]
public string Code { get; set; }
[Required]
[Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
}
}
| 22.625 | 69 | 0.646409 | [
"MIT"
] | GuilhermeEsteves/EquinoxProject | src/Equinox.Infra.CrossCutting.Identity/Models/ManageViewModels/VerifyPhoneNumberViewModel.cs | 364 | C# |
using System;
using System.Collections.Generic;
using DataStructuresLib.Basic;
using DataStructuresLib.Collections.PeriodicLists2D;
namespace DataStructuresLib.Collections
{
public static class CollectionsUtils
{
public static Pair<T> GetItemsPair<T>(this IReadOnlyList<T> inputsList, IPair<int> itemIndices)
{
return new Pair<T>(
inputsList[itemIndices.Item1],
inputsList[itemIndices.Item2]
);
}
public static Pair<T> GetItemsPair<T>(this IReadOnlyList<T> inputsList, int index1)
{
return new Pair<T>(
inputsList[index1],
inputsList[index1 + 1]
);
}
public static Pair<T> GetItemsPair<T>(this IReadOnlyList<T> inputsList, int index1, int index2)
{
return new Pair<T>(
inputsList[index1],
inputsList[index2]
);
}
public static Triplet<T> GetItemsTriplet<T>(this IReadOnlyList<T> inputsList, ITriplet<int> itemIndices)
{
return new Triplet<T>(
inputsList[itemIndices.Item1],
inputsList[itemIndices.Item2],
inputsList[itemIndices.Item3]
);
}
public static Triplet<T> GetItemsTriplet<T>(this IReadOnlyList<T> inputsList, int index1, int index2, int index3)
{
return new Triplet<T>(
inputsList[index1],
inputsList[index2],
inputsList[index3]
);
}
public static Triplet<T> GetItemsTriplet<T>(this IReadOnlyList<T> inputsList, int index1)
{
return new Triplet<T>(
inputsList[index1],
inputsList[index1 + 1],
inputsList[index1 + 2]
);
}
public static Quad<T> GetItemsQuad<T>(this IReadOnlyList<T> inputsList, IQuad<int> itemIndices)
{
return new Quad<T>(
inputsList[itemIndices.Item1],
inputsList[itemIndices.Item2],
inputsList[itemIndices.Item3],
inputsList[itemIndices.Item4]
);
}
public static Quad<T> GetItemsQuad<T>(this IReadOnlyList<T> inputsList, int index1, int index2, int index3, int index4)
{
return new Quad<T>(
inputsList[index1],
inputsList[index2],
inputsList[index3],
inputsList[index4]
);
}
public static Quad<T> GetItemsQuad<T>(this IReadOnlyList<T> inputsList, int index1)
{
return new Quad<T>(
inputsList[index1],
inputsList[index1 + 1],
inputsList[index1 + 2],
inputsList[index1 + 3]
);
}
public static int GetItemIndex<T>(this IReadOnlyList2D<T> inputList, int index1, int index2)
{
index1 = index1.Mod(inputList.Count1);
index2 = index2.Mod(inputList.Count2);
return index1 + index2 * inputList.Count1;
}
public static Tuple<int, int> GetItemIndexTuple<T>(this IPeriodicReadOnlyList2D<T> inputList, int index)
{
index = index.Mod(inputList.Count);
var index1 = index % inputList.Count1;
var index2 = (index - index1) / inputList.Count1;
return new Tuple<int, int>(index1, index2);
}
public static Tuple<int, int> GetItemIndexTuple<T>(this IReadOnlyList2D<T> inputList, int index)
{
index = index.Mod(inputList.Count);
var index1 = index % inputList.Count1;
var index2 = (index - index1) / inputList.Count1;
return new Tuple<int, int>(index1, index2);
}
public static Pair<int> GetItemIndexPair<T>(this IReadOnlyList2D<T> inputList, int index)
{
index = index.Mod(inputList.Count);
var index1 = index % inputList.Count1;
var index2 = (index - index1) / inputList.Count1;
return new Pair<int>(index1, index2);
}
public static bool IsNullOrEmpty<T>(this IReadOnlyCollection<T> collection)
{
return collection == null || collection.Count == 0;
}
}
}
| 31.661871 | 127 | 0.551238 | [
"MIT"
] | ga-explorer/GMac | DataStructuresLib/DataStructuresLib/Collections/CollectionsUtils.cs | 4,403 | C# |
#region Copyright (c) 2019 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Arqs
{
using System;
using System.Collections.Generic;
using System.Linq;
public interface ICliRecord
{
T Match<T>(Func<IArg, T> argSelector,
Func<string, T> textSelector);
}
public static class CliRecord
{
static readonly ICliRecord BlankText = new TextCliRecord(string.Empty);
public static ICliRecord Text(string text) =>
string.IsNullOrEmpty(text) ? BlankText : new TextCliRecord(text);
sealed class TextCliRecord : ICliRecord
{
readonly string _text;
public TextCliRecord(string text) => _text = text;
public T Match<T>(Func<IArg, T> argSelector, Func<string, T> textSelector) =>
textSelector(_text);
}
public static IEnumerable<IArg> GetArgs(this ICli cli) =>
from ir in cli.Inspect()
select ir.Match(arg => arg, _ => null) into arg
where arg != null
select arg;
}
}
| 31.037736 | 89 | 0.648024 | [
"Apache-2.0"
] | atifaziz/Arqs | src/ICliRecord.cs | 1,645 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Support.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Contact information associated with the support ticket.
/// </summary>
public partial class ContactProfile
{
/// <summary>
/// Initializes a new instance of the ContactProfile class.
/// </summary>
public ContactProfile()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ContactProfile class.
/// </summary>
/// <param name="firstName">First name.</param>
/// <param name="lastName">Last name.</param>
/// <param name="preferredContactMethod">Preferred contact method.
/// Possible values include: 'email', 'phone'</param>
/// <param name="primaryEmailAddress">Primary email address.</param>
/// <param name="preferredTimeZone">Time zone of the user. This is the
/// name of the time zone from [Microsoft Time Zone Index
/// Values](https://support.microsoft.com/help/973627/microsoft-time-zone-index-values).</param>
/// <param name="country">Country of the user. This is the ISO 3166-1
/// alpha-3 code.</param>
/// <param name="preferredSupportLanguage">Preferred language of
/// support from Azure. Support languages vary based on the severity
/// you choose for your support ticket. Learn more at [Azure Severity
/// and
/// responsiveness](https://azure.microsoft.com/support/plans/response).
/// Use the standard language-country code. Valid values are 'en-us'
/// for English, 'zh-hans' for Chinese, 'es-es' for Spanish, 'fr-fr'
/// for French, 'ja-jp' for Japanese, 'ko-kr' for Korean, 'ru-ru' for
/// Russian, 'pt-br' for Portuguese, 'it-it' for Italian, 'zh-tw' for
/// Chinese and 'de-de' for German.</param>
/// <param name="additionalEmailAddresses">Additional email addresses
/// listed will be copied on any correspondence about the support
/// ticket.</param>
/// <param name="phoneNumber">Phone number. This is required if
/// preferred contact method is phone.</param>
public ContactProfile(string firstName, string lastName, string preferredContactMethod, string primaryEmailAddress, string preferredTimeZone, string country, string preferredSupportLanguage, IList<string> additionalEmailAddresses = default(IList<string>), string phoneNumber = default(string))
{
FirstName = firstName;
LastName = lastName;
PreferredContactMethod = preferredContactMethod;
PrimaryEmailAddress = primaryEmailAddress;
AdditionalEmailAddresses = additionalEmailAddresses;
PhoneNumber = phoneNumber;
PreferredTimeZone = preferredTimeZone;
Country = country;
PreferredSupportLanguage = preferredSupportLanguage;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets first name.
/// </summary>
[JsonProperty(PropertyName = "firstName")]
public string FirstName { get; set; }
/// <summary>
/// Gets or sets last name.
/// </summary>
[JsonProperty(PropertyName = "lastName")]
public string LastName { get; set; }
/// <summary>
/// Gets or sets preferred contact method. Possible values include:
/// 'email', 'phone'
/// </summary>
[JsonProperty(PropertyName = "preferredContactMethod")]
public string PreferredContactMethod { get; set; }
/// <summary>
/// Gets or sets primary email address.
/// </summary>
[JsonProperty(PropertyName = "primaryEmailAddress")]
public string PrimaryEmailAddress { get; set; }
/// <summary>
/// Gets or sets additional email addresses listed will be copied on
/// any correspondence about the support ticket.
/// </summary>
[JsonProperty(PropertyName = "additionalEmailAddresses")]
public IList<string> AdditionalEmailAddresses { get; set; }
/// <summary>
/// Gets or sets phone number. This is required if preferred contact
/// method is phone.
/// </summary>
[JsonProperty(PropertyName = "phoneNumber")]
public string PhoneNumber { get; set; }
/// <summary>
/// Gets or sets time zone of the user. This is the name of the time
/// zone from [Microsoft Time Zone Index
/// Values](https://support.microsoft.com/help/973627/microsoft-time-zone-index-values).
/// </summary>
[JsonProperty(PropertyName = "preferredTimeZone")]
public string PreferredTimeZone { get; set; }
/// <summary>
/// Gets or sets country of the user. This is the ISO 3166-1 alpha-3
/// code.
/// </summary>
[JsonProperty(PropertyName = "country")]
public string Country { get; set; }
/// <summary>
/// Gets or sets preferred language of support from Azure. Support
/// languages vary based on the severity you choose for your support
/// ticket. Learn more at [Azure Severity and
/// responsiveness](https://azure.microsoft.com/support/plans/response).
/// Use the standard language-country code. Valid values are 'en-us'
/// for English, 'zh-hans' for Chinese, 'es-es' for Spanish, 'fr-fr'
/// for French, 'ja-jp' for Japanese, 'ko-kr' for Korean, 'ru-ru' for
/// Russian, 'pt-br' for Portuguese, 'it-it' for Italian, 'zh-tw' for
/// Chinese and 'de-de' for German.
/// </summary>
[JsonProperty(PropertyName = "preferredSupportLanguage")]
public string PreferredSupportLanguage { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (FirstName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "FirstName");
}
if (LastName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "LastName");
}
if (PreferredContactMethod == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "PreferredContactMethod");
}
if (PrimaryEmailAddress == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "PrimaryEmailAddress");
}
if (PreferredTimeZone == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "PreferredTimeZone");
}
if (Country == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Country");
}
if (PreferredSupportLanguage == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "PreferredSupportLanguage");
}
}
}
}
| 42.451613 | 301 | 0.608156 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/support/Microsoft.Azure.Management.Support/src/Generated/Models/ContactProfile.cs | 7,896 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WhatYouGotLibrary.Models;
using WhatYouGotLibrary.Interfaces;
using Microsoft.Extensions.Logging;
namespace WhatYouGotAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ReviewsController : ControllerBase
{
private readonly ILogger<ReviewsController> _logger;
private readonly IReviewRepo _reviewRepo;
public ReviewsController(ILogger<ReviewsController> logger, IReviewRepo reviewRepo)
{
_logger = logger;
_reviewRepo = reviewRepo;
}
// GET: api/Reviews
[HttpGet]
public IEnumerable<Review> GetReview()
{
IEnumerable<Review> reviews = _reviewRepo.GetReviews();
if (reviews != null)
{
_logger.LogInformation("Getting all reviews.");
return reviews.ToList();
}
_logger.LogWarning("Attempted to get reviews but no reviews were available.");
return null;
}
// GET: api/Reviews/5
[HttpGet("{userId}/{recipeId}")]
public IActionResult GetReview(int userId, int recipeId)
{
if (!ReviewExists(userId, recipeId))
{
_logger.LogWarning($"Review with user id: {userId} and recipe id: {recipeId} does not exist.");
return NotFound();
}
Review review = _reviewRepo.GetReviewById(userId, recipeId);
_logger.LogInformation($"Getting review with user id: {userId} and recipe id: {recipeId}.");
return Ok(review);
}
[HttpGet("ReviewsByUserId/{userId}")]
public IActionResult GetReviewsByUserId(int userId)
{
if (!ReviewByUserIdExists(userId))
{
_logger.LogWarning($"Review with user id: {userId} does not exist.");
return NotFound();
}
IEnumerable<Review> reviews = _reviewRepo.GetReviewsByUserId(userId);
_logger.LogInformation($"Getting review with user id: {userId}.");
return Ok(reviews);
}
[HttpGet("ReviewsByRecipeId/{recipeId}")]
public IActionResult GetReviewsByRecipeId(int recipeId)
{
if (!ReviewByRecipeIdExists(recipeId))
{
_logger.LogWarning($"Review with user id: {recipeId} does not exist.");
return NotFound();
}
IEnumerable<Review> reviews = _reviewRepo.GetReviewsByRecipeId(recipeId);
_logger.LogInformation($"Getting review with user id: {recipeId}.");
return Ok(reviews);
}
//PUT: api/Reviews/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPut("{userId}/{recipeId}")]
public IActionResult PutReview(int userId, int recipeId, Review review)
{
if (userId != review.UserId || recipeId != review.RecipeId)
{
_logger.LogWarning($"Route values: user id: {userId} and recipe id: {recipeId} does not " +
$"match Review user id: {review.UserId} and Review recipe id: {review.RecipeId}");
return BadRequest();
}
if (!ReviewExists(userId, recipeId))
{
_logger.LogWarning($"Review with user id: {userId} and recipe id: {recipeId} does not exist.");
return NotFound();
}
_reviewRepo.UpdateReview(review);
_reviewRepo.SaveChanges();
_logger.LogInformation($"Review with user id: {userId} and recipe id: {recipeId} has been updated.");
return NoContent();
}
//POST: api/Reviews
//To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public IActionResult PostReview(Review review)
{
if (ReviewExists(review.UserId, review.RecipeId))
{
_logger.LogWarning($"Review with user id: {review.UserId} and recipe id: {review.RecipeId} already exists.");
return Conflict();
}
_reviewRepo.AddReview(review);
_reviewRepo.SaveChanges();
_logger.LogInformation($"Review with user id: {review.UserId} and recipe id: {review.RecipeId} has been added.");
return CreatedAtAction(nameof(GetReview), review);
}
//DELETE: api/Reviews/5
[HttpDelete("{userId}/{recipeId}")]
public IActionResult DeleteReview(int userId, int recipeId)
{
if (!ReviewExists(userId, recipeId))
{
_logger.LogWarning($"Review with user id: {userId} and recipe id: {recipeId} does not exist.");
return NotFound();
}
_reviewRepo.DeleteReviewById(userId, recipeId);
_reviewRepo.SaveChanges();
_logger.LogInformation($"Review with user id: {userId} and recipe id: {recipeId} has been deleted.");
return Content($"Review with user id: {userId} and recipe id: {recipeId} has been deleted.");
}
private bool ReviewExists(int userId, int recipeId)
{
return _reviewRepo.ReviewExists(userId, recipeId);
}
private bool ReviewByUserIdExists(int userId)
{
return _reviewRepo.ReviewByUserIdExists(userId);
}
private bool ReviewByRecipeIdExists(int recipeId)
{
return _reviewRepo.ReviewByRecipeIdExists(recipeId);
}
}
}
| 35.1 | 125 | 0.594268 | [
"MIT"
] | 200106-UTA-PRS-NET/P2-FridgeThings | WhatYouGotAPI/WhatYouGotAPI/Controllers/ReviewsController.cs | 5,969 | C# |
/* INFINITY CODE 2013-2017 */
/* http://www.infinity-code.com */
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
/// <summary>
/// The Google Places API allows you to query for place information on a variety of categories, such as: establishments, prominent points of interest, geographic locations, and more. \n
/// You can search for places either by proximity or a text string. \n
/// A Place Search returns a list of places along with summary information about each place.\n
/// https://developers.google.com/places/web-service/search
/// </summary>
public class OnlineMapsGooglePlaces: OnlineMapsGoogleAPIQuery
{
protected OnlineMapsGooglePlaces()
{
}
protected OnlineMapsGooglePlaces(string key, RequestParams p)
{
_status = OnlineMapsQueryStatus.downloading;
StringBuilder url = new StringBuilder();
url.AppendFormat("https://maps.googleapis.com/maps/api/place/{0}/xml?sensor=false", p.typePath);
if (!string.IsNullOrEmpty(key)) url.Append("&key=").Append(key);
p.AppendParams(url);
www = OnlineMapsUtils.GetWWW(url);
www.OnComplete += OnRequestComplete;
}
/// <summary>
/// A Nearby Search lets you search for places within a specified area. \n
/// You can refine your search request by supplying keywords or specifying the type of place you are searching for.
/// </summary>
/// <param name="lnglat">The longitude/latitude around which to retrieve place information. </param>
/// <param name="radius">
/// Defines the distance (in meters) within which to return place results. \n
/// The maximum allowed radius is 50 000 meters.
/// </param>
/// <param name="key">
/// Your application's API key. \n
/// This key identifies your application for purposes of quota management and so that places added from your application are made immediately available to your app. \n
/// Visit the Google APIs Console to create an API Project and obtain your key.
/// </param>
/// <param name="keyword">A term to be matched against all content that Google has indexed for this place, including but not limited to name, type, and address, as well as customer reviews and other third-party content.</param>
/// <param name="name">
/// One or more terms to be matched against the names of places, separated with a space character. \n
/// Results will be restricted to those containing the passed name values. \n
/// Note that a place may have additional names associated with it, beyond its listed name. \n
/// The API will try to match the passed name value against all of these names. \n
/// As a result, places may be returned in the results whose listed names do not match the search term, but whose associated names do.
/// </param>
/// <param name="types">
/// Restricts the results to places matching at least one of the specified types. \n
/// Types should be separated with a pipe symbol (type1|type2|etc).\n
/// See the list of supported types:\n
/// https://developers.google.com/places/documentation/supported_types
/// </param>
/// <param name="minprice">
/// Restricts results to only those places within the specified range. \n
/// Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </param>
/// <param name="maxprice">
/// Restricts results to only those places within the specified range. \n
/// Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </param>
/// <param name="opennow">
/// Returns only those places that are open for business at the time the query is sent. \n
/// Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query.
/// </param>
/// <param name="rankBy">Specifies the order in which results are listed.</param>
/// <returns>Query instance to the Google API.</returns>
public static OnlineMapsGooglePlaces FindNearby(Vector2 lnglat, int radius, string key, string keyword = null, string name = null, string types = null, int minprice = -1, int maxprice = -1, bool opennow = false, OnlineMapsFindPlacesRankBy rankBy = OnlineMapsFindPlacesRankBy.prominence)
{
NearbyParams p = new NearbyParams(lnglat, radius)
{
keyword = keyword,
name = name,
types = types,
};
if (minprice != -1) p.minprice = minprice;
if (maxprice != -1) p.maxprice = maxprice;
if (opennow) p.opennow = true;
if (rankBy != OnlineMapsFindPlacesRankBy.prominence) p.rankBy = rankBy;
return new OnlineMapsGooglePlaces(key, p);
}
/// <summary>
/// A Nearby Search lets you search for places within a specified area. \n
/// You can refine your search request by supplying keywords or specifying the type of place you are searching for.
/// </summary>
/// <param name="key">
/// Your application's API key. \n
/// This key identifies your application for purposes of quota management and so that places added from your application are made immediately available to your app. \n
/// Visit the Google APIs Console to create an API Project and obtain your key.
/// </param>
/// <param name="p">The object containing the request parameters.</param>
/// <returns>Query instance to the Google API.</returns>
public static OnlineMapsGooglePlaces FindNearby(string key, NearbyParams p)
{
return new OnlineMapsGooglePlaces(key, p);
}
/// <summary>
/// Returns information about a set of places based on a string — for example "pizza in New York" or "shoe stores near Ottawa". \n
/// The service responds with a list of places matching the text string and any location bias that has been set. \n
/// The search response will include a list of places.
/// </summary>
/// <param name="query">
/// The text string on which to search, for example: "restaurant". \n
/// The Google Places service will return candidate matches based on this string and order the results based on their perceived relevance.
/// </param>
/// <param name="key">
/// Your application's API key. \n
/// This key identifies your application for purposes of quota management and so that places added from your application are made immediately available to your app. \n
/// Visit the Google APIs Console to create an API Project and obtain your key.
/// </param>
/// <param name="lnglat">The longitude/latitude around which to retrieve place information.</param>
/// <param name="radius">
/// Defines the distance (in meters) within which to bias place results. \n
/// The maximum allowed radius is 50 000 meters. \n
/// Results inside of this region will be ranked higher than results outside of the search circle; however, prominent results from outside of the search radius may be included.
/// </param>
/// <param name="language">The language code, indicating in which language the results should be returned, if possible. </param>
/// <param name="types">
/// Restricts the results to places matching at least one of the specified types. \n
/// Types should be separated with a pipe symbol (type1|type2|etc). \n
/// See the list of supported types:\n
/// https://developers.google.com/maps/documentation/places/supported_types
/// </param>
/// <param name="minprice">
/// Restricts results to only those places within the specified price level. \n
/// Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </param>
/// <param name="maxprice">
/// Restricts results to only those places within the specified price level. \n
/// Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </param>
/// <param name="opennow">
/// Returns only those places that are open for business at the time the query is sent. \n
/// Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query.
/// </param>
/// <returns>Query instance to the Google API.</returns>
public static OnlineMapsGooglePlaces FindText(string query, string key, Vector2 lnglat = default(Vector2), int radius = -1, string language = null, string types = null, int minprice = -1, int maxprice = -1, bool opennow = false)
{
TextParams p = new TextParams(query)
{
language = language,
types = types,
};
if (lnglat != default(Vector2)) p.lnglat = lnglat;
if (radius != -1) p.radius = radius;
if (minprice != -1) p.minprice = minprice;
if (maxprice != -1) p.maxprice = maxprice;
if (opennow) p.opennow = true;
return new OnlineMapsGooglePlaces(key, p);
}
/// <summary>
/// Returns information about a set of places based on a string — for example "pizza in New York" or "shoe stores near Ottawa". \n
/// The service responds with a list of places matching the text string and any location bias that has been set. \n
/// The search response will include a list of places.
/// </summary>
/// <param name="key">
/// Your application's API key. \n
/// This key identifies your application for purposes of quota management and so that places added from your application are made immediately available to your app. \n
/// Visit the Google APIs Console to create an API Project and obtain your key.
/// </param>
/// <param name="p">The object containing the request parameters.</param>
/// <returns>Query instance to the Google API.</returns>
public static OnlineMapsGooglePlaces FindText(string key, TextParams p)
{
return new OnlineMapsGooglePlaces(key, p);
}
/// <summary>
/// The Google Places API Radar Search Service allows you to search for up to 200 places at once, but with less detail than is typically returned from a Text Search or Nearby Search request. \n
/// With Radar Search, you can create applications that help users identify specific areas of interest within a geographic area.
/// </summary>
/// <param name="lnglat">The longitude/latitude around which to retrieve place information.</param>
/// <param name="radius">
/// Defines the distance (in meters) within which to return place results. \n
/// The maximum allowed radius is 50 000 meters.
/// </param>
/// <param name="key">
/// Your application's API key. \n
/// This key identifies your application for purposes of quota management and so that places added from your application are made immediately available to your app. \n
/// Visit the Google APIs Console to create an API Project and obtain your key.
/// </param>
/// <param name="keyword">A term to be matched against all content that Google has indexed for this place, including but not limited to name, type, and address, as well as customer reviews and other third-party content.</param>
/// <param name="name">
/// One or more terms to be matched against the names of places, separated by a space character. \n
/// Results will be restricted to those containing the passed name values. \n
/// Note that a place may have additional names associated with it, beyond its listed name. \n
/// The API will try to match the passed name value against all of these names. \n
/// As a result, places may be returned in the results whose listed names do not match the search term, but whose associated names do.
/// </param>
/// <param name="types">
/// Restricts the results to places matching at least one of the specified types. \n
/// Types should be separated with a pipe symbol (type1|type2|etc). \n
/// See the list of supported types:\n
/// https://developers.google.com/maps/documentation/places/supported_types
/// </param>
/// <param name="minprice">
/// Restricts results to only those places within the specified price level. \n
/// Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </param>
/// <param name="maxprice">
/// Restricts results to only those places within the specified price level. \n
/// Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </param>
/// <param name="opennow">
/// Returns only those places that are open for business at the time the query is sent. \n
/// Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query.
/// </param>
/// <returns>Query instance to the Google API.</returns>
public static OnlineMapsGooglePlaces FindRadar(Vector2 lnglat, int radius, string key, string keyword = null, string name = null, string types = null, int minprice = -1, int maxprice = -1, bool opennow = false)
{
RadarParams p = new RadarParams(lnglat, radius)
{
keyword = keyword,
name = name,
types = types,
};
if (minprice != -1) p.minprice = minprice;
if (maxprice != -1) p.maxprice = maxprice;
if (opennow) p.opennow = true;
return new OnlineMapsGooglePlaces(key, p);
}
/// <summary>
/// The Google Places API Radar Search Service allows you to search for up to 200 places at once, but with less detail than is typically returned from a Text Search or Nearby Search request. \n
/// With Radar Search, you can create applications that help users identify specific areas of interest within a geographic area.
/// </summary>
/// <param name="key">
/// Your application's API key. \n
/// This key identifies your application for purposes of quota management and so that places added from your application are made immediately available to your app. \n
/// Visit the Google APIs Console to create an API Project and obtain your key.
/// </param>
/// <param name="p">The object containing the request parameters.</param>
/// <returns>Query instance to the Google API.</returns>
public static OnlineMapsGooglePlaces FindRadar(string key, RadarParams p)
{
return new OnlineMapsGooglePlaces(key, p);
}
/// <summary>
/// Converts response into an array of results.
/// </summary>
/// <param name="response">Response of Google API.</param>
/// <returns>Array of result.</returns>
public static OnlineMapsGooglePlacesResult[] GetResults(string response)
{
string nextPageToken;
return GetResults(response, out nextPageToken);
}
/// <summary>
/// Converts response into an array of results.
/// </summary>
/// <param name="response">Response of Google API.</param>
/// <param name="nextPageToken">
/// Contains a token that can be used to return up to 20 additional results.\n
/// A next_page_token will not be returned if there are no additional results to display.\n
/// The maximum number of results that can be returned is 60.\n
/// There is a short delay between when a next_page_token is issued, and when it will become valid.
/// </param>
/// <returns>Array of result.</returns>
public static OnlineMapsGooglePlacesResult[] GetResults(string response, out string nextPageToken)
{
nextPageToken = null;
try
{
OnlineMapsXML xml = OnlineMapsXML.Load(response);
string status = xml.Find<string>("//status");
if (status != "OK") return null;
nextPageToken = xml.Find<string>("//next_page_token");
OnlineMapsXMLList resNodes = xml.FindAll("//result");
List<OnlineMapsGooglePlacesResult> results = new List<OnlineMapsGooglePlacesResult>(resNodes.count);
foreach (OnlineMapsXML node in resNodes) results.Add(new OnlineMapsGooglePlacesResult(node));
return results.ToArray();
}
catch (Exception exception)
{
Debug.Log(exception.Message + "\n" + exception.StackTrace);
}
return null;
}
/// <summary>
/// The base class containing the request parameters.
/// </summary>
public abstract class RequestParams
{
public abstract string typePath { get; }
public abstract void AppendParams(StringBuilder url);
}
/// <summary>
/// Request parameters for Nearby Search
/// </summary>
public class NearbyParams:RequestParams
{
/// <summary>
/// The longitude around which to retrieve place information.
/// </summary>
public double? longitude;
/// <summary>
/// The latitude around which to retrieve place information.
/// </summary>
public double? latitude;
/// <summary>
/// Defines the distance (in meters) within which to return place results. \n
/// The maximum allowed radius is 50 000 meters.
/// </summary>
public int? radius;
/// <summary>
/// A term to be matched against all content that Google has indexed for this place, including but not limited to name, type, and address, as well as customer reviews and other third-party content.
/// </summary>
public string keyword;
/// <summary>
/// One or more terms to be matched against the names of places, separated with a space character. \n
/// Results will be restricted to those containing the passed name values. \n
/// Note that a place may have additional names associated with it, beyond its listed name. \n
/// The API will try to match the passed name value against all of these names. \n
/// As a result, places may be returned in the results whose listed names do not match the search term, but whose associated names do.
/// </summary>
public string name;
/// <summary>
/// Restricts the results to places matching at least one of the specified types. \n
/// Types should be separated with a pipe symbol (type1|type2|etc).\n
/// See the list of supported types:\n
/// https://developers.google.com/places/documentation/supported_types
/// </summary>
public string types;
/// <summary>
/// Restricts results to only those places within the specified range. \n
/// Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </summary>
public int? minprice;
/// <summary>
/// Restricts results to only those places within the specified range. \n
/// Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </summary>
public int? maxprice;
/// <summary>
/// Returns only those places that are open for business at the time the query is sent. \n
/// Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query.
/// </summary>
public bool? opennow;
/// <summary>
/// Specifies the order in which results are listed.
/// </summary>
public OnlineMapsFindPlacesRankBy? rankBy;
/// <summary>
/// Returns the next 20 results from a previously run search. \n
/// Setting a pagetoken parameter will execute a search with the same parameters used previously — all parameters other than pagetoken will be ignored.
/// </summary>
public string pagetoken;
/// <summary>
/// Add this parameter (just the parameter name, with no associated value) to restrict your search to locations that are Zagat selected businesses.\n
/// This parameter must not include a true or false value. The zagatselected parameter is experimental, and is only available to Google Places API customers with a Premium Plan license.
/// </summary>
public bool? zagatselected;
/// <summary>
/// The longitude/latitude around which to retrieve place information.
/// </summary>
public Vector2 lnglat
{
get { return new Vector2((float)longitude.Value, (float)latitude.Value);}
set
{
longitude = value.x;
latitude = value.y;
}
}
public override string typePath
{
get { return "nearbysearch"; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="longitude">The longitude around which to retrieve place information.</param>
/// <param name="latitude">The latitude around which to retrieve place information.</param>
/// <param name="radius">
/// Defines the distance (in meters) within which to return place results. \n
/// The maximum allowed radius is 50 000 meters.
/// </param>
public NearbyParams(double longitude, double latitude, int radius)
{
this.longitude = longitude;
this.latitude = latitude;
this.radius = radius;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="lnglat">The longitude/latitude around which to retrieve place information.</param>
/// <param name="radius">
/// Defines the distance (in meters) within which to return place results. \n
/// The maximum allowed radius is 50 000 meters.
/// </param>
public NearbyParams(Vector2 lnglat, int radius)
{
this.lnglat = lnglat;
this.radius = radius;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="pagetoken">
/// Returns the next 20 results from a previously run search. \n
/// Setting a pagetoken parameter will execute a search with the same parameters used previously — all parameters other than pagetoken will be ignored.
/// </param>
public NearbyParams(string pagetoken)
{
this.pagetoken = pagetoken;
}
public override void AppendParams(StringBuilder url)
{
if (latitude.HasValue && longitude.HasValue) url.Append("&location=").Append(latitude.Value).Append(",").Append(longitude.Value);
if (radius.HasValue) url.Append("&radius=").Append(radius.Value);
if (!string.IsNullOrEmpty(keyword)) url.Append("&keyword=").Append(keyword);
if (!string.IsNullOrEmpty(name)) url.Append("&name=").Append(name);
if (!string.IsNullOrEmpty(types)) url.Append("&types=").Append(types);
if (minprice.HasValue) url.Append("&minprice=").Append(minprice.Value);
if (maxprice.HasValue) url.Append("&maxprice=").Append(maxprice.Value);
if (opennow.HasValue) url.Append("&opennow");
if (rankBy.HasValue) url.Append("&rankby=").Append(rankBy.Value);
if (!string.IsNullOrEmpty(pagetoken)) url.Append("&pagetoken=").Append(OnlineMapsWWW.EscapeURL(pagetoken));
if (zagatselected.HasValue && zagatselected.Value) url.Append("&zagatselected");
}
}
/// <summary>
/// Request parameters for Text Search
/// </summary>
public class TextParams : RequestParams
{
/// <summary>
/// The text string on which to search, for example: "restaurant". \n
/// The Google Places service will return candidate matches based on this string and order the results based on their perceived relevance.
/// </summary>
public string query;
/// <summary>
/// The longitude around which to retrieve place information.
/// </summary>
public double? longitude;
/// <summary>
/// The latitude around which to retrieve place information.
/// </summary>
public double? latitude;
/// <summary>
/// Defines the distance (in meters) within which to bias place results. \n
/// The maximum allowed radius is 50 000 meters. \n
/// Results inside of this region will be ranked higher than results outside of the search circle; however, prominent results from outside of the search radius may be included.
/// </summary>
public int? radius;
/// <summary>
/// The language code, indicating in which language the results should be returned, if possible.
/// </summary>
public string language;
/// <summary>
/// Restricts the results to places matching at least one of the specified types. \n
/// Types should be separated with a pipe symbol (type1|type2|etc). \n
/// See the list of supported types:\n
/// https://developers.google.com/maps/documentation/places/supported_types
/// </summary>
public string types;
/// <summary>
/// Restricts results to only those places within the specified price level. \n
/// Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </summary>
public int? minprice;
/// <summary>
/// Restricts results to only those places within the specified price level. \n
/// Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </summary>
public int? maxprice;
/// <summary>
/// Returns only those places that are open for business at the time the query is sent. \n
/// Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query.
/// </summary>
public bool? opennow;
/// <summary>
/// Returns the next 20 results from a previously run search. \n
/// Setting a pagetoken parameter will execute a search with the same parameters used previously — all parameters other than pagetoken will be ignored.
/// </summary>
public string pagetoken;
/// <summary>
/// Add this parameter (just the parameter name, with no associated value) to restrict your search to locations that are Zagat selected businesses.\n
/// This parameter must not include a true or false value. The zagatselected parameter is experimental, and is only available to Google Places API customers with a Premium Plan license.
/// </summary>
public bool? zagatselected;
/// <summary>
/// The longitude/latitude around which to retrieve place information.
/// </summary>
public Vector2 lnglat
{
get { return new Vector2((float)longitude.Value, (float)latitude.Value); }
set
{
longitude = value.x;
latitude = value.y;
}
}
public override string typePath
{
get { return "textsearch"; }
}
/// <summary>
/// Contstructor
/// </summary>
/// <param name="query">
/// The text string on which to search, for example: "restaurant". \n
/// The Google Places service will return candidate matches based on this string and order the results based on their perceived relevance.
/// </param>
public TextParams(string query)
{
this.query = query;
}
public override void AppendParams(StringBuilder url)
{
if (latitude.HasValue && longitude.HasValue) url.Append("&location=").Append(latitude.Value).Append(",").Append(longitude.Value);
if (radius.HasValue) url.Append("&radius=").Append(radius.Value);
if (!string.IsNullOrEmpty(types)) url.Append("&types=").Append(types);
if (!string.IsNullOrEmpty(query)) url.Append("&query=").Append(OnlineMapsWWW.EscapeURL(query));
if (!string.IsNullOrEmpty(language)) url.Append("&language=").Append(language);
if (minprice.HasValue) url.Append("&minprice=").Append(minprice.Value);
if (maxprice.HasValue) url.Append("&maxprice=").Append(maxprice.Value);
if (opennow.HasValue && opennow.Value) url.Append("&opennow");
if (!string.IsNullOrEmpty(pagetoken)) url.Append("&pagetoken=").Append(pagetoken);
if (zagatselected.HasValue && zagatselected.Value) url.Append("&zagatselected");
}
}
/// <summary>
/// Request parameters for Radar Search
/// </summary>
public class RadarParams : RequestParams
{
/// <summary>
/// The longitude around which to retrieve place information.
/// </summary>
public double? longitude;
/// <summary>
/// The latitude around which to retrieve place information.
/// </summary>
public double? latitude;
/// <summary>
/// Defines the distance (in meters) within which to return place results. \n
/// The maximum allowed radius is 50 000 meters.
/// </summary>
public int? radius;
/// <summary>
/// A term to be matched against all content that Google has indexed for this place, including but not limited to name, type, and address, as well as customer reviews and other third-party content.
/// </summary>
public string keyword;
/// <summary>
/// One or more terms to be matched against the names of places, separated by a space character. \n
/// Results will be restricted to those containing the passed name values. \n
/// Note that a place may have additional names associated with it, beyond its listed name. \n
/// The API will try to match the passed name value against all of these names. \n
/// As a result, places may be returned in the results whose listed names do not match the search term, but whose associated names do.
/// </summary>
public string name;
/// <summary>
/// Restricts the results to places matching at least one of the specified types. \n
/// Types should be separated with a pipe symbol (type1|type2|etc). \n
/// See the list of supported types:\n
/// https://developers.google.com/maps/documentation/places/supported_types
/// </summary>
public string types;
/// <summary>
/// Restricts results to only those places within the specified price level. \n
/// Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </summary>
public int? minprice;
/// <summary>
/// Restricts results to only those places within the specified price level. \n
/// Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive. \n
/// The exact amount indicated by a specific value will vary from region to region.
/// </summary>
public int? maxprice;
/// <summary>
/// Returns only those places that are open for business at the time the query is sent. \n
/// Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query.
/// </summary>
public bool? opennow;
/// <summary>
/// Add this parameter (just the parameter name, with no associated value) to restrict your search to locations that are Zagat selected businesses.\n
/// This parameter must not include a true or false value. The zagatselected parameter is experimental, and is only available to Google Places API customers with a Premium Plan license.
/// </summary>
public bool? zagatselected;
/// <summary>
/// The longitude/latitude around which to retrieve place information.
/// </summary>
public Vector2 lnglat
{
get { return new Vector2((float)longitude.Value, (float)latitude.Value); }
set
{
longitude = value.x;
latitude = value.y;
}
}
public override string typePath
{
get { return "radarsearch"; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="longitude">The longitude around which to retrieve place information.</param>
/// <param name="latitude">The latitude around which to retrieve place information.</param>
/// <param name="radius">
/// Defines the distance (in meters) within which to return place results. \n
/// The maximum allowed radius is 50 000 meters.
/// </param>
public RadarParams(double longitude, double latitude, int radius)
{
this.longitude = longitude;
this.latitude = latitude;
this.radius = radius;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="lnglat">The longitude/latitude around which to retrieve place information.</param>
/// <param name="radius">
/// Defines the distance (in meters) within which to return place results. \n
/// The maximum allowed radius is 50 000 meters.
/// </param>
public RadarParams(Vector2 lnglat, int radius)
{
this.lnglat = lnglat;
this.radius = radius;
}
public override void AppendParams(StringBuilder url)
{
if (latitude.HasValue && longitude.HasValue) url.Append("&location=").Append(latitude.Value).Append(",").Append(longitude.Value);
if (radius.HasValue) url.Append("&radius=").Append(radius.Value);
if (!string.IsNullOrEmpty(keyword)) url.Append("&keyword=").Append(keyword);
if (!string.IsNullOrEmpty(name)) url.Append("&name=").Append(name);
if (!string.IsNullOrEmpty(types)) url.Append("&types=").Append(types);
if (minprice.HasValue) url.Append("&minprice=").Append(minprice.Value);
if (maxprice.HasValue) url.Append("&maxprice=").Append(maxprice.Value);
if (opennow.HasValue && opennow.Value) url.Append("&opennow");
if (zagatselected.HasValue && zagatselected.Value) url.Append("&zagatselected");
}
}
/// <summary>
/// Specifies the order in which results are listed.
/// </summary>
public enum OnlineMapsFindPlacesRankBy
{
/// <summary>
/// This option sorts results based on their importance. \n
/// Ranking will favor prominent places within the specified area. \n
/// Prominence can be affected by a place's ranking in Google's index, global popularity, and other factors.
/// </summary>
prominence,
/// <summary>
/// This option sorts results in ascending order by their distance from the specified location. \n
/// When distance is specified, one or more of keyword, name, or types is required.
/// </summary>
distance
}
} | 48.962264 | 290 | 0.6436 | [
"Apache-2.0"
] | Mobinlion/Asphault | Assets/Infinity Code/Online maps/Scripts/WebServices/OnlineMapsGooglePlaces.cs | 36,362 | C# |
/*
* Copyright (c) 2014, Furore (info@furore.com) and contributors
* See the file CONTRIBUTORS for details.
*
* This file is licensed under the BSD 3-Clause license
* available at https://raw.githubusercontent.com/ewoutkramer/fhir-net-api/master/LICENSE
*/
using Hl7.Fhir.Introspection;
using Hl7.Fhir.Model;
using Hl7.Fhir.Support;
using System;
using System.Collections;
using System.Linq;
namespace Hl7.Fhir.Serialization
{
internal class ComplexTypeWriter
{
private IFhirWriter _writer;
private ModelInspector _inspector;
internal enum SerializationMode
{
AllMembers,
ValueElement,
NonValueElements
}
public ComplexTypeWriter(IFhirWriter writer)
{
_writer = writer;
_inspector = SerializationConfig.Inspector;
}
internal void Serialize(ClassMapping mapping, object instance, bool summary, SerializationMode mode = SerializationMode.AllMembers)
{
if (mapping == null) throw Error.ArgumentNull("mapping");
_writer.WriteStartComplexContent();
// Emit members that need xml /attributes/ first (to facilitate stream writer API)
foreach (var prop in mapping.PropertyMappings.Where(pm => pm.SerializationHint == XmlSerializationHint.Attribute))
if(!summary || prop.InSummary || instance is Bundle || prop.Name == "id") write(mapping, instance, summary, prop, mode);
// Then emit the rest
foreach (var prop in mapping.PropertyMappings.Where(pm => pm.SerializationHint != XmlSerializationHint.Attribute))
if (!summary || prop.InSummary || instance is Bundle || prop.Name == "id") write(mapping, instance, summary, prop, mode);
_writer.WriteEndComplexContent();
}
private void write(ClassMapping mapping, object instance, bool summary, PropertyMapping prop, SerializationMode mode)
{
// Check whether we are asked to just serialize the value element (Value members of primitive Fhir datatypes)
// or only the other members (Extension, Id etc in primitive Fhir datatypes)
// Default is all
if (mode == SerializationMode.ValueElement && !prop.RepresentsValueElement) return;
if (mode == SerializationMode.NonValueElements && prop.RepresentsValueElement) return;
var value = prop.GetValue(instance);
var isEmptyArray = (value as IList) != null && ((IList)value).Count == 0;
// Message.Info("Handling member {0}.{1}", mapping.Name, prop.Name);
if (value != null && !isEmptyArray)
{
string memberName = prop.Name;
// For Choice properties, determine the actual name of the element
// by appending its type to the base property name (i.e. deceasedBoolean, deceasedDate)
if (prop.Choice == ChoiceType.DatatypeChoice)
{
memberName = determineElementMemberName(prop.Name, GetSerializationTypeForDataTypeChoiceElements(prop, value));
}
_writer.WriteStartProperty(memberName);
var writer = new DispatchingWriter(_writer);
// Now, if our writer does not use dual properties for primitive values + rest (xml),
// or this is a complex property without value element, serialize data normally
if (!_writer.HasValueElementSupport || !serializedIntoTwoProperties(prop, value))
{
writer.Serialize(prop, value, summary, SerializationMode.AllMembers);
}
else
{
// else split up between two properties, name and _name
writer.Serialize(prop, value, summary, SerializationMode.ValueElement);
_writer.WriteEndProperty();
_writer.WriteStartProperty("_" + memberName);
if (!isFhirPrimitive(value))
{
writer.Serialize(prop, value, summary, SerializationMode.NonValueElements);
}
}
_writer.WriteEndProperty();
}
}
private Type GetSerializationTypeForDataTypeChoiceElements( PropertyMapping prop, object value)
{
Type serializationType = value.GetType();
if (!prop.IsPrimitive && false)
{
#if PORTABLE45
Type baseType = serializationType.GetTypeInfo().BaseType;
while (baseType != typeof(Element) && baseType != typeof(object))
{
serializationType = baseType;
baseType = baseType.GetTypeInfo().BaseType;
}
#else
Type baseType = serializationType.BaseType;
while (baseType != typeof(Element) && baseType != typeof(object))
{
serializationType = baseType;
baseType = baseType.BaseType;
}
#endif
}
return serializationType;
}
// If we have a normal complex property, for which the type has a primitive value member...
private bool serializedIntoTwoProperties(PropertyMapping prop, object instance)
{
if (instance is IList)
instance = ((IList)instance)[0];
if (!prop.IsPrimitive && prop.Choice != ChoiceType.ResourceChoice)
{
var mapping = _inspector.ImportType(instance.GetType());
return mapping.HasPrimitiveValueMember;
}
else
return false;
}
private bool isFhirPrimitive(object instance)
{
if (instance is IList)
instance = ((IList) instance)[0];
Type type = instance.GetType();
if(type == typeof(FhirString) ||
type == typeof(FhirBoolean) ||
type == typeof(FhirDateTime) ||
type == typeof(FhirDecimal))
return true;
return false;
}
private static string upperCamel(string p)
{
if (p == null) return p;
var c = p[0];
return Char.ToUpperInvariant(c) + p.Remove(0, 1);
}
private string determineElementMemberName(string memberName, Type type)
{
var mapping = _inspector.ImportType(type);
var suffix = mapping.Name;
return memberName + upperCamel(suffix);
}
}
}
| 37.458101 | 139 | 0.580313 | [
"BSD-3-Clause"
] | bnantz/fhir-net-api | src/Hl7.Fhir.Core/Serialization/ComplexTypeWriter.cs | 6,707 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Threading;
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
public class CallbackStressTest
{
static int s_LoopCounter = 10;
static int s_FinallyCalled = 0;
static int s_CatchCalled = 0;
static int s_OtherExceptionCatchCalled = 0;
static int s_SEHExceptionCatchCalled = 0;
static int s_WrongPInvokesExecuted = 0;
static int s_PInvokesExecuted = 0;
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SetResolve()
{
Console.WriteLine("Setting PInvoke Resolver");
DllImportResolver resolver =
(string libraryName, Assembly asm, DllImportSearchPath? dllImportSearchPath) =>
{
if (string.Equals(libraryName, NativeLibraryToLoad.InvalidName))
{
if (dllImportSearchPath != DllImportSearchPath.System32)
{
Console.WriteLine($"Unexpected dllImportSearchPath: {dllImportSearchPath.ToString()}");
throw new ArgumentException();
}
return NativeLibrary.Load(NativeLibraryToLoad.Name, asm, null);
}
return IntPtr.Zero;
};
NativeLibrary.SetDllImportResolver(
Assembly.GetExecutingAssembly(),
resolver);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void DoCall()
{
NativeSum(10, 10);
s_WrongPInvokesExecuted++;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void DoCallTryCatch(bool shouldThrow)
{
try
{
var a = NativeSum(10, 10);
if (shouldThrow)
s_WrongPInvokesExecuted++;
else
s_PInvokesExecuted += (a == 20 ? 1 : 0);
}
catch (DllNotFoundException) { s_CatchCalled++; }
throw new ArgumentException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void DoCallTryRethrowInCatch()
{
try
{
var a = NativeSum(10, 10);
s_WrongPInvokesExecuted++;
}
catch (DllNotFoundException) { s_CatchCalled++; throw; }
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void DoCallTryRethrowDifferentExceptionInCatch()
{
try
{
var a = NativeSum(10, 10);
s_WrongPInvokesExecuted++;
}
catch (DllNotFoundException) { s_CatchCalled++; throw new InvalidOperationException(); }
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void DoCallTryFinally()
{
try
{
NativeSum(10, 10);
s_WrongPInvokesExecuted++;
}
finally { s_FinallyCalled++; }
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ManualRaiseException()
{
#if WINDOWS
try
{
RaiseException(5, 0, 0, IntPtr.Zero);
}
catch(SEHException ex) { GC.Collect(); s_SEHExceptionCatchCalled++; }
#else
// TODO: test on Unix when implementing pinvoke inlining
s_SEHExceptionCatchCalled++;
#endif
}
public static int Main()
{
for(int i = 0; i < s_LoopCounter; i++)
{
try
{
NativeSum(10, 10);
s_WrongPInvokesExecuted++;
}
catch (DllNotFoundException) { GC.Collect(); s_CatchCalled++; }
try { DoCall(); }
catch (DllNotFoundException) { GC.Collect(); s_CatchCalled++; }
try { DoCallTryFinally(); }
catch (DllNotFoundException) { GC.Collect(); s_CatchCalled++; }
try { DoCallTryCatch(true); }
catch (ArgumentException) { GC.Collect(); s_OtherExceptionCatchCalled++; }
try { DoCallTryRethrowInCatch(); }
catch (DllNotFoundException) { GC.Collect(); s_CatchCalled++; }
try { DoCallTryRethrowDifferentExceptionInCatch(); }
catch (InvalidOperationException) { GC.Collect(); s_OtherExceptionCatchCalled++; }
ManualRaiseException();
}
SetResolve();
for(int i = 0; i < s_LoopCounter; i++)
{
var a = NativeSum(10, 10);
var b = NativeSum(10, 10);
s_PInvokesExecuted += (a == b && a == 20)? 2 : 0;
try { DoCallTryCatch(false); }
catch (ArgumentException) { GC.Collect(); s_OtherExceptionCatchCalled++; }
ManualRaiseException();
}
if (s_FinallyCalled == s_LoopCounter &&
s_CatchCalled == (s_LoopCounter * 7) &&
s_OtherExceptionCatchCalled == (s_LoopCounter * 3) &&
s_WrongPInvokesExecuted == 0 &&
s_PInvokesExecuted == (s_LoopCounter * 3) &&
s_SEHExceptionCatchCalled == (s_LoopCounter * 2))
{
Console.WriteLine("PASS");
return 100;
}
Console.WriteLine("s_FinallyCalled = " + s_FinallyCalled);
Console.WriteLine("s_CatchCalled = " + s_CatchCalled);
Console.WriteLine("s_OtherExceptionCatchCalled = " + s_OtherExceptionCatchCalled);
Console.WriteLine("s_SEHExceptionCatchCalled = " + s_SEHExceptionCatchCalled);
Console.WriteLine("s_WrongPInvokesExecuted = " + s_WrongPInvokesExecuted);
Console.WriteLine("s_PInvokesExecuted = " + s_PInvokesExecuted);
return -1;
}
[DllImport(NativeLibraryToLoad.InvalidName)]
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
static extern int NativeSum(int arg1, int arg2);
#if WINDOWS
[DllImport("kernel32")]
static extern void RaiseException(uint dwExceptionCode, uint dwExceptionFlags, uint nNumberOfArguments, IntPtr lpArguments);
#endif
}
| 32.093264 | 128 | 0.608815 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/Interop/NativeLibrary/Callback/CallbackStressTest.cs | 6,194 | C# |
function cc_js_t(s) {
if (s == "Brazil") { return "Brazil"; }
if (s == "Canada") { return "Canada"; }
if (s == "Italy") { return "Italy"; }
if (s == "Creative Commons") { return "Creative Commons"; }
if (s == "Serbia") { return "Serbia"; }
if (s == "Malta") { return "Malta"; }
if (s == "France") { return "France"; }
if (s == "Peru") { return "Peru"; }
if (s == "Argentina") { return "Argentina"; }
if (s == "Norway") { return "Norsko"; }
if (s == "New Zealand") { return "Nový Zéland"; }
if (s == "Ecuador") { return "Ecuador"; }
if (s == "Czech Republic") { return "Česko"; }
if (s == "Israel") { return "Israel"; }
if (s == "Australia") { return "Australia"; }
if (s == "Korea") { return "Korea"; }
if (s == "Singapore") { return "Singapore"; }
if (s == "Thailand") { return "Thailand"; }
if (s == "South Africa") { return "South Africa"; }
if (s == "We have updated the version of your license to the most recent one available.") { return "We have updated the version of your license to the most recent one available."; }
if (s == "Slovenia") { return "Slovenia"; }
if (s == "Guatemala") { return "Guatemala"; }
if (s == "The licensor permits others to copy, distribute and transmit the work. In return, licensees may not use the work for commercial purposes — unless they get the licensor's permission.") { return "Poskytovatel licence souhlasí s tím, aby ostatní kopírovali, šířili, zobrazovali a užívali jeho dílo, ale pro komerční účely - pokud k tomu nezískají svolení přímo od poskytovatele licence,"; }
if (s == "Noncommercial") { return "Neužívejte dílo komerčně"; }
if (s == "Puerto Rico") { return "Puerto Rico"; }
if (s == "Belgium") { return "Belgium"; }
if (s == "Germany") { return "Germany"; }
if (s == "We have updated the version of your license to the most recent one available in your jurisdiction.") { return "We have updated the version of your license to the most recent one available in your jurisdiction."; }
if (s == "Hong Kong") { return "Hong Kong"; }
if (s == "Poland") { return "Poland"; }
if (s == "Spain") { return "Spain"; }
if (s == "This ${work_type} is licensed under a <a rel=\"license\" href=\"${license_url}\">Creative Commons ${license_name} License</a>.") { return "Uvedená práce (${work_type}) podléhá licenci <a rel=\"license\" href=\"${license_url}\">Creative Commons ${license_name}</a>"; }
if (s == "Remix") { return "Remix"; }
if (s == "Netherlands") { return "Netherlands"; }
if (s == "UK: England & Wales") { return "UK: England & Wales"; }
if (s == "Chile") { return "Chile"; }
if (s == "Unported") { return "Unported"; }
if (s == "Denmark") { return "Denmark"; }
if (s == "Philippines") { return "Philippines"; }
if (s == "Finland") { return "Finland"; }
if (s == "Macedonia") { return "Macedonia"; }
if (s == "United States") { return "United States"; }
if (s == "Sweden") { return "Sweden"; }
if (s == "No license chosen") { return "No license chosen"; }
if (s == "Croatia") { return "Croatia"; }
if (s == "Luxembourg") { return "Luxembourg"; }
if (s == "Japan") { return "Japan"; }
if (s == "Switzerland") { return "Switzerland"; }
if (s == "UK: Scotland") { return "UK: Scotland"; }
if (s == "With a Creative Commons license, you keep your copyright but allow people to copy and distribute your work provided they give you credit — and only on the conditions you specify here.") { return "With a Creative Commons license, you keep your copyright but allow people to copy and distribute your work provided they give you credit — and only on the conditions you specify here."; }
if (s == "Taiwan") { return "Taiwan"; }
if (s == "If you desire a license governed by the Copyright Law of a specific jurisdiction, please select the appropriate jurisdiction.") { return "Pokud si přejete, aby licence byla v souladu s právním řádem upravujícím autorské právo v dané zemi, vyberte požadovaný stát. "; }
if (s == "Bulgaria") { return "Bulgaria"; }
if (s == "Romania") { return "Romania"; }
if (s == "Licensor permits others to make derivative works") { return "Držitel licence dovoluje ostatním vytvářet odvozená díla. "; }
if (s == "Portugal") { return "Portugal"; }
if (s == "Mexico") { return "Mexico"; }
if (s == "work") { return "dílo"; }
if (s == "India") { return "India"; }
if (s == "China Mainland") { return "China Mainland"; }
if (s == "Malaysia") { return "Malaysia"; }
if (s == "Austria") { return "Austria"; }
if (s == "Colombia") { return "Colombia"; }
if (s == "Greece") { return "Řecko"; }
if (s == "Hungary") { return "Hungary"; }
if (s == "Share Alike") { return "Zachovejte licenci"; }
if (s == "The licensor permits others to distribute derivative works only under the same license or one compatible with the one that governs the licensor's work.") { return "Poskytovatel licence souhlasí s tím, aby ostatní šířili dílo odvozené z jeho díla, ale pouze v případě, že tak budou činit pod stejnou nebo podobnou licencí."; }
alert("Falling off the end.");
return s;
} | 71.450704 | 399 | 0.635916 | [
"MIT"
] | cc-archive/labs | docs/demos/jswidget/trunk/cc-translations.js.cs | 5,146 | C# |
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace VismaTwitter
{
public static class FindLink
{
public static string Find(string text)
{
foreach (Match item in Regex.Matches(text, @"(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"))
{
text= text.Replace(item.Value,"<A HREF='" + item.Value + "' TARGET='_new'>" + item.Value + "</A>");
// Console.WriteLine(item.Value);
}
return text;
}
}
} | 26.727273 | 157 | 0.494898 | [
"MIT"
] | viidarhagen/VismaTwitter | src/LinkFinder.cs | 590 | C# |
using System.Collections.Generic;
using System.Collections.Immutable;
using Panther.CodeAnalysis.Syntax;
namespace Panther.CodeAnalysis.CSharp
{
internal class ExpressionFlattener : SyntaxVisitor<SyntaxNode>
{
protected readonly List<StatementSyntax> _statements = new List<StatementSyntax>();
private ExpressionFlattener()
{
}
protected override SyntaxNode DefaultVisit(SyntaxNode node)
{
return node;
}
public static (ImmutableArray<StatementSyntax> statments, ExpressionSyntax expression) Flatten(ExpressionSyntax node)
{
var visitor = new ExpressionFlattener();
var expression = (ExpressionSyntax)node.Accept(visitor);
return (visitor._statements.ToImmutableArray(), expression);
}
public override SyntaxNode VisitBlockExpression(BlockExpressionSyntax node)
{
foreach (var statement in node.Statements)
{
statement.Accept(this);
}
return node.Expression.Accept(this);
}
public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node)
{
var result = (ExpressionStatementSyntax)base.VisitExpressionStatement(node);
if(result.Expression.Kind != SyntaxKind.UnitExpression)
{
_statements.Add(result);
}
return result;
}
public override SyntaxNode VisitVariableDeclarationStatement(VariableDeclarationStatementSyntax node)
{
var result = (StatementSyntax)base.VisitVariableDeclarationStatement(node);
_statements.Add(result);
return result;
}
}
} | 32.036364 | 125 | 0.643587 | [
"MIT"
] | kthompson/panther | src/Panther/CodeAnalysis/CSharp/ExpressionFlattener.cs | 1,764 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
namespace King_of_Thieves.Actors.Effects
{
class CThunder : CActor
{
public CThunder()
{
swapImage("thunder");
}
protected override void _initializeResources()
{
base._initializeResources();
_imageIndex.Add("thunder", new Graphics.CSprite("effects:Thunder", Graphics.CTextures.textures["effects:Thunder"]));
}
public override void init(string name, Vector2 position, string dataType, int compAddress, params string[] additional)
{
base.init(name, position, dataType, compAddress, additional);
_followRoot = true;
}
public override void drawMe(bool useOverlay = false)
{
base.drawMe();
}
protected override void applyEffects()
{
}
public override void destroy(object sender)
{
}
}
}
| 23.311111 | 128 | 0.593899 | [
"MIT"
] | MGZero/king-of-thieves-mono | King of Thieves/Actors/Effects/CThunder.cs | 1,051 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Palaso.Email;
using Palaso.Reporting;
using Palaso.UI.WindowsForms.Keyboarding;
namespace EmailTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "hello");
}
private void button2_Click(object sender, EventArgs e)
{
ErrorReport.ReportNonFatalException(new Exception("test"));
}
private void button3_Click(object sender, EventArgs e)
{
Logger.Init();
Logger.WriteEvent("testing");
ErrorReport.ReportFatalException(new Exception("test"));
}
private void _keyman7TestBox_Enter(object sender, EventArgs e)
{
string name = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7)[0].Name;
KeyboardController.ActivateKeyboard(name);
}
private void _keyman6TestBox_Enter(object sender, EventArgs e)
{
if(KeyboardController.EngineAvailable(KeyboardController.Engines.Keyman6))
{
string name = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman6)[0].Name;
KeyboardController.ActivateKeyboard(name);
}
MessageBox.Show("keyman 6 not available");
}
private void OnExceptionWithPolicyClick(object sender, EventArgs e)
{
try
{
throw new Exception("hello");
}
catch (Exception exception)
{
ErrorReport.ReportNonFatalException(exception, new ShowOncePerSessionBasedOnExactMessagePolicy() );
}
}
private void OnNonFatalMessageWithStack(object sender, EventArgs e)
{
ErrorReport.ReportNonFatalMessageWithStackTrace("{0} {1}", "hello","there");
}
private void button6_Click(object sender, EventArgs e)
{
IEmailProvider emailProvider = Palaso.Email.EmailProviderFactory.PreferredEmailProvider();
IEmailMessage message = emailProvider.CreateMessage();
message.To.Add("nowhere@example.com");
message.AttachmentFilePath.Add("/etc/hosts");
message.Subject = "Test Message";
message.Body = "Just a test message.\nWith more than one\nor two lines";
message.Send(emailProvider);
}
private void WritingSystemPickerButton_Click(object sender, EventArgs e)
{
}
private void button7_Click(object sender, EventArgs e)
{
Palaso.Reporting.ErrorReport.NotifyUserOfProblem(@"
x
x
x
x
x
x
x
x
x
x
x
x
x
xx
x
x
x
the end.");
}
private void _probWithExitButton_Click(object sender, EventArgs e)
{
Palaso.Reporting.ErrorReport.NotifyUserOfProblem(new ShowAlwaysPolicy(), "Foobar", DialogResult.No,
"Notice, you can click Foobar.");
}
}
} | 24.068966 | 103 | 0.746777 | [
"MIT"
] | JohnThomson/libpalaso | TestApps/EmailTest/Form1.cs | 2,792 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace AlibabaCloud.SDK.ROS.CDK.Ess
{
#pragma warning disable CS8618
/// <summary>Properties for defining a `ALIYUN::ESS::LifecycleHook`.</summary>
[JsiiByValue(fqn: "@alicloud/ros-cdk-ess.LifecycleHookProps")]
public class LifecycleHookProps : AlibabaCloud.SDK.ROS.CDK.Ess.ILifecycleHookProps
{
/// <summary>Property lifecycleTransition: The scaling activities to which lifecycle hooks apply Value range: SCALE_OUT: scale-out event SCALE_IN: scale-in event.</summary>
[JsiiProperty(name: "lifecycleTransition", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public object LifecycleTransition
{
get;
set;
}
/// <summary>Property scalingGroupId: The ID of the scaling group.</summary>
[JsiiProperty(name: "scalingGroupId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public object ScalingGroupId
{
get;
set;
}
/// <summary>Property defaultResult: The action that the scaling group takes when the lifecycle hook times out.</summary>
/// <remarks>
/// Value range:
/// CONTINUE: the scaling group continues with the scale-in or scale-out process.
/// ABANDON: the scaling group stops any remaining action of the scale-in or scale-out event.
/// Default value: CONTINUE
/// If the scaling group has multiple lifecycle hooks and one of them is terminated by the DefaultResult=ABANDON parameter during a scale-in event (SCALE_IN), the remaining lifecycle hooks under the same scaling group will also be terminated. Otherwise, the action following the wait state is the next action, as specified in the parameter DefaultResult, after the last lifecycle event under the same scaling group.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "defaultResult", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? DefaultResult
{
get;
set;
}
/// <summary>Property heartbeatTimeout: The time, in seconds, that can elapse before the lifecycle hook times out.</summary>
/// <remarks>
/// If the lifecycle hook times out, the scaling group performs the default action (DefaultResult). The range is from 30 to 21,600 seconds. The default value is 600 seconds.
/// You can prevent the lifecycle hook from timing out by calling the RecordLifecycleActionHeartbeat operation. You can also terminate the lifecycle action by calling the CompleteLifecycleAction operation.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "heartbeatTimeout", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? HeartbeatTimeout
{
get;
set;
}
/// <summary>Property lifecycleHookName: The name of the lifecycle hook.</summary>
/// <remarks>
/// Each name must be unique within a scaling group. The name must be 2 to 64 characters in length and can contain letters, numbers, Chinese characters, and special characters including underscores (_), hyphens (-) and periods (.).
/// Default value: Lifecycle Hook ID
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "lifecycleHookName", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? LifecycleHookName
{
get;
set;
}
/// <summary>Property notificationArn: The Alibaba Cloud Resource Name (ARN) of the notification target that Auto Scaling will use to notify you when an instance is in the transition state for the lifecycle hook.</summary>
/// <remarks>
/// This target can be either an MNS queue or an MNS topic. The format of the parameter value is acs:ess:{region}:{account-id}:{resource-relative-id}.
/// region: the region to which the scaling group locates
/// account-id: Alibaba Cloud ID
/// For example:
/// MNS queue: acs:ess:{region}:{account-id}:queue/{queuename}
/// MNS topic: acs:ess:{region}:{account-id}:topic/{topicname}
/// OOS template: acs:ess:{region}:{account-id}:oos/{templatename}
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "notificationArn", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? NotificationArn
{
get;
set;
}
/// <summary>Property notificationMetadata: The fixed string that you want to include when Auto Scaling sends a message about the wait state of the scaling activity to the notification target.</summary>
/// <remarks>
/// The length of the parameter can be up to 4096 characters. Auto Scaling will send the specified NotificationMetadata parameter along with the notification message so that you can easily categorize your notifications. The NotificationMetadata parameter will only take effect after you specify the NotificationArn parameter.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "notificationMetadata", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? NotificationMetadata
{
get;
set;
}
}
}
| 58.029412 | 423 | 0.647745 | [
"Apache-2.0"
] | piotr-kalanski/Resource-Orchestration-Service-Cloud-Development-Kit | multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Ess/AlibabaCloud/SDK/ROS/CDK/Ess/LifecycleHookProps.cs | 5,919 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Internal.Runtime.CompilerServices;
namespace System
{
// The String class represents a static string of characters. Many of
// the string methods perform some type of transformation on the current
// instance and return the result as a new string. As with arrays, character
// positions (indices) are zero-based.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed partial class String : IComparable, IEnumerable, IConvertible, IEnumerable<char>, IComparable<string>, IEquatable<string>, ICloneable
{
// String constructors
// These are special. The implementation methods for these have a different signature from the
// declared constructors.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char[] value);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private string Ctor(char[] value)
{
if (value == null || value.Length == 0)
return Empty;
string result = FastAllocateString(value.Length);
unsafe
{
fixed (char* dest = &result._firstChar, source = value)
wstrcpy(dest, source, value.Length);
}
return result;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char[] value, int startIndex, int length);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private string Ctor(char[] value, int startIndex, int length)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (startIndex > value.Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length == 0)
return Empty;
string result = FastAllocateString(length);
unsafe
{
fixed (char* dest = &result._firstChar, source = value)
wstrcpy(dest, source + startIndex, length);
}
return result;
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern unsafe String(char* value);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(char* ptr)
{
if (ptr == null)
return Empty;
int count = wcslen(ptr);
if (count == 0)
return Empty;
string result = FastAllocateString(count);
fixed (char* dest = &result._firstChar)
wstrcpy(dest, ptr, count);
return result;
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern unsafe String(char* value, int startIndex, int length);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(char* ptr, int startIndex, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
char* pStart = ptr + startIndex;
// overflow check
if (pStart < ptr)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
if (length == 0)
return Empty;
if (ptr == null)
throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR);
string result = FastAllocateString(length);
fixed (char* dest = &result._firstChar)
wstrcpy(dest, pStart, length);
return result;
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe String(sbyte* value);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(sbyte* value)
{
byte* pb = (byte*)value;
if (pb == null)
return Empty;
int numBytes = strlen((byte*)value);
return CreateStringForSByteConstructor(pb, numBytes);
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe String(sbyte* value, int startIndex, int length);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(sbyte* value, int startIndex, int length)
{
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (value == null)
{
if (length == 0)
return Empty;
throw new ArgumentNullException(nameof(value));
}
byte* pStart = (byte*)(value + startIndex);
// overflow check
if (pStart < value)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_PartialWCHAR);
return CreateStringForSByteConstructor(pStart, length);
}
// Encoder for String..ctor(sbyte*) and String..ctor(sbyte*, int, int)
private static unsafe string CreateStringForSByteConstructor(byte *pb, int numBytes)
{
Debug.Assert(numBytes >= 0);
Debug.Assert(pb <= (pb + numBytes));
if (numBytes == 0)
return Empty;
#if PLATFORM_WINDOWS
int numCharsRequired = Interop.Kernel32.MultiByteToWideChar(Interop.Kernel32.CP_ACP, Interop.Kernel32.MB_PRECOMPOSED, pb, numBytes, (char*)null, 0);
if (numCharsRequired == 0)
throw new ArgumentException(SR.Arg_InvalidANSIString);
string newString = FastAllocateString(numCharsRequired);
fixed (char *pFirstChar = &newString._firstChar)
{
numCharsRequired = Interop.Kernel32.MultiByteToWideChar(Interop.Kernel32.CP_ACP, Interop.Kernel32.MB_PRECOMPOSED, pb, numBytes, pFirstChar, numCharsRequired);
}
if (numCharsRequired == 0)
throw new ArgumentException(SR.Arg_InvalidANSIString);
return newString;
#else
return Encoding.UTF8.GetString(pb, numBytes);
#endif
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe String(sbyte* value, int startIndex, int length, Encoding enc);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(sbyte* value, int startIndex, int length, Encoding enc)
{
if (enc == null)
return new string(value, startIndex, length);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (value == null)
{
if (length == 0)
return Empty;
throw new ArgumentNullException(nameof(value));
}
byte* pStart = (byte*)(value + startIndex);
// overflow check
if (pStart < value)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
return enc.GetString(new ReadOnlySpan<byte>(pStart, length));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char c, int count);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private string Ctor(char c, int count)
{
if (count <= 0)
{
if (count == 0)
return Empty;
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
}
string result = FastAllocateString(count);
if (c != '\0') // Fast path null char string
{
unsafe
{
fixed (char* dest = &result._firstChar)
{
uint cc = (uint)((c << 16) | c);
uint* dmem = (uint*)dest;
if (count >= 4)
{
count -= 4;
do
{
dmem[0] = cc;
dmem[1] = cc;
dmem += 2;
count -= 4;
} while (count >= 0);
}
if ((count & 2) != 0)
{
*dmem = cc;
dmem++;
}
if ((count & 1) != 0)
((char*)dmem)[0] = c;
}
}
}
return result;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(ReadOnlySpan<char> value);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(ReadOnlySpan<char> value)
{
if (value.Length == 0)
return Empty;
string result = FastAllocateString(value.Length);
fixed (char* dest = &result._firstChar, src = &MemoryMarshal.GetReference(value))
wstrcpy(dest, src, value.Length);
return result;
}
public static string Create<TState>(int length, TState state, SpanAction<char, TState> action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
if (length <= 0)
{
if (length == 0)
return Empty;
throw new ArgumentOutOfRangeException(nameof(length));
}
string result = FastAllocateString(length);
action(new Span<char>(ref result.GetRawStringData(), length), state);
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator ReadOnlySpan<char>(string value) =>
value != null ? new ReadOnlySpan<char>(ref value.GetRawStringData(), value.Length) : default;
public object Clone()
{
return this;
}
public static unsafe string Copy(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
string result = FastAllocateString(str.Length);
fixed (char* dest = &result._firstChar, src = &str._firstChar)
wstrcpy(dest, src, str.Length);
return result;
}
// Converts a substring of this string to an array of characters. Copies the
// characters of this string beginning at position sourceIndex and ending at
// sourceIndex + count - 1 to the character array buffer, beginning
// at destinationIndex.
//
public unsafe void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
if (count > Length - sourceIndex)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexCount);
if (destinationIndex > destination.Length - count || destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount);
fixed (char* src = &_firstChar, dest = destination)
wstrcpy(dest + destinationIndex, src + sourceIndex, count);
}
// Returns the entire string as an array of characters.
public unsafe char[] ToCharArray()
{
if (Length == 0)
return Array.Empty<char>();
char[] chars = new char[Length];
fixed (char* src = &_firstChar, dest = &chars[0])
wstrcpy(dest, src, Length);
return chars;
}
// Returns a substring of this string as an array of characters.
//
public unsafe char[] ToCharArray(int startIndex, int length)
{
// Range check everything.
if (startIndex < 0 || startIndex > Length || startIndex > Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length <= 0)
{
if (length == 0)
return Array.Empty<char>();
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
}
char[] chars = new char[length];
fixed (char* src = &_firstChar, dest = &chars[0])
wstrcpy(dest, src + startIndex, length);
return chars;
}
[NonVersionable]
public static bool IsNullOrEmpty(string value)
{
// Using 0u >= (uint)value.Length rather than
// value.Length == 0 as it will elide the bounds check to
// the first char: value[0] if that is performed following the test
// for the same test cost.
// Ternary operator returning true/false prevents redundant asm generation:
// https://github.com/dotnet/coreclr/issues/914
return (value == null || 0u >= (uint)value.Length) ? true : false;
}
[System.Runtime.CompilerServices.IndexerName("Chars")]
public char this[Index index]
{
get
{
int actualIndex = index.GetOffset(Length);
return this[actualIndex];
}
}
[System.Runtime.CompilerServices.IndexerName("Chars")]
public string this[Range range] => Substring(range);
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null) return true;
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i])) return false;
}
return true;
}
internal ref char GetRawStringData() => ref _firstChar;
// Helper for encodings so they can talk to our buffer directly
// stringLength must be the exact size we'll expect
internal static unsafe string CreateStringFromEncoding(
byte* bytes, int byteLength, Encoding encoding)
{
Debug.Assert(bytes != null);
Debug.Assert(byteLength >= 0);
// Get our string length
int stringLength = encoding.GetCharCount(bytes, byteLength);
Debug.Assert(stringLength >= 0, "stringLength >= 0");
// They gave us an empty string if they needed one
// 0 bytelength might be possible if there's something in an encoder
if (stringLength == 0)
return Empty;
string s = FastAllocateString(stringLength);
fixed (char* pTempChars = &s._firstChar)
{
int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength);
Debug.Assert(stringLength == doubleCheck,
"Expected encoding.GetChars to return same length as encoding.GetCharCount");
}
return s;
}
// This is only intended to be used by char.ToString.
// It is necessary to put the code in this class instead of Char, since _firstChar is a private member.
// Making _firstChar internal would be dangerous since it would make it much easier to break String's immutability.
internal static string CreateFromChar(char c)
{
string result = FastAllocateString(1);
result._firstChar = c;
return result;
}
internal static string CreateFromChar(char c1, char c2)
{
string result = FastAllocateString(2);
result._firstChar = c1;
Unsafe.Add(ref result._firstChar, 1) = c2;
return result;
}
internal static unsafe void wstrcpy(char* dmem, char* smem, int charCount)
{
Buffer.Memmove((byte*)dmem, (byte*)smem, ((uint)charCount) * 2);
}
// Returns this string.
public override string ToString()
{
return this;
}
// Returns this string.
public string ToString(IFormatProvider provider)
{
return this;
}
public CharEnumerator GetEnumerator()
{
return new CharEnumerator(this);
}
IEnumerator<char> IEnumerable<char>.GetEnumerator()
{
return new CharEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new CharEnumerator(this);
}
/// <summary>
/// Returns an enumeration of <see cref="Rune"/> from this string.
/// </summary>
/// <remarks>
/// Invalid sequences will be represented in the enumeration by <see cref="Rune.ReplacementChar"/>.
/// </remarks>
public StringRuneEnumerator EnumerateRunes()
{
return new StringRuneEnumerator(this);
}
internal static unsafe int wcslen(char* ptr)
{
char* end = ptr;
// First make sure our pointer is aligned on a word boundary
int alignment = IntPtr.Size - 1;
// If ptr is at an odd address (e.g. 0x5), this loop will simply iterate all the way
while (((uint)end & (uint)alignment) != 0)
{
if (*end == 0) goto FoundZero;
end++;
}
#if !BIT64
// The following code is (somewhat surprisingly!) significantly faster than a naive loop,
// at least on x86 and the current jit.
// The loop condition below works because if "end[0] & end[1]" is non-zero, that means
// neither operand can have been zero. If is zero, we have to look at the operands individually,
// but we hope this going to fairly rare.
// In general, it would be incorrect to access end[1] if we haven't made sure
// end[0] is non-zero. However, we know the ptr has been aligned by the loop above
// so end[0] and end[1] must be in the same word (and therefore page), so they're either both accessible, or both not.
while ((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0))
{
end += 2;
}
Debug.Assert(end[0] == 0 || end[1] == 0);
if (end[0] != 0) end++;
#else // !BIT64
// Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
// 64-bit implementation: process 1 ulong (word) at a time
// What we do here is add 0x7fff from each of the
// 4 individual chars within the ulong, using MagicMask.
// If the char > 0 and < 0x8001, it will have its high bit set.
// We then OR with MagicMask, to set all the other bits.
// This will result in all bits set (ulong.MaxValue) for any
// char that fits the above criteria, and something else otherwise.
// Note that for any char > 0x8000, this will be a false
// positive and we will fallback to the slow path and
// check each char individually. This is OK though, since
// we optimize for the common case (ASCII chars, which are < 0x80).
// NOTE: We can access a ulong a time since the ptr is aligned,
// and therefore we're only accessing the same word/page. (See notes
// for the 32-bit version above.)
const ulong MagicMask = 0x7fff7fff7fff7fff;
while (true)
{
ulong word = *(ulong*)end;
word += MagicMask; // cause high bit to be set if not zero, and <= 0x8000
word |= MagicMask; // set everything besides the high bits
if (word == ulong.MaxValue) // 0xffff...
{
// all of the chars have their bits set (and therefore none can be 0)
end += 4;
continue;
}
// at least one of them didn't have their high bit set!
// go through each char and check for 0.
if (end[0] == 0) goto EndAt0;
if (end[1] == 0) goto EndAt1;
if (end[2] == 0) goto EndAt2;
if (end[3] == 0) goto EndAt3;
// if we reached here, it was a false positive-- just continue
end += 4;
}
EndAt3: end++;
EndAt2: end++;
EndAt1: end++;
EndAt0:
#endif // !BIT64
FoundZero:
Debug.Assert(*end == 0);
int count = (int)(end - ptr);
#if BIT64
// Check for overflow
if (ptr + count != end)
throw new ArgumentException(SR.Arg_MustBeNullTerminatedString);
#else
Debug.Assert(ptr + count == end);
#endif
return count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe int strlen(byte* ptr)
{
// IndexOf processes memory in aligned chunks, and thus it won't crash even if it accesses memory beyond the null terminator.
int length = SpanHelpers.IndexOf(ref *ptr, (byte)'\0', int.MaxValue);
if (length < 0)
{
ThrowMustBeNullTerminatedString();
}
return length;
}
private static void ThrowMustBeNullTerminatedString()
{
throw new ArgumentException(SR.Arg_MustBeNullTerminatedString);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.String;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(this, provider);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(this, provider);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(this, provider);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(this, provider);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(this, provider);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(this, provider);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(this, provider);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(this, provider);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(this, provider);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(this, provider);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(this, provider);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(this, provider);
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(this, provider);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return Convert.ToDateTime(this, provider);
}
object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
// Normalization Methods
// These just wrap calls to Normalization class
public bool IsNormalized()
{
return IsNormalized(NormalizationForm.FormC);
}
public bool IsNormalized(NormalizationForm normalizationForm)
{
#if CORECLR
if (this.IsFastSort())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return true;
}
#endif
return Normalization.IsNormalized(this, normalizationForm);
}
public string Normalize()
{
return Normalize(NormalizationForm.FormC);
}
public string Normalize(NormalizationForm normalizationForm)
{
#if CORECLR
if (this.IsAscii())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return this;
}
#endif
return Normalization.Normalize(this, normalizationForm);
}
}
}
| 34.181595 | 174 | 0.565008 | [
"MIT"
] | WardenGnaw/coreclr | src/System.Private.CoreLib/shared/System/String.cs | 27,858 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Glimpse.TelerikDataAccess.Plugin.Tab
{
class DataAccessTabStatistics
{
public int ConnectionCount { get; set; }
public int QueryCount { get; set; }
public int TransactionCount { get; set; }
public int Rows { get; set; }
public TimeSpan ExecutionTime { get; set; }
public TimeSpan ConnectionOpenTime { get; set; }
public int SecondLevelHits { get; set; }
public int SecondLevelObjects { get; set; }
public int SplittedCount { get; set; }
public string GCCounts { get; set; }
}
}
| 29.086957 | 56 | 0.647235 | [
"Apache-2.0"
] | tkcode123/glimpse-telerik-dataaccess | Glimpse.TelerikDataAccess/Source/Glimpse.TelerikDataAccess.Plugin/Tab/DataAccessTabStatistics.cs | 671 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DataBoxEdge.Latest
{
[Obsolete(@"The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-nextgen:databoxedge:getOrder'.")]
public static class GetOrder
{
/// <summary>
/// The order details.
/// Latest API Version: 2020-09-01.
/// </summary>
public static Task<GetOrderResult> InvokeAsync(GetOrderArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetOrderResult>("azure-nextgen:databoxedge/latest:getOrder", args ?? new GetOrderArgs(), options.WithVersion());
}
public sealed class GetOrderArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The device name.
/// </summary>
[Input("deviceName", required: true)]
public string DeviceName { get; set; } = null!;
/// <summary>
/// The resource group name.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetOrderArgs()
{
}
}
[OutputType]
public sealed class GetOrderResult
{
/// <summary>
/// The contact details.
/// </summary>
public readonly Outputs.ContactDetailsResponse ContactInformation;
/// <summary>
/// Current status of the order.
/// </summary>
public readonly Outputs.OrderStatusResponse CurrentStatus;
/// <summary>
/// Tracking information for the package delivered to the customer whether it has an original or a replacement device.
/// </summary>
public readonly ImmutableArray<Outputs.TrackingInfoResponse> DeliveryTrackingInfo;
/// <summary>
/// The path ID that uniquely identifies the object.
/// </summary>
public readonly string Id;
/// <summary>
/// The object name.
/// </summary>
public readonly string Name;
/// <summary>
/// List of status changes in the order.
/// </summary>
public readonly ImmutableArray<Outputs.OrderStatusResponse> OrderHistory;
/// <summary>
/// Tracking information for the package returned from the customer whether it has an original or a replacement device.
/// </summary>
public readonly ImmutableArray<Outputs.TrackingInfoResponse> ReturnTrackingInfo;
/// <summary>
/// Serial number of the device.
/// </summary>
public readonly string SerialNumber;
/// <summary>
/// ShipmentType of the order
/// </summary>
public readonly string? ShipmentType;
/// <summary>
/// The shipping address.
/// </summary>
public readonly Outputs.AddressResponse? ShippingAddress;
/// <summary>
/// The hierarchical type of the object.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetOrderResult(
Outputs.ContactDetailsResponse contactInformation,
Outputs.OrderStatusResponse currentStatus,
ImmutableArray<Outputs.TrackingInfoResponse> deliveryTrackingInfo,
string id,
string name,
ImmutableArray<Outputs.OrderStatusResponse> orderHistory,
ImmutableArray<Outputs.TrackingInfoResponse> returnTrackingInfo,
string serialNumber,
string? shipmentType,
Outputs.AddressResponse? shippingAddress,
string type)
{
ContactInformation = contactInformation;
CurrentStatus = currentStatus;
DeliveryTrackingInfo = deliveryTrackingInfo;
Id = id;
Name = name;
OrderHistory = orderHistory;
ReturnTrackingInfo = returnTrackingInfo;
SerialNumber = serialNumber;
ShipmentType = shipmentType;
ShippingAddress = shippingAddress;
Type = type;
}
}
}
| 33.661538 | 166 | 0.615174 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataBoxEdge/Latest/GetOrder.cs | 4,376 | C# |
namespace ClojSharp.Core.Language
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public interface IObject : IMetadata
{
IObject WithMetadata(Map map);
}
}
| 18.923077 | 41 | 0.634146 | [
"MIT"
] | ajlopez/ClojSharp | Src/ClojSharp.Core/Language/IObject.cs | 248 | C# |
using Abot.Core;
using NUnit.Framework;
using System;
using System.Threading;
namespace Abot.Tests.Unit.Core
{
[TestFixture]
public abstract class ThreadManagerTest
{
IThreadManager _unitUnderTest;
const int MAXTHREADS = 10;
protected abstract IThreadManager GetInstance(int maxThreads);
[SetUp]
public void SetUp()
{
_unitUnderTest = GetInstance(MAXTHREADS);
}
[TearDown]
public void TearDown()
{
if (_unitUnderTest != null)
_unitUnderTest.Dispose();
}
[Test]
public void Constructor_CreatesDefaultInstance()
{
Assert.IsNotNull(_unitUnderTest);
Assert.AreEqual(MAXTHREADS, _unitUnderTest.MaxThreads);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void Constructor_OverMax()
{
_unitUnderTest = GetInstance(101);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void Constructor_BelowMinimum()
{
_unitUnderTest = GetInstance(0);
}
[Test]
public void HasRunningThreads()
{
//No threads should be running
Assert.IsFalse(_unitUnderTest.HasRunningThreads());
//Add word to be run on a thread
_unitUnderTest.DoWork(() => System.Threading.Thread.Sleep(300));
System.Threading.Thread.Sleep(20);
//Should have 1 running thread
Assert.IsTrue(_unitUnderTest.HasRunningThreads());
//Wait for the 1 running thread to finish
System.Threading.Thread.Sleep(400);
//Should have 0 threads running since the thread should have completed by now
Assert.IsFalse(_unitUnderTest.HasRunningThreads());
}
[Test]
public void DoWork_WorkItemsEqualToThreads_WorkIsCompletedAsync()
{
int count = 0;
for (int i = 0; i < MAXTHREADS; i++)
{
_unitUnderTest.DoWork(() =>
{
System.Threading.Thread.Sleep(5);
Interlocked.Increment(ref count);
});
}
Assert.IsTrue(count < MAXTHREADS);
System.Threading.Thread.Sleep(80);//was 20 but had to bump it up or the TaskThreadManager would fail, its way slower
Assert.AreEqual(MAXTHREADS, count);
}
[Test]
public void DoWork_MoreWorkThenThreads_WorkIsCompletedAsync()
{
int count = 0;
for (int i = 0; i < 2 * MAXTHREADS; i++)
{
_unitUnderTest.DoWork(() =>
{
System.Threading.Thread.Sleep(5);
Interlocked.Increment(ref count);
});
}
//Assert.IsTrue(count < MAXTHREADS);//Manual has completed more then the thread count by the time it gets here
System.Threading.Thread.Sleep(80);//was 20 but had to bump it up or the TaskThreadManager would fail, its way slower
Assert.AreEqual(2 * MAXTHREADS, count);
}
[Test]
public void DoWork_SingleThreaded_WorkIsCompletedSynchronously()
{
_unitUnderTest = GetInstance(1);
int count = 0;
for (int i = 0; i < MAXTHREADS; i++)
{
_unitUnderTest.DoWork(() =>
{
System.Threading.Thread.Sleep(5);
Interlocked.Increment(ref count);
});
}
Assert.AreEqual(MAXTHREADS, count);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void DoWork_ActionIsNull()
{
_unitUnderTest.DoWork(null);
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void DoWork_CalledAfterAbortAll()
{
_unitUnderTest.AbortAll();
_unitUnderTest.DoWork(() => System.Threading.Thread.Sleep(10));
}
[Test]
public void Dispose()
{
Assert.IsTrue(_unitUnderTest is IDisposable);
}
[Test]
public void Abort_SetsHasRunningThreadsToZero()
{
for (int i = 0; i < 2 * MAXTHREADS; i++)
{
_unitUnderTest.DoWork(() => System.Threading.Thread.Sleep(5));
}
_unitUnderTest.AbortAll();
Assert.IsFalse(_unitUnderTest.HasRunningThreads());
}
}
}
| 29.443038 | 128 | 0.545787 | [
"Apache-2.0"
] | ArsenShnurkov/abot | Abot.Tests.Unit/Core/ThreadManagerTest.cs | 4,654 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.Integrations
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Cloud_CollectionObjectType : INotifyPropertyChanged
{
private Cloud_CollectionObjectIDType[] idField;
private string descriptorField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement("ID", Order = 0)]
public Cloud_CollectionObjectIDType[] ID
{
get
{
return this.idField;
}
set
{
this.idField = value;
this.RaisePropertyChanged("ID");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Descriptor
{
get
{
return this.descriptorField;
}
set
{
this.descriptorField = value;
this.RaisePropertyChanged("Descriptor");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 22.032787 | 136 | 0.734375 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.Integrations/Cloud_CollectionObjectType.cs | 1,344 | C# |
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Transformalize.Transform.CSharp.Autofac")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Transformalize")]
[assembly: AssemblyProduct("Transformalize.Transform.CSharp.Autofac")]
[assembly: AssemblyCopyright("Copyright © 2018-2020 Dale Newman")]
[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("cd3477b9-14e5-4ea3-90b0-ca9299bcae73")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.8.29.0")]
[assembly: AssemblyFileVersion("0.8.29.0")]
[assembly: NeutralResourcesLanguage("en-US")]
| 38.725 | 84 | 0.758554 | [
"Apache-2.0"
] | dalenewman/Transformalize.Transform.CSharp | src/Transformalize.Transform.CSharp.Autofac/Properties/AssemblyInfo.cs | 1,552 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.