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 ISP.Good.Code.Interfaces; namespace ISP.Good.Code.Machines { public class OldFashionedPrinter : IPrint { /// <summary> /// Old fashioned printer just prints, no other implements are required. /// </summary> public void Print() { throw new System.NotImplementedException(); } } }
22.4375
80
0.593315
[ "Unlicense" ]
yigityuksel/Fundamentals
ISP.Good.Code/Machines/OldFashionedPrinter.cs
361
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Xunit; namespace Microsoft.AspNetCore.Mvc.ModelBinding.Test { public class ModelBindingResultTest { [Fact] public void Success_SetsProperties() { // Arrange var model = "some model"; // Act var result = ModelBindingResult.Success(model); // Assert Assert.True(result.IsModelSet); Assert.Same(model, result.Model); } [Fact] public void Failed_SetsProperties() { // Arrange & Act var result = ModelBindingResult.Failed(); // Assert Assert.False(result.IsModelSet); Assert.Null(result.Model); } } }
24.861111
111
0.569832
[ "Apache-2.0" ]
belav/aspnetcore
src/Mvc/Mvc.Core/test/ModelBinding/ModelBindingResultTest.cs
895
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services // // Microsoft Cognitive Services (formerly Project Oxford) GitHub: // https://github.com/Microsoft/Cognitive-Video-Windows // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Windows; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace VideoAPI_WPF_Samples { static class Helpers { public static string SubscriptionKey { get { MainWindow window = (MainWindow)Application.Current.MainWindow; return window._scenariosControl.SubscriptionKey; } } public static string PickFile() { MainWindow window = (MainWindow)Application.Current.MainWindow; Microsoft.Win32.OpenFileDialog openDlg = new Microsoft.Win32.OpenFileDialog(); openDlg.Filter = "Video files (*.mp4, *.mov, *.wmv)|*.mp4;*.mov;*.wmv"; bool? result = openDlg.ShowDialog(window); if (!result.GetValueOrDefault(false)) return null; return openDlg.FileName; } public static T FromJson<T>(string json) { return JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.IsoDateFormat, NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver() }); } public static string FormatJson<T>(string json) { return JsonConvert.SerializeObject(FromJson<T>(json), Formatting.Indented); } public static void Log(string identifier, string message, params object[] args) { MainWindow window = (MainWindow)Application.Current.MainWindow; window.Log(string.Format("[{0}] {1}", identifier, string.Format(message, args))); } } }
37.406977
103
0.676096
[ "MIT" ]
Bhaskers-Blu-Org2/Cognitive-Video-Windows
Sample-WPF/Helpers.cs
3,219
C#
using System; using System.Collections; using System.IO; using System.Net.Sockets; using System.Threading.Tasks; namespace LMP.MasterServer.Http { public class HttpProcessor { public static string JQueryCallBack; public TcpClient Socket; public string HttpMethod; public string HttpUrl; public string HttpProtocolVersionstring; public Hashtable HttpHeaders = new Hashtable(); public HttpProcessor(TcpClient s) { Socket = s; } private static async Task<string> StreamReadLine(Stream inputStream) { var data = ""; while (true) { var nextChar = inputStream.ReadByte(); if (nextChar == '\n') { break; } switch (nextChar) { case '\r': continue; case -1: await Task.Delay(MasterServer.ServerMsTick); continue; } ; data += Convert.ToChar(nextChar); } return data; } public void Process() { using (var inputStream = new BufferedStream(Socket.GetStream())) using (var outputStream = new StreamWriter(new BufferedStream(Socket.GetStream()))) { try { ParseRequest(inputStream); ReadHeaders(inputStream); if (HttpMethod.Equals("GET")) { HandleGetRequest(outputStream); } } catch (Exception) { WriteFailure(outputStream); } outputStream.Flush(); Socket.Close(); Socket.Dispose(); } } public async void ParseRequest(BufferedStream inputStream) { var request = await StreamReadLine(inputStream); var tokens = request.Split(' '); if (tokens.Length != 3) { //invalid http request line return; } HttpMethod = tokens[0].ToUpper(); HttpUrl = tokens[1]; JQueryCallBack = GetJQueryCallback(); HttpProtocolVersionstring = tokens[2]; } private string GetJQueryCallback() { try { return HttpUrl.Contains("jQuery") ? HttpUrl.Substring(0, HttpUrl.LastIndexOf("&")).Substring(HttpUrl.IndexOf("jQuery")) : string.Empty; } catch (Exception) { return string.Empty; } } public async void ReadHeaders(BufferedStream inputStream) { string line; while ((line = await StreamReadLine(inputStream)) != null) { if (line.Equals("")) { return; } var separator = line.IndexOf(':'); if (separator == -1) { return; } var name = line.Substring(0, separator); var pos = separator + 1; while (pos < line.Length && line[pos] == ' ') { pos++; // strip any spaces } var value = line.Substring(pos, line.Length - pos); HttpHeaders[name] = value; } } public void HandleGetRequest(StreamWriter outputStream) { LunaHttpServer.HandleGetRequest(outputStream); } public void WriteFailure(StreamWriter outputStream) { outputStream.WriteLine("HTTP/1.0 404 File not found"); outputStream.WriteLine("Connection: close"); outputStream.WriteLine(""); } } }
29.057971
151
0.464339
[ "MIT" ]
Badca52/LunaMultiplayer
LMP.MasterServer/Http/HttpProcessor.cs
4,012
C#
namespace SerialPort { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.cmdConnect = new System.Windows.Forms.Button(); this.serialPort1 = new System.IO.Ports.SerialPort(this.components); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.cmbstopbits = new System.Windows.Forms.ComboBox(); this.cmbparity = new System.Windows.Forms.ComboBox(); this.cmbbaudrate = new System.Windows.Forms.ComboBox(); this.cmbdatabits = new System.Windows.Forms.ComboBox(); this.button1 = new System.Windows.Forms.Button(); this.txtDatatoSend = new System.Windows.Forms.TextBox(); this.cmdClose = new System.Windows.Forms.Button(); this.txtPort = new System.Windows.Forms.ComboBox(); this.txtReceive = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // cmdConnect // this.cmdConnect.Location = new System.Drawing.Point(12, 146); this.cmdConnect.Name = "cmdConnect"; this.cmdConnect.Size = new System.Drawing.Size(61, 23); this.cmdConnect.TabIndex = 0; this.cmdConnect.Text = "Connect"; this.cmdConnect.UseVisualStyleBackColor = true; this.cmdConnect.Click += new System.EventHandler(this.cmdConnect_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 95); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(31, 13); this.label1.TabIndex = 3; this.label1.Text = "Port:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(211, 95); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(51, 13); this.label2.TabIndex = 5; this.label2.Text = "Databits:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(143, 95); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(39, 13); this.label3.TabIndex = 7; this.label3.Text = "Parity:"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(280, 95); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(50, 13); this.label4.TabIndex = 9; this.label4.Text = "Stopbits:"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(74, 95); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(61, 13); this.label5.TabIndex = 11; this.label5.Text = "Baud Rate:"; // // cmbstopbits // this.cmbstopbits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbstopbits.FormattingEnabled = true; this.cmbstopbits.Items.AddRange(new object[] { "None", "One", "OnePointFive", "Two"}); this.cmbstopbits.Location = new System.Drawing.Point(283, 111); this.cmbstopbits.Name = "cmbstopbits"; this.cmbstopbits.Size = new System.Drawing.Size(51, 21); this.cmbstopbits.TabIndex = 12; // // cmbparity // this.cmbparity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbparity.FormattingEnabled = true; this.cmbparity.Items.AddRange(new object[] { "Even", "Odd", "None", "Mark", "Space"}); this.cmbparity.Location = new System.Drawing.Point(146, 111); this.cmbparity.Name = "cmbparity"; this.cmbparity.Size = new System.Drawing.Size(51, 21); this.cmbparity.TabIndex = 13; // // cmbbaudrate // this.cmbbaudrate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbbaudrate.FormattingEnabled = true; this.cmbbaudrate.Items.AddRange(new object[] { "9600"}); this.cmbbaudrate.Location = new System.Drawing.Point(77, 111); this.cmbbaudrate.Name = "cmbbaudrate"; this.cmbbaudrate.Size = new System.Drawing.Size(51, 21); this.cmbbaudrate.TabIndex = 15; // // cmbdatabits // this.cmbdatabits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbdatabits.FormattingEnabled = true; this.cmbdatabits.Items.AddRange(new object[] { "4", "5", "6", "7", "8"}); this.cmbdatabits.Location = new System.Drawing.Point(214, 111); this.cmbdatabits.Name = "cmbdatabits"; this.cmbdatabits.Size = new System.Drawing.Size(51, 21); this.cmbdatabits.TabIndex = 14; // // button1 // this.button1.Location = new System.Drawing.Point(273, 146); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(61, 23); this.button1.TabIndex = 16; this.button1.Text = "Send"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // txtDatatoSend // this.txtDatatoSend.Location = new System.Drawing.Point(146, 147); this.txtDatatoSend.Name = "txtDatatoSend"; this.txtDatatoSend.Size = new System.Drawing.Size(121, 20); this.txtDatatoSend.TabIndex = 17; // // cmdClose // this.cmdClose.Location = new System.Drawing.Point(74, 146); this.cmdClose.Name = "cmdClose"; this.cmdClose.Size = new System.Drawing.Size(61, 23); this.cmdClose.TabIndex = 18; this.cmdClose.Text = "Close"; this.cmdClose.UseVisualStyleBackColor = true; this.cmdClose.Click += new System.EventHandler(this.cmdClose_Click_1); // // txtPort // this.txtPort.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.txtPort.FormattingEnabled = true; this.txtPort.Location = new System.Drawing.Point(12, 111); this.txtPort.Name = "txtPort"; this.txtPort.Size = new System.Drawing.Size(59, 21); this.txtPort.TabIndex = 19; // // txtReceive // this.txtReceive.Location = new System.Drawing.Point(15, 12); this.txtReceive.Multiline = true; this.txtReceive.Name = "txtReceive"; this.txtReceive.ReadOnly = true; this.txtReceive.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtReceive.Size = new System.Drawing.Size(326, 72); this.txtReceive.TabIndex = 20; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(353, 175); this.Controls.Add(this.txtReceive); this.Controls.Add(this.txtPort); this.Controls.Add(this.cmdClose); this.Controls.Add(this.txtDatatoSend); this.Controls.Add(this.button1); this.Controls.Add(this.cmbbaudrate); this.Controls.Add(this.cmbdatabits); this.Controls.Add(this.cmbparity); this.Controls.Add(this.cmbstopbits); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.cmdConnect); this.Name = "Form1"; this.Text = "SerialPort"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button cmdConnect; private System.IO.Ports.SerialPort serialPort1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cmbstopbits; private System.Windows.Forms.ComboBox cmbparity; private System.Windows.Forms.ComboBox cmbbaudrate; private System.Windows.Forms.ComboBox cmbdatabits; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox txtDatatoSend; private System.Windows.Forms.Button cmdClose; private System.Windows.Forms.ComboBox txtPort; private System.Windows.Forms.TextBox txtReceive; } }
43.271654
108
0.550086
[ "MIT" ]
moamenibrahim/Orion-GUI
SerialPort/SerialPort/SerialPort/Form1.Designer.cs
10,993
C#
namespace ProjectSnowshoes { partial class CanWeMakeAHoverFormLikeThisIsThisLegal { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Font = new System.Drawing.Font("Maven Pro", 16.875F); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(450, 36); this.label1.TabIndex = 0; this.label1.Text = "This Is The Time | Billy Joel | Turntable"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // CanWeMakeAHoverFormLikeThisIsThisLegal // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(254))))); this.ClientSize = new System.Drawing.Size(450, 36); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); this.Name = "CanWeMakeAHoverFormLikeThisIsThisLegal"; this.TopMost = true; this.TransparencyKey = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(254))))); this.Load += new System.EventHandler(this.CanWeMakeAHoverFormLikeThisIsThisLegal_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; } }
42.318841
137
0.585274
[ "Apache-2.0" ]
IndigoBox/ProjectSnowshoes
ProjectSnowshoes/CanWeMakeAHoverFormLikeThisIsThisLegal.Designer.cs
2,922
C#
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using System.Web; using ASC.Common.Caching; using ASC.Common.Web; using ASC.Core; using ASC.FederatedLogin; using ASC.FederatedLogin.Helpers; using ASC.FederatedLogin.LoginProviders; using ASC.Files.Core; using ASC.Web.Files.Classes; using DriveFile = Google.Apis.Drive.v3.Data.File; namespace ASC.Files.Thirdparty.GoogleDrive { [DebuggerDisplay("{CustomerTitle}")] public class GoogleDriveProviderInfo : IProviderInfo, IDisposable { private OAuth20Token _token; private readonly FolderType _rootFolderType; private readonly DateTime _createOn; private string _driveRootId; internal GoogleDriveStorage Storage { get { if (HttpContext.Current != null) { var key = "__GOOGLE_STORAGE" + ID; var wrapper = (StorageDisposableWrapper)DisposableHttpContext.Current[key]; if (wrapper == null || !wrapper.Storage.IsOpened) { wrapper = new StorageDisposableWrapper(CreateStorage()); DisposableHttpContext.Current[key] = wrapper; } return wrapper.Storage; } return CreateStorage(); } } internal bool StorageOpened { get { if (HttpContext.Current != null) { var key = "__GOOGLE_STORAGE" + ID; var wrapper = (StorageDisposableWrapper)DisposableHttpContext.Current[key]; return wrapper != null && wrapper.Storage.IsOpened; } return false; } } public int ID { get; set; } public Guid Owner { get; private set; } public string CustomerTitle { get; private set; } public DateTime CreateOn { get { return _createOn; } } public object RootFolderId { get { return "drive-" + ID; } } public string ProviderKey { get; private set; } public FolderType RootFolderType { get { return _rootFolderType; } } public string DriveRootId { get { if (string.IsNullOrEmpty(_driveRootId)) { try { _driveRootId = Storage.GetRootFolderId(); } catch (Exception ex) { Global.Logger.Error("GoogleDrive error", ex); return null; } } return _driveRootId; } } public GoogleDriveProviderInfo(int id, string providerKey, string customerTitle, string token, Guid owner, FolderType rootFolderType, DateTime createOn) { if (string.IsNullOrEmpty(providerKey)) throw new ArgumentNullException("providerKey"); if (string.IsNullOrEmpty(token)) throw new ArgumentException("Token can't be null"); ID = id; CustomerTitle = customerTitle; Owner = owner == Guid.Empty ? SecurityContext.CurrentAccount.ID : owner; ProviderKey = providerKey; _token = OAuth20Token.FromJson(token); _rootFolderType = rootFolderType; _createOn = createOn; } public void Dispose() { if (StorageOpened) Storage.Close(); } public bool CheckAccess() { try { return !string.IsNullOrEmpty(DriveRootId); } catch (UnauthorizedAccessException) { return false; } } public void InvalidateStorage() { if (HttpContext.Current != null) { var key = "__GOOGLE_STORAGE" + ID; var storage = (StorageDisposableWrapper)DisposableHttpContext.Current[key]; if (storage != null) { storage.Dispose(); } } CacheReset(); } internal void UpdateTitle(string newtitle) { CustomerTitle = newtitle; } private GoogleDriveStorage CreateStorage() { var driveStorage = new GoogleDriveStorage(); CheckToken(); driveStorage.Open(_token); return driveStorage; } private void CheckToken() { if (_token == null) throw new UnauthorizedAccessException("Cannot create GoogleDrive session with given token"); if (_token.IsExpired) { _token = OAuth20TokenHelper.RefreshToken<GoogleLoginProvider>(_token); using (var dbDao = new CachedProviderAccountDao(CoreContext.TenantManager.GetCurrentTenant().TenantId, FileConstant.DatabaseId)) { var authData = new AuthData(token: _token.ToJson()); dbDao.UpdateProviderInfo(ID, authData); } } } private class StorageDisposableWrapper : IDisposable { public GoogleDriveStorage Storage { get; private set; } public StorageDisposableWrapper(GoogleDriveStorage storage) { Storage = storage; } public void Dispose() { Storage.Close(); } } private static readonly TimeSpan CacheExpiration = TimeSpan.FromMinutes(1); private static readonly ICache CacheEntry = AscCache.Memory; private static readonly ICache CacheChildFiles = AscCache.Memory; private static readonly ICache CacheChildFolders = AscCache.Memory; private static readonly ICacheNotify CacheNotify; static GoogleDriveProviderInfo() { CacheNotify = AscCache.Notify; CacheNotify.Subscribe<GoogleDriveCacheItem>((i, action) => { if (action != CacheNotifyAction.Remove) return; if (i.ResetEntry) { CacheEntry.Remove("drive-" + i.Key); } if (i.ResetAll) { CacheEntry.Remove(new Regex("^drive-" + i.Key + ".*")); CacheChildFiles.Remove(new Regex("^drivef-" + i.Key + ".*")); CacheChildFolders.Remove(new Regex("^drived-" + i.Key + ".*")); } if (i.ResetChilds) { if (!i.ChildFolder.HasValue || !i.ChildFolder.Value) { CacheChildFiles.Remove("drivef-" + i.Key); } if (!i.ChildFolder.HasValue || i.ChildFolder.Value) { CacheChildFolders.Remove("drived-" + i.Key); } } }); } internal DriveFile GetDriveEntry(string driveId) { var entry = CacheEntry.Get<DriveFile>("drive-" + ID + "-" + driveId); if (entry == null) { entry = Storage.GetEntry(driveId); if (entry != null) CacheEntry.Insert("drive-" + ID + "-" + driveId, entry, DateTime.UtcNow.Add(CacheExpiration)); } return entry; } internal List<DriveFile> GetDriveEntries(string parentDriveId, bool? folder = null) { if (folder.HasValue) { if (folder.Value) { var value = CacheChildFolders.Get<List<DriveFile>>("drived-" + ID + "-" + parentDriveId); if (value == null) { value = Storage.GetEntries(parentDriveId, true); if (value != null) CacheChildFolders.Insert("drived-" + ID + "-" + parentDriveId, value, DateTime.UtcNow.Add(CacheExpiration)); } return value; } else { var value = CacheChildFiles.Get<List<DriveFile>>("drivef-" + ID + "-" + parentDriveId); if (value == null) { value = Storage.GetEntries(parentDriveId, false); if (value != null) CacheChildFiles.Insert("drivef-" + ID + "-" + parentDriveId, value, DateTime.UtcNow.Add(CacheExpiration)); } return value; } } if (CacheChildFiles.Get<List<DriveFile>>("drivef-" + ID + "-" + parentDriveId) == null && CacheChildFolders.Get<List<DriveFile>>("drived-" + ID + "-" + parentDriveId) == null) { var entries = Storage.GetEntries(parentDriveId); CacheChildFiles.Insert("drivef-" + ID + "-" + parentDriveId, entries.Where(entry => entry.MimeType != GoogleLoginProvider.GoogleDriveMimeTypeFolder).ToList(), DateTime.UtcNow.Add(CacheExpiration)); CacheChildFolders.Insert("drived-" + ID + "-" + parentDriveId, entries.Where(entry => entry.MimeType == GoogleLoginProvider.GoogleDriveMimeTypeFolder).ToList(), DateTime.UtcNow.Add(CacheExpiration)); return entries; } var folders = CacheChildFolders.Get<List<DriveFile>>("drived-" + ID + "-" + parentDriveId); if (folders == null) { folders = Storage.GetEntries(parentDriveId, true); CacheChildFolders.Insert("drived-" + ID + "-" + parentDriveId, folders, DateTime.UtcNow.Add(CacheExpiration)); } var files = CacheChildFiles.Get<List<DriveFile>>("drivef-" + ID + "-" + parentDriveId); if (files == null) { files = Storage.GetEntries(parentDriveId, false); CacheChildFiles.Insert("drivef-" + ID + "-" + parentDriveId, files, DateTime.UtcNow.Add(CacheExpiration)); } return folders.Concat(files).ToList(); } internal void CacheReset(DriveFile driveEntry) { if (driveEntry != null) { CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, Key = ID + "-" + driveEntry.Id }, CacheNotifyAction.Remove); } } internal void CacheReset(string driveId = null, bool? childFolder = null) { var key = ID + "-"; if (driveId == null) { CacheNotify.Publish(new GoogleDriveCacheItem { ResetAll = true, Key = key }, CacheNotifyAction.Remove); } else { if (driveId == DriveRootId) { driveId = "root"; } key += driveId; CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, ResetChilds = true, Key = key, ChildFolder = childFolder }, CacheNotifyAction.Remove); } } internal void CacheResetChilds(string parentDriveId, bool? childFolder = null) { CacheNotify.Publish(new GoogleDriveCacheItem { ResetChilds = true, Key = ID + "-" + parentDriveId, ChildFolder = childFolder }, CacheNotifyAction.Remove); } private class GoogleDriveCacheItem { public bool ResetAll { get; set; } public bool ResetEntry { get; set; } public bool ResetChilds { get; set; } public string Key { get; set; } public bool? ChildFolder { get; set; } } } }
36.437673
216
0.50783
[ "Apache-2.0" ]
jeanluctritsch/CommunityServer
module/ASC.Files.Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs
13,154
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace AppAdvisory.MathGame { public class gotoMM18 :ButtonHelper { public GameObject level; override public void OnClicked() { menuManager.backtonormal(); Destroy(level); menuManager.GoToMM18(); RemoveListener(); } } }
17
36
0.749226
[ "MIT" ]
MrD005/Math-Game
BODMAS/Assets/MathGame/Scripts/Multiplication/GoTOLevel/gotoMM18.cs
325
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Edge.Hub.Core { using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.Devices.Edge.Hub.Core.Device; using Microsoft.Azure.Devices.Edge.Hub.Core.Identity; using Microsoft.Azure.Devices.Edge.Hub.Core.Identity.Service; using Microsoft.Azure.Devices.Edge.Util; using Microsoft.Extensions.Logging; public abstract class DeviceScopeAuthenticator<T> : IAuthenticator where T : IClientCredentials { readonly IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache; readonly IAuthenticator underlyingAuthenticator; readonly bool allowDeviceAuthForModule; readonly bool syncServiceIdentityOnFailure; readonly bool nestedEdgeEnabled; protected DeviceScopeAuthenticator( IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache, IAuthenticator underlyingAuthenticator, bool allowDeviceAuthForModule, bool syncServiceIdentityOnFailure, bool nestedEdgeEnabled) { this.underlyingAuthenticator = Preconditions.CheckNotNull(underlyingAuthenticator, nameof(underlyingAuthenticator)); this.deviceScopeIdentitiesCache = Preconditions.CheckNotNull(deviceScopeIdentitiesCache, nameof(deviceScopeIdentitiesCache)); this.allowDeviceAuthForModule = allowDeviceAuthForModule; this.syncServiceIdentityOnFailure = syncServiceIdentityOnFailure; this.nestedEdgeEnabled = nestedEdgeEnabled; } public async Task<bool> AuthenticateAsync(IClientCredentials clientCredentials) { if (!(clientCredentials is T tCredentials)) { return false; } (bool isAuthenticated, bool shouldFallback) = await this.AuthenticateInternalAsync(tCredentials, false); Events.AuthenticatedInScope(clientCredentials.Identity, isAuthenticated); if (!isAuthenticated && shouldFallback) { isAuthenticated = await this.underlyingAuthenticator.AuthenticateAsync(clientCredentials); } return isAuthenticated; } public async Task<bool> ReauthenticateAsync(IClientCredentials clientCredentials) { if (!(clientCredentials is T tCredentials)) { return false; } (bool isAuthenticated, bool shouldFallback) = await this.AuthenticateInternalAsync(tCredentials, true); Events.ReauthenticatedInScope(clientCredentials.Identity, isAuthenticated); if (!isAuthenticated && shouldFallback) { Events.ServiceIdentityNotFound(tCredentials.Identity); isAuthenticated = await this.underlyingAuthenticator.ReauthenticateAsync(clientCredentials); } return isAuthenticated; } protected abstract bool AreInputCredentialsValid(T credentials); protected abstract bool ValidateWithServiceIdentity(ServiceIdentity serviceIdentity, T credentials); async Task<(bool isAuthenticated, bool shouldFallback)> AuthenticateInternalAsync(T tCredentials, bool reauthenticating) { try { if (!this.AreInputCredentialsValid(tCredentials)) { Events.InputCredentialsNotValid(tCredentials.Identity); return (false, false); } bool syncServiceIdentity = this.syncServiceIdentityOnFailure && !reauthenticating; bool isAuthenticated = false; bool valueFound = false; // Try to get the actor from the client auth chain, this will only be valid for OnBehalfOf authentication Option<string> onBehalfOfActorDeviceId = AuthChainHelpers.GetActorDeviceId(tCredentials.AuthChain); if (this.nestedEdgeEnabled && onBehalfOfActorDeviceId.HasValue) { // OnBehalfOf means an EdgeHub is trying to use its own auth to // connect as a child device or module. So if acting EdgeHub is // different than the target identity, then we know we're // processing an OnBehalfOf authentication. (isAuthenticated, valueFound) = await this.AuthenticateWithAuthChain(tCredentials, onBehalfOfActorDeviceId.OrDefault(), syncServiceIdentity); } else { // Default scenario where the credential is for the target identity (isAuthenticated, valueFound) = await this.AuthenticateWithServiceIdentity(tCredentials, tCredentials.Identity.Id, syncServiceIdentity); if (!isAuthenticated && this.allowDeviceAuthForModule && tCredentials.Identity is IModuleIdentity moduleIdentity) { // The module could have used the Device key to sign its token Events.AuthenticatingWithDeviceIdentity(moduleIdentity); (isAuthenticated, valueFound) = await this.AuthenticateWithServiceIdentity(tCredentials, moduleIdentity.DeviceId, syncServiceIdentity); } } // In the return value, the first flag indicates if the authentication succeeded. // The second flag indicates whether the authenticator should fall back to the underlying authenticator. This is done if // the ServiceIdentity was not found (which means the device/module is not in scope). return (isAuthenticated, !valueFound); } catch (Exception e) { Events.ErrorAuthenticating(e, tCredentials, reauthenticating); return (false, true); } } async Task<(bool isAuthenticated, bool serviceIdentityFound)> AuthenticateWithAuthChain(T credentials, string actorDeviceId, bool syncServiceIdentity) { // The auth target is the first element of the authchain Option<string> authTargetOption = AuthChainHelpers.GetAuthTarget(credentials.AuthChain); string authTarget = authTargetOption.Expect(() => new InvalidOperationException("Credentials should always have a valid auth-chain for OnBehalfOf authentication")); // For nested Edge, we need to check that we have // a valid authchain for the target identity Option<string> authChain = await this.deviceScopeIdentitiesCache.GetAuthChain(authTarget); if (!authChain.HasValue) { // The auth-target might be a new device that was recently added, and our // cache might not have it yet. Try refreshing the target identity to see // if we can get it from upstream. Events.NoAuthChainResyncing(authTarget, actorDeviceId); await this.deviceScopeIdentitiesCache.RefreshServiceIdentityOnBehalfOf(authTarget, actorDeviceId); authChain = await this.deviceScopeIdentitiesCache.GetAuthChain(authTarget); if (!authChain.HasValue) { // Still don't have a valid auth-chain for the target, it must be // out of scope, so we're done here Events.NoAuthChain(authTarget); return (false, false); } } // Check that the actor is authorized to connect OnBehalfOf of the target if (!AuthChainHelpers.ValidateAuthChain(actorDeviceId, authTarget, authChain.OrDefault())) { // We found the target identity in our cache, but can't proceed with auth Events.UnauthorizedAuthChain(actorDeviceId, authTarget, authChain.OrDefault()); return (false, true); } // Check credentials against the acting EdgeHub, since we would have // already refreshed the target identity on failure, there's no need // to have AuthenticateWithServiceIdentity do it again. string actorEdgeHubId = actorDeviceId + $"/{Constants.EdgeHubModuleId}"; return await this.AuthenticateWithServiceIdentity(credentials, actorEdgeHubId, false); } async Task<(bool isAuthenticated, bool serviceIdentityFound)> AuthenticateWithServiceIdentity(T credentials, string serviceIdentityId, bool syncServiceIdentity) { Option<ServiceIdentity> serviceIdentity = await this.deviceScopeIdentitiesCache.GetServiceIdentity(serviceIdentityId); (bool isAuthenticated, bool serviceIdentityFound) = serviceIdentity.Map(s => (this.ValidateWithServiceIdentity(s, credentials), true)).GetOrElse((false, false)); if (!isAuthenticated && (!serviceIdentityFound || syncServiceIdentity)) { Events.ResyncingServiceIdentity(credentials.Identity, serviceIdentityId); await this.deviceScopeIdentitiesCache.RefreshServiceIdentity(serviceIdentityId); serviceIdentity = await this.deviceScopeIdentitiesCache.GetServiceIdentity(serviceIdentityId); if (!serviceIdentity.HasValue) { // Identity still doesn't exist, this can happen if the identity // is newly added and we couldn't refresh the individual identity // because we don't know where it resides in the nested hierarchy. // In this case our only recourse is to refresh the whole cache // and hope the identity shows up. this.deviceScopeIdentitiesCache.InitiateCacheRefresh(); await this.deviceScopeIdentitiesCache.WaitForCacheRefresh(TimeSpan.FromSeconds(100)); serviceIdentity = await this.deviceScopeIdentitiesCache.GetServiceIdentity(serviceIdentityId); } (isAuthenticated, serviceIdentityFound) = serviceIdentity.Map(s => (this.ValidateWithServiceIdentity(s, credentials), true)).GetOrElse((false, false)); } return (isAuthenticated, serviceIdentityFound); } static class Events { const int IdStart = HubCoreEventIds.DeviceScopeAuthenticator; static readonly ILogger Log = Logger.Factory.CreateLogger<DeviceScopeAuthenticator<T>>(); enum EventIds { ErrorAuthenticating = IdStart, ServiceIdentityNotFound, NoAuthChain, AuthenticatedInScope, InputCredentialsNotValid, ResyncingServiceIdentity, NoAuthChainResyncing, AuthenticatingWithDeviceIdentity } public static void ErrorAuthenticating(Exception exception, IClientCredentials credentials, bool reauthenticating) { string operation = reauthenticating ? "reauthenticating" : "authenticating"; Log.LogWarning((int)EventIds.ErrorAuthenticating, exception, $"Error {operation} credentials for {credentials.Identity.Id}"); } public static void ServiceIdentityNotFound(IIdentity identity) { Log.LogDebug((int)EventIds.ServiceIdentityNotFound, $"Service identity for {identity.Id} not found. Using underlying authenticator to authenticate"); } public static void NoAuthChain(string id) { Log.LogDebug((int)EventIds.NoAuthChain, $"Could not get valid auth-chain for service identity {id}"); } public static void UnauthorizedAuthChain(string actorId, string targetId, string authChain) { Log.LogDebug((int)EventIds.NoAuthChain, $"{actorId} not authorized to act OnBehalfOf {targetId}, auth-chain: {authChain}"); } public static void AuthenticatedInScope(IIdentity identity, bool isAuthenticated) { string authenticated = isAuthenticated ? "authenticated" : "not authenticated"; Log.LogInformation((int)EventIds.AuthenticatedInScope, $"Client {identity.Id} in device scope {authenticated} locally."); } public static void ReauthenticatedInScope(IIdentity identity, bool isAuthenticated) { string authenticated = isAuthenticated ? "reauthenticated" : "not reauthenticated"; Log.LogDebug((int)EventIds.AuthenticatedInScope, $"Client {identity.Id} in device scope {authenticated} locally."); } public static void InputCredentialsNotValid(IIdentity identity) { Log.LogInformation((int)EventIds.InputCredentialsNotValid, $"Credentials for client {identity.Id} are not valid."); } public static void ResyncingServiceIdentity(IIdentity identity, string serviceIdentityId) { Log.LogInformation((int)EventIds.ResyncingServiceIdentity, $"Unable to authenticate client {identity.Id} with cached service identity {serviceIdentityId}. Resyncing service identity..."); } public static void NoAuthChainResyncing(string authTarget, string actorDevice) { Log.LogInformation((int)EventIds.NoAuthChainResyncing, $"No cached auth-chain when authenticating {actorDevice} OnBehalfOf {authTarget}. Resyncing service identity..."); } public static void AuthenticatingWithDeviceIdentity(IModuleIdentity moduleIdentity) { Log.LogInformation((int)EventIds.AuthenticatingWithDeviceIdentity, $"Unable to authenticate client {moduleIdentity.Id} with module credentials. Attempting to authenticate using device {moduleIdentity.DeviceId} credentials."); } } } }
52.69145
241
0.645971
[ "MIT" ]
chzawist/iotedge
edge-hub/core/src/Microsoft.Azure.Devices.Edge.Hub.Core/DeviceScopeAuthenticator.cs
14,174
C#
namespace Examples.Issues.ComplexGenerics { /* Written in response to a question about how to handle multiple "packet" subclasses; * may as well keep it as a test... * */ using ProtoBuf; using System.Data; using NUnit.Framework; using System; using System.ComponentModel; using System.IO; [TestFixture] public class ComplexGenericTest { [Test] public void TestX() { Query query = new X { Result = "abc" }; Assert.AreEqual(typeof(string), query.GetQueryType()); Query clone = Serializer.DeepClone<Query>(query); Assert.IsNotNull(clone); Assert.AreNotSame(clone, query); Assert.IsInstanceOfType(query.GetType(), clone); Assert.AreEqual(((X)query).Result, ((X)clone).Result); } [Test] public void TestY() { Query query = new Y { Result = 1234}; Assert.AreEqual(typeof(int), query.GetQueryType()); Query clone = Serializer.DeepClone<Query>(query); Assert.IsNotNull(clone); Assert.AreNotSame(clone, query); Assert.IsInstanceOfType(query.GetType(), clone); Assert.AreEqual(((Y)query).Result, ((Y)clone).Result); } } public static class QueryExt { public static Type GetQueryType(this IQuery query) { if (query == null) throw new ArgumentNullException("query"); foreach (Type type in query.GetType().GetInterfaces()) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IQuery<>)) { return type.GetGenericArguments()[0]; } } throw new ArgumentException("No typed query implemented", "query"); } } public interface IQuery { string Result { get; set; } } public interface IQuery<T> : IQuery { new T Result { get; set; } } [ProtoInclude(21, typeof(W))] [ProtoInclude(22, typeof(X))] [ProtoInclude(23, typeof(Y))] [ProtoInclude(25, typeof(SpecialQuery))] [ProtoContract] abstract class Query : IQuery { public string Result { get { return ResultString; } set { ResultString = value; } } protected abstract string ResultString { get; set; } protected static string FormatQueryString<T>(T value) { return TypeDescriptor.GetConverter(typeof(T)) .ConvertToInvariantString(value); } protected static T ParseQueryString<T>(string value) { return (T) TypeDescriptor.GetConverter(typeof(T)) .ConvertFromInvariantString(value); } } [ProtoContract] [ProtoInclude(21, typeof(Z))] abstract class SpecialQuery : Query, IQuery<DataSet> { public new DataSet Result { get; set; } [ProtoMember(1)] protected override string ResultString { get { if (Result == null) return null; using (StringWriter sw = new StringWriter()) { Result.WriteXml(sw, XmlWriteMode.WriteSchema); return sw.ToString(); } } set { if (value == null) { Result = null; return; } using (StringReader sr = new StringReader(value)) { DataSet ds = new DataSet(); ds.ReadXml(sr, XmlReadMode.ReadSchema); } } } } [ProtoContract] class W : Query, IQuery<bool> { [ProtoMember(1)] public new bool Result { get; set; } protected override string ResultString { get {return FormatQueryString(Result); } set { Result = ParseQueryString<bool>(value); } } } [ProtoContract] class X : Query, IQuery<string> { [ProtoMember(1)] public new string Result { get; set; } protected override string ResultString { get { return Result ; } set { Result = value; } } } [ProtoContract] class Y : Query, IQuery<int> { [ProtoMember(1)] public new int Result { get; set; } protected override string ResultString { get { return FormatQueryString(Result); } set { Result = ParseQueryString<int>(value); } } } [ProtoContract] class Z : SpecialQuery { } }
29.16875
86
0.534176
[ "MIT" ]
Bhaskers-Blu-Org2/vsminecraft
dependencies/protobuf-net/Examples/Issues/ComplexGenerics/ComplexGenericExample.cs
4,669
C#
using System; using Covid19Radar.Api.Common; using Covid19Radar.Api.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Covid19Radar.Api.Tests.Common.Models { [TestClass] [TestCategory("Models")] public class DiagnosisModelTest { [TestMethod] public void CreateMethod() { // action var model = new DiagnosisModel(); } [TestMethod] public void PropertiesTest() { // preparation var model = new DiagnosisModel(); // model property access Helper.ModelTestHelper.PropetiesTest(model); } } }
21.483871
56
0.596096
[ "MPL-2.0-no-copyleft-exception", "MPL-2.0", "Apache-2.0" ]
178inaba/Covid19Radar
src/Covid19Radar.Api.Tests/Common/Models/DiagnosisModelTest.cs
668
C#
using Bluegiga; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace BGLibExt.Samples.MiTemperatureHumidityMonitor { internal class Program { private readonly BleDeviceManager _bleDeviceManager; private readonly BleModuleConnection _bleModuleConnection; private readonly ILogger<Program> _logger; public Program(BleModuleConnection bleModuleConnection, BleDeviceManager bleDeviceManager, ILogger<Program> logger = null) { _bleModuleConnection = bleModuleConnection; _bleDeviceManager = bleDeviceManager; _logger = logger; } private static void Main(string[] args) { var servicesProvider = new ServiceCollection() .AddLogging(configure => configure.AddConsole().SetMinimumLevel(LogLevel.Debug)) .AddSingleton<BGLib, BGLibDebug>() .AddSingleton<BleModuleConnection>() .AddTransient<BleDeviceManager>() .AddTransient<Program>() .BuildServiceProvider(); var program = servicesProvider.GetRequiredService<Program>(); program.RunAsync().Wait(); } private async Task RunAsync() { _bleModuleConnection.Start("COM3"); _logger?.LogInformation("Discover and connect to device"); var miTemperatureHumidityMonitor = await _bleDeviceManager.ConnectByServiceUuidAsync("0F180A18".HexStringToByteArray()); _logger?.LogInformation("Read device status"); var battery = await miTemperatureHumidityMonitor.CharacteristicsByUuid[new Guid("00002a19-0000-1000-8000-00805f9b34fb")].ReadValueAsync(); var batteryLevel = battery[0]; var firmware = await miTemperatureHumidityMonitor.CharacteristicsByUuid[new Guid("00002a26-0000-1000-8000-00805f9b34fb")].ReadValueAsync(); var firmwareVersion = Encoding.ASCII.GetString(firmware).TrimEnd(new char[] { (char)0 }); _logger?.LogInformation($"Battery level: {batteryLevel}%"); _logger?.LogInformation($"Firmware version: {firmwareVersion}"); _logger?.LogInformation("Read device sensor data"); miTemperatureHumidityMonitor.CharacteristicsByUuid[new Guid("226caa55-6476-4566-7562-66734470666d")].ValueChanged += (sender, args) => { var dataString = Encoding.ASCII.GetString(args.Value).TrimEnd(new char[] { (char)0 }); var match = Regex.Match(dataString, @"T=([\d\.]*)\s+?H=([\d\.]*)"); if (match.Success) { var temperature = float.Parse(match.Groups[1].Captures[0].Value); var airHumidity = float.Parse(match.Groups[2].Captures[0].Value); _logger?.LogInformation($"Temperature: {temperature} °C"); _logger?.LogInformation($"Air humidity: {airHumidity}%"); } }; _logger?.LogInformation("Enable notifications"); await miTemperatureHumidityMonitor.CharacteristicsByUuid[new Guid("226caa55-6476-4566-7562-66734470666d")].WriteCccAsync(BleCccValue.NotificationsEnabled); var ccc = await miTemperatureHumidityMonitor.CharacteristicsByUuid[new Guid("226caa55-6476-4566-7562-66734470666d")].ReadCccAsync(); await Task.Delay(10000); await miTemperatureHumidityMonitor.DisconnectAsync(); _bleModuleConnection.Stop(); } } }
47.307692
167
0.649051
[ "MIT" ]
BGLibExt/BGLibExt.NET
BGLibExt.Samples.MiTemperatureHumidityMonitor/Program.cs
3,693
C#
namespace MbDotNet.Models.Responses.Fields { public abstract class ResponseFields { } }
14.428571
43
0.70297
[ "MIT" ]
DraKOCDS/MbDotNet
MbDotNet/Models/Responses/Fields/ResponseFields.cs
103
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // 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.Collections.Immutable; using System.Reflection.Metadata; #if SRM namespace System.Reflection.Metadata.Decoding #else namespace Roslyn.Reflection.Metadata.Decoding #endif { /// <summary> /// Represents a method (definition, reference, or standalone) or property signature. /// In the case of properties, the signature matches that of a getter with a distinguishing <see cref="SignatureHeader"/>. /// </summary> #if SRM && FUTURE public #endif internal struct MethodSignature<TType> { private readonly SignatureHeader _header; private readonly TType _returnType; private readonly int _requiredParameterCount; private readonly int _genericParameterCount; private readonly ImmutableArray<TType> _parameterTypes; public MethodSignature(SignatureHeader header, TType returnType, int requiredParameterCount, int genericParameterCount, ImmutableArray<TType> parameterTypes) { _header = header; _returnType = returnType; _genericParameterCount = genericParameterCount; _requiredParameterCount = requiredParameterCount; _parameterTypes = parameterTypes; } /// <summary> /// Represents the information in the leading byte of the signature (kind, calling convention, flags). /// </summary> public SignatureHeader Header { get { return _header; } } /// <summary> /// Gets the method's return type. /// </summary> public TType ReturnType { get { return _returnType; } } /// <summary> /// Gets the number of parameters that are required. Will be equal to the length <see cref="ParameterTypes"/> of /// unless this signature represents the standalone call site of a vararg method, in which case the entries /// extra entries in <see cref="ParameterTypes"/> are the types used for the optional parameters. /// </summary> public int RequiredParameterCount { get { return _requiredParameterCount; } } /// <summary> /// Gets the number of generic type parameters of the method. Will be 0 for non-generic methods. /// </summary> public int GenericParameterCount { get { return _genericParameterCount; } } /// <summary> /// Gets the method's parameter types. /// </summary> public ImmutableArray<TType> ParameterTypes { get { return _parameterTypes; } } } }
36.072289
165
0.650301
[ "Apache-2.0" ]
HaloFour/roslyn
src/Debugging/Roslyn.Reflection.Metadata.Decoding/MethodSignature.cs
2,994
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using Azure.Core; namespace Azure.ResourceManager.DesktopVirtualization.Models { /// <summary> ApplicationGroup properties that can be patched. </summary> public partial class ApplicationGroupPatch : Resource { /// <summary> Initializes a new instance of ApplicationGroupPatch. </summary> public ApplicationGroupPatch() { Tags = new ChangeTrackingDictionary<string, string>(); } /// <summary> Initializes a new instance of ApplicationGroupPatch. </summary> /// <param name="id"> Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. </param> /// <param name="name"> The name of the resource. </param> /// <param name="type"> The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. </param> /// <param name="tags"> tags to be updated. </param> /// <param name="description"> Description of ApplicationGroup. </param> /// <param name="friendlyName"> Friendly name of ApplicationGroup. </param> internal ApplicationGroupPatch(string id, string name, string type, IDictionary<string, string> tags, string description, string friendlyName) : base(id, name, type) { Tags = tags; Description = description; FriendlyName = friendlyName; } /// <summary> tags to be updated. </summary> public IDictionary<string, string> Tags { get; } /// <summary> Description of ApplicationGroup. </summary> public string Description { get; set; } /// <summary> Friendly name of ApplicationGroup. </summary> public string FriendlyName { get; set; } } }
45.590909
225
0.671984
[ "MIT" ]
maincotech/azure-sdk-for-net
sdk/desktopvirtualization/Azure.ResourceManager.DesktopVirtualization/src/Generated/Models/ApplicationGroupPatch.cs
2,006
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace System.Reflection { public static class RuntimeReflectionExtensions { private const BindingFlags everything = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; private static void CheckAndThrow(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); if (!(type is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); } private static void CheckAndThrow(MethodInfo method) { if (method == null) throw new ArgumentNullException(nameof(method)); if (!(method is RuntimeMethodInfo)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo")); } public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type) { CheckAndThrow(type); return type.GetProperties(everything); } public static IEnumerable<EventInfo> GetRuntimeEvents(this Type type) { CheckAndThrow(type); return type.GetEvents(everything); } public static IEnumerable<MethodInfo> GetRuntimeMethods(this Type type) { CheckAndThrow(type); return type.GetMethods(everything); } public static IEnumerable<FieldInfo> GetRuntimeFields(this Type type) { CheckAndThrow(type); return type.GetFields(everything); } public static PropertyInfo GetRuntimeProperty(this Type type, string name) { CheckAndThrow(type); return type.GetProperty(name); } public static EventInfo GetRuntimeEvent(this Type type, string name) { CheckAndThrow(type); return type.GetEvent(name); } public static MethodInfo GetRuntimeMethod(this Type type, string name, Type[] parameters) { CheckAndThrow(type); return type.GetMethod(name, parameters); } public static FieldInfo GetRuntimeField(this Type type, string name) { CheckAndThrow(type); return type.GetField(name); } public static MethodInfo GetRuntimeBaseDefinition(this MethodInfo method){ CheckAndThrow(method); return method.GetBaseDefinition(); } public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo, Type interfaceType) { if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo)); if (!(typeInfo is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); return typeInfo.GetInterfaceMap(interfaceType); } public static MethodInfo GetMethodInfo(this Delegate del) { if (del == null) throw new ArgumentNullException(nameof(del)); return del.Method; } } }
37.157303
143
0.649531
[ "MIT" ]
guhuro/coreclr
src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
3,307
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; namespace ComposingMethods.QuickWin { public class ModelState { public static void AddModelError(string key, string errorMessage) { } } public class QuickWin { private readonly SmtpClient _mailEngine = new SmtpClient(); public ActionResult ImportStudents(string csv) { foreach (string[] d in csv.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) .Select(line => line.Split(new[] { '|' }))) { int id; if (int.TryParse(d[0], out id)) { var existing = StudentRepository.GetById(id); if (existing == null) { var student = new Student { Id = id, FirstName = d[1], LastName = d[2], Email = d[3].ToLower(), ClassId = int.Parse(d[4]), Telephone = d[5], StreetName = d[6], StreetNumber = int.Parse(d[7]), ZipCode = d[8], City = d[9], }; string password = PasswordGenerator.CreateRandomPassword(); student.Password = Crypto.HashPassword(password); SendMailWithPassword(student.FirstName, student.LastName, student.Email, password); StudentRepository.Add(student); } else { ModelState.AddModelError("", $"Student with {id} already exists."); return View(); } } else { ModelState.AddModelError("", $"Student id {id} is not a number."); return View(); } } return View(); } private void SendMailWithPassword(string firstName, string lastName, string email, string password) { var msg = new MailMessage(new MailAddress("admin@university.com", "Admin"), new MailAddress(email, firstName + lastName)) { Body = string.Format("Dear {0},{0}{0}Welcome to the Refactoring University.{0}These are your login data.{0}Username: {3}{0}Password: {2}", firstName, Environment.NewLine, password, email), Subject = "New Student Account", }; _mailEngine.Send(msg); } private ActionResult View() { return new ActionResult(); } } #region Other Classes internal class Crypto { internal static string HashPassword(string password) { return null; } } internal class PasswordGenerator { internal static string CreateRandomPassword() { return null; } } internal class Student { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public int ClassId { get; set; } public string Telephone { get; set; } public int StreetNumber { get; set; } public string StreetName { get; set; } public string ZipCode { get; set; } public string City { get; set; } public string Password { get; internal set; } } internal class StudentRepository { internal static void Add(Student student) { } internal static Student GetById(int id) { return new Student(); } } public class ActionResult { } #endregion }
30.34058
154
0.465488
[ "MIT" ]
fabiogalante/refactoring-c-sharp
1ComposingMethods/00. Quick Win/QuickWin.cs
4,189
C#
using Pokloni.ba.WinUI.Korisnici; using Pokloni.ba.WinUI.Proizvodi; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Pokloni.ba.WinUI { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmLogin()); } } }
22.136364
65
0.669405
[ "MIT" ]
tarikcosovic/Cross-Platform-Application-Pokloni.ba-
Pokloni.ba.WinUI/Program.cs
489
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reflection; namespace Microsoft.Extensions.DependencyInjection.ServiceLookup { internal class GenericService : IGenericService { private readonly ServiceDescriptor _descriptor; public GenericService(ServiceDescriptor descriptor) { _descriptor = descriptor; } public ServiceLifetime Lifetime { get { return _descriptor.Lifetime; } } public IService GetService(Type closedServiceType) { Type[] genericArguments = closedServiceType.GetGenericArguments(); Type closedImplementationType = _descriptor.ImplementationType.MakeGenericType(genericArguments); var closedServiceDescriptor = new ServiceDescriptor(closedServiceType, closedImplementationType, Lifetime); return new Service(closedServiceDescriptor); } } }
32.029412
119
0.69146
[ "Apache-2.0" ]
Wodsoft/DependencyInjection
src/Microsoft.Extensions.DependencyInjection/ServiceLookup/GenericService.cs
1,089
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; namespace Api.Controllers { [Route("identity")] [Authorize] public class IdentityController : ControllerBase { [HttpGet] public IActionResult Get() { return new JsonResult(from c in User.Claims select new { c.Type, c.Value }); } } }
28.4
107
0.681338
[ "Apache-2.0" ]
samlu91/IdentityServer4.Samples
Quickstarts/1_ClientCredentials/Api/Controllers/IdentityController.cs
570
C#
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.ComponentModel.Composition; using System.Windows.Forms; using Sce.Atf; using Sce.Atf.Applications; using Sce.Sled.Shared; namespace Sce.Sled.Lua { [Export(typeof(IInitializable))] [Export(typeof(ISledLuaLuaVersionService))] [PartCreationPolicy(CreationPolicy.Shared)] sealed class SledLuaLuaVersionService : IInitializable, ISledLuaLuaVersionService { [ImportingConstructor] public SledLuaLuaVersionService(ICommandService commandService) { m_luaVerBox = new ToolStripComboBox("Lua Version"); { var ver = new VersionWrapper(LuaVersion.Lua51, "Lua 5.1.4"); m_luaVerBox.Items.Add(ver); m_luaVerBox.Items.Add(new VersionWrapper(LuaVersion.Lua52, "Lua 5.2.3")); m_luaVerBox.SelectedItem = ver; CurrentLuaVersion = ver.Version; } m_luaVerBox.SelectedIndexChanged += LuaVerBoxSelectedIndexChanged; } #region Implementation of IInitializable void IInitializable.Initialize() { SledLuaMenuShared.MenuInfo.GetToolStrip().Items.Add(m_luaVerBox); } #endregion #region Implementation of ISledLuaLuaVersionService public LuaVersion CurrentLuaVersion { get { return m_currentLuaVersion; } private set { if (m_currentLuaVersion == value) return; m_currentLuaVersion = value; SledOutDevice.OutLine(SledMessageType.Info, "[Lua]: Now using {0}", m_luaVerBox.SelectedItem); CurrentLuaVersionChanged.Raise(this, EventArgs.Empty); } } public event EventHandler CurrentLuaVersionChanged; #endregion private void LuaVerBoxSelectedIndexChanged(object sender, EventArgs e) { var wrapper = (VersionWrapper)m_luaVerBox.SelectedItem; CurrentLuaVersion = wrapper.Version; } #region Private Classes private class VersionWrapper { public VersionWrapper(LuaVersion version, string verString) { Version = version; m_verString = verString; } public LuaVersion Version { get; private set; } public override string ToString() { return m_verString; } private readonly string m_verString; } #endregion private LuaVersion m_currentLuaVersion; private readonly ToolStripComboBox m_luaVerBox; } public interface ISledLuaLuaVersionService { LuaVersion CurrentLuaVersion { get; } event EventHandler CurrentLuaVersionChanged; } public enum LuaVersion { Lua51, Lua52 } }
26.60177
110
0.608117
[ "Apache-2.0" ]
MasterScott/SLED
tool/SledLuaLanguagePlugin/SledLuaLuaVersionService.cs
3,006
C#
bool isSkewSymmetricMatrix(int[][] matrix) { for (int i = 0; matrix.Length > i; ++i) for (int j = 0; matrix[0].Length > j; ++j) if (matrix[i][j] != -matrix[j][i]) return false; return true; }
29.5
50
0.5
[ "MIT" ]
gurfinkel/codeSignal
tournaments/isSkewSymmetricMatrix/isSkewSymmetricMatrix.cs
236
C#
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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 System; using System.Security.Authentication; using Nini.Config; namespace OpenSim.Framework { public class NetworkServersInfo { public string AssetSendKey = String.Empty; public string AssetURL = "http://127.0.0.1:" + ConfigSettings.DefaultAssetServerHttpPort.ToString() + "/"; public string GridRecvKey = String.Empty; public string GridSendKey = String.Empty; public string GridURL = String.Empty; public uint HttpListenerPort = ConfigSettings.DefaultRegionHttpPort; public string InventoryURL = String.Empty; public bool secureInventoryServer = false; public bool isSandbox; private uint? m_defaultHomeLocX; private uint? m_defaultHomeLocY; public string UserRecvKey = String.Empty; public string UserSendKey = String.Empty; public string UserURL = String.Empty; public string HostName = String.Empty; public bool HttpUsesSSL = false; public string HttpSSLCN = String.Empty; public string HttpSSLCert = String.Empty; public string HttpSSLPassword = String.Empty; public uint httpSSLPort = 9001; public bool useHTTPS = false; public SslProtocols sslProtocol = SslProtocols.Default; public string MessagingURL = String.Empty; public NetworkServersInfo() { } public NetworkServersInfo(uint defaultHomeLocX, uint defaultHomeLocY) { m_defaultHomeLocX = defaultHomeLocX; m_defaultHomeLocY = defaultHomeLocY; } public uint DefaultHomeLocX { get { return m_defaultHomeLocX.Value; } } public uint DefaultHomeLocY { get { return m_defaultHomeLocY.Value; } } public void loadFromConfiguration(IConfigSource config) { m_defaultHomeLocX = (uint) config.Configs["StandAlone"].GetInt("default_location_x", 1000); m_defaultHomeLocY = (uint) config.Configs["StandAlone"].GetInt("default_location_y", 1000); HostName = config.Configs["Network"].GetString("hostname", Util.RetrieveListenAddress()); HttpListenerPort = (uint) config.Configs["Network"].GetInt("http_listener_port", (int) ConfigSettings.DefaultRegionHttpPort); httpSSLPort = (uint)config.Configs["Network"].GetInt("http_listener_sslport", ((int)ConfigSettings.DefaultRegionHttpPort+1)); HttpUsesSSL = config.Configs["Network"].GetBoolean("http_listener_ssl", false); HttpSSLCN = config.Configs["Network"].GetString("http_listener_cn", "localhost"); HttpSSLCert = config.Configs["Network"].GetString("http_listener_ssl_cert", String.Empty); HttpSSLPassword = config.Configs["Network"].GetString("http_listener_ssl_passwd", String.Empty); useHTTPS = config.Configs["Network"].GetBoolean("use_https", false); string sslproto = config.Configs["Network"].GetString("https_ssl_protocol", "Default"); try { sslProtocol = (SslProtocols)Enum.Parse(typeof(SslProtocols), sslproto); } catch { sslProtocol = SslProtocols.Default; } ConfigSettings.DefaultRegionRemotingPort = (uint) config.Configs["Network"].GetInt("remoting_listener_port", (int) ConfigSettings.DefaultRegionRemotingPort); GridURL = config.Configs["Network"].GetString("grid_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultGridServerHttpPort.ToString()); GridSendKey = config.Configs["Network"].GetString("grid_send_key", "null"); GridRecvKey = config.Configs["Network"].GetString("grid_recv_key", "null"); UserURL = config.Configs["Network"].GetString("user_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultUserServerHttpPort.ToString()); UserSendKey = config.Configs["Network"].GetString("user_send_key", "null"); UserRecvKey = config.Configs["Network"].GetString("user_recv_key", "null"); AssetURL = config.Configs["Network"].GetString("asset_server_url", AssetURL); InventoryURL = config.Configs["Network"].GetString("inventory_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultInventoryServerHttpPort.ToString()); secureInventoryServer = config.Configs["Network"].GetBoolean("secure_inventory_server", true); MessagingURL = config.Configs["Network"].GetString("messaging_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultMessageServerHttpPort); } } }
51.147287
137
0.651864
[ "BSD-3-Clause" ]
ConnectionMaster/halcyon
OpenSim/Framework/NetworkServersInfo.cs
6,598
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using DSharpPlus.Entities; namespace DSharpPlus.SlashCommands { /// <summary> /// All choice providers must inherit from this interface. /// </summary> public interface IChoiceProvider { /// <summary> /// Sets the choices for the slash command. /// </summary> Task<IEnumerable<DiscordApplicationCommandOptionChoice>> Provider(); } }
24.631579
76
0.675214
[ "MIT" ]
DSharpPlus/DSharpPlus
DSharpPlus.SlashCommands/IChoiceProvider.cs
468
C#
/** * Puma - CityEngine Plugin for Rhinoceros * * See https://esri.github.io/cityengine/puma for documentation. * * Copyright (c) 2021 Esri R&D Center Zurich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Grasshopper.Kernel; using Grasshopper.Kernel.Parameters; using Grasshopper.Kernel.Types; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PumaGrasshopper { public enum ReportTypes { PT_PT_UNDEFINED, ///< Undefined type. PT_STRING, ///< String type. PT_FLOAT, ///< Float type. PT_BOOL, ///< Boolean type. PT_INT, ///< Integer type. PT_STRING_ARRAY, ///< String array type. PT_FLOAT_ARRAY, ///< Float array type. PT_BOOL_ARRAY, ///< Boolean array type. PT_INT_ARRAY, ///< Integer array type. PT_BLIND_DATA, ///< Blind data type. PT_BLIND_DATA_ARRAY, ///< Blind data array type. PT_COUNT }; public class ReportAttribute: GH_Goo<Param_GenericObject> { private readonly string mKey; private readonly ReportTypes mType; public override bool IsValid => true; public override string TypeName => "ReportAttribute"; public override string TypeDescription => "Contains a cga report {key : value} where key is the report name and value is either a double, a boolean or a string."; public int InitialShapeIndex { get; } public string StringValue { get; set; } = ""; public double DoubleValue { get; set; } = 0; public bool BoolValue { get; set; } = false; public ReportAttribute(int initialShapeIndex, string key, ReportTypes type) : base() { this.InitialShapeIndex = initialShapeIndex; this.mKey = key; this.mType = type; } public string GetFormatedValue() { switch(mType) { case ReportTypes.PT_FLOAT: return DoubleValue.ToString(); case ReportTypes.PT_STRING: return StringValue; case ReportTypes.PT_BOOL: return BoolValue.ToString(); default: return "UNDEFINED"; } } public string GetReportKey() { return mKey; } public ReportTypes GetReportType() { return mType; } public static ReportAttribute CreateReportAttribute(int initialShapeIndex, string name, ReportTypes type, string value) { ReportAttribute report = new ReportAttribute(initialShapeIndex, name, type) { StringValue = value }; return report; } public static ReportAttribute CreateReportAttribute(int initialShapeIndex, string name, ReportTypes type, double value) { ReportAttribute report = new ReportAttribute(initialShapeIndex, name, type) { DoubleValue = value }; return report; } public static ReportAttribute CreateReportAttribute(int initialShapeIndex, string name, ReportTypes type, bool value) { ReportAttribute report = new ReportAttribute(initialShapeIndex, name, type) { BoolValue = value }; return report; } public override IGH_Goo Duplicate() { return this; } public override string ToString() { return "[ InitialShapeIndex: " + InitialShapeIndex + ", Key: " + mKey + ", Value: " + GetFormatedValue() + " ]"; } public string ToNiceString() { return " " + mKey + " : " + GetFormatedValue(); } } }
32.353383
170
0.611201
[ "Apache-2.0" ]
Esri/puma
PumaGrasshopper/ReportAttribute.cs
4,305
C#
using System.Threading.Tasks; using Qmmands; namespace Volte.Commands { public abstract class ActionResult : CommandResult { public override bool IsSuccessful => true; public abstract ValueTask<ResultCompletionData> ExecuteResultAsync(VolteContext ctx); public static implicit operator Task<ActionResult>(ActionResult res) => Task.FromResult(res); } }
26.866667
93
0.717122
[ "MIT" ]
BoredManCodes/Bolte
src/Commands/Results/ActionResult.cs
403
C#
using System; using System.Diagnostics; namespace Bistrotic.Application.Commands { [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class CommandHandlerAttribute : Attribute { public Type? Command { get; set; } private string DebuggerDisplay => $"{Command?.Name} command handler"; } }
28.785714
77
0.694789
[ "MIT" ]
Bistrotic/Bistrotic
src/Core/Application/Bistrotic.Application.Abstractions/Commands/CommandHandlerAttribute.cs
405
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Practices.Composite.Presentation.Events; using Microsoft.Practices.Composite.Presentation.Commands; using System.Windows.Data; using System.ComponentModel; using System.Windows; namespace EclipsePOS.WPF.SystemManager.PosSetup.Views.Customer { public class CustomerViewPresenter { private ICustomerView _view; private CollectionView _colView; private EclipsePOS.WPF.SystemManager.Data.customerDataSet customerData; private EclipsePOS.WPF.SystemManager.Data.organizationLookupDataSet organizationData; private EclipsePOS.WPF.SystemManager.Data.customerDataSetTableAdapters.TableAdapterManager taManager = new EclipsePOS.WPF.SystemManager.Data.customerDataSetTableAdapters.TableAdapterManager(); public DelegateCommand<object> MoveToFirstCommand; public DelegateCommand<object> MoveToPreviousCommand; public DelegateCommand<object> MoveToNextCommand; public DelegateCommand<object> MoveToLastCommand; public DelegateCommand<object> DeleteCommand; public DelegateCommand<object> AddCommand; public DelegateCommand<object> RevertCommand; public DelegateCommand<object> SaveCommand; public CustomerViewPresenter() { MoveToFirstCommand = new DelegateCommand<object>(OnMoveToFirstCommandExecute, OnMoveToFirstCommandCanExecute); MoveToPreviousCommand = new DelegateCommand<object>(OnMoveToPreviousCommandExecute, OnMoveToPreviousCommandCanExecute); MoveToNextCommand = new DelegateCommand<object>(OnMoveToNextCommandExecute, OnMoveToNextCommandCanExecute); MoveToLastCommand = new DelegateCommand<object>(OnMoveToLastCommandExecute, OnMoveToLastCommandCanExecute); DeleteCommand = new DelegateCommand<object>(OnDeleteCommandExecute, OnDeleteCommandCanExecute); AddCommand = new DelegateCommand<object>(OnAddCommandExecute, OnAddCommandCanExecute); RevertCommand = new DelegateCommand<object>(OnRevertCommandExecute, OnRevertCommandCanExecute); SaveCommand = new DelegateCommand<object>(OnSaveCommandExecute, OnSaveCommandCanExecute); } public ICustomerView View { set { _view = value; } get { return _view; } } public void OnShowCustomer() { //Organization organizationData = new EclipsePOS.WPF.SystemManager.Data.organizationLookupDataSet(); EclipsePOS.WPF.SystemManager.Data.organizationLookupDataSetTableAdapters.organizationTableAdapter organizationTa = new EclipsePOS.WPF.SystemManager.Data.organizationLookupDataSetTableAdapters.organizationTableAdapter(); organizationTa.Fill(organizationData.organization); View.SetOrganizationDataContext(organizationData.organization); //Customer customerData = new EclipsePOS.WPF.SystemManager.Data.customerDataSet(); EclipsePOS.WPF.SystemManager.Data.customerDataSetTableAdapters.customerTableAdapter customerTa = new EclipsePOS.WPF.SystemManager.Data.customerDataSetTableAdapters.customerTableAdapter(); customerTa.Fill(customerData.customer); View.SetCustomerDataContext(customerData.customer); _colView = CollectionViewSource.GetDefaultView(customerData.customer) as CollectionView; taManager.customerTableAdapter = customerTa; View.SetMoveToFirstBtnDataContext(MoveToFirstCommand); View.SetMoveToPreviousBtnDataContext(MoveToPreviousCommand); View.SetMoveToNextBtnDataContext(MoveToNextCommand); View.SetMoveToLastBtnDataContext(MoveToLastCommand); View.SetDeleteBtnDataContext(DeleteCommand); View.SetAddBtnDataContext(AddCommand); View.SetRevertBtnDataContext(RevertCommand); View.SetSaveBtnDataContext(SaveCommand); _colView.CurrentChanged +=new EventHandler(_colView_CurrentChanged); } void _colView_CurrentChanged(object sender, EventArgs e) { if (_colView.IsEmpty || _colView.IsCurrentAfterLast || _colView.IsCurrentBeforeFirst) { View.SetColumnsEnabled(false); } else { View.SetColumnsEnabled(true); } } #region MoveToFirst Command public void OnMoveToFirstCommandExecute(object obj) { _colView.MoveCurrentToFirst(); View.SetSelectedItemCursor(); } public bool OnMoveToFirstCommandCanExecute(object obj) { // Implement business logic for myCommand enablement. return true; } #endregion #region MoveToPrevioust Command public void OnMoveToPreviousCommandExecute(object obj) { _colView.MoveCurrentToPrevious(); if (_colView.IsCurrentBeforeFirst) _colView.MoveCurrentToFirst(); View.SetSelectedItemCursor(); } public bool OnMoveToPreviousCommandCanExecute(object obj) { // Implement business logic for myCommand enablement. return true; } #endregion #region MoveToNext Command public void OnMoveToNextCommandExecute(object obj) { _colView.MoveCurrentToNext(); if (_colView.IsCurrentAfterLast) _colView.MoveCurrentToLast(); View.SetSelectedItemCursor(); } public bool OnMoveToNextCommandCanExecute(object obj) { // Implement business logic for myCommand enablement. return true; } #endregion #region MoveToLast Command public void OnMoveToLastCommandExecute(object obj) { _colView.MoveCurrentToLast(); View.SetSelectedItemCursor(); } public bool OnMoveToLastCommandCanExecute(object obj) { // Implement business logic for myCommand enablement. return true; } #endregion #region Delete Command public void OnDeleteCommandExecute(object obj) { try { System.Data.DataRow dataRow = ((System.Data.DataRowView)_colView.CurrentItem).Row; dataRow.Delete(); } catch { } } public bool OnDeleteCommandCanExecute(object obj) { // Implement business logic for myCommand enablement. return true; } #endregion #region Add Command public void OnAddCommandExecute(object obj) { if (string.IsNullOrEmpty(View.SelectedOrganizationNo())) { Microsoft.Windows.Controls.MessageBox.Show("Please set the default organization and try this option again", "Add command", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (!customerData.HasErrors) { EclipsePOS.WPF.SystemManager.Data.customerDataSet.customerRow dataRow = customerData.customer.NewcustomerRow(); dataRow.addr1 = ""; dataRow.organization_no = this.View.SelectedOrganizationNo(); dataRow.addr2 = ""; dataRow.alt_phone = ""; dataRow.card = ""; dataRow.city = ""; dataRow.country = ""; dataRow.current_debt = 0; dataRow.customer_first_name = ""; dataRow.customer_last_name = ""; dataRow.customer_search_key = ""; dataRow.creation_date = System.DateTime.Now; dataRow.email = ""; dataRow.fax = ""; dataRow.max_debt = 0; dataRow.notes = ""; dataRow.phone = ""; dataRow.postel_code = ""; dataRow.region = ""; dataRow.status = 1; dataRow.tax_id = ""; customerData.customer.AddcustomerRow(dataRow); _colView.MoveCurrentToLast(); View.SetSelectedItemCursor(); View.SetFocusToFirstElement(); } } public bool OnAddCommandCanExecute(object obj) { // Implement business logic for myCommand enablement. return true; } #endregion #region Revert Command public void OnRevertCommandExecute(object obj) { if (customerData.HasChanges()) { MessageBoxResult result = Microsoft.Windows.Controls.MessageBox.Show("Are sure you want to loose all your changes", "Revert command", MessageBoxButton.YesNo, MessageBoxImage.Warning); if ( result == MessageBoxResult.Yes) { customerData.RejectChanges(); } } } public bool OnRevertCommandCanExecute(object obj) { // Implement business logic for myCommand enablement. return true; } #endregion #region Save Command public void OnSaveCommandExecute(object obj) { if (customerData.HasErrors) { Microsoft.Windows.Controls.MessageBox.Show("Please correct the errors first", "Save command", MessageBoxButton.OK, MessageBoxImage.Error); } else { if (customerData.HasChanges()) { try { if (taManager.UpdateAll(customerData) > 0) { Microsoft.Windows.Controls.MessageBox.Show("Saved", "Save command", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { Microsoft.Windows.Controls.MessageBox.Show("Unable to save changes" , "Save command", MessageBoxButton.OK, MessageBoxImage.Error); this.customerData.RejectChanges(); } } } } public bool OnSaveCommandCanExecute(object obj) { // Implement business logic for myCommand enablement. return true; } #endregion public void FilterCustomerByOrganizationNo(string organizationNo) { BindingListCollectionView view2 = CollectionViewSource.GetDefaultView(this.customerData.customer) as BindingListCollectionView; if (view2 != null) { view2.CustomFilter = "organization_no = '" + organizationNo + "'"; } } } }
33.402402
231
0.608559
[ "MIT" ]
naushard/EclipsePOS
V.1.0.8/EclipsePOS.WPF.SystemManager/EclipsePOS.WPF.SystemManager.PosSetup/Views/Customer/CustomerViewPresenter.cs
11,125
C#
using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace myBOOKs.Droid { [Activity(Label = "myBOOKs", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
41
270
0.722099
[ "MIT" ]
felipe-felizardo/myBOOKs
myBOOKs/myBOOKs.Android/MainActivity.cs
1,355
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; using System.Diagnostics; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Intermediate; namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X; public class AssemblyAttributeInjectionPass : IntermediateNodePassBase, IRazorOptimizationPass { private const string RazorViewAttribute = "global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute"; private const string RazorPageAttribute = "global::Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.RazorPageAttribute"; protected override void ExecuteCore(RazorCodeDocument codeDocument, DocumentIntermediateNode documentNode) { if (documentNode.Options.DesignTime) { return; } var @namespace = documentNode.FindPrimaryNamespace(); if (@namespace == null || string.IsNullOrEmpty(@namespace.Content)) { // No namespace node or it's incomplete. Skip. return; } var @class = documentNode.FindPrimaryClass(); if (@class == null || string.IsNullOrEmpty(@class.ClassName)) { // No class node or it's incomplete. Skip. return; } var generatedTypeName = $"{@namespace.Content}.{@class.ClassName}"; // The MVC attributes require a relative path to be specified so that we can make a view engine path. // We can't use a rooted path because we don't know what the project root is. // // If we can't sanitize the path, we'll just set it to null and let is blow up at runtime - we don't // want to create noise if this code has to run in some unanticipated scenario. var escapedPath = MakeVerbatimStringLiteral(ConvertToViewEnginePath(codeDocument.Source.RelativePath)); string attribute; if (documentNode.DocumentKind == MvcViewDocumentClassifierPass.MvcViewDocumentKind) { attribute = $"[assembly:{RazorViewAttribute}({escapedPath}, typeof({generatedTypeName}))]"; } else if (documentNode.DocumentKind == RazorPageDocumentClassifierPass.RazorPageDocumentKind && PageDirective.TryGetPageDirective(documentNode, out var pageDirective)) { var escapedRoutePrefix = MakeVerbatimStringLiteral(pageDirective.RouteTemplate); attribute = $"[assembly:{RazorPageAttribute}({escapedPath}, typeof({generatedTypeName}), {escapedRoutePrefix})]"; } else { return; } var index = documentNode.Children.IndexOf(@namespace); Debug.Assert(index >= 0); var pageAttribute = new CSharpCodeIntermediateNode(); pageAttribute.Children.Add(new IntermediateToken() { Kind = TokenKind.CSharp, Content = attribute, }); documentNode.Children.Insert(index, pageAttribute); } private static string MakeVerbatimStringLiteral(string value) { if (value == null) { return "null"; } value = value.Replace("\"", "\"\""); return $"@\"{value}\""; } private static string ConvertToViewEnginePath(string relativePath) { if (string.IsNullOrEmpty(relativePath)) { return null; } // Checking for both / and \ because a \ will become a /. if (!relativePath.StartsWith("/", StringComparison.Ordinal) && !relativePath.StartsWith("\\", StringComparison.Ordinal)) { relativePath = "/" + relativePath; } relativePath = relativePath.Replace('\\', '/'); return relativePath; } }
36.390476
128
0.651924
[ "MIT" ]
dotnet/razor-compiler
src/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/AssemblyAttributeInjectionPass.cs
3,823
C#
using Aow.Infrastructure.IRepositories; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Aow.Services.UserPayment { [Service] public class GetUserPayments { private IRepositoryWrapper _repoWrapper; public GetUserPayments(IRepositoryWrapper repoWrapper) { _repoWrapper = repoWrapper; } public class UserPaymentsResponse { public Guid Id { get; set; } public string RazorpayPaymentId { get; set; } public string RazorpayOrderId { get; set; } public string RazorpaySignature { get; set; } public string RazorReference { get; set; } public string SessionId { get; set; } public string UserId { get; set; } public Guid CompanyId { get; set; } public string Email { get; set; } public string ContactNo { get; set; } public decimal Amount { get; set; } public string upi { get; set; } public string rrnNo { get; set; } public string status { get; set; } public string AddressLine1 { get; set; } public string City { get; set; } public string PostCode { get; set; } public DateTime StartDateUtc { get; set; } public DateTime EndDateUtc { get; set; } public string Currency { get; set; } public string Receipt { get; set; } public string Offerid { get; set; } public string Attempts { get; set; } public string Notes { get; set; } public string CreatedAt { get; set; } public int NoOfDays { get; set; } } public async Task<IEnumerable<UserPaymentsResponse>> Do(string userName, Guid cmpId) { var user = await _repoWrapper.UserRepo.GetUserByName(userName); if (user == null) { return null; }; var list = _repoWrapper.CompanyRepo.GetCompany(cmpId); // var list = _repoWrapper.UserPaymentRepo.GetUserPaymentsByCompany(pagingParameters, user.Id,cmpId).GetAwaiter().GetResult(); // var list = _companyRepository.GetCompanies(pagingParameters).GetAwaiter().GetResult(); var newList = list.UserPayments.Select(x => new UserPaymentsResponse { Id = x.Id, CompanyId = x.CompanyId, StartDateUtc = x.Company.StartDateUtc, EndDateUtc = x.Company.EndDateUtc, NoOfDays = x.Company.NoOfDays }); return newList; } } }
38.098592
139
0.572643
[ "Apache-2.0" ]
dpk2789/aow-new-api
Aow.Services/UserPayment/GetUserPayments.cs
2,707
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the auditmanager-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AuditManager.Model { /// <summary> /// This is the response object from the BatchAssociateAssessmentReportEvidence operation. /// </summary> public partial class BatchAssociateAssessmentReportEvidenceResponse : AmazonWebServiceResponse { private List<AssessmentReportEvidenceError> _errors = new List<AssessmentReportEvidenceError>(); private List<string> _evidenceIds = new List<string>(); /// <summary> /// Gets and sets the property Errors. /// <para> /// A list of errors that the <code>BatchAssociateAssessmentReportEvidence</code> API /// returned. /// </para> /// </summary> public List<AssessmentReportEvidenceError> Errors { get { return this._errors; } set { this._errors = value; } } // Check to see if Errors property is set internal bool IsSetErrors() { return this._errors != null && this._errors.Count > 0; } /// <summary> /// Gets and sets the property EvidenceIds. /// <para> /// The list of evidence identifiers. /// </para> /// </summary> [AWSProperty(Min=0, Max=50)] public List<string> EvidenceIds { get { return this._evidenceIds; } set { this._evidenceIds = value; } } // Check to see if EvidenceIds property is set internal bool IsSetEvidenceIds() { return this._evidenceIds != null && this._evidenceIds.Count > 0; } } }
32
110
0.63742
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/AuditManager/Generated/Model/BatchAssociateAssessmentReportEvidenceResponse.cs
2,496
C#
using Millistream.Streaming.DataTypes.Parsing; using System; using System.Text; namespace Millistream.Streaming.DataTypes { /// <summary> /// Represents a semi-annual calendar year. /// </summary> public readonly struct SemiAnnual : IComparable, IComparable<SemiAnnual>, IEquatable<SemiAnnual> { #region Fields private readonly int _comparableValue; #endregion #region Constructors /// <summary> /// Creates an instance of a <see cref="SemiAnnual"/>. /// </summary> /// <param name="year">A calendar year.</param> /// <param name="number">A value between 1 and 2 that represents the half of the calendar year.</param> public SemiAnnual(Year year, int number) { Number = (number < 1 || number > 2) ? throw new ArgumentOutOfRangeException(nameof(number)) : number; Year = year; _comparableValue = year * 2 + number; } #endregion #region Properties /// <summary> /// Gets the <see cref="Year"/> of the <see cref="SemiAnnual"/>. /// </summary> public readonly Year Year { get; } /// <summary> /// Gets the half of the <see cref="Year"/> of the <see cref="SemiAnnual"/>. /// </summary> public readonly int Number { get; } #endregion #region Methods /// <summary> /// Converts a memory span that contains a UTF-8 string representation of a semi-annual year on the format YYYY-Hx, where x is an integer between 1 and 2, to its <see cref="SemiAnnual"/> equivalent. /// </summary> /// <param name="value">The memory span that contains the UTF-8 string value to parse.</param> /// <returns>A <see cref="SemiAnnual"/> object that is equivalent to the value contained in <paramref name="value"/>.</returns> /// <exception cref="ArgumentException"></exception> public static SemiAnnual Parse(ReadOnlySpan<char> value) => TryParse(value, out SemiAnnual semiAnnual) ? semiAnnual : throw new ArgumentException(Constants.ParseArgumentExceptionMessage, nameof(value)); /// <summary> /// Converts a memory span that contains the bytes of a UTF-8 string representation of a semi-annual year on the format YYYY-Hx, where x is an integer between 1 and 2, to its <see cref="SemiAnnual"/> equivalent. /// </summary> /// <param name="value">The memory span that contains the bytes of the UTF-8 string value to parse.</param> /// <returns>A <see cref="SemiAnnual"/> object that is equivalent to the value contained in <paramref name="value"/>.</returns> /// <exception cref="ArgumentException"></exception> public static SemiAnnual Parse(ReadOnlySpan<byte> value) => TryParse(value, out SemiAnnual semiAnnual) ? semiAnnual : throw new ArgumentException(Constants.ParseArgumentExceptionMessage, nameof(value)); /// <summary> /// Tries to convert a memory span that contains a UTF-8 string representation of a semi-annual year on the format YYYY-Hx, where x is an integer between 1 and 2, to its <see cref="Date"/> equivalent and returns a value that indicates whether the conversion succeeded. /// </summary> /// <param name="value">The memory span that contains the UTF-8 string value to parse.</param> /// <param name="semiAnnual">Contains the <see cref="SemiAnnual"/> value equivalent to the value contained in <paramref name="value"/>, if the conversion succeeded, or default if the conversion failed.</param> /// <returns>true if the <paramref name="value"/> parameter was converted successfully; otherwise, false.</returns> public static bool TryParse(ReadOnlySpan<char> value, out SemiAnnual semiAnnual) { if (value.Length == 7) { Span<byte> bytes = stackalloc byte[7]; Encoding.UTF8.GetBytes(value, bytes); return TryParse(bytes, out semiAnnual); } semiAnnual = default; return false; } /// <summary> /// Tries to convert a memory span that contains bet bytes of a UTF-8 string representation of a semi-annual year on the format YYYY-Hx, where x is an integer between 1 and 2, to its <see cref="SemiAnnual"/> equivalent and returns a value that indicates whether the conversion succeeded. /// </summary> /// <param name="value">The memory span that contains the bytes of the UTF-8 string value to parse.</param> /// <param name="semiAnnual">Contains the <see cref="SemiAnnual"/> value equivalent to the value contained in <paramref name="value"/>, if the conversion succeeded, or default if the conversion failed.</param> /// <returns>true if the <paramref name="value"/> parameter was converted successfully; otherwise, false.</returns> public static bool TryParse(ReadOnlySpan<byte> value, out SemiAnnual semiAnnual) { if (value.Length == 7 && value[4] == (byte)'-' && value[5] == (byte)'H' && Utf8Parser.TryParse(value.Slice(0, 4), out uint year) && Utf8Parser.TryParse(value.Slice(6, 1), out uint h)) { try { semiAnnual = new SemiAnnual(new Year((int)year), (int)h); return true; } catch { } } semiAnnual = default; return false; } /// <summary> /// Compares this instance to a specified object and returns an indication of their relative values. /// </summary> /// <param name="obj">An object to compare, or null.</param> /// <returns>A signed number indicating the relative values of this instance and <paramref name="obj"/>.</returns> public readonly int CompareTo(object obj) { if (obj == null) return 1; if (!(obj is SemiAnnual semiAnnual)) throw new ArgumentException($"Argument must be of type {nameof(SemiAnnual)}.", nameof(obj)); return CompareTo(semiAnnual); } /// <summary> /// Compares this instance to a specified <see cref="SemiAnnual"/> object and returns an indication of their relative values. /// </summary> /// <param name="other">A <see cref="SemiAnnual"/> object to compare.</param> /// <returns>A signed number indicating the relative values of this instance and <paramref name="other"/>.</returns> public readonly int CompareTo(SemiAnnual other) => _comparableValue.CompareTo(other._comparableValue); /// <summary> /// Returns a value indicating whether this instance is equal to a specified <see cref="SemiAnnual"/> value. /// </summary> /// <param name="other">A <see cref="SemiAnnual"/> value to compare to this instance.</param> /// <returns>true if <paramref name="other"/> has the same value as this instance; otherwise, false.</returns> public readonly bool Equals(SemiAnnual other) => _comparableValue == other._comparableValue; /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A 32-bit signed integer hash code.</returns> public readonly override int GetHashCode() => _comparableValue.GetHashCode(); /// <summary> /// Returns a value indicating whether this instance is equal to a specified object. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>true if <paramref name="obj"/> is an instance of <see cref="SemiAnnual"/> and equals the value of this instance; otherwise, false.</returns> public readonly override bool Equals(object obj) => obj is SemiAnnual semiAnnual && Equals(semiAnnual); /// <summary> /// Converts the value of the current <see cref="SemiAnnual"/> object to its equivalent string representation. /// </summary> /// <returns>A string representation of the value of the current <see cref="SemiAnnual"/> object.</returns> public readonly override string ToString() => $"{Year}-H{Number}"; #endregion #region Operators /// <summary> /// Indicates whether two <see cref="SemiAnnual"/> instances are equal. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>true if the values of <paramref name="left"/> and <paramref name="right"/> are equal; otherwise, false.</returns> public static bool operator ==(SemiAnnual left, SemiAnnual right) => left.Equals(right); /// <summary> /// Indicates whether two <see cref="SemiAnnual"/> instances are not equal. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>true if the values of <paramref name="left"/> and <paramref name="right"/> are not equal; otherwise, false.</returns> public static bool operator !=(SemiAnnual left, SemiAnnual right) => !left.Equals(right); /// <summary> /// Determines whether one specified <see cref="SemiAnnual"/> is earlier than another specified <see cref="SemiAnnual"/>. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>true if <paramref name="left"/> is earlier than <paramref name="right"/>; otherwise, false.</returns> public static bool operator <(SemiAnnual left, SemiAnnual right) => left.CompareTo(right) < 0; /// <summary> /// Determines whether one specified <see cref="SemiAnnual"/> is the same as or earlier than another specified <see cref="SemiAnnual"/>. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>true if <paramref name="left"/> is the same as or earlier than <paramref name="right"/>; otherwise, false.</returns> public static bool operator <=(SemiAnnual left, SemiAnnual right) => left.CompareTo(right) <= 0; /// <summary> /// Determines whether one specified <see cref="SemiAnnual"/> is later than another specified <see cref="SemiAnnual"/>. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>true if <paramref name="left"/> is later than <paramref name="right"/>; otherwise, false.</returns> public static bool operator >(SemiAnnual left, SemiAnnual right) => left.CompareTo(right) > 0; /// <summary> /// Determines whether one specified <see cref="SemiAnnual"/> is the same as or later than another specified <see cref="SemiAnnual"/>. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>true if <paramref name="left"/> is the same as or later than <paramref name="right"/>; otherwise, false.</returns> public static bool operator >=(SemiAnnual left, SemiAnnual right) => left.CompareTo(right) >= 0; #endregion } }
57.166667
295
0.627165
[ "MIT" ]
mgnsm/Millistream.NET
Source/Millistream.Streaming.DataTypes/SemiAnnual.cs
11,664
C#
namespace TelegramClient.UnitTests.Framework { using Autofac; public abstract class TestBase { public ContainerBuilder ContainerBuilder { get; } = new ContainerBuilder(); private IContainer _container; public IContainer Container => _container ?? (_container = ContainerBuilder.Build()); } }
28.75
94
0.675362
[ "MIT" ]
a-rahmani1998/TelegramClient
tests/TelegramClient.UnitTests/Framework/TestBase.cs
347
C#
namespace Win.TiendaElectronicos { partial class FormReporteVentas { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.crystalReportViewer1 = new CrystalDecisions.Windows.Forms.CrystalReportViewer(); this.SuspendLayout(); // // crystalReportViewer1 // this.crystalReportViewer1.ActiveViewIndex = -1; this.crystalReportViewer1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.crystalReportViewer1.Cursor = System.Windows.Forms.Cursors.Default; this.crystalReportViewer1.Dock = System.Windows.Forms.DockStyle.Fill; this.crystalReportViewer1.Location = new System.Drawing.Point(0, 0); this.crystalReportViewer1.Name = "crystalReportViewer1"; this.crystalReportViewer1.ShowGroupTreeButton = false; this.crystalReportViewer1.Size = new System.Drawing.Size(419, 359); this.crystalReportViewer1.TabIndex = 0; this.crystalReportViewer1.ToolPanelView = CrystalDecisions.Windows.Forms.ToolPanelViewType.None; // // FormReporteVentas // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(419, 359); this.Controls.Add(this.crystalReportViewer1); this.Name = "FormReporteVentas"; this.Text = "Reporte Ventas"; this.ResumeLayout(false); } #endregion private CrystalDecisions.Windows.Forms.CrystalReportViewer crystalReportViewer1; } }
39.904762
108
0.616945
[ "MIT" ]
Daniel-LM94/Ventas
1.6 - Tienda Electronicos/TiendaElectronicos/Win.TiendaElectronicos/FormReporteVentas.Designer.cs
2,516
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the route53-2013-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Route53.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.Route53.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GetHealthCheck operation /// </summary> public class GetHealthCheckResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { GetHealthCheckResponse response = new GetHealthCheckResponse(); UnmarshallResult(context,response); return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, GetHealthCheckResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 1; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("HealthCheck", targetDepth)) { var unmarshaller = HealthCheckUnmarshaller.Instance; response.HealthCheck = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return; } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("IncompatibleVersion")) { return IncompatibleVersionExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInput")) { return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchHealthCheck")) { return NoSuchHealthCheckExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonRoute53Exception(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static GetHealthCheckResponseUnmarshaller _instance = new GetHealthCheckResponseUnmarshaller(); internal static GetHealthCheckResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetHealthCheckResponseUnmarshaller Instance { get { return _instance; } } } }
38.440299
163
0.60629
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Route53/Generated/Model/Internal/MarshallTransformations/GetHealthCheckResponseUnmarshaller.cs
5,151
C#
namespace Atlas.Roleplay.Library.Events { public enum EventType { Send, Request, Response } }
14.333333
39
0.565891
[ "MIT" ]
Local9/Atlas
Atlas.Roleplay.Library/Events/EventType.cs
129
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\MethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type WorkbookFunctionsFixedRequestBuilder. /// </summary> public partial class WorkbookFunctionsFixedRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsFixedRequest>, IWorkbookFunctionsFixedRequestBuilder { /// <summary> /// Constructs a new <see cref="WorkbookFunctionsFixedRequestBuilder"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="number">A number parameter for the OData method call.</param> /// <param name="decimals">A decimals parameter for the OData method call.</param> /// <param name="noCommas">A noCommas parameter for the OData method call.</param> public WorkbookFunctionsFixedRequestBuilder( string requestUrl, IBaseClient client, Newtonsoft.Json.Linq.JToken number, Newtonsoft.Json.Linq.JToken decimals, Newtonsoft.Json.Linq.JToken noCommas) : base(requestUrl, client) { this.SetParameter("number", number, true); this.SetParameter("decimals", decimals, true); this.SetParameter("noCommas", noCommas, true); } /// <summary> /// A method used by the base class to construct a request class instance. /// </summary> /// <param name="functionUrl">The request URL to </param> /// <param name="options">The query and header options for the request.</param> /// <returns>An instance of a specific request class.</returns> protected override IWorkbookFunctionsFixedRequest CreateRequest(string functionUrl, IEnumerable<Option> options) { var request = new WorkbookFunctionsFixedRequest(functionUrl, this.Client, options); if (this.HasParameter("number")) { request.RequestBody.Number = this.GetParameter<Newtonsoft.Json.Linq.JToken>("number"); } if (this.HasParameter("decimals")) { request.RequestBody.Decimals = this.GetParameter<Newtonsoft.Json.Linq.JToken>("decimals"); } if (this.HasParameter("noCommas")) { request.RequestBody.NoCommas = this.GetParameter<Newtonsoft.Json.Linq.JToken>("noCommas"); } return request; } } }
43.914286
165
0.607027
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsFixedRequestBuilder.cs
3,074
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <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 ASP { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Web.Mvc.Html; using System.Web.Routing; using System.Web.Security; using System.Web.UI; using System.Web.WebPages; #line 2 "..\..\Views\EditFriendlyMatch.cshtml" using ClientDependency.Core.Mvc; #line default #line hidden using Examine; #line 4 "..\..\Views\EditFriendlyMatch.cshtml" using Stoolball.Security; #line default #line hidden #line 3 "..\..\Views\EditFriendlyMatch.cshtml" using Stoolball.Web.Matches; #line default #line hidden using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web; using Umbraco.Web.Mvc; using Umbraco.Web.PublishedModels; [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")] [System.Web.WebPages.PageVirtualPathAttribute("~/Views/EditFriendlyMatch.cshtml")] public partial class _Views_EditFriendlyMatch_cshtml : Umbraco.Web.Mvc.UmbracoViewPage<EditFriendlyMatchViewModel> { public _Views_EditFriendlyMatch_cshtml() { } public override void Execute() { DefineSection("head", () => { WriteLiteral("\r\n <meta"); WriteLiteral(" name=\"robots\""); WriteLiteral(" content=\"noindex,follow\""); WriteLiteral(" />\r\n"); }); #line 8 "..\..\Views\EditFriendlyMatch.cshtml" Html.EnableClientValidation(); Html.EnableUnobtrusiveJavaScript(); Html.RequiresJs("~/scripts/jquery.validate.min.js"); Html.RequiresJs("~/scripts/jquery.validate.unobtrusive.min.js"); Html.RequiresJs("~/js/libs/jquery.autocomplete.min.js", 50); Html.RequiresCss("~/css/autocomplete.min.css"); Html.RequiresCss("~/css/related-items.min.css"); Html.RequiresJs("~/js/related-item.js"); Html.RequiresJs("/umbraco/lib/tinymce/tinymce.min.js", 90); Html.RequiresJs("/js/tinymce.js"); #line default #line hidden WriteLiteral("\r\n<div"); WriteLiteral(" class=\"container-xl\""); WriteLiteral(">\r\n <h1>Edit "); #line 24 "..\..\Views\EditFriendlyMatch.cshtml" Write(Html.MatchFullName(Model.Match, x => Model.DateFormatter.FormatDate(x, false, false, false))); #line default #line hidden WriteLiteral("</h1>\r\n\r\n"); #line 26 "..\..\Views\EditFriendlyMatch.cshtml" #line default #line hidden #line 26 "..\..\Views\EditFriendlyMatch.cshtml" if (Model.IsAuthorized[AuthorizedAction.EditMatch]) { using (Html.BeginUmbracoForm<EditFriendlyMatchSurfaceController> ("UpdateMatch")) { #line default #line hidden WriteLiteral(" <button"); WriteLiteral(" class=\"sr-only\""); WriteLiteral(">Save match</button>\r\n"); #line 32 "..\..\Views\EditFriendlyMatch.cshtml" #line default #line hidden #line 32 "..\..\Views\EditFriendlyMatch.cshtml" Write(Html.Partial("_CreateOrEditFriendlyMatch")); #line default #line hidden #line 32 "..\..\Views\EditFriendlyMatch.cshtml" #line default #line hidden #line 33 "..\..\Views\EditFriendlyMatch.cshtml" Write(Html.Partial("_EditMatchResultTypeFuture")); #line default #line hidden #line 33 "..\..\Views\EditFriendlyMatch.cshtml" #line default #line hidden WriteLiteral(" <button"); WriteLiteral(" class=\"btn btn-primary\""); WriteLiteral(">Save match</button>\r\n"); #line 35 "..\..\Views\EditFriendlyMatch.cshtml" } } else { #line default #line hidden #line 39 "..\..\Views\EditFriendlyMatch.cshtml" Write(Html.Partial("_Login")); #line default #line hidden #line 39 "..\..\Views\EditFriendlyMatch.cshtml" } #line default #line hidden WriteLiteral("</div>"); } } } #pragma warning restore 1591
25.956098
118
0.53411
[ "Apache-2.0" ]
stoolball-england/stoolball-org-uk
Stoolball.Web/Views/EditFriendlyMatch.generated.cs
5,323
C#
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // //********************************************************* using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Devices.Usb; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace UsbCdcControl { /// <summary> /// Page containing working sample code to demonstrate how to read data from a CDC ACM device. /// </summary> internal sealed partial class CdcAcmRead : UsbCdcControl.SingleDevicePage { public CdcAcmRead() { this.InitializeComponent(); } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="navigationParameter">The parameter value passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested. /// </param> /// <param name="pageState">A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited.</param> protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { if (pageState != null) { var enumerator = pageState.GetEnumerator(); do { var pair = enumerator.Current; var control = Util.FindControl(this, pair.Key); var textBox = control as Windows.UI.Xaml.Controls.TextBox; if (textBox != null) { textBox.Text = pair.Value as String; continue; } var comboBox = control as Windows.UI.Xaml.Controls.ComboBox; if (comboBox != null) { for (int j = 0; j < comboBox.Items.Count; j ++) { var comboBoxItem = comboBox.Items[j] as Windows.UI.Xaml.Controls.ComboBoxItem; if (comboBoxItem.Content as String == pair.Value as String) { comboBox.SelectedIndex = j; break; } } continue; } } while (enumerator.MoveNext()); } if (this.SerialPortInfo != null) { this.textBlockDeviceInUse.Text = this.SerialPortInfo.Name; } else { this.buttonReadBulkIn.IsEnabled = false; this.buttonWatchBulkIn.IsEnabled = false; this.buttonStopWatching.IsEnabled = false; this.textBlockDeviceInUse.Text = "No device selected."; this.textBlockDeviceInUse.Foreground = new SolidColorBrush(Windows.UI.Colors.OrangeRed); } UsbCdcControl.UsbDeviceList.Singleton.DeviceAdded += this.OnDeviceAdded; UsbCdcControl.UsbDeviceList.Singleton.DeviceRemoved += this.OnDeviceRemoved; } /// <summary> /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <see cref="SuspensionManager.SessionState"/>. /// </summary> /// <param name="pageState">An empty dictionary to be populated with serializable state.</param> protected override void SaveState(Dictionary<String, Object> pageState) { UsbCdcControl.UsbDeviceList.Singleton.DeviceAdded -= this.OnDeviceAdded; UsbCdcControl.UsbDeviceList.Singleton.DeviceRemoved -= this.OnDeviceRemoved; if (pageState != null) { pageState.Add(textBoxBytesToRead.Name, textBoxBytesToRead.Text); pageState.Add(textBoxReadTimeout.Name, textBoxReadTimeout.Text); } } private void buttonReadBulkIn_Click(object sender, RoutedEventArgs e) { if (buttonReadBulkIn.Content.ToString() == "Read") { uint bytesToRead = uint.Parse(textBoxBytesToRead.Text); if (bytesToRead > 0) { // UI status. buttonReadBulkIn.Content = "Stop Read"; buttonWatchBulkIn.IsEnabled = false; SDKTemplate.MainPage.Current.NotifyUser("Reading", SDKTemplate.NotifyType.StatusMessage); var buffer = new Windows.Storage.Streams.Buffer(bytesToRead); buffer.Length = bytesToRead; int timeout = int.Parse(textBoxReadTimeout.Text); var dispatcher = this.Dispatcher; Action readAction = async () => { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () => { int count = 0; try { count = await this.Read(buffer, timeout); } catch (System.OperationCanceledException) { // cancel. SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage); return; } catch (System.Exception exception) { if (exception.HResult == -2146233088) { // Device removed. return; } else { throw; } } finally { this.cancelTokenSrcOpRead = null; } this.buttonReadBulkIn.Content = "Read"; this.buttonWatchBulkIn.IsEnabled = true; if (count < bytesToRead) { // This would be timeout. SDKTemplate.MainPage.Current.NotifyUser("Timeout: read " + count.ToString() + " byte(s)", SDKTemplate.NotifyType.ErrorMessage); } else { SDKTemplate.MainPage.Current.NotifyUser("Completed", SDKTemplate.NotifyType.StatusMessage); } if (count > 0) { var isAscii = this.radioButtonAscii.IsChecked.Value == true; var temp = this.textBoxReadBulkInLogger.Text; temp += isAscii ? Util.AsciiBufferToAsciiString(buffer) : Util.BinaryBufferToBinaryString(buffer); this.textBoxReadBulkInLogger.Text = temp; } })); }; readAction.Invoke(); } } else { this.buttonStopWatching_Click(this, null); this.buttonReadBulkIn.Content = "Read"; } } private void buttonWatchBulkIn_Click(object sender, RoutedEventArgs e) { this.buttonReadBulkIn.IsEnabled = false; this.buttonWatchBulkIn.IsEnabled = false; this.buttonStopWatching.IsEnabled = true; SDKTemplate.MainPage.Current.NotifyUser("", SDKTemplate.NotifyType.StatusMessage); this.ReadByteOneByOne(); } private void buttonStopWatching_Click(object sender, RoutedEventArgs e) { if (this.cancelTokenSrcOpRead != null) { this.cancelTokenSrcOpRead.Cancel(); this.cancelTokenSrcOpRead = null; } this.buttonReadBulkIn.IsEnabled = true; this.buttonWatchBulkIn.IsEnabled = true; this.buttonStopWatching.IsEnabled = false; } private void textBoxLogger_TextChanged(object sender, TextChangedEventArgs e) { Util.GotoEndPosTextBox(sender as TextBox); } private void radioButtonDataFormat_Checked(object sender, RoutedEventArgs e) { if (sender.Equals(this.radioButtonAscii)) { var binary = this.textBoxReadBulkInLogger.Text; var separator = new String[1]; separator[0] = " "; var byteArray = binary.Split(separator, StringSplitOptions.None); // Binary to Unicode. uint strlen = 0; var writer = new Windows.Storage.Streams.DataWriter(); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; foreach (var onebyte in byteArray) { if (onebyte.Length < 2) { continue; } writer.WriteByte(byte.Parse(onebyte, System.Globalization.NumberStyles.HexNumber)); strlen++; } var reader = Windows.Storage.Streams.DataReader.FromBuffer(writer.DetachBuffer()); this.textBoxReadBulkInLogger.Text = reader.ReadString(strlen); } else if (sender.Equals(this.radioButtonBinary)) { var ascii = this.textBoxReadBulkInLogger.Text; // Unicode to ASCII. var chars = ascii.ToCharArray(0, ascii.Length); var writer = new Windows.Storage.Streams.DataWriter(); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; foreach (var onechar in chars) { writer.WriteByte((byte)onechar); } var str = Util.BinaryBufferToBinaryString(writer.DetachBuffer()); this.textBoxReadBulkInLogger.Text = str; } } private void OnDeviceAdded(object sender, UsbDeviceInfo info) { } private Windows.Foundation.IAsyncAction OnDeviceRemoved(object sender, UsbDeviceInfo info) { var dispatcher = this.Dispatcher; IAsyncOperation<Windows.UI.Popups.IUICommand> dialogShowAsync = null; var uiThreadTasks = dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => { if (this.SerialPortInfo != null && this.SerialPortInfo.DeviceId == info.Id) { dialogShowAsync = (new Windows.UI.Popups.MessageDialog(info.Name + " has been removed.")).ShowAsync(); if (this.cancelTokenSrcOpRead != null) { this.buttonStopWatching_Click(this, null); // cancel read op if possible. } this.buttonReadBulkIn.IsEnabled = false; this.buttonWatchBulkIn.IsEnabled = false; this.buttonStopWatching.IsEnabled = false; this.textBlockDeviceInUse.Text = "No device selected."; this.textBlockDeviceInUse.Foreground = new SolidColorBrush(Windows.UI.Colors.OrangeRed); } })); return System.Threading.Tasks.Task.Run(async () => { await uiThreadTasks; if (dialogShowAsync != null) { await dialogShowAsync; } } ).AsAsyncAction(); } private void ReadByteOneByOne() { var dispatcher = this.Dispatcher; var buffer = new Windows.Storage.Streams.Buffer(1); buffer.Length = 1; System.Threading.Tasks.Task.Run(async () => { int count = 0; try { count = await this.Read(buffer, -1); } catch (System.OperationCanceledException) { return; // StopWatching seems clicked. } finally { this.cancelTokenSrcOpRead = null; } if (count > 0) { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => { var isAscii = this.radioButtonAscii.IsChecked.Value == true; var temp = this.textBoxReadBulkInLogger.Text; temp += isAscii ? Util.AsciiBufferToAsciiString(buffer) : Util.BinaryBufferToBinaryString(buffer); this.textBoxReadBulkInLogger.Text = temp; })); } this.ReadByteOneByOne(); }); } private Windows.Foundation.IAsyncOperation<int> Read(Windows.Storage.Streams.Buffer buffer, int timeout) { this.SerialPortInfo.Port.ReadTimeout = timeout; var source = this.cancelTokenSrcOpRead = new System.Threading.CancellationTokenSource(); return this.SerialPortInfo.Port.Read(buffer, 0, buffer.Length, source.Token); } private System.Threading.CancellationTokenSource cancelTokenSrcOpRead = null; } }
43.045977
160
0.495594
[ "MIT" ]
mfloresn90/CSharpSources
USB CDC Control sample/C#/Scenario2_Read.xaml.cs
14,982
C#
using Abp.Events.Bus; using System; using System.Collections.Generic; using System.Text; namespace ABPsinglePageProj1.Events { public class EmployeeCompletedEventData:EventData { public int empId { get; set; } public string empname { get; set; } public DateTime empcreationtime { get; set; } public long? empcreatorid { get; set; } } }
23.8125
53
0.67979
[ "MIT" ]
Heba-Ahmed-Magdy/ABPSPProj1
aspnet-core/src/ABPsinglePageProj1.Core/Events/EmployeeCompletedEventData.cs
383
C#
using System; namespace ReactiveUI.Routing.Presentation { public abstract class Presenter<TRequest> : IPresenterFor<TRequest> where TRequest : PresenterRequest { public IObservable<PresenterResponse> Present(PresenterRequest request) { if (request == null) throw new ArgumentNullException(nameof(request)); if (!(request is TRequest)) throw new ArgumentException($"Given presenter request must be assignable to {typeof(TRequest)}", nameof(request)); return PresentCore((TRequest)request); } protected abstract IObservable<PresenterResponse> PresentCore(TRequest request); } }
37.055556
154
0.70015
[ "MIT" ]
KallynGowdy/ReactiveUI.Routing
src/ReactiveUI.Routing.Core/Presentation/Presenter.cs
669
C#
#pragma checksum "..\..\..\..\..\PropertyGrid\Implementation\Editors\CollectionEditor.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "9D9E058CDB7BD654B60258AF3E84DF9D4E36C50505CFB0A2FC14C5EAF3B900DA" //------------------------------------------------------------------------------ // <auto-generated> // Il codice è stato generato da uno strumento. // Versione runtime:4.0.30319.42000 // // Le modifiche apportate a questo file possono provocare un comportamento non corretto e andranno perse se // il codice viene rigenerato. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using Xceed.Wpf.Toolkit.Chromes; namespace Xceed.Wpf.Toolkit.PropertyGrid.Editors { /// <summary> /// CollectionEditor /// </summary> public partial class CollectionEditor : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/Xceed.Wpf.Toolkit;component/propertygrid/implementation/editors/collectioneditor" + ".xaml", System.UriKind.Relative); #line 1 "..\..\..\..\..\PropertyGrid\Implementation\Editors\CollectionEditor.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: #line 78 "..\..\..\..\..\PropertyGrid\Implementation\Editors\CollectionEditor.xaml" ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Click); #line default #line hidden return; } this._contentLoaded = true; } } }
41.613636
200
0.660022
[ "BSD-2-Clause" ]
3DSG-dev/CHIMERA-obj-importer
ExtendedWPFToolkit/Xceed.Wpf.Toolkit/obj/Debug/PropertyGrid/Implementation/Editors/CollectionEditor.g.cs
3,665
C#
using SkiaSharp; using System; namespace SkiaRate { public partial class RatingView { #region properties /// <summary> /// Gets or sets the spacing between two rating elements /// </summary> public float Spacing { get; set; } = 8; /// <summary> /// Gets or sets the color of the canvas background. /// </summary> /// <value>The color of the canvas background.</value> public SKColor CanvasBackgroundColor { get; set; } = SKColors.Transparent; /// <summary> /// Gets or sets the width of the stroke. /// </summary> /// <value>The width of the stroke.</value> public float StrokeWidth { get; set; } = 0.1f; #endregion #region public methods /// <summary> /// Clamps the value between 0 and the number of items. /// </summary> /// <returns>The value.</returns> /// <param name="val">Value.</param> public double ClampValue(double val) { if (val < 0) return 0; else if (val > this.Count) return this.Count; else return val; } /// <summary> /// Sets the Rating value /// </summary> /// <param name="x"></param> /// <param name="y"></param> public void SetValue(double x, double y) { var val = this.CalculateValue(x); switch (this.RatingType) { case RatingType.Full: this.Value = ClampValue((double)Math.Ceiling(val)); break; case RatingType.Half: this.Value = ClampValue((double)Math.Round(val * 2)/2); break; case RatingType.Floating: this.Value = ClampValue(val); break; } } /// <summary> /// Draws the rating view /// </summary> /// <param name="canvas"></param> /// <param name="width"></param> /// <param name="height"></param> public void Draw(SKCanvas canvas, int width, int height) { canvas.Clear(this.CanvasBackgroundColor); var path = SKPath.ParseSvgPathData(this.Path); var itemWidth = ((width - (this.Count - 1) * this.Spacing)) / this.Count; var scaleX = (itemWidth / (path.Bounds.Width)); scaleX = (itemWidth - scaleX * this.StrokeWidth) / path.Bounds.Width; this.ItemHeight = height; var scaleY = this.ItemHeight / (path.Bounds.Height); scaleY = (this.ItemHeight - scaleY * this.StrokeWidth) / (path.Bounds.Height); this.CanvasScale = Math.Min(scaleX , scaleY); this.ItemWidth = path.Bounds.Width * this.CanvasScale; canvas.Scale(this.CanvasScale); canvas.Translate(this.StrokeWidth / 2, this.StrokeWidth / 2); canvas.Translate(-path.Bounds.Left, 0); canvas.Translate(0, -path.Bounds.Top); using (var strokePaint = new SKPaint { Style = SKPaintStyle.Stroke, Color = this.SKOutlineOnColor, StrokeWidth = this.StrokeWidth, StrokeJoin = SKStrokeJoin.Round, IsAntialias = true, }) using (var fillPaint = new SKPaint { Style = SKPaintStyle.Fill, Color = this.SKColorOn, IsAntialias = true, }) { for (int i = 0; i < this.Count; i++) { if (i <= this.Value - 1) // Full { canvas.DrawPath(path, fillPaint); canvas.DrawPath(path, strokePaint); } else if (i < this.Value) //Partial { float filledPercentage = (float)(this.Value - Math.Truncate(this.Value)); strokePaint.Color = this.SKOutlineOffColor; canvas.DrawPath(path, strokePaint); using (var rectPath = new SKPath()) { var rect = SKRect.Create(path.Bounds.Left + path.Bounds.Width * filledPercentage, path.Bounds.Top, path.Bounds.Width * (1 - filledPercentage), this.ItemHeight); rectPath.AddRect(rect); canvas.ClipPath(rectPath, SKClipOperation.Difference); canvas.DrawPath(path, fillPaint); } } else //Empty { strokePaint.Color = this.SKOutlineOffColor; canvas.DrawPath(path, strokePaint); } canvas.Translate((this.ItemWidth + this.Spacing) / this.CanvasScale, 0); } } } #endregion #region private private float ItemWidth { get; set; } private float ItemHeight { get; set; } private float CanvasScale { get; set; } private SKColor SKColorOn { get; set; } = MaterialColors.Amber; private SKColor SKOutlineOnColor { get; set; } = SKColors.Transparent; private SKColor SKOutlineOffColor { get; set; } = MaterialColors.Grey; private double CalculateValue(double x) { if (x < this.ItemWidth) return (double)x / this.ItemWidth; else if (x < this.ItemWidth + this.Spacing) return 1; else return 1 + CalculateValue(x - (this.ItemWidth + this.Spacing)); } #endregion } }
35.137725
188
0.492161
[ "MIT" ]
clovisnicolas/SkiaRate
Sources/SkiaRate.Shared/RatingView.cs
5,870
C#
using Newtonsoft.Json; namespace FreshdeskApi.Client.Contacts.Models { public class Contact : ContactBase { /// <summary> /// Additional companies associated with the contact /// /// Note that this field is only returned when getting a single /// contact, not when listing/filtering. /// </summary> [JsonProperty("other_companies")] public ContactCompany[]? OtherCompanies { get; set; } } }
27.588235
71
0.622601
[ "MIT" ]
knippers/FreshdeskApiDotnet
FreshdeskApi.Client/Contacts/Models/Contact.cs
471
C#
using System; using System.Collections.Generic; using System.Text; namespace Catapult.Protocol { public class NetworkProtocolMarker : IProtocolMarker { } }
15.454545
56
0.747059
[ "MIT" ]
klukule/FallGuys.Protocol
FallGuys.Protocol/Protocol/NetworkProtocolMarker.cs
172
C#
namespace RecyclingStation.WasteDisposal.Interfaces { /// <summary> /// Interface that Garbage objects should implement. /// </summary> public interface IWaste { /// <summary> /// The name of the waste product. /// </summary> string Name { get; } /// <summary> /// Defines the volume in cubic centimeters (cm3) that 1 kilogram of Garbage takes. /// </summary> double VolumePerKg { get; } /// <summary> /// Holds the weight of the garbage in kilograms. /// </summary> double Weight { get; } double TotalVolume { get; } } }
26.12
91
0.551302
[ "MIT" ]
mayapeneva/C-Sharp-OOP-Advanced
Exams.NET_Framework/RecyclingStation/RecyclingStation/RecyclingStation/WasteDisposal/Interfaces/IWaste.cs
655
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using Azure.Core; namespace Azure.Monitor.Query { /// <summary> /// Provides the client configuration options for connecting to Azure Monitor Logs service. /// </summary> public class LogsQueryClientOptions: ClientOptions { private readonly ServiceVersion _version; /// <summary> /// The latest service version supported by this client library. /// </summary> private const ServiceVersion LatestVersion = ServiceVersion.V1; /// <summary> /// Initializes a new instance of the <see cref="LogsQueryClientOptions"/> class. /// </summary> /// <param name="version"> /// The <see cref="ServiceVersion"/> of the service API used when /// making requests. /// </param> public LogsQueryClientOptions(ServiceVersion version = LatestVersion) { _version = version; Diagnostics.LoggedHeaderNames.Add("prefer"); } /// <summary> /// The versions of Azure Monitor Logs service supported by this client /// library. /// </summary> public enum ServiceVersion { /// <summary> /// The V1 version of the service /// </summary> V1 = 1, } /// <summary> /// Gets or sets the authentication scope to use for authentication with Azure Active Directory. The default scope will be used if the property is null. /// </summary> public string AuthenticationScope { get; set; } internal string GetVersionString() { return _version switch { ServiceVersion.V1 => "v1", _ => throw new ArgumentException(@"Unknown version {_version}") }; } } }
31.016129
160
0.582423
[ "MIT" ]
adminnz/azure-sdk-for-net
sdk/monitor/Azure.Monitor.Query/src/LogsQueryClientOptions.cs
1,923
C#
//------------------------------------------------------------------------------ // <copyright file="MembershipPasswordCompatibilityMode.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Configuration { public enum MembershipPasswordCompatibilityMode { Framework20 = 0, Framework40 = 1, } }
34.214286
80
0.463466
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/xsp/system/ApplicationServices/Configuration/MembershipPasswordCompatibilityMode.cs
479
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("Grit.Sequence")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Grit.Sequence")] [assembly: AssemblyCopyright("Copyright © 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("a47e99f0-2cee-4737-9cc4-814000a4ab4f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.810811
84
0.744103
[ "Apache-2.0" ]
hotjk/ace
Grit.Sequence/Properties/AssemblyInfo.cs
1,402
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IMethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IWorkbookFunctionsRightRequestBuilder. /// </summary> public partial interface IWorkbookFunctionsRightRequestBuilder : IBaseRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IWorkbookFunctionsRightRequest Request(IEnumerable<Option> options = null); } }
37.206897
153
0.585728
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IWorkbookFunctionsRightRequestBuilder.cs
1,079
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebApiClient; using WebApiClient.Attributes; using WebApiClient.Contexts; namespace Demo { /// <summary> /// 记录日志 /// </summary> class Logger : ApiActionFilterAttribute { public override Task OnBeginRequestAsync(ApiActionContext context) { var request = context.RequestMessage; Console.WriteLine("{0} {1} {2}", DateTime.Now.ToString("HH:mm:ss.fff"), request.Method, request.RequestUri); return base.OnBeginRequestAsync(context); } public override Task OnEndRequestAsync(ApiActionContext context) { var request = context.RequestMessage; Console.WriteLine("{0} {1} {2}完成", DateTime.Now.ToString("HH:mm:ss.fff"), request.Method, request.RequestUri.AbsolutePath); return base.OnEndRequestAsync(context); } } }
30.46875
135
0.664615
[ "MIT" ]
wanglong/WebApiClient
Demo/Logger.cs
989
C#
using System; using System.ComponentModel; using Avalonia.Controls; using Avalonia.Diagnostics.Models; using Avalonia.Input; using Avalonia.Threading; using Avalonia.VisualTree; namespace Avalonia.Diagnostics.ViewModels { internal class MainViewModel : ViewModelBase, IDisposable { private readonly TopLevel _root; private readonly TreePageViewModel _logicalTree; private readonly TreePageViewModel _visualTree; private readonly EventsPageViewModel _events; private readonly IDisposable _pointerOverSubscription; private ViewModelBase _content; private int _selectedTab; private string _focusedControl; private string _pointerOverElement; private bool _shouldVisualizeMarginPadding = true; private bool _shouldVisualizeDirtyRects; private bool _showFpsOverlay; public MainViewModel(TopLevel root) { _root = root; _logicalTree = new TreePageViewModel(this, LogicalTreeNode.Create(root)); _visualTree = new TreePageViewModel(this, VisualTreeNode.Create(root)); _events = new EventsPageViewModel(this); UpdateFocusedControl(); KeyboardDevice.Instance.PropertyChanged += KeyboardPropertyChanged; SelectedTab = 0; _pointerOverSubscription = root.GetObservable(TopLevel.PointerOverElementProperty) .Subscribe(x => PointerOverElement = x?.GetType().Name); Console = new ConsoleViewModel(UpdateConsoleContext); } public bool ShouldVisualizeMarginPadding { get => _shouldVisualizeMarginPadding; set => RaiseAndSetIfChanged(ref _shouldVisualizeMarginPadding, value); } public bool ShouldVisualizeDirtyRects { get => _shouldVisualizeDirtyRects; set { _root.Renderer.DrawDirtyRects = value; RaiseAndSetIfChanged(ref _shouldVisualizeDirtyRects, value); } } public void ToggleVisualizeDirtyRects() { ShouldVisualizeDirtyRects = !ShouldVisualizeDirtyRects; } public void ToggleVisualizeMarginPadding() { ShouldVisualizeMarginPadding = !ShouldVisualizeMarginPadding; } public bool ShowFpsOverlay { get => _showFpsOverlay; set { _root.Renderer.DrawFps = value; RaiseAndSetIfChanged(ref _showFpsOverlay, value); } } public void ToggleFpsOverlay() { ShowFpsOverlay = !ShowFpsOverlay; } public ConsoleViewModel Console { get; } public ViewModelBase Content { get { return _content; } private set { if (_content is TreePageViewModel oldTree && value is TreePageViewModel newTree && oldTree?.SelectedNode?.Visual is IControl control) { // HACK: We want to select the currently selected control in the new tree, but // to select nested nodes in TreeView, currently the TreeView has to be able to // expand the parent nodes. Because at this point the TreeView isn't visible, // this will fail unless we schedule the selection to run after layout. DispatcherTimer.RunOnce( () => { try { newTree.SelectControl(control); } catch { } }, TimeSpan.FromMilliseconds(0), DispatcherPriority.ApplicationIdle); } RaiseAndSetIfChanged(ref _content, value); } } public int SelectedTab { get { return _selectedTab; } set { _selectedTab = value; switch (value) { case 0: Content = _logicalTree; break; case 1: Content = _visualTree; break; case 2: Content = _events; break; } RaisePropertyChanged(); } } public string FocusedControl { get { return _focusedControl; } private set { RaiseAndSetIfChanged(ref _focusedControl, value); } } public string PointerOverElement { get { return _pointerOverElement; } private set { RaiseAndSetIfChanged(ref _pointerOverElement, value); } } private void UpdateConsoleContext(ConsoleContext context) { context.root = _root; if (Content is TreePageViewModel tree) { context.e = tree.SelectedNode?.Visual; } } public void SelectControl(IControl control) { var tree = Content as TreePageViewModel; tree?.SelectControl(control); } public void EnableSnapshotStyles(bool enable) { if (Content is TreePageViewModel treeVm && treeVm.Details != null) { treeVm.Details.SnapshotStyles = enable; } } public void Dispose() { KeyboardDevice.Instance.PropertyChanged -= KeyboardPropertyChanged; _pointerOverSubscription.Dispose(); _logicalTree.Dispose(); _visualTree.Dispose(); _root.Renderer.DrawDirtyRects = false; _root.Renderer.DrawFps = false; } private void UpdateFocusedControl() { FocusedControl = KeyboardDevice.Instance.FocusedElement?.GetType().Name; } private void KeyboardPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(KeyboardDevice.Instance.FocusedElement)) { UpdateFocusedControl(); } } public void RequestTreeNavigateTo(IControl control, bool isVisualTree) { var tree = isVisualTree ? _visualTree : _logicalTree; var node = tree.FindNode(control); if (node != null) { SelectedTab = isVisualTree ? 1 : 0; tree.SelectControl(control); } } } }
31.816901
99
0.544489
[ "MIT" ]
ShadowsInRain/Avalonia
src/Avalonia.Diagnostics/Diagnostics/ViewModels/MainViewModel.cs
6,779
C#
using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using OrchardCore.DisplayManagement.Handlers; namespace OrchardCore.DisplayManagement.Descriptors { public interface IShapeTableManager { ShapeTable GetShapeTable(string themeId); } public interface IShapeTableProvider { void Discover(ShapeTableBuilder builder); } public interface IShapeTableHarvester : IShapeTableProvider { } /// <summary> /// Represents a marker interface for classes that have Shape methods tagged with <see cref="ShapeAttribute"/>. /// </summary> public interface IShapeAttributeProvider { } public static class ShapeProviderExtensions { public static IServiceCollection AddShapeAttributes<T>(this IServiceCollection services) where T : class, IShapeAttributeProvider { services.AddScoped<T>(); services.AddScoped<IShapeAttributeProvider>(sp => sp.GetService<T>()); return services; } } /// <summary> /// Represents a marker interface for classes that provide Shape placement informations /// </summary> public interface IShapePlacementProvider { /// <summary> /// Builds a contextualized <see cref="IPlacementInfoResolver"/> /// </summary> /// <param name="context">The <see cref="IBuildShapeContext"/> for which we need a placement resolver</param> /// <returns>An instance of <see cref="IPlacementInfoResolver"/> for the current context or <see cref="null"/> if this provider is not concerned.</returns> Task<IPlacementInfoResolver> BuildPlacementInfoResolverAsync(IBuildShapeContext context); } /// <summary> /// Represents a class capable of resolving <see cref="PlacementInfo"/> of Shapes /// </summary> public interface IPlacementInfoResolver { /// <summary> /// Resolves <see cref="PlacementInfo"/> for the provided <see cref="ShapePlacementContext"/> /// </summary> /// <param name="placementContext">The <see cref="ShapePlacementContext"/></param> /// <returns>An <see cref="PlacementInfo"/> or <see cref="null"/> if not concerned.</returns> PlacementInfo ResolvePlacement(ShapePlacementContext placementContext); } }
35.830769
163
0.68012
[ "BSD-3-Clause" ]
NuxeeStars/My.First.Orchard.Shop
src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/Interfaces.cs
2,329
C#
// Copyright (c) 2019 DHGMS Solutions and Contributors. All rights reserved. // This file is licensed to you under the MIT license. // See the LICENSE file in the project root for full license information. using Dhgms.GripeWithRoslyn.Analyzer.CodeCracker.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using DiagnosticSeverity = Microsoft.CodeAnalysis.DiagnosticSeverity; namespace Dhgms.GripeWithRoslyn.Analyzer.Analyzers.ReactiveUi { /// <summary> /// Analyzer for checking that a class that has the ViewModel suffix inherits from ReactiveUI.ReactiveObject. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class ViewModelClassShouldInheritReactiveObjectAnalyzer : BaseClassDeclarationSuffixShouldInheritTypes { internal const string Title = "ViewModel classes should inherit from ReactiveUI.ReactiveObject."; private const string MessageFormat = Title; private const string Category = SupportedCategories.Maintainability; private const string Description = "ViewModels should follow a consistent design of using ReactiveUI's ReactiveObject and an Interface"; /// <summary> /// Initializes a new instance of the <see cref="ViewModelClassShouldInheritReactiveObjectAnalyzer"/> class. /// </summary> public ViewModelClassShouldInheritReactiveObjectAnalyzer() : base( DiagnosticIdsHelper.ViewModelClassShouldInheritReactiveObject, Title, MessageFormat, Category, Description, DiagnosticSeverity.Warning) { } /// <inheritdoc /> protected override string ClassNameSuffix => "ViewModel"; /// <inheritdoc /> protected override string BaseClassFullName => "global::ReactiveUI.IReactiveObject"; } }
41.425532
120
0.70981
[ "MIT" ]
DHGMS-Solutions/GripeWithRoslyn
src/Dhgms.GripeWithRoslyn.Analyzer/Analyzers/ReactiveUi/ViewModelClassShouldInheritReactiveObjectAnalyzer.cs
1,949
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.CosmosDB.Models; namespace Azure.ResourceManager.CosmosDB { /// <summary> Migrate an Azure Cosmos DB Cassandra Keyspace from autoscale to manual throughput. </summary> public partial class CassandraResourcesMigrateCassandraKeyspaceToManualThroughputOperation : Operation<ThroughputSettingsGetResults>, IOperationSource<ThroughputSettingsGetResults> { private readonly ArmOperationHelpers<ThroughputSettingsGetResults> _operation; /// <summary> Initializes a new instance of CassandraResourcesMigrateCassandraKeyspaceToManualThroughputOperation for mocking. </summary> protected CassandraResourcesMigrateCassandraKeyspaceToManualThroughputOperation() { } internal CassandraResourcesMigrateCassandraKeyspaceToManualThroughputOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response) { _operation = new ArmOperationHelpers<ThroughputSettingsGetResults>(this, clientDiagnostics, pipeline, request, response, OperationFinalStateVia.Location, "CassandraResourcesMigrateCassandraKeyspaceToManualThroughputOperation"); } /// <inheritdoc /> public override string Id => _operation.Id; /// <inheritdoc /> public override ThroughputSettingsGetResults Value => _operation.Value; /// <inheritdoc /> public override bool HasCompleted => _operation.HasCompleted; /// <inheritdoc /> public override bool HasValue => _operation.HasValue; /// <inheritdoc /> public override Response GetRawResponse() => _operation.GetRawResponse(); /// <inheritdoc /> public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); /// <inheritdoc /> public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<ThroughputSettingsGetResults>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<ThroughputSettingsGetResults>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); ThroughputSettingsGetResults IOperationSource<ThroughputSettingsGetResults>.CreateResult(Response response, CancellationToken cancellationToken) { using var document = JsonDocument.Parse(response.ContentStream); return ThroughputSettingsGetResults.DeserializeThroughputSettingsGetResults(document.RootElement); } async ValueTask<ThroughputSettingsGetResults> IOperationSource<ThroughputSettingsGetResults>.CreateResultAsync(Response response, CancellationToken cancellationToken) { using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); return ThroughputSettingsGetResults.DeserializeThroughputSettingsGetResults(document.RootElement); } } }
49.671233
243
0.767512
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/cosmosdb/Azure.ResourceManager.CosmosDB/src/Generated/CassandraResourcesMigrateCassandraKeyspaceToManualThroughputOperation.cs
3,626
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Diagnostics; using Microsoft.AspNetCore.Components.Rendering; namespace Microsoft.AspNetCore.Components.Routing { /// <summary> /// A component that renders an anchor tag, automatically toggling its 'active' /// class based on whether its 'href' matches the current URI. /// </summary> public class NavLink : ComponentBase, IDisposable { private const string DefaultActiveClass = "active"; private bool _isActive; private string? _hrefAbsolute; private string? _class; /// <summary> /// Gets or sets the CSS class name applied to the NavLink when the /// current route matches the NavLink href. /// </summary> [Parameter] public string? ActiveClass { get; set; } /// <summary> /// Gets or sets a collection of additional attributes that will be added to the generated /// <c>a</c> element. /// </summary> [Parameter(CaptureUnmatchedValues = true)] public IReadOnlyDictionary<string, object>? AdditionalAttributes { get; set; } /// <summary> /// Gets or sets the computed CSS class based on whether or not the link is active. /// </summary> protected string? CssClass { get; set; } /// <summary> /// Gets or sets the child content of the component. /// </summary> [Parameter] public RenderFragment? ChildContent { get; set; } /// <summary> /// Gets or sets a value representing the URL matching behavior. /// </summary> [Parameter] public NavLinkMatch Match { get; set; } [Inject] private NavigationManager NavigationManager { get; set; } = default!; /// <inheritdoc /> protected override void OnInitialized() { // We'll consider re-rendering on each location change NavigationManager.LocationChanged += OnLocationChanged; } /// <inheritdoc /> protected override void OnParametersSet() { // Update computed state var href = (string?)null; if (AdditionalAttributes != null && AdditionalAttributes.TryGetValue("href", out var obj)) { href = Convert.ToString(obj, CultureInfo.InvariantCulture); } _hrefAbsolute = href == null ? null : NavigationManager.ToAbsoluteUri(href).AbsoluteUri; _isActive = ShouldMatch(NavigationManager.Uri); _class = (string?)null; if (AdditionalAttributes != null && AdditionalAttributes.TryGetValue("class", out obj)) { _class = Convert.ToString(obj, CultureInfo.InvariantCulture); } UpdateCssClass(); } /// <inheritdoc /> public void Dispose() { // To avoid leaking memory, it's important to detach any event handlers in Dispose() NavigationManager.LocationChanged -= OnLocationChanged; } private void UpdateCssClass() { CssClass = _isActive ? CombineWithSpace(_class, ActiveClass ?? DefaultActiveClass) : _class; } private void OnLocationChanged(object? sender, LocationChangedEventArgs args) { // We could just re-render always, but for this component we know the // only relevant state change is to the _isActive property. var shouldBeActiveNow = ShouldMatch(args.Location); if (shouldBeActiveNow != _isActive) { _isActive = shouldBeActiveNow; UpdateCssClass(); StateHasChanged(); } } private bool ShouldMatch(string currentUriAbsolute) { if (_hrefAbsolute == null) { return false; } if (EqualsHrefExactlyOrIfTrailingSlashAdded(currentUriAbsolute)) { return true; } if (Match == NavLinkMatch.Prefix && IsStrictlyPrefixWithSeparator(currentUriAbsolute, _hrefAbsolute)) { return true; } return false; } private bool EqualsHrefExactlyOrIfTrailingSlashAdded(string currentUriAbsolute) { Debug.Assert(_hrefAbsolute != null); if (string.Equals(currentUriAbsolute, _hrefAbsolute, StringComparison.OrdinalIgnoreCase)) { return true; } if (currentUriAbsolute.Length == _hrefAbsolute.Length - 1) { // Special case: highlight links to http://host/path/ even if you're // at http://host/path (with no trailing slash) // // This is because the router accepts an absolute URI value of "same // as base URI but without trailing slash" as equivalent to "base URI", // which in turn is because it's common for servers to return the same page // for http://host/vdir as they do for host://host/vdir/ as it's no // good to display a blank page in that case. if (_hrefAbsolute[_hrefAbsolute.Length - 1] == '/' && _hrefAbsolute.StartsWith(currentUriAbsolute, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } /// <inheritdoc/> protected override void BuildRenderTree(RenderTreeBuilder builder) { builder.OpenElement(0, "a"); builder.AddMultipleAttributes(1, AdditionalAttributes); builder.AddAttribute(2, "class", CssClass); builder.AddContent(3, ChildContent); builder.CloseElement(); } private string? CombineWithSpace(string? str1, string str2) => str1 == null ? str2 : $"{str1} {str2}"; private static bool IsStrictlyPrefixWithSeparator(string value, string prefix) { var prefixLength = prefix.Length; if (value.Length > prefixLength) { return value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && ( // Only match when there's a separator character either at the end of the // prefix or right after it. // Example: "/abc" is treated as a prefix of "/abc/def" but not "/abcdef" // Example: "/abc/" is treated as a prefix of "/abc/def" but not "/abcdef" prefixLength == 0 || !char.IsLetterOrDigit(prefix[prefixLength - 1]) || !char.IsLetterOrDigit(value[prefixLength]) ); } else { return false; } } } }
36.311558
111
0.565873
[ "Apache-2.0" ]
1n5an1ty/aspnetcore
src/Components/Web/src/Routing/NavLink.cs
7,226
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.Oci.DatabaseManagement.Outputs { [OutputType] public sealed class ManagedDatabasesChangeDatabaseParameterCredentials { /// <summary> /// The password for the database user name. /// </summary> public readonly string? Password; /// <summary> /// The role of the database user. Indicates whether the database user is a normal user or sysdba. /// </summary> public readonly string? Role; /// <summary> /// The database user name used to perform management activity. /// </summary> public readonly string? UserName; [OutputConstructor] private ManagedDatabasesChangeDatabaseParameterCredentials( string? password, string? role, string? userName) { Password = password; Role = role; UserName = userName; } } }
29.232558
106
0.628481
[ "ECL-2.0", "Apache-2.0" ]
EladGabay/pulumi-oci
sdk/dotnet/DatabaseManagement/Outputs/ManagedDatabasesChangeDatabaseParameterCredentials.cs
1,257
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.EntityFrameworkCore.Metadata { /// <summary> /// Names for well-known model annotations. Applications should not use these names /// directly, but should instead use API surface to access these features. /// They are exposed here for use by database providers and conventions. /// </summary> public static class CoreAnnotationNames { /// <summary> /// Indicates the maximum length of the annotated item. /// </summary> public const string MaxLength = "MaxLength"; /// <summary> /// Indicates that the annotated item supports Unicode. /// </summary> public const string Unicode = "Unicode"; /// <summary> /// Indicates the product version used to build the model. /// </summary> public const string ProductVersion = "ProductVersion"; /// <summary> /// The name of annotations that specify a <see cref="ValueGeneration.ValueGeneratorFactory" /> to use. /// </summary> public const string ValueGeneratorFactory = "ValueGeneratorFactory"; /// <summary> /// Indicates the <see cref="EntityFrameworkCore.PropertyAccessMode" /> for the annotated item. /// </summary> public const string PropertyAccessMode = "PropertyAccessMode"; /// <summary> /// Indicates the special <see cref="EntityFrameworkCore.PropertyAccessMode" /> for annotated navigation properties. /// </summary> public const string NavigationAccessMode = "NavigationAccessMode"; /// <summary> /// Indicates the <see cref="EntityFrameworkCore.ChangeTrackingStrategy" /> used for entities in the model. /// </summary> public const string ChangeTrackingStrategy = "ChangeTrackingStrategy"; /// <summary> /// Used while model building to keep a reference to owned types. /// </summary> public const string OwnedTypes = "OwnedTypes"; /// <summary> /// The name for discriminator property annotations. /// </summary> public const string DiscriminatorProperty = "DiscriminatorProperty"; /// <summary> /// The name for discriminator value annotations. /// </summary> public const string DiscriminatorValue = "DiscriminatorValue"; /// <summary> /// Indicates the <see cref="Metadata.ConstructorBinding" /> to use for the annotated item. /// </summary> public const string ConstructorBinding = "ConstructorBinding"; /// <summary> /// Indicates the <see cref="Storage.CoreTypeMapping" /> to use for the annotated item. /// </summary> public const string TypeMapping = "TypeMapping"; /// <summary> /// Indicates the <see cref="Storage.CoreTypeMapping" /> to use for the annotated item. /// </summary> public const string ValueConverter = "ValueConverter"; /// <summary> /// Indicates the <see cref="ChangeTracking.ValueComparer" /> to use for the annotated item. /// </summary> public const string ValueComparer = "ValueComparer"; /// <summary> /// Indicates the <see cref="ChangeTracking.ValueComparer" /> to use for the annotated item when used as a key. /// </summary> public const string KeyValueComparer = "KeyValueComparer"; /// <summary> /// Indicates the <see cref="ChangeTracking.ValueComparer" /> when structural, as opposed to reference, comparison is required. /// </summary> public const string StructuralValueComparer = "StructuralValueComparer"; /// <summary> /// Indicates the <see cref="PropertySaveBehavior" /> for a property after the entity is saved to the database. /// </summary> public const string AfterSaveBehavior = "AfterSaveBehavior"; /// <summary> /// Indicates the <see cref="PropertySaveBehavior" /> for a property before the entity is saved to the database. /// </summary> public const string BeforeSaveBehavior = "BeforeSaveBehavior"; /// <summary> /// Indicates the LINQ expression filter automatically applied to queries for this entity type. /// </summary> public const string QueryFilter = "QueryFilter"; /// <summary> /// Indicates the LINQ query used as the default source for queries of this type. /// </summary> public const string DefiningQuery = "DefiningQuery"; /// <summary> /// Indicates whether the navigation should be eager loaded by default. /// </summary> public const string EagerLoaded = "EagerLoaded"; /// <summary> /// Indicates the <see cref="System.Type" /> used by the provider for the annotated item. /// </summary> public const string ProviderClrType = "ProviderClrType"; } }
42.145161
139
0.622273
[ "Apache-2.0" ]
Wrank/EntityFrameworkCore
src/EFCore/Metadata/CoreAnnotationNames.cs
5,226
C#
using System; using System.Collections.Generic; using System.Data; using System.Configuration; using System.Collections; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Security; using System.Web.Services.Description; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Graffiti.Core; using Telligent.Glow; namespace Graffiti.Web { public class FileBrowserControl : System.Web.UI.UserControl { #region private variables private string platformFilesMediaPath = Path.Combine("files", "media"); private string basicFilesMediaPath = @"files\media"; #endregion #region Child Controls protected Literal theBreadCrumbs; protected Graffiti.Core.Repeater FolderList; protected MultiView FileViews; protected View FileLists; protected System.Web.UI.WebControls.Repeater LeftFiles; protected System.Web.UI.WebControls.Repeater RightFiles; protected View FileDetails; protected HyperLink FileDetailsName; protected Literal FileDetailsText; protected StatusMessage ActionMessage; protected HtmlGenericControl revsionLI; protected Literal FileDetailsRevision; protected HtmlGenericControl assemblyLI; protected Literal FileDetailsAssemblyVersion; protected Literal FileDetailsSize; protected Literal FileDetailsLastModified; protected Button DownloadButton; protected HtmlInputButton EditButton; protected Button DeleteButton; protected View FileEditor; protected HyperLink EditFileName; protected StatusMessage EditMessage; protected TextBox EditBox; protected Button Button1; protected Telligent.Glow.DropDownList VersionHistory; protected HtmlControl VersionHistoryArea; #endregion #region Public Properties public string OnClientFileClickedFunction { get { return (string)ViewState["OnClientFileClickedFunction"] ?? "null"; } set { ViewState["OnClientFileClickedFunction"] = value; } } public bool IncludeUtilityBreadCrumbs { get { return (bool)(ViewState["IncludeUtilityBreadCrumbs"] ?? true); } set { ViewState["IncludeUtilityBreadCrumbs"] = value; } } public bool EnableResizeToHeight { get { return (bool)(ViewState["EnableResizeToHeight"] ?? false); } set { ViewState["EnableResizeToHeight"] = value; } } public int ContentHeightOffset { get { return (int)(ViewState["ContentHeightOffset"] ?? 0); } set { ViewState["ContentHeightOffset"] = value; } } #endregion private string version; protected void Page_Load(object sender, EventArgs e) { LiHyperLink.SetNameToCompare(Context, "settings"); DeleteButton.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this file? This action cannot be undone!');"); string rootPath = Server.MapPath("~/"); string path = Request.QueryString["path"] ?? ""; if (!path.ToLower().StartsWith(basicFilesMediaPath) && !GraffitiUsers.IsAdmin(GraffitiUsers.Current)) Response.Redirect(Request.Url.AbsolutePath + "?path=" + basicFilesMediaPath, true); path = Path.Combine( rootPath, Util.NormalizePath( path ) ); string fileName = Request.QueryString["f"]; DirectoryInfo di = new DirectoryInfo(path); if (!di.FullName.ToLower().StartsWith(rootPath.ToLower())) { Log.Error("FileBrowser", "A request was made to an invalid directory {0}. If this persists, you should contact your ISP", di.FullName); throw new Exception("Bad Path"); } SetBreadCrumbs(fileName); SetFolders(di, rootPath); if (string.IsNullOrEmpty(fileName)) { FileViews.SetActiveView(FileLists); SetFileList(di); } else { FileInfo fi = new FileInfo(Path.Combine(path, fileName)); if (!fi.Exists) { Log.Warn("FileBrowser", "A requested file {0} does not exist", fi.FullName); throw new Exception("File does not exist"); } if (!FileFilters.IsValidFile(fi.Name)) { Log.Error("FileBrowser", "A forbidden file {0} was requested by the FileBrowser. Access to view/edit this file has been denied.", fi.FullName); throw new Exception("File does not exist"); } if (Request.QueryString["edit"] != "true") { SetFileDetails(fi); } else { SetFileEdit(fi); } } } private FileInfo GetFile() { string path = Request.QueryString["path"] ?? ""; path = Path.Combine(Server.MapPath("~/"), path); string fileName = Request.QueryString["f"]; return new FileInfo(Path.Combine(path, fileName)); } protected void DeleteFile_Click(object sender, EventArgs e) { FileInfo file = GetFile(); if (FileFilters.IsDeletable(file.Name)) { try { file.Delete(); ActionMessage.Text = "The file " + file.Name + " was deleted"; ActionMessage.Type = StatusType.Success; DownloadButton.Visible = false; EditButton.Visible = false; DeleteButton.Visible = false; } catch (Exception ex) { Log.Error("FileBrowser", "The file {0} could not be deleted\n\nReason: {1}", file.FullName, ex.Message); ActionMessage.Text = "The file " + file.Name + " could not be deleted"; ActionMessage.Type = StatusType.Error; } } } protected void SaveFile_Click(object sender, EventArgs e) { FileInfo fi = GetFile(); if (FileFilters.IsEditable(fi.Name) && FileFilters.IsValidFile(fi.Name)) { try { bool isversioned = FileFilters.IsVersionable(fi.Name); if (isversioned && VersionStore.CurrentVersion(fi) == 0) { VersionStore.VersionFile(fi); } using (StreamWriter sw = new StreamWriter(fi.FullName, false)) { sw.Write(EditBox.Text); sw.Close(); } if (isversioned) { fi = GetFile(); VersionStore.VersionFile(fi); version = VersionStore.CurrentVersion(fi).ToString(); SetVersioning(fi.FullName); } EditMessage.Text = "<strong>" + fi.Name + "</strong> was successfully updated."; EditMessage.Type = StatusType.Success; } catch (Exception ex) { EditMessage.Text = "Your file could not be updated. \n\n Reason: " + ex.Message; EditMessage.Type = StatusType.Error; } } } protected void DownloadFile_Click(object sender, EventArgs e) { FileInfo fi = GetFile(); if (FileFilters.IsDownloadable(fi.Name)) { Context.Response.AppendHeader("content-disposition", "attachment; filename=" + fi.Name); Context.Response.ContentType = Util.GetMapping(fi.Name); Context.Response.WriteFile(fi.FullName); Context.Response.End(); } } private void SetFileEdit(FileInfo fi) { FileViews.SetActiveView(FileEditor); if (!FileFilters.IsEditable(fi.Name)) { Log.Error("FileBrowser", "Invalid attempt to edit the file {0} which is not editable", fi.FullName); throw new Exception("File does not exist"); } EditFileName.Text = fi.Name; EditFileName.NavigateUrl = "~/" + (Request.QueryString["path"] ?? "") + "/" + fi.Name; if (!IsPostBack) { using (StreamReader sr = new StreamReader(fi.FullName)) { EditBox.Text = sr.ReadToEnd(); sr.Close(); } SetVersioning(fi.FullName); } } private void SetVersioning(string fileName) { // set up versioning VersionStoreCollection vsc = VersionStore.GetVersionHistory(fileName); if (vsc.Count > 1) { VersionHistoryArea.Visible = true; string versionHtml = "<div style=\"width: 280px; overflow: hidden; padding: 6px 0; border-bottom: 1px solid #ccc;\"><b>Revision {0}</b> ({1})<div>by {2}</div><div style=\"font-style: italic;\"></div></div>"; string versionText = "Revision {0}"; foreach (VersionStore vs in vsc) { VersionHistory.Items.Add( new DropDownListItem( string.Format(versionHtml, vs.Version, vs.CreatedOn, vs.CreatedBy), string.Format(versionText, vs.Version), vs.Version.ToString())); } VersionHistory.Attributes["onchange"] = "window.location = '" + ResolveUrl( "~/graffiti-admin/site-options/utilities/FileBrowser.aspx") + "?path=" + Server.UrlEncode(Request.QueryString["path"]) + "&f=" + Server.UrlEncode(Request.QueryString["f"]) + "&edit=true" + "&v=' + this.options[this.selectedIndex].value;"; VersionStore selected; if (!String.IsNullOrEmpty(Request.QueryString["v"])) { if (!String.IsNullOrEmpty(version)) { selected = vsc.Find( delegate(VersionStore vs) { return vs.Version.ToString() == version; }); } else { selected = vsc.Find( delegate(VersionStore vs) { return vs.Version.ToString() == Request.QueryString["v"]; }); } } else { selected = vsc[vsc.Count - 1]; } if (selected != null) { VersionHistory.SelectedValue = selected.Version.ToString(); EditBox.Text = selected.Data; if (selected.Version < vsc[vsc.Count - 1].Version) { EditMessage.Text = "You are editing a previous version of this file. If you click <b>Save Changes</b>, a new version of this file (revision " + (vsc.Count + 1) + ") will be created."; EditMessage.Type = StatusType.Warning; } } } else { VersionHistoryArea.Visible = false; } } private void SetFileDetails(FileInfo fi) { FileViews.SetActiveView(FileDetails); FileDetailsLastModified.Text = fi.LastWriteTime.ToLongDateString() + " " + fi.LastWriteTime.ToShortTimeString(); if (FileFilters.IsLinkable(fi.Name)) { FileDetailsName.Text = fi.Name; FileDetailsName.NavigateUrl = "~/" + (Request.QueryString["path"] ?? "") + "/" + fi.Name; } else { FileDetailsName.Visible = false; FileDetailsText.Text = fi.Name; } DownloadButton.Visible = FileFilters.IsDownloadable(fi.Name); EditButton.Visible = FileFilters.IsEditable(fi.Name); DeleteButton.Visible = FileFilters.IsDeletable(fi.Name); if (fi.Extension == ".dll") { Assembly assembly = Assembly.LoadFile(fi.FullName); FileDetailsAssemblyVersion.Text = assembly.GetName().Version.ToString(); } else { assemblyLI.Visible = false; } if (FileFilters.IsVersionable(fi.Name)) { FileDetailsRevision.Text = (VersionStore.CurrentVersion(fi) == 0 ? 1 : VersionStore.CurrentVersion(fi)).ToString(); } else { FileDetailsRevision.Text = "n.a."; revsionLI.Visible = false; } FileDetailsSize.Text = fi.Length.ToString("0,0") + " kB"; } private void SetFolders(DirectoryInfo di, string rootPath) { DirectoryInfo[] directories = di.GetDirectories(); List<Folder> folders = new List<Folder>(); foreach (DirectoryInfo d in directories) { if (d.Name != ".svn") { Folder folder = new Folder(); folder.Name = d.Name; folder.Path = d.FullName.Substring(rootPath.Length); folders.Add(folder); } } FolderList.DataSource = folders; FolderList.DataBind(); } private void SetFileList(DirectoryInfo di) { FileInfo[] files = di.GetFiles(); List<FileInfo> the_Files = new List<FileInfo>(); foreach (FileInfo fi in files) { if (FileFilters.IsValidFile(fi.Name)) the_Files.Add(fi); } if (the_Files.Count > 0) { the_Files.Sort(delegate(FileInfo f1, FileInfo f2) { return Comparer<string>.Default.Compare(f1.Name, f2.Name); }); int half = the_Files.Count / 2 + the_Files.Count % 2; List<AFile> left = new List<AFile>(); List<AFile> right = new List<AFile>(); for (int i = 0; i < the_Files.Count; i++) { AFile af = new AFile(); af.Name = the_Files[i].Name; af.Path = Request.QueryString["path"] ?? ""; af.OnClick = string.IsNullOrEmpty(this.OnClientFileClickedFunction) ? "" : "return select('" + GetJavaScriptUrl(the_Files[i].FullName) + "');"; if (i + 1 <= half) left.Add(af); else right.Add(af); } LeftFiles.DataSource = left; LeftFiles.DataBind(); RightFiles.DataSource = right; RightFiles.DataBind(); } } private string GetJavaScriptUrl(string fullPath) { Uri url = (new Uri(Context.Request.Url, Context.Response.ApplyAppPathModifier("~" + fullPath.Substring(Context.Request.PhysicalApplicationPath.Length - 1).Replace("\\", "/")))); return url.PathAndQuery.ToString().Replace("'", "\\'"); } private void SetBreadCrumbs(string fileName) { string thePath = Request.QueryString["path"] ?? ""; if (thePath.EndsWith("\\")) thePath = thePath.Substring(0, thePath.Length - 1); // if(thePath.Trim().Length == 0 && string.IsNullOrEmpty(fileName)) // return; StringBuilder sb = new StringBuilder("<div class=\"breadcrumbs\">"); if (this.IncludeUtilityBreadCrumbs) { sb.Append("<a href=\"../\">Site Options</a>"); sb.Append("<span class=\"seperator\">></span>"); sb.Append("<a href=\"../utilities/\">Utilities</a>"); sb.Append("<span class=\"seperator\">></span>"); } bool isAdmin = GraffitiUsers.IsAdmin(GraffitiUsers.Current); if (isAdmin) sb.Append("<a href=\"?path=\">Home</a>"); else sb.Append("Home"); string previous = "?path="; if (thePath.IndexOf("\\") > -1) { while (thePath.IndexOf("\\") != -1) { sb.Append("<span class=\"seperator\">></span>"); string text = thePath.Substring(0, thePath.IndexOf("\\")); previous += text + "\\"; thePath = thePath.Substring(text.Length + 1); if (previous.ToLower().StartsWith("?path=" + basicFilesMediaPath) || isAdmin) sb.AppendFormat("<a href=\"{0}\">{1}</a>", previous.Substring(0, previous.Length - 1), text); else sb.Append(text); } } if (thePath.Trim().Length > 0) { sb.Append("<span class=\"seperator\">></span>"); if (!string.IsNullOrEmpty(fileName)) { sb.AppendFormat("<a href=\"?path={0}\">{1}</a>", Request.QueryString["path"] ?? "", thePath.Trim()); } else { sb.Append(thePath.Trim()); } } if (!string.IsNullOrEmpty(fileName)) { sb.Append("<span class=\"seperator\">></span>"); sb.Append(fileName); } sb.Append("</div>"); theBreadCrumbs.Text = sb.ToString(); } } public class AFile { private string _name; private string _onClick; public string Name { get { return _name; } set { _name = value; } } private string _path; public string Path { get { return _path; } set { _path = value; } } public string Url { get { return "?path=" + Path + "&f=" + Name; } } public string OnClick { get { return _onClick; } set { _onClick = value; } } public string CssClass { get { string ext = System.IO.Path.GetExtension(Name); if (ext.Length > 0) ext = ext.Substring(1).ToLower(); switch (ext) { case "ascx": return "ascx"; case "aspx": return "aspx"; case "bmp": return "bmp"; case "config": return "config"; case "cs": return "cs"; case "css": return "css"; case "dll": return "dll"; case "doc": return "doc"; case "exe": return "exe"; case "gif": return "gif"; case "png": return "image"; case "tff": return "image"; case "mp3": case "wmv": return "ipod"; case "mdb": return "mdb"; case "js": return "js"; case "pdf": return "pdf"; case "ppt": return "ppt"; case "vb": return "vb"; case "vm": return "vm"; case "xml": return "xml"; default: return "file"; } } } } public class Folder { private string _name; public string Name { get { return _name; } set { _name = value; } } private string _path; public string Path { get { return _path; } set { _path = value; } } public string Url { get { return "?path=" + Path; } } } }
33.946457
206
0.476109
[ "MIT" ]
harder/GraffitiCMS
src/Graffiti.Web/graffiti-admin/site-options/utilities/FileBrowser.ascx.cs
21,556
C#
namespace ForwardMiddleware.ApiConfig { using System.Collections.Generic; using System.Threading.Tasks; /// <summary> /// API config handler. /// </summary> public interface IApiConfigHandler { /// <summary> /// Gets the apis async. /// </summary> /// <returns>The apis async.</returns> Task<List<ApiModel>> GetApisAsync(); } }
22.333333
46
0.584577
[ "MIT" ]
catcherwong-archive/ForwardMiddleware
ForwardMiddleware/ApiConfig/IApiConfigHandler.cs
404
C#
using Android.Support.V4.Media.Session; using MediaManager.Volume; namespace MediaManager.Platforms.Android { public class VolumeManager : IVolumeManager //VolumeProviderCompat.Callback { private MediaManagerImplementation _mediaManagerImplementation; private MediaControllerCompat _mediaController => _mediaManagerImplementation.MediaBrowserManager.MediaController; //TODO: Probably inject another class public VolumeManager(MediaManagerImplementation mediaManagerImplementation) { _mediaManagerImplementation = mediaManagerImplementation; } public int CurrentVolume { get => _mediaController.GetPlaybackInfo().CurrentVolume; set { _mediaController.SetVolumeTo(value, 0); VolumeChanged?.Invoke(this, new VolumeChangedEventArgs(value, Muted)); } } public int MaxVolume { get => _mediaController.GetPlaybackInfo().MaxVolume; set { if (CurrentVolume > value) CurrentVolume = value; } } protected int preMutedVolume = 0; public bool Muted { get => CurrentVolume == 0; set { if (!Muted) { preMutedVolume = CurrentVolume; CurrentVolume = 0; } else CurrentVolume = preMutedVolume; } } public event VolumeChangedEventHandler VolumeChanged; } }
29.285714
122
0.568902
[ "MIT" ]
brminnick/XamarinMediaManager
MediaManager/Platforms/Android/Volume/VolumeManager.cs
1,642
C#
/* Copyright (c) 2015 Ki 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.Linq; using System.Xml.Linq; using ILSpy.BamlDecompiler.Xaml; namespace ILSpy.BamlDecompiler.Rewrite { internal class MarkupExtensionRewritePass : IRewritePass { XName key; XName ctor; public void Run(XamlContext ctx, XDocument document) { key = ctx.GetKnownNamespace("Key", XamlContext.KnownNamespace_Xaml); ctor = ctx.GetPseudoName("Ctor"); bool doWork; do { doWork = false; foreach (var elem in document.Elements()) { doWork |= ProcessElement(ctx, elem); } } while (doWork); } bool ProcessElement(XamlContext ctx, XElement elem) { bool doWork = false; foreach (var child in elem.Elements()) { doWork |= RewriteElement(ctx, elem, child); doWork |= ProcessElement(ctx, child); } return doWork; } bool RewriteElement(XamlContext ctx, XElement parent, XElement elem) { var type = parent.Annotation<XamlType>(); var property = elem.Annotation<XamlProperty>(); if ((property == null || type == null) && elem.Name != key) return false; if (elem.Elements().Count() != 1 || elem.Attributes().Any(t => t.Name.Namespace != XNamespace.Xmlns)) return false; var value = elem.Elements().Single(); if (!CanInlineExt(ctx, value)) return false; var ext = InlineExtension(ctx, value); if (ext == null) return false; ctx.CancellationToken.ThrowIfCancellationRequested(); var extValue = ext.ToString(ctx, parent); var attrName = elem.Name; if (attrName != key) attrName = property.ToXName(ctx, parent, property.IsAttachedTo(type)); if (!parent.Attributes(attrName).Any()) { var attr = new XAttribute(attrName, extValue); var list = new List<XAttribute>(parent.Attributes()); if (attrName == key) list.Insert(0, attr); else list.Add(attr); parent.RemoveAttributes(); parent.ReplaceAttributes(list); } elem.Remove(); return true; } bool CanInlineExt(XamlContext ctx, XElement ctxElement) { var type = ctxElement.Annotation<XamlType>(); if (type != null && type.ResolvedType != null) { var typeDef = type.ResolvedType.GetDefinition()?.DirectBaseTypes.FirstOrDefault(); bool isExt = false; while (typeDef != null) { if (typeDef.FullName == "System.Windows.Markup.MarkupExtension") { isExt = true; break; } typeDef = typeDef.DirectBaseTypes.FirstOrDefault(); } if (!isExt) return false; } else if (ctxElement.Annotation<XamlProperty>() == null && ctxElement.Name != ctor) return false; foreach (var child in ctxElement.Elements()) { if (!CanInlineExt(ctx, child)) return false; } return true; } object InlineObject(XamlContext ctx, XNode obj) { if (obj is XText) return ((XText)obj).Value; else if (obj is XElement) return InlineExtension(ctx, (XElement)obj); else return null; } object[] InlineCtor(XamlContext ctx, XElement ctor) { if (ctor.HasAttributes) return null; var args = new List<object>(); foreach (var child in ctor.Nodes()) { var arg = InlineObject(ctx, child); if (arg == null) return null; args.Add(arg); } return args.ToArray(); } XamlExtension InlineExtension(XamlContext ctx, XElement ctxElement) { var type = ctxElement.Annotation<XamlType>(); if (type == null) return null; var ext = new XamlExtension(type); foreach (var attr in ctxElement.Attributes().Where(attr => attr.Name.Namespace != XNamespace.Xmlns)) ext.NamedArguments[attr.Name.LocalName] = attr.Value; foreach (var child in ctxElement.Nodes()) { var elem = child as XElement; if (elem == null) return null; if (elem.Name == ctor) { if (ext.Initializer != null) return null; var args = InlineCtor(ctx, elem); if (args == null) return null; ext.Initializer = args; continue; } var property = elem.Annotation<XamlProperty>(); if (property == null || elem.Nodes().Count() != 1 || elem.Attributes().Any(attr => attr.Name.Namespace != XNamespace.Xmlns)) return null; var name = property.PropertyName; var value = InlineObject(ctx, elem.Nodes().Single()); ext.NamedArguments[name] = value; } return ext; } } }
26.669951
104
0.67307
[ "MIT" ]
AraHaan/ILSpy
ILSpy.BamlDecompiler/Rewrite/MarkupExtensionRewritePass.cs
5,416
C#
using StoryLine.Contracts; namespace StoryLine.Selenium.Actions { public class Navigate : IActionBuilder { private string _url; public Navigate Url(string url) { _url = url; return this; } public IAction Build() { return new NavigateAction(_url); } } }
16.454545
44
0.535912
[ "BSD-3-Clause" ]
DiamondDragon/StoryLine.Selenium
StoryLine.Selenium/Actions/Navigate.cs
364
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class resolution : MonoBehaviour { // Use this for initialization void Start () { Screen.SetResolution(1280, 720, true); } }
15.466667
46
0.706897
[ "MIT" ]
figgyfunk/awkward_sim
Assets/Scripts/resolution.cs
234
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using JX.Core; using JX.Core.Entity; namespace JX.Core { /// <summary> /// 数据库表:U_Award 的仓储接口. /// </summary> public partial interface IU_AwardRepositoryADO : IRepositoryADO<U_Award> { /// <summary> /// 通过主键删除 /// </summary> /// <returns></returns> bool Delete(System.Int32 id); /// <summary> /// 通过主键删除 /// </summary> /// <returns></returns> Task<bool> DeleteAsync(System.Int32 id); /// <summary> /// 通过主键返回第一条信息的实体类。 /// </summary> /// <returns></returns> U_Award GetEntity(System.Int32 id); /// <summary> /// 通过主键返回第一条信息的实体类。 /// </summary> /// <returns></returns> Task<U_Award> GetEntityAsync(System.Int32 id); } }
20.702703
73
0.643603
[ "Apache-2.0" ]
lixiong24/IPS2.1
CodeSmith/output/IRepositoriesADO/IU_AwardRepositoryADO.cs
876
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 elasticache-2015-02-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElastiCache.Model { /// <summary> /// Container for the parameters to the FailoverGlobalReplicationGroup operation. /// Used to failover the primary region to a selected secondary region. The selected secondary /// region will become primary, and all other clusters will become secondary. /// </summary> public partial class FailoverGlobalReplicationGroupRequest : AmazonElastiCacheRequest { private string _globalReplicationGroupId; private string _primaryRegion; private string _primaryReplicationGroupId; /// <summary> /// Gets and sets the property GlobalReplicationGroupId. /// <para> /// The name of the Global Datastore /// </para> /// </summary> [AWSProperty(Required=true)] public string GlobalReplicationGroupId { get { return this._globalReplicationGroupId; } set { this._globalReplicationGroupId = value; } } // Check to see if GlobalReplicationGroupId property is set internal bool IsSetGlobalReplicationGroupId() { return this._globalReplicationGroupId != null; } /// <summary> /// Gets and sets the property PrimaryRegion. /// <para> /// The AWS region of the primary cluster of the Global Datastore /// </para> /// </summary> [AWSProperty(Required=true)] public string PrimaryRegion { get { return this._primaryRegion; } set { this._primaryRegion = value; } } // Check to see if PrimaryRegion property is set internal bool IsSetPrimaryRegion() { return this._primaryRegion != null; } /// <summary> /// Gets and sets the property PrimaryReplicationGroupId. /// <para> /// The name of the primary replication group /// </para> /// </summary> [AWSProperty(Required=true)] public string PrimaryReplicationGroupId { get { return this._primaryReplicationGroupId; } set { this._primaryReplicationGroupId = value; } } // Check to see if PrimaryReplicationGroupId property is set internal bool IsSetPrimaryReplicationGroupId() { return this._primaryReplicationGroupId != null; } } }
33.11
109
0.645726
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/ElastiCache/Generated/Model/FailoverGlobalReplicationGroupRequest.cs
3,311
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.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementGeoMatchStatementGetArgs : Pulumi.ResourceArgs { [Input("countryCodes", required: true)] private InputList<string>? _countryCodes; /// <summary> /// Array of two-character country codes, for example, [ "US", "CN" ], from the alpha-2 country ISO codes of the `ISO 3166` international standard. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_GeoMatchStatement.html) for valid values. /// </summary> public InputList<string> CountryCodes { get => _countryCodes ?? (_countryCodes = new InputList<string>()); set => _countryCodes = value; } /// <summary> /// Configuration for inspecting IP addresses in an HTTP header that you specify, instead of using the IP address that's reported by the web request origin. See Forwarded IP Config below for details. /// </summary> [Input("forwardedIpConfig")] public Input<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementGeoMatchStatementForwardedIpConfigGetArgs>? ForwardedIpConfig { get; set; } public WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementGeoMatchStatementGetArgs() { } } }
47.236842
277
0.728691
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementGeoMatchStatementGetArgs.cs
1,795
C#
using DataStructures; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DataStructuresTests { [TestClass] public class DoublyLinkedListTests { [TestMethod] public void InitalizeEmptyTest() { DoublyLinkedList<int> ints = new DoublyLinkedList<int>(); Assert.AreEqual(0, ints.Count); } [TestMethod] public void AddHeadTest() { DoublyLinkedList<int> ints = new DoublyLinkedList<int>(); for (int i = 1; i <= 5; i++) { ints.AddHead(i); Assert.AreEqual(i, ints.Count); } int expected = 5; foreach (int x in ints) { Assert.AreEqual(expected--, x); } } [TestMethod] public void AddTailTest() { DoublyLinkedList<int> ints = new DoublyLinkedList<int>(); for (int i = 1; i <= 5; i++) { ints.AddTail(i); Assert.AreEqual(i, ints.Count); } int expected = 1; foreach (int x in ints) { Assert.AreEqual(expected++, x); } } [TestMethod] public void RemoveTest() { DoublyLinkedList<int> delete1to10 = create(1, 10); Assert.AreEqual(10, delete1to10.Count); for (int i = 1; i <= 10; i++) { Assert.IsTrue(delete1to10.Remove(i)); Assert.IsFalse(delete1to10.Remove(i)); } Assert.AreEqual(0, delete1to10.Count); DoublyLinkedList<int> delete10to1 = create(1, 10); Assert.AreEqual(10, delete10to1.Count); for (int i = 10; i >= 1; i--) { Assert.IsTrue(delete10to1.Remove(i)); Assert.IsFalse(delete10to1.Remove(i)); } Assert.AreEqual(0, delete10to1.Count); } [TestMethod] public void ContainsTest() { DoublyLinkedList<int> ints = create(1, 10); for (int i = 1; i <= 10; i++) { Assert.IsTrue(ints.Contains(i)); } Assert.IsFalse(ints.Contains(0)); Assert.IsFalse(ints.Contains(11)); } [TestMethod] public void ReverseIteratorTest() { DoublyLinkedList<int> ints = create(1, 10); int expected = 10; foreach(int actual in ints.GetReverseEnumerator()) { Assert.AreEqual(expected--, actual); } } private DoublyLinkedList<int> create(int start, int end) { DoublyLinkedList<int> ints = new DoublyLinkedList<int>(); for (int i = start; i <= end; i++) { ints.AddTail(i); } return ints; } } }
26.830357
69
0.468885
[ "CC0-1.0" ]
GabrielGrigore17/ADS-in-CSharp
ADS1/DataStructures/DataStructuresTests/DoublyLinkedListTests.cs
3,005
C#
using Content.Shared.Chat; using Robust.Shared.Log; using Robust.Shared.Maths; namespace Content.Client.Chat { public class StoredChatMessage { // TODO Make me reflected with respect to MsgChatMessage /// <summary> /// Client's own copies of chat messages used in filtering locally /// </summary> /// <summary> /// Actual Message contents, i.e. words /// </summary> public string Message { get; set; } /// <summary> /// Message channel, used for filtering /// </summary> public ChatChannel Channel { get; set; } /// <summary> /// What to "wrap" the message contents with. Example is stuff like 'Joe says: "{0}"' /// </summary> public string MessageWrap { get; set; } /// <summary> /// The override color of the message /// </summary> public Color MessageColorOverride { get; set; } /// <summary> /// Whether the user has read this message at least once. /// </summary> public bool Read { get; set; } /// <summary> /// Constructor to copy a net message into stored client variety /// </summary> public StoredChatMessage(MsgChatMessage netMsg) { Message = netMsg.Message; Channel = netMsg.Channel; MessageWrap = netMsg.MessageWrap; MessageColorOverride = netMsg.MessageColorOverride; } } }
29.153846
97
0.560686
[ "MIT" ]
A-Box-12/space-station-14
Content.Client/Chat/StoredChatMessage.cs
1,516
C#
using System; using System.Collections.Generic; using System.Text; namespace MxNet.GluonTS.Dataset { class ProcessTimeSeriesField { } }
13.636364
33
0.733333
[ "Apache-2.0" ]
AnshMittal1811/MxNet.Sharp
src/MxNet.GluonTS/Dataset/ProcessTimeSeriesField.cs
152
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class SnakeBody : NetworkBehaviour { public GameObject forwardSnakeBody; public float speed; public bool onGround; public GameObject mySnake; public bool isShock; private Transform targetTf; private Rigidbody rb; private void Start() { rb = GetComponent<Rigidbody>(); SetTargetTf(forwardSnakeBody); speed = 7f; } public void AddSpeed(float speedPlus) { if (!hasAuthority) return; speed += speedPlus; if (speed > 10f) speed = 10f; print(speed); } private void FixedUpdate() { if (!hasAuthority) return; if (isShock) { return; } if (onGround == true) { rb.velocity = new Vector3(rb.velocity.x, -.001f, rb.velocity.z); } if (targetTf != null) { if (Vector3.Distance(targetTf.position, transform.position) > 2f) { transform.LookAt(targetTf); rb.angularVelocity = Vector3.zero; rb.velocity -= Vector3.Project(rb.velocity, transform.right); if (rb.velocity.magnitude < 15f) { rb.AddForce(transform.forward * 500f); } else { rb.velocity = rb.velocity.normalized * 10f; } } else { if (rb.velocity.magnitude > speed) { rb.velocity = rb.velocity.normalized * speed; } } } } private void Update() { if (!hasAuthority) return; if (isShock) return; DetectOnGround(); } private void SetTargetTf(GameObject ob) { if (ob != null) { forwardSnakeBody = ob; targetTf = ob.transform;//得到上一个目标 } } private void CancelSetTargetTf() { forwardSnakeBody = null; targetTf = null; } private void DetectOnGround() { onGround = false; Collider[] colliders; float radius = 0.95f; if (GetComponent<SnakeHead>() != null) {//这截身体是脑袋 radius = 1.45f; } colliders = Physics.OverlapBox(transform.position, transform.localScale / radius); if (colliders.Length != 0) { foreach (Collider collider in colliders) { if (collider.tag == "Ground") { onGround = true; break; } } } } [ClientRpc] private void RpcTakeDamage(float damageValue) { if (!hasAuthority) return; print("TakeDmage InSnake"); mySnake.GetComponent<Snake>().CmdTakeDamage(damageValue); } }
28.969388
90
0.52906
[ "MIT" ]
IdlessChaye/Unity
Game/SnakeBoom/SnakeBoom/Assets/Scripts/SnakeBody.cs
2,869
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace TatliSozlukProject { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
24.416667
99
0.59215
[ "MIT" ]
alpercevizz/TatliSozlukProject
TatliSozlukProject/App_Start/RouteConfig.cs
588
C#
using BattleAxe; namespace bxl.Data { public static class Error { public static ProcedureDefinition Insert { get { return new ProcedureDefinition("bxl.Error_Insert", Connection.Value); } } } }
20
85
0.576923
[ "MIT" ]
DNCarroll/bxl
bxl/Data/Error.cs
262
C#
namespace BullOak.Test.EndToEnd.Stub.Shared.ViewingQuery { using System; public class VewingVM { public Guid ViewingId { get; set; } public string MovieName { get; set; } } }
19
57
0.631579
[ "MIT" ]
BullOak/BullOak
src/BullOak.Test.EndToEnd/Stub/Shared/ViewingQuery/VewingVM.cs
211
C#
using System; using System.Collections.Generic; using System.Linq; using Azure.Messaging.EventHubs; using Newtonsoft.Json; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Streams; namespace Orleans.ServiceBus.Providers { /// <summary> /// Batch container that is delivers payload and stream position information for a set of events in an EventHub EventData. /// </summary> [Serializable] [GenerateSerializer] public class EventHubBatchContainer : IBatchContainer { [JsonProperty] [Id(0)] private readonly EventHubMessage eventHubMessage; [JsonIgnore] [field: NonSerialized] internal Serializer Serializer { get; set; } [JsonProperty] [Id(1)] private readonly EventHubSequenceToken token; /// <summary> /// Stream identifier for the stream this batch is part of. /// </summary> public StreamId StreamId => eventHubMessage.StreamId; /// <summary> /// Stream Sequence Token for the start of this batch. /// </summary> public StreamSequenceToken SequenceToken => token; // Payload is local cache of deserialized payloadBytes. Should never be serialized as part of batch container. During batch container serialization raw payloadBytes will always be used. [NonSerialized] private Body payload; private Body GetPayload() => payload ?? (payload = this.Serializer.Deserialize<Body>(eventHubMessage.Payload)); [Serializable] [GenerateSerializer] internal class Body { [Id(0)] public List<object> Events { get; set; } [Id(1)] public Dictionary<string, object> RequestContext { get; set; } } /// <summary> /// Batch container that delivers events from cached EventHub data associated with an orleans stream /// </summary> public EventHubBatchContainer(EventHubMessage eventHubMessage, Serializer serializer) { this.eventHubMessage = eventHubMessage; this.Serializer = serializer; token = new EventHubSequenceTokenV2(eventHubMessage.Offset, eventHubMessage.SequenceNumber, 0); } [GeneratedActivatorConstructor] internal EventHubBatchContainer(Serializer serializer) { this.Serializer = serializer; } /// <summary> /// Gets events of a specific type from the batch. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public IEnumerable<Tuple<T, StreamSequenceToken>> GetEvents<T>() { return GetPayload().Events.Cast<T>().Select((e, i) => Tuple.Create<T, StreamSequenceToken>(e, new EventHubSequenceTokenV2(token.EventHubOffset, token.SequenceNumber, i))); } /// <summary> /// Gives an opportunity to IBatchContainer to set any data in the RequestContext before this IBatchContainer is sent to consumers. /// It can be the data that was set at the time event was generated and enqueued into the persistent provider or any other data. /// </summary> /// <returns>True if the RequestContext was indeed modified, false otherwise.</returns> public bool ImportRequestContext() { if (GetPayload().RequestContext != null) { RequestContextExtensions.Import(GetPayload().RequestContext); return true; } return false; } /// <summary> /// Put events list and its context into a EventData object /// </summary> public static EventData ToEventData<T>(Serializer bodySerializer, StreamId streamId, IEnumerable<T> events, Dictionary<string, object> requestContext) { var payload = new Body { Events = events.Cast<object>().ToList(), RequestContext = requestContext }; var bytes = bodySerializer.SerializeToArray(payload); var eventData = new EventData(bytes); eventData.SetStreamNamespaceProperty(streamId.GetNamespace()); return eventData; } } }
36.87931
195
0.628799
[ "MIT" ]
AmedeoV/orleans
src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/EventHubBatchContainer.cs
4,278
C#
using System; using Microsoft.Xna.Framework.Input; namespace Farmhand.Events.Arguments.ControlEvents { public class EventArgsKeyPressed : EventArgs { public EventArgsKeyPressed(Keys keyPressed) { KeyPressed = keyPressed; } public Keys KeyPressed { get; private set; } } }
21.625
53
0.630058
[ "MIT" ]
Entoarox/Stardew-Farmhand
Libraries/Farmhand/Events/Arguments/ControlEvents/EventArgsKeyPressed.cs
348
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // 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("ImageProcessor")] [assembly: AssemblyDescription("A library for on-the-fly processing of image files written in C#")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("James South")] [assembly: AssemblyProduct("ImageProcessor")] [assembly: AssemblyCopyright("Copyright © James South")] [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("bdaae9bd-0dc8-4b06-8722-e2e0c9a74301")] // 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.6.0.0")] [assembly: AssemblyFileVersion("1.6.0.0")]
38.578947
99
0.754434
[ "Apache-2.0" ]
hputtick/ImageProcessor
src/ImageProcessor/Properties/AssemblyInfo.cs
1,469
C#
namespace _Com_Ciurea_Seminar4_1046 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.labelCod = new System.Windows.Forms.Label(); this.labelSex = new System.Windows.Forms.Label(); this.labelVarsta = new System.Windows.Forms.Label(); this.labelNume = new System.Windows.Forms.Label(); this.tbCod = new System.Windows.Forms.TextBox(); this.tbVarsta = new System.Windows.Forms.TextBox(); this.tbNume = new System.Windows.Forms.TextBox(); this.cbSex = new System.Windows.Forms.ComboBox(); this.tbNote = new System.Windows.Forms.TextBox(); this.labelNote = new System.Windows.Forms.Label(); this.btnCreareStudent = new System.Windows.Forms.Button(); this.btnAfisare = new System.Windows.Forms.Button(); this.tbAfisareStudent = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // labelCod // this.labelCod.AutoSize = true; this.labelCod.Location = new System.Drawing.Point(49, 28); this.labelCod.Name = "labelCod"; this.labelCod.Size = new System.Drawing.Size(37, 17); this.labelCod.TabIndex = 0; this.labelCod.Text = "Cod:"; // // labelSex // this.labelSex.AutoSize = true; this.labelSex.Location = new System.Drawing.Point(49, 86); this.labelSex.Name = "labelSex"; this.labelSex.Size = new System.Drawing.Size(35, 17); this.labelSex.TabIndex = 1; this.labelSex.Text = "Sex:"; // // labelVarsta // this.labelVarsta.AutoSize = true; this.labelVarsta.Location = new System.Drawing.Point(49, 151); this.labelVarsta.Name = "labelVarsta"; this.labelVarsta.Size = new System.Drawing.Size(53, 17); this.labelVarsta.TabIndex = 2; this.labelVarsta.Text = "Varsta:"; // // labelNume // this.labelNume.AutoSize = true; this.labelNume.Location = new System.Drawing.Point(49, 221); this.labelNume.Name = "labelNume"; this.labelNume.Size = new System.Drawing.Size(49, 17); this.labelNume.TabIndex = 3; this.labelNume.Text = "Nume:"; // // tbCod // this.tbCod.Location = new System.Drawing.Point(157, 28); this.tbCod.Name = "tbCod"; this.tbCod.Size = new System.Drawing.Size(121, 22); this.tbCod.TabIndex = 4; // // tbVarsta // this.tbVarsta.Location = new System.Drawing.Point(157, 151); this.tbVarsta.Name = "tbVarsta"; this.tbVarsta.Size = new System.Drawing.Size(121, 22); this.tbVarsta.TabIndex = 5; // // tbNume // this.tbNume.Location = new System.Drawing.Point(157, 221); this.tbNume.Name = "tbNume"; this.tbNume.Size = new System.Drawing.Size(121, 22); this.tbNume.TabIndex = 6; // // cbSex // this.cbSex.FormattingEnabled = true; this.cbSex.Items.AddRange(new object[] { "M", "F"}); this.cbSex.Location = new System.Drawing.Point(157, 86); this.cbSex.Name = "cbSex"; this.cbSex.Size = new System.Drawing.Size(121, 24); this.cbSex.TabIndex = 7; // // tbNote // this.tbNote.Location = new System.Drawing.Point(157, 279); this.tbNote.Name = "tbNote"; this.tbNote.Size = new System.Drawing.Size(121, 22); this.tbNote.TabIndex = 8; // // labelNote // this.labelNote.AutoSize = true; this.labelNote.Location = new System.Drawing.Point(49, 279); this.labelNote.Name = "labelNote"; this.labelNote.Size = new System.Drawing.Size(42, 17); this.labelNote.TabIndex = 9; this.labelNote.Text = "Note:"; // // btnCreareStudent // this.btnCreareStudent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255))))); this.btnCreareStudent.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnCreareStudent.Location = new System.Drawing.Point(52, 344); this.btnCreareStudent.Name = "btnCreareStudent"; this.btnCreareStudent.Size = new System.Drawing.Size(226, 43); this.btnCreareStudent.TabIndex = 10; this.btnCreareStudent.Text = "Creare Student"; this.btnCreareStudent.UseVisualStyleBackColor = false; this.btnCreareStudent.Click += new System.EventHandler(this.btnCreareStudent_Click); // // btnAfisare // this.btnAfisare.Location = new System.Drawing.Point(597, 311); this.btnAfisare.Name = "btnAfisare"; this.btnAfisare.Size = new System.Drawing.Size(127, 52); this.btnAfisare.TabIndex = 12; this.btnAfisare.Text = "Afisare"; this.btnAfisare.UseVisualStyleBackColor = true; this.btnAfisare.Click += new System.EventHandler(this.btnAfisare_Click); // // tbAfisareStudent // this.tbAfisareStudent.Location = new System.Drawing.Point(356, 64); this.tbAfisareStudent.Multiline = true; this.tbAfisareStudent.Name = "tbAfisareStudent"; this.tbAfisareStudent.Size = new System.Drawing.Size(562, 174); this.tbAfisareStudent.TabIndex = 11; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(982, 513); this.Controls.Add(this.btnAfisare); this.Controls.Add(this.tbAfisareStudent); this.Controls.Add(this.btnCreareStudent); this.Controls.Add(this.labelNote); this.Controls.Add(this.tbNote); this.Controls.Add(this.cbSex); this.Controls.Add(this.tbNume); this.Controls.Add(this.tbVarsta); this.Controls.Add(this.tbCod); this.Controls.Add(this.labelNume); this.Controls.Add(this.labelVarsta); this.Controls.Add(this.labelSex); this.Controls.Add(this.labelCod); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label labelCod; private System.Windows.Forms.Label labelSex; private System.Windows.Forms.Label labelVarsta; private System.Windows.Forms.Label labelNume; private System.Windows.Forms.TextBox tbCod; private System.Windows.Forms.TextBox tbVarsta; private System.Windows.Forms.TextBox tbNume; private System.Windows.Forms.ComboBox cbSex; private System.Windows.Forms.TextBox tbNote; private System.Windows.Forms.Label labelNote; private System.Windows.Forms.Button btnCreareStudent; private System.Windows.Forms.Button btnAfisare; private System.Windows.Forms.TextBox tbAfisareStudent; } }
43.054726
174
0.564826
[ "MIT" ]
Adriana-Giol/Laborator-Programare-Aplicatii-Windows
1. Laborator/4. Seminar 4/[Com]Ciurea_Seminar4_1046/Form1.Designer.cs
8,656
C#
using Octokit.Internal; using Octokit.Reflection; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Octokit { internal static class ReflectionExtensions { public static string GetJsonFieldName(this MemberInfo memberInfo) { var memberName = memberInfo.Name; var paramAttr = memberInfo.GetCustomAttribute<ParameterAttribute>(); if (paramAttr != null && !string.IsNullOrEmpty(paramAttr.Key)) { memberName = paramAttr.Key; } return memberName.ToRubyCase(); } public static IEnumerable<PropertyOrField> GetPropertiesAndFields(this Type type) { return ReflectionUtils.GetProperties(type).Select(property => new PropertyOrField(property)) .Union(ReflectionUtils.GetFields(type).Select(field => new PropertyOrField(field))) .Where(p => (p.IsPublic || p.HasParameterAttribute) && !p.IsStatic); } public static bool IsDateTimeOffset(this Type type) { return type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?); } public static bool IsNullable(this Type type) { return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } #if !HAS_TYPEINFO public static Type GetTypeInfo(this Type type) { return type; } #else public static IEnumerable<MemberInfo> GetMember(this Type type, string name) { return type.GetTypeInfo().DeclaredMembers.Where(m => m.Name == name); } public static PropertyInfo GetProperty(this Type t, string propertyName) { return t.GetTypeInfo().GetDeclaredProperty(propertyName); } public static bool IsAssignableFrom(this Type type, Type otherType) { return type.GetTypeInfo().IsAssignableFrom(otherType.GetTypeInfo()); } #endif public static IEnumerable<PropertyInfo> GetAllProperties(this Type type) { #if HAS_TYPEINFO var typeInfo = type.GetTypeInfo(); var properties = typeInfo.DeclaredProperties; var baseType = typeInfo.BaseType; return baseType == null ? properties : properties.Concat(baseType.GetAllProperties()); #else return type.GetProperties(BindingFlags.Instance | BindingFlags.Public); #endif } public static bool IsEnumeration(this Type type) { return type.GetTypeInfo().IsEnum; } } }
31.951807
109
0.630468
[ "MIT" ]
3shape/octokit.net
Octokit/Helpers/ReflectionExtensions.cs
2,654
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using YogoServer.StartupManager; namespace YogoServer.ErrorHandling.Middleware { public class ApiErrorHanlder { private readonly RequestDelegate _next; private readonly ILogger _logger; private readonly JsonSerializerOptions _jsonSerializerOptions = JsonConfiguration.Get(); public ApiErrorHanlder(RequestDelegate next, ILoggerFactory loggerFactory) { _next = next; _logger = loggerFactory.CreateLogger<ApiErrorHanlder>(); } public async Task Invoke(HttpContext context) { if (context is null) { _logger.LogCritical($"{JsonSerializer.Serialize("Contexto nulo.", _jsonSerializerOptions)}"); throw new ArgumentNullException(nameof(context), "Contexto nulo."); } try { context.Response.ContentType = MediaTypeNames.Application.Json; await _next(context); } catch (ApiException ex) { string logDetails = string.Empty; if (ex.MessagesToLog != null && ex.MessagesToLog.Any()) { logDetails = string.Join(Environment.NewLine, ex.MessagesToLog); } string exceptionName = ex.GetType().Name; context.Response.StatusCode = ex.Status; await context.Response.WriteAsync(GetError(context.Response.StatusCode, ex.Message, ex.MessagesToLog)); } catch (Exception) { context.Response.StatusCode = StatusCodes.Status500InternalServerError; await context.Response.WriteAsync(GetError(context.Response.StatusCode, "An unexpected error ocurred")); } } private string GetError(int status, string message) { return GetError(status, message, Enumerable.Empty<string>()); } private string GetError(int status, string message, IEnumerable<string> messageToLog) { ApiException erroMessage = new ApiException(status, message,messageToLog); string result = JsonSerializer.Serialize(erroMessage, _jsonSerializerOptions); return result; } } }
32.448718
120
0.620703
[ "MIT" ]
victorsimas/yogo-server
src/YogoServer/ErrorHandling/Middleware/ApiErrorHanlder.cs
2,531
C#
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. namespace ImageMagick { /// <summary> /// Skews the current coordinate system in the vertical direction. /// </summary> public sealed class DrawableSkewY : IDrawable, IDrawingWand { /// <summary> /// Initializes a new instance of the <see cref="DrawableSkewY"/> class. /// </summary> /// <param name="angle">The angle.</param> public DrawableSkewY(double angle) { Angle = angle; } /// <summary> /// Gets or sets the angle. /// </summary> public double Angle { get; set; } /// <summary> /// Draws this instance with the drawing wand. /// </summary> /// <param name="wand">The want to draw on.</param> void IDrawingWand.Draw(DrawingWand wand) => wand?.SkewY(Angle); } }
29.212121
80
0.567427
[ "Apache-2.0" ]
ScriptBox99/Magick.NET
src/Magick.NET/Drawables/DrawableSkewY.cs
964
C#
using FluentValidation; namespace Ordering.Application.Features.Orders.Commands.CheckoutOrder { public class CheckoutOrderCommandValidator : AbstractValidator<CheckoutOrderCommand> { public CheckoutOrderCommandValidator() { RuleFor(p => p.UserName) .NotEmpty().WithMessage("{Username} is required.") .NotNull() .MaximumLength(50).WithMessage("{Username} must not exceed 50 characters."); RuleFor(p => p.EmailAddress) .NotEmpty().WithMessage("{EmailAddress} is required."); RuleFor(p => p.TotalPrice) .NotEmpty().WithMessage("{TotalPrice} is required.") .GreaterThan(0).WithMessage("{TotalPrice} should be greater than zero."); } } }
33.583333
92
0.610422
[ "MIT" ]
StrahinjaHT/AspnetMicroservices
src/Services/Ordering/Ordering.Application/Features/Orders/Commands/CheckoutOrder/CheckoutOrderCommandValidator.cs
808
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 Lucene.Net.Analysis.Tokenattributes; using Lucene.Net.Test.Analysis; using NUnit.Framework; using Version = Lucene.Net.Util.Version; namespace Lucene.Net.Analysis { [TestFixture] public class TestStopAnalyzer:BaseTokenStreamTestCase { private StopAnalyzer stop = new StopAnalyzer(Version.LUCENE_CURRENT); private HashSet<string> inValidTokens = new HashSet<string>(); public TestStopAnalyzer(System.String s):base(s) { } public TestStopAnalyzer() { } [SetUp] public override void SetUp() { base.SetUp(); inValidTokens.UnionWith(StopAnalyzer.ENGLISH_STOP_WORDS_SET); } [Test] public virtual void TestDefaults() { Assert.IsTrue(stop != null); System.IO.StringReader reader = new System.IO.StringReader("This is a test of the english stop analyzer"); TokenStream stream = stop.TokenStream("test", reader); Assert.IsTrue(stream != null); ITermAttribute termAtt = stream.GetAttribute<ITermAttribute>(); while (stream.IncrementToken()) { Assert.IsFalse(inValidTokens.Contains(termAtt.Term)); } } [Test] public virtual void TestStopList() { var stopWordsSet = new System.Collections.Generic.HashSet<string>(); stopWordsSet.Add("good"); stopWordsSet.Add("test"); stopWordsSet.Add("analyzer"); StopAnalyzer newStop = new StopAnalyzer(Version.LUCENE_24, stopWordsSet); System.IO.StringReader reader = new System.IO.StringReader("This is a good test of the english stop analyzer"); TokenStream stream = newStop.TokenStream("test", reader); Assert.IsNotNull(stream); ITermAttribute termAtt = stream.GetAttribute<ITermAttribute>(); IPositionIncrementAttribute posIncrAtt = stream.AddAttribute<IPositionIncrementAttribute>(); while (stream.IncrementToken()) { System.String text = termAtt.Term; Assert.IsFalse(stopWordsSet.Contains(text)); Assert.AreEqual(1, posIncrAtt.PositionIncrement); // in 2.4 stop tokenizer does not apply increments. } } [Test] public virtual void TestStopListPositions() { var stopWordsSet = new System.Collections.Generic.HashSet<string>(); stopWordsSet.Add("good"); stopWordsSet.Add("test"); stopWordsSet.Add("analyzer"); var newStop = new StopAnalyzer(Version.LUCENE_CURRENT, stopWordsSet); var reader = new System.IO.StringReader("This is a good test of the english stop analyzer with positions"); int[] expectedIncr = { 1, 1, 1, 3, 1, 1, 1, 2, 1}; TokenStream stream = newStop.TokenStream("test", reader); Assert.NotNull(stream); int i = 0; ITermAttribute termAtt = stream.GetAttribute<ITermAttribute>(); IPositionIncrementAttribute posIncrAtt = stream.AddAttribute<IPositionIncrementAttribute>(); while (stream.IncrementToken()) { string text = termAtt.Term; Assert.IsFalse(stopWordsSet.Contains(text)); Assert.AreEqual(expectedIncr[i++], posIncrAtt.PositionIncrement); } } } }
36.846847
119
0.677262
[ "Apache-2.0" ]
Tasteful/lucene.net
test/core/Analysis/TestStopAnalyzer.cs
4,090
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Bot.Builder.Dialogs { /// <summary> /// Provides context for a step in a <see cref="WaterfallDialog"/>. /// </summary> /// <remarks>The <see cref="DialogContext.Context"/> property contains the <see cref="ITurnContext"/> /// for the current turn.</remarks> public class WaterfallStepContext : DialogContext { private readonly WaterfallDialog _parentWaterfall; private bool _nextCalled; /// <summary> /// Initializes a new instance of the <see cref="WaterfallStepContext"/> class. /// </summary> /// <param name= "parentWaterfall">The parent of the waterfall dialog.</param> /// <param name= "dc">The dialog's context.</param> /// <param name= "options">Any options to call the waterfall dialog with.</param> /// <param name= "values">A dictionary of values which will be persisted across all waterfall steps.</param> /// <param name= "index">The index of the current waterfall to execute.</param> /// <param name= "reason">The reason the waterfall step is being executed.</param> /// <param name= "result">Results returned by a dialog called in the previous waterfall step.</param> internal WaterfallStepContext( WaterfallDialog parentWaterfall, DialogContext dc, object options, IDictionary<string, object> values, int index, DialogReason reason, object result = null) : base( dc.Dialogs, parentDialogContext: dc, state: new DialogState(dc.Stack)) { _parentWaterfall = parentWaterfall; _nextCalled = false; Parent = dc.Parent; Index = index; Options = options; Reason = reason; Result = result; Values = values; } /// <summary> /// Gets the index of the current waterfall step being executed. /// </summary> /// <value> /// The index of the current waterfall step being executed. /// </value> public int Index { get; } /// <summary> /// Gets any options the waterfall dialog was called with. /// </summary> /// <value> /// Any options the waterfall dialog was called with. /// </value> public object Options { get; } /// <summary> /// Gets the reason the waterfall step is being executed. /// </summary> /// <value> /// The reason the waterfall step is being executed. /// </value> public DialogReason Reason { get; } /// <summary> /// Gets the result from the previous waterfall step. /// </summary> /// <value> /// The result from the previous waterfall step. /// </value> /// <remarks>The result is often the return value of a child dialog that was started in /// the previous step of the waterfall.</remarks> public object Result { get; } /// <summary> /// Gets a dictionary of values which will be persisted across all waterfall actions. /// </summary> /// <value> /// A dictionary of values which will be persisted across all waterfall steps. /// </value> public IDictionary<string, object> Values { get; } /// <summary> /// Skips to the next step of the waterfall. /// </summary> /// <param name="result">Optional, result to pass to the next step of the current waterfall dialog.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>In the next step of the waterfall, the <see cref="Result"/> property of the /// waterfall step context will contain the value of the <paramref name="result"/>.</remarks> public async Task<DialogTurnResult> NextAsync(object result = null, CancellationToken cancellationToken = default(CancellationToken)) { if (result is CancellationToken) { throw new ArgumentException($"{nameof(result)} cannot be a cancellation token"); } // Ensure next hasn't been called if (_nextCalled) { throw new Exception($"WaterfallStepContext.NextAsync(): method already called for dialog and step '{_parentWaterfall.Id}[{Index}]'."); } // Trigger next step _nextCalled = true; return await _parentWaterfall.ResumeDialogAsync(this, DialogReason.NextCalled, result, cancellationToken).ConfigureAwait(false); } } }
41.080645
150
0.596781
[ "MIT" ]
Divyansh-Choudhary/BotBuilder
libraries/Microsoft.Bot.Builder.Dialogs/WaterfallStepContext.cs
5,096
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Regardingobjectidadoxioapplicationbpfv3 operations. /// </summary> public partial class Regardingobjectidadoxioapplicationbpfv3 : IServiceOperations<DynamicsClient>, IRegardingobjectidadoxioapplicationbpfv3 { /// <summary> /// Initializes a new instance of the Regardingobjectidadoxioapplicationbpfv3 class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Regardingobjectidadoxioapplicationbpfv3(DynamicsClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DynamicsClient /// </summary> public DynamicsClient Client { get; private set; } /// <summary> /// Get regardingobjectid_adoxio_applicationbpfv3 from mailboxtrackingfolders /// </summary> /// <param name='mailboxtrackingfolderid'> /// key: mailboxtrackingfolderid of mailboxtrackingfolder /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationbpfv3>> GetWithHttpMessagesAsync(string mailboxtrackingfolderid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (mailboxtrackingfolderid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "mailboxtrackingfolderid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("mailboxtrackingfolderid", mailboxtrackingfolderid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "mailboxtrackingfolders({mailboxtrackingfolderid})/regardingobjectid_adoxio_applicationbpfv3").ToString(); _url = _url.Replace("{mailboxtrackingfolderid}", System.Uri.EscapeDataString(mailboxtrackingfolderid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationbpfv3>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationbpfv3>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get regardingobjectid_adoxio_applicationbpfv3 from processsessions /// </summary> /// <param name='processsessionid'> /// key: processsessionid of processsession /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationbpfv3>> Get1WithHttpMessagesAsync(string processsessionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (processsessionid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "processsessionid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("processsessionid", processsessionid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get1", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "processsessions({processsessionid})/regardingobjectid_adoxio_applicationbpfv3").ToString(); _url = _url.Replace("{processsessionid}", System.Uri.EscapeDataString(processsessionid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioApplicationbpfv3>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioApplicationbpfv3>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
44.416
364
0.574087
[ "Apache-2.0" ]
BrendanBeachBC/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/Regardingobjectidadoxioapplicationbpfv3.cs
16,656
C#
/** * ======================================================================== * Copyright (c) 2019 Karve Informatica S.L. * Licensed under the Karve License to our customers. * 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. * EVERY USE IS STRICTLY FORBIDDEN WITHOUT A WRITTEN AGREMENT WITH Karve Informatica S.L. * ------------------------------------------------------------------------ * @author Giorgio Zoppi <giorgio@fleetadmiral.net> * @date 30th July 2019 */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using KarveDataServices; using KarveDataAccessLayer.DataObjects; using KarveModel; using KarveRepository.OData; using AutoMapper; using KarveCommon.Services.Filters; using KarveDataAccessLayer.SQL; using Monad; namespace KarveRepository { public class GroupRepository : AbstractRepository, IRepository<Group> { private IBasicDataServices _dataService; public GroupRepository(QueryStoreFactory queryStoreFactory) : base(queryStoreFactory) { _dataService = DataSource.GetHelperDataServices(); } public Task<bool> AddAsync(Group entity) { throw new NotImplementedException(); } public async Task<long> CountAsync() { var count = await _dataService.GetItemsCount<GRUPOS>().ConfigureAwait(false); return count; } public Task<bool> DeleteAsync(string entityId) { throw new NotImplementedException(); } public Task<List<Group>> GetAllAsync() { throw new NotImplementedException(); } public async Task<List<Group>> GetAsync(int top, int skip) { var itemList = await _dataService.GetPagedCollectionAsync<GRUPOS>(top, skip); var remapped = itemList.Select( x => { var vehicle = new Group() { Code = x.CODIGO, Name = x.NOMBRE, LastModification = x.ULTMODI, CurrentUser = x.USUARIO }; return vehicle; }).ToList(); return remapped; } public async Task<Option<Group>> GetByIdAsync(string entityId) { await Task.Delay(1); return Option.Nothing<Group>(); } public async Task<IEnumerable<Group>> GetFilteredAsync(ODataOptionsValue dataOptionsValue) { QueryOptions<IMapper> options = new QueryOptions<IMapper>(); int top = dataOptionsValue.Top; int skip = dataOptionsValue.Skip; var orderByClause = dataOptionsValue.OrderByClause; var filterByClause = dataOptionsValue.FilterClause; var filterManager = new FilterManager(); MappedQueryFields = new Dictionary<string, string>() { {"Code", "CODIGO"}, { "Name","NOMBRE"}, { "LastModification", "ULTMODI" }, { "CurrentUser", "USUARIO" } }; filterManager.UpdateFilter(filterByClause, orderByClause, MappedQueryFields); var currentResolvedFilter = filterManager.ResolvedFilter; // options filters. options.Skip = (skip <= 0) ? 1 : skip; options.Top = top; options.Mapper = Mapper; options.RawFilter = currentResolvedFilter; var filterSummary = await _dataService.SearchByFilterPaged<GRUPOS, Group, IMapper>((int)QueryType.QueryVehicleGroupPaged, options).ConfigureAwait(false); return filterSummary; } public Group New() { throw new NotImplementedException(); } public Task SaveChanges(Group entity) { throw new NotImplementedException(); } protected override void Configure(IDataServices services) { _dataService = services.GetHelperDataServices(); } } }
36.684615
134
0.522122
[ "Apache-2.0" ]
giorgiozoppi/fleetadmiral
src/repository/GroupRepository.cs
4,771
C#
using System; using System.Collections.Generic; using System.Linq; namespace AOC1._1 { public class Day7 { private class Bag { public Bag(string name) { Name = name; Children = new Dictionary<Bag, int>(); } public string Name { get; } public Dictionary<Bag, int> Children { get; } } public static void Task1() { string[] lines = System.IO.File.ReadAllLines(@"C:\Remote\AdventOfCoding2020\AOC1.1\Resources\Data7.txt"); Dictionary<string, Bag> dictionary = GetDictionary(lines); var bagsWhichCanCarry = new HashSet<Bag> { dictionary["shiny gold"] }; foreach (var bag in dictionary.Values) { if (bagsWhichCanCarry.Contains(bag)) { continue; } foreach (var child in bag.Children.Keys) { if (bagsWhichCanCarry.Contains(child)) { bagsWhichCanCarry.Add(bag); } var chainSet = new HashSet<Bag> { bag, child }; RecursiveSearch(bagsWhichCanCarry, child, chainSet); } } Console.WriteLine($"Day 7, task 1: {bagsWhichCanCarry.Count - 1}"); } public static void Task2() { string[] lines = System.IO.File.ReadAllLines(@"C:\Remote\AdventOfCoding2020\AOC1.1\Resources\Data7.txt"); Dictionary<string, Bag> dictionary = GetDictionary(lines); var shinyGoldBag = dictionary["shiny gold"]; int count = 0; AddBagsCount(ref count, shinyGoldBag, 1, shinyGoldBag); Console.WriteLine($"Day 7, task 2: {count}"); } private static Dictionary<string, Bag> GetDictionary(string[] lines) { var dictionary = new Dictionary<string, Bag>(); foreach (var line in lines) { var tempLine = line.Replace(" bags", "").Replace(" bag", "").Replace(".", ""); var parentWithChildren = tempLine.Split(" contain "); var parentName = parentWithChildren[0]; var parentBag = GetBag(dictionary, parentName); if (parentWithChildren[1].Contains("no other")) { continue; } var childrenStrings = parentWithChildren[1].Split(", "); foreach (var childString in childrenStrings) { var parts = childString.Split(" "); int count = int.Parse(parts[0]); string childName = $"{parts[1]} {parts[2]}"; var childBag = GetBag(dictionary, childName); parentBag.Children.Add(childBag, count); } } return dictionary; } private static Bag GetBag(Dictionary<string, Bag> dictionary, string name) { Bag bag; if (dictionary.ContainsKey(name)) { bag = dictionary[name]; } else { bag = new Bag(name); dictionary[name] = bag; } return bag; } private static void RecursiveSearch(HashSet<Bag> bagsWhichCanCarry, Bag bag, HashSet<Bag> chainSet) { foreach (var child in bag.Children) { if (chainSet.Contains(child.Key)) { //Expected infinity loop recursion but that didn't happen return; } if (bagsWhichCanCarry.Contains(child.Key)) { foreach (var chainBag in chainSet) { bagsWhichCanCarry.Add(chainBag); } return; } var currentChainSet = chainSet.ToHashSet(); currentChainSet.Add(child.Key); foreach (var childChild in child.Key.Children) { RecursiveSearch(bagsWhichCanCarry, childChild.Key, currentChainSet); } } } private static void AddBagsCount(ref int count, Bag bag, int requiredBagAmount, Bag mainBag) { if (bag.Children.Count == 0) { count += requiredBagAmount; return; } foreach (var childWithCount in bag.Children) { AddBagsCount(ref count, childWithCount.Key, childWithCount.Value * requiredBagAmount, mainBag); } if (bag != mainBag) { count += requiredBagAmount; } } } }
30.790123
117
0.476945
[ "MIT" ]
QLerin/AdventOfCode
AOC1.1/Day7.cs
4,990
C#
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace MxWeiXinPF.Web.admin.diancai { public partial class caidan_list_all { /// <summary> /// Head1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlHead Head1; /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// btnDelete 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.LinkButton btnDelete; /// <summary> /// txtKeywords 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtKeywords; /// <summary> /// lbtnSearch 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.LinkButton lbtnSearch; /// <summary> /// rptList 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Repeater rptList; /// <summary> /// txtPageNum 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtPageNum; /// <summary> /// PageContent 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl PageContent; } }
27.75
84
0.464373
[ "MIT" ]
herrylau/wwzkushop
MxWeiXinPF.Web/admin/diancai/caidan_list_all.aspx.designer.cs
3,180
C#
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.ComponentModel; using System.IO; using Microsoft.Win32; using Sce.Atf.Wpf.Applications; using Sce.Atf.Wpf.Controls; namespace Sce.Atf.Wpf.Models { internal sealed class SettingsLoadSaveViewModel : DialogViewModelBase { /// <summary> /// Constructor</summary> /// <param name="settings">Settings service to use for saving and loading the settings</param> public SettingsLoadSaveViewModel(SettingsService settings) { Title = "Load and Save Settings".Localize(); if (settings == null) throw new ArgumentNullException(); m_settingsService = settings; m_saveDialog = new SaveFileDialog(); m_saveDialog.OverwritePrompt = true; m_saveDialog.Title = "Export settings"; m_saveDialog.Filter = "Setting file(*.xml)|*.xml"; m_openDialog = new OpenFileDialog(); m_openDialog.Title = "Import settings"; m_openDialog.CheckFileExists = true; m_openDialog.CheckPathExists = true; m_openDialog.Multiselect = false; m_openDialog.Filter = "Setting file(*.xml)|*.xml"; Action = SettingsAction.Save; } public SettingsAction Action { get { return m_action; } set { m_action = value; OnPropertyChanged(ActionArgs); } } /// <summary> /// Event called when the dialog is closing.</summary> /// <param name="args"></param> protected override void OnCloseDialog(CloseDialogEventArgs args) { if (args.DialogResult == true) { if (Action == SettingsAction.Save) { if (m_saveDialog.ShowCommonDialogWorkaround() == true) { SaveSettings(m_saveDialog.FileName); } else { return; } } else if (Action == SettingsAction.Load) { if (m_openDialog.ShowCommonDialogWorkaround() == true) { if (!LoadSettings(m_openDialog.FileName)) return; } else { return; } } } RaiseCloseDialog(args); } private void SaveSettings(string fullFileName) { Stream stream = null; try { stream = File.Create(fullFileName); m_settingsService.SerializeInternal(stream); } finally { if (stream != null) stream.Close(); } } private bool LoadSettings(string fullFileName) { bool retVal = false; Stream stream = null; try { stream = File.OpenRead(fullFileName); retVal = m_settingsService.DeserializeInternal(stream); if (retVal) m_settingsService.SaveSettings(); } catch (Exception ex) { Outputs.WriteLine(OutputMessageType.Error, ex.Message); } finally { if (stream != null) stream.Close(); } return retVal; } private SettingsAction m_action; private static readonly PropertyChangedEventArgs ActionArgs = ObservableUtil.CreateArgs<FindFileDialogViewModel>(x => x.Action); private readonly SettingsService m_settingsService; private readonly SaveFileDialog m_saveDialog; private readonly OpenFileDialog m_openDialog; } }
31.311111
103
0.48687
[ "Apache-2.0" ]
HaKDMoDz/ATF
Framework/Atf.Gui.Wpf/Models/SettingsLoadSaveDialogViewModel.cs
4,096
C#
using System; using System.ComponentModel.Composition; using NuPattern.ComponentModel.Design; using NuPattern.Library.Properties; using NuPattern.Runtime; using NuPattern.Runtime.Events; namespace NuPattern.Library.Events { /// <summary> /// Exposes the event raised when any runtime component in the pattern state /// is being deleted. /// </summary> public interface IOnElementDeletingEvent : IObservable<IEvent<EventArgs>>, IObservableEvent { } /// <summary> /// Assumes there can only be one state opened at any given time. /// </summary> [DisplayNameResource(@"OnElementDeletingEvent_DisplayName", typeof(Resources))] [DescriptionResource(@"OnElementDeletingEvent_Description", typeof(Resources))] [CategoryResource(@"AutomationCategory_Automation", typeof(Resources))] [Event(typeof(IOnElementDeletingEvent))] [Export(typeof(IOnElementDeletingEvent))] [PartCreationPolicy(CreationPolicy.Shared)] internal sealed class OnElementDeletingEvent : IOnElementDeletingEvent, IDisposable { private IPatternManager patternManager; /// <summary> /// The event that is the source to which subscribers subscribe. /// In this case, it's our own event that we republish from /// the underlying event, as we change the sender and the /// event args. /// </summary> private IObservable<IEvent<EventArgs>> sourceEvent; /// <summary> /// This is the underlying state event that we internally /// subscribe for republishing. /// </summary> private IObservable<IEvent<ValueEventArgs<IInstanceBase>>> storeEvent; /// <summary> /// The subscription to the <see cref="storeEvent"/> for disposal when /// IsOpen changes in the <see cref="patternManager"/>. /// </summary> private IDisposable storeEventSubscription; /// <summary> /// Current element that the event exists on and which is used to /// filter out the events that do not belong to this element. /// </summary> private IInstanceBase currentElement; /// <summary> /// Initializes a new instance of the <see cref="OnElementDeletedEvent"/> class. /// </summary> [ImportingConstructor] public OnElementDeletingEvent( [Import(AllowDefault = true)] IPatternManager patternManager, [Import(AllowDefault = true)] IInstanceBase currentElement) { this.currentElement = currentElement; this.patternManager = patternManager; this.sourceEvent = WeakObservable.FromEvent<EventArgs>( handler => this.ElementDeleting += handler, handler => this.ElementDeleting -= handler); if (patternManager != null) { this.patternManager.IsOpenChanged += (sender, args) => this.OnOpenChanged(); if (this.patternManager.IsOpen) { this.storeEvent = WeakObservable.FromEvent<ValueEventArgs<IInstanceBase>>( handler => this.patternManager.Store.ElementDeleting += handler, handler => this.patternManager.Store.ElementDeleting -= handler); this.storeEventSubscription = this.storeEvent.Subscribe(this.OnStoreElementDeleting); } } } /// <summary> /// Private event used to re-publish the state event with the right sender (the Activated element). /// </summary> private event EventHandler<EventArgs> ElementDeleting = (sender, args) => { }; /// <summary> /// Subscribes the specified observer. /// </summary> public IDisposable Subscribe(IObserver<IEvent<EventArgs>> observer) { Guard.NotNull(() => observer, observer); return this.sourceEvent.Subscribe(observer); } /// <summary> /// Cleans up subscriptions. /// </summary> public void Dispose() { if (this.storeEventSubscription != null) { this.storeEventSubscription.Dispose(); } if (this.patternManager != null) this.patternManager.IsOpenChanged -= (sender, args) => this.OnOpenChanged(); } private void OnOpenChanged() { if (this.storeEventSubscription != null) { this.storeEventSubscription.Dispose(); } if (this.patternManager.IsOpen) { this.storeEvent = WeakObservable.FromEvent<ValueEventArgs<IInstanceBase>>( handler => this.patternManager.Store.ElementDeleting += handler, handler => this.patternManager.Store.ElementDeleting -= handler); this.storeEventSubscription = this.storeEvent.Subscribe(this.OnStoreElementDeleting); } } private void OnStoreElementDeleting(IEvent<ValueEventArgs<IInstanceBase>> args) { if (args.EventArgs.Value == this.currentElement) this.ElementDeleting(args.EventArgs.Value, EventArgs.Empty); } } }
39.028777
108
0.599631
[ "Apache-2.0" ]
dbremner/nupattern
Src/Library/Source/Events/OnElementDeletingEvent.cs
5,427
C#
/* MIT License Copyright (c) 2018 Grega Mohorko 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. Project: GM.Tools Created: 2018-2-1 Author: GregaMohorko */ using System; using System.Collections.Generic; using System.Text; namespace GM.Tools.Google.API.Maps.DistanceMatrix { /// <summary> /// Distances may be calculated that adhere to certain restrictions. /// </summary> public enum Restriction { /// <summary> /// None. /// </summary> NONE, /// <summary> /// Tolls. /// </summary> tolls, /// <summary> /// Highways. /// </summary> highways, /// <summary> /// Ferries. /// </summary> ferries, /// <summary> /// Indoor. /// </summary> indoor } }
27
78
0.73178
[ "MIT" ]
GregaMohorko/GM.Tools
src/GM.Tools/GM.Tools/Google/API/Maps/DistanceMatrix/Restriction.cs
1,676
C#
using System; using System.Collections.Generic; namespace Hao.Geometry { // Token: 0x0200003B RID: 59 public static class IntersectionCircle2 { // Token: 0x06000269 RID: 617 RVA: 0x0000A540 File Offset: 0x00008740 public static bool Intersects(this Circle2 circle, Circle2 other) { IntersectionCircle2Circle2 intersectionCircle2Circle = new IntersectionCircle2Circle2(circle, other); return intersectionCircle2Circle.Find(); } // Token: 0x0600026A RID: 618 RVA: 0x0000A560 File Offset: 0x00008760 public static ICollection<Vector2> IntersectionPointsWith(this Circle2 circle, Circle2 other) { IntersectionCircle2Circle2 intersectionCircle2Circle = new IntersectionCircle2Circle2(circle, other); intersectionCircle2Circle.Find(); List<Vector2> list = new List<Vector2>(); Vector2[] array = new Vector2[] { intersectionCircle2Circle.Point0, intersectionCircle2Circle.Point1 }; for (int i = 0; i < intersectionCircle2Circle.Quantity; i++) { list.Add(array[i]); } return list; } // Token: 0x0600026B RID: 619 RVA: 0x0000A5C7 File Offset: 0x000087C7 public static bool Intersects(this Circle2 circle, Arc2 arc) { return arc.Intersects(circle); } // Token: 0x0600026C RID: 620 RVA: 0x0000A5D0 File Offset: 0x000087D0 public static ICollection<Vector2> IntersectionPointsWith(this Circle2 circle, Arc2 arc) { return arc.IntersectionPointsWith(circle); } // Token: 0x0600026D RID: 621 RVA: 0x0000A5D9 File Offset: 0x000087D9 public static bool Intersects(this Circle2 circle, Line2 line) { return line.Intersects(circle); } // Token: 0x0600026E RID: 622 RVA: 0x0000A5E2 File Offset: 0x000087E2 public static ICollection<Vector2> IntersectionPointsWith(this Circle2 circle, Line2 line) { return line.IntersectionPointsWith(circle); } // Token: 0x0600026F RID: 623 RVA: 0x0000A5EB File Offset: 0x000087EB public static bool Intersects(this Circle2 circle, Ray2 ray) { return ray.Intersects(circle); } // Token: 0x06000270 RID: 624 RVA: 0x0000A5F4 File Offset: 0x000087F4 public static ICollection<Vector2> IntersectionPointsWith(this Circle2 circle, Ray2 ray) { return ray.IntersectionPointsWith(circle); } } }
31.605634
104
0.748217
[ "Apache-2.0" ]
JieGou/mh-master
Hao.Geometry/IntersectionCircle2.cs
2,246
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the servicediscovery-2017-03-14.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ServiceDiscovery.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ServiceDiscovery.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for TooManyTagsException Object /// </summary> public class TooManyTagsExceptionUnmarshaller : IErrorResponseUnmarshaller<TooManyTagsException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public TooManyTagsException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public TooManyTagsException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse) { context.Read(); TooManyTagsException unmarshalledObject = new TooManyTagsException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ResourceName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ResourceName = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static TooManyTagsExceptionUnmarshaller _instance = new TooManyTagsExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static TooManyTagsExceptionUnmarshaller Instance { get { return _instance; } } } }
36.571429
132
0.63762
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ServiceDiscovery/Generated/Model/Internal/MarshallTransformations/TooManyTagsExceptionUnmarshaller.cs
3,328
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using CycleCycleCycle.Models; namespace CycleCycleCycle.Services.RouteFileCreator { public interface IRouteFileCreator { XDocument CreateRoute(Route route, out string filename); } }
20.866667
64
0.769968
[ "MIT" ]
JamesRandall/CycleCycleCycle.com
CycleCycleCycle/Services/RouteFileCreator/IRouteFileCreator.cs
315
C#
using MongoDB.Driver; using System; using System.Collections.Generic; using System.Text; namespace ProgramPet.Repository { public class conection { public IMongoDatabase startconection() { var client = new MongoClient(""); var database = client.GetDatabase("developersdb00"); return database; } } }
18.75
64
0.626667
[ "MIT" ]
gustavoguerra/Pet
ProgramPet/ProgramPet.Repository/conection.cs
377
C#
#region License /* * HttpRequestHeader.cs * * This code is derived from System.Net.HttpRequestHeader.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2014 sta.blockhead * * 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 #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion namespace crystal.network.websockets.Net { /// <summary> /// Contains the HTTP headers that may be specified in a client request. /// </summary> /// <remarks> /// The HttpRequestHeader enumeration contains the HTTP request headers defined in /// <see href="http://tools.ietf.org/html/rfc2616#section-14" langword="null">RFC 2616</see> for the HTTP/1.1 and /// <see href="http://tools.ietf.org/html/rfc6455#section-11.3" langword="null">RFC 6455</see> for the WebSocket. /// </remarks> public enum HttpRequestHeader { /// <summary> /// Indicates the Cache-Control header. /// </summary> CacheControl, /// <summary> /// Indicates the Connection header. /// </summary> Connection, /// <summary> /// Indicates the Date header. /// </summary> Date, /// <summary> /// Indicates the Keep-Alive header. /// </summary> KeepAlive, /// <summary> /// Indicates the Pragma header. /// </summary> Pragma, /// <summary> /// Indicates the Trailer header. /// </summary> Trailer, /// <summary> /// Indicates the Transfer-Encoding header. /// </summary> TransferEncoding, /// <summary> /// Indicates the Upgrade header. /// </summary> Upgrade, /// <summary> /// Indicates the Via header. /// </summary> Via, /// <summary> /// Indicates the Warning header. /// </summary> Warning, /// <summary> /// Indicates the Allow header. /// </summary> Allow, /// <summary> /// Indicates the Content-Length header. /// </summary> ContentLength, /// <summary> /// Indicates the Content-Type header. /// </summary> ContentType, /// <summary> /// Indicates the Content-Encoding header. /// </summary> ContentEncoding, /// <summary> /// Indicates the Content-Language header. /// </summary> ContentLanguage, /// <summary> /// Indicates the Content-Location header. /// </summary> ContentLocation, /// <summary> /// Indicates the Content-MD5 header. /// </summary> ContentMd5, /// <summary> /// Indicates the Content-Range header. /// </summary> ContentRange, /// <summary> /// Indicates the Expires header. /// </summary> Expires, /// <summary> /// Indicates the Last-Modified header. /// </summary> LastModified, /// <summary> /// Indicates the Accept header. /// </summary> Accept, /// <summary> /// Indicates the Accept-Charset header. /// </summary> AcceptCharset, /// <summary> /// Indicates the Accept-Encoding header. /// </summary> AcceptEncoding, /// <summary> /// Indicates the Accept-Language header. /// </summary> AcceptLanguage, /// <summary> /// Indicates the Authorization header. /// </summary> Authorization, /// <summary> /// Indicates the Cookie header. /// </summary> Cookie, /// <summary> /// Indicates the Expect header. /// </summary> Expect, /// <summary> /// Indicates the From header. /// </summary> From, /// <summary> /// Indicates the Host header. /// </summary> Host, /// <summary> /// Indicates the If-Match header. /// </summary> IfMatch, /// <summary> /// Indicates the If-Modified-Since header. /// </summary> IfModifiedSince, /// <summary> /// Indicates the If-None-Match header. /// </summary> IfNoneMatch, /// <summary> /// Indicates the If-Range header. /// </summary> IfRange, /// <summary> /// Indicates the If-Unmodified-Since header. /// </summary> IfUnmodifiedSince, /// <summary> /// Indicates the Max-Forwards header. /// </summary> MaxForwards, /// <summary> /// Indicates the Proxy-Authorization header. /// </summary> ProxyAuthorization, /// <summary> /// Indicates the Referer header. /// </summary> Referer, /// <summary> /// Indicates the Range header. /// </summary> Range, /// <summary> /// Indicates the TE header. /// </summary> Te, /// <summary> /// Indicates the Translate header. /// </summary> Translate, /// <summary> /// Indicates the User-Agent header. /// </summary> UserAgent, /// <summary> /// Indicates the Sec-WebSocket-Key header. /// </summary> SecWebSocketKey, /// <summary> /// Indicates the Sec-WebSocket-Extensions header. /// </summary> SecWebSocketExtensions, /// <summary> /// Indicates the Sec-WebSocket-Protocol header. /// </summary> SecWebSocketProtocol, /// <summary> /// Indicates the Sec-WebSocket-Version header. /// </summary> SecWebSocketVersion } }
27.008547
117
0.608228
[ "MIT" ]
n30np14gu3/crystal
crystal/network/websockets/Net/HttpRequestHeader.cs
6,320
C#
using System; namespace _07ConcatNames { class Program { static void Main(string[] args) { string firstName = Console.ReadLine(); string secondName = Console.ReadLine(); string delimiter = Console.ReadLine(); string result = firstName + delimiter + secondName; Console.WriteLine(result); } } }
21.833333
63
0.56743
[ "MIT" ]
kalintsenkov/SoftUni-Software-Engineering
CSharp-Technology-Fundamentals/Homeworks-And-Labs/02DataTypesLab/07ConcatNames/Program.cs
395
C#
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski 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. // namespace NLog.Internal.FileAppenders { using Targets; /// <summary> /// Interface that provides parameters for create file function. /// </summary> internal interface ICreateFileParameters { /// <summary> /// Gets or sets the delay in milliseconds to wait before attempting to write to the file again. /// </summary> int FileOpenRetryCount { get; } /// <summary> /// Gets or sets the number of times the write is appended on the file before NLog /// discards the log message. /// </summary> int FileOpenRetryDelay { get; } /// <summary> /// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on the same host. /// </summary> /// <remarks> /// This makes multi-process logging possible. NLog uses a special technique /// that lets it keep the files open for writing. /// </remarks> bool ConcurrentWrites { get; } /// <summary> /// Gets or sets a value indicating whether to create directories if they do not exist. /// </summary> /// <remarks> /// Setting this to false may improve performance a bit, but you'll receive an error /// when attempting to write to a directory that's not present. /// </remarks> bool CreateDirs { get; } /// <summary> /// Gets or sets a value indicating whether to enable log file(s) to be deleted. /// </summary> bool EnableFileDelete { get; } /// <summary> /// Gets or sets the log file buffer size in bytes. /// </summary> int BufferSize { get; } /// <summary> /// Gets or set a value indicating whether a managed file stream is forced, instead of using the native implementation. /// </summary> bool ForceManaged { get; } /// <summary> /// Gets or sets the file attributes (Windows only). /// </summary> Win32FileAttributes FileAttributes { get; } /// <summary> /// Should archive mutex be created? /// </summary> bool IsArchivingEnabled { get; } /// <summary> /// Should manual simple detection of file deletion be enabled? /// </summary> bool EnableFileDeleteSimpleMonitor { get; } } }
39.436893
127
0.654357
[ "BSD-3-Clause" ]
304NotModified/NLog
src/NLog/Internal/FileAppenders/ICreateFileParameters.cs
4,062
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace YoloCutomTrainModel.UnitTest { [TestClass] public class DetectHinhNguoi { [TestMethod] public async Task Run() { } } }
15.714286
52
0.681818
[ "MIT" ]
badpaybad/darknet-yolo-dataset-creator
YoloCutomTrainModel.UnitTest/DetectHinhNguoi.cs
332
C#