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 |
|---|---|---|---|---|---|---|---|---|
// Copyright 2009 Jeffrey Cameron
//
// 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 Concordion.Api;
using Concordion.Api.Listener;
namespace Concordion.Internal.Listener
{
public class VerifyRowResultRenderer : IVerifyRowsListener
{
#region IVerifyRowsListener Members
public void ExpressionEvaluated(ExpressionEvaluatedEvent expressionEvaluatedEvent)
{
}
public void MissingRow(MissingRowEvent missingRowEvent)
{
Element element = missingRowEvent.RowElement;
element.AddStyleClass("missing");
}
public void SurplusRow(SurplusRowEvent surplusRowEvent)
{
Element element = surplusRowEvent.RowElement;
element.AddStyleClass("surplus");
}
#endregion
}
}
| 29.311111 | 90 | 0.701289 | [
"ECL-2.0",
"Apache-2.0"
] | KidFashion/concordion-net | Concordion/Internal/Listener/VerifyRowResultRenderer.cs | 1,319 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Grpc.Core.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Google Inc. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.1.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 43.782609 | 81 | 0.747766 | [
"BSD-3-Clause"
] | jonywtf/grpc | src/csharp/Grpc.Core.Tests/Properties/AssemblyInfo.cs | 1,007 | C# |
using Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Flow.Helpers
{
public class FlowHelper
{
public static async Task<Customer> GetFlowOutput(string userId)
{
using (HttpClient httpClient = new HttpClient())
{
try
{
httpClient.Timeout = new TimeSpan(0, 2, 0); //2 minutes
// Create a JSON object
JObject user = new JObject();
user.Add("userId", userId);
// Get response from Microsoft Flow
var stringContent = new StringContent(user.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync("https://prod-81.westus.logic.azure.com:443/workflows/a4c85f0fb48f4e3e94ed88c4271afdce/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=e1Pw3CXokS9J4Gk8MhHMaWgth1AlDHRcNYxOdky9DE0", stringContent);
var array = response.Content.ReadAsStringAsync().Result.Split('|');
// Customer
return new Customer()
{
Name = array[0],
Address = array[1],
MobileNumber = array[2]
};
}
catch(Exception ex)
{
throw ex;
}
}
}
}
}
| 34.833333 | 319 | 0.522727 | [
"MIT"
] | CurlyBytes/CognitiveRocket | Community/2019/DynamicsPowerSydney/Demos/Flow/Helpers/FlowHelper.cs | 1,674 | C# |
using System;
namespace ComputerStoreWeb.App.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | 19.818182 | 70 | 0.678899 | [
"MIT"
] | 1902-feb18-net/william-project0 | ComputerStore.ui/ComputerStoreWeb.App/Models/ErrorViewModel.cs | 218 | C# |
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// Copyright (c) 2011 Garrett Serack . All rights reserved.
// </copyright>
// <license>
// The software is licensed under the Apache 2.0 License (the "License")
// You may not use the software except in compliance with the License.
// </license>
//-----------------------------------------------------------------------
namespace CoApp.Toolkit.Win32 {
using System.Runtime.InteropServices;
public class Winmm {
[DllImport("winmm.dll")]
private static extern int midiOutOpen(ref int handle, int deviceID, MidiCallback proc, int instance, int flags);
[DllImport("winmm.dll")]
protected static extern int midiOutShortMsg(int handle, int message);
#region Nested type: MidiCallback
protected delegate void MidiCallback(int handle, int msg, int instance, int param1, int param2);
#endregion
}
} | 37.666667 | 121 | 0.566372 | [
"Apache-2.0"
] | fearthecowboy/coapp | toolkit/Win32/Winmm.cs | 1,019 | C# |
using Mews.Fiscalization.Greece.Model.Types;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mews.Fiscalization.Greece.Model
{
public abstract class Invoice
{
public Invoice(
LocalCompany issuer,
InvoiceHeader header,
IEnumerable<Revenue> revenueItems,
StringIdentifier invoiceIdentifier = null,
InvoiceRegistrationNumber invoiceRegistrationNumber = null,
InvoiceRegistrationNumber cancelledByInvoiceRegistrationNumber = null,
ForeignCompany counterpart = null,
IEnumerable<Payment> payments = null)
{
Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer));
Header = header ?? throw new ArgumentNullException(nameof(header));
InvoiceIdentifier = invoiceIdentifier;
InvoiceRegistrationNumber = invoiceRegistrationNumber;
CanceledByInvoiceRegistrationNumber = cancelledByInvoiceRegistrationNumber;
Counterpart = counterpart;
RevenueItems = revenueItems;
Payments = payments;
if (revenueItems.Count() == 0)
{
throw new ArgumentException($"Minimal count of {nameof(revenueItems)} is 1.");
}
}
public InvoiceHeader Header { get; set; }
public StringIdentifier InvoiceIdentifier { get; }
public InvoiceRegistrationNumber InvoiceRegistrationNumber { get; }
public InvoiceRegistrationNumber CanceledByInvoiceRegistrationNumber { get; }
public LocalCompany Issuer { get; }
public ForeignCompany Counterpart { get; }
public IEnumerable<Revenue> RevenueItems { get; }
public IEnumerable<Payment> Payments { get; set; }
}
}
| 35.431373 | 94 | 0.66021 | [
"MIT"
] | yurypat/fiscalization-greece | src/Mews.Fiscalization.Greece/Model/Invoice.cs | 1,809 | C# |
namespace Telephony
{
public interface ICalling
{
string Calling(string phoneNumber);
}
} | 15.714286 | 43 | 0.645455 | [
"MIT"
] | NeikoGrozev/CSharpAdvanced | OOP/Exercises/08. Interfaces and Abstraction - Exercise/04.Telephony/ICalling.cs | 112 | C# |
using System;
/*
* Для каких случайных экспериментов естественно считать исходы
* равновероятными?
*
* Отметьте все подходящие.
*/
namespace step_3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("а) бросаем игральную кость (кубик)");
Console.WriteLine("б) случайно вытаскиваем три карты из колоды");
}
}
}
| 19.857143 | 78 | 0.592326 | [
"Unlicense"
] | tshemake/Software-Development | stepik/2911/46760/step_3/Program.cs | 572 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MesOpc.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=(localdb)\\v11.0;Initial Catalog=MesOpc;Integrated Security=True;Conne" +
"ct Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWr" +
"ite;MultiSubnetFailover=False")]
public string connectionString {
get {
return ((string)(this["connectionString"]));
}
}
}
}
| 45.615385 | 153 | 0.623946 | [
"Apache-2.0"
] | WagoL/ping-rep | MesOpc/MesOpc/Properties/Settings.Designer.cs | 1,781 | C# |
using System.ComponentModel.DataAnnotations;
namespace MisFinanzas.Api.Models
{
public class LoginModel
{
public string TenancyName { get; set; }
[Required]
public string UsernameOrEmailAddress { get; set; }
[Required]
public string Password { get; set; }
}
} | 21 | 58 | 0.638095 | [
"MIT"
] | jjairocj/MisFinanzas | MisFinanzas.WebApi/Api/Models/LoginModel.cs | 317 | C# |
namespace Microsoft.Recognizers.Text.Sequence.English
{
public class MentionExtractor : BaseMentionExtractor
{
}
}
| 18.285714 | 56 | 0.742188 | [
"MIT"
] | 7i77an/Recognizers-Text | .NET/Microsoft.Recognizers.Text.Sequence/English/Extractors/MentionExtractor.cs | 130 | C# |
namespace MVP.App.Common
{
using Android.OS;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Practices.ServiceLocation;
public abstract class BaseActivityViewModel : ViewModelBase
{
protected BaseActivityViewModel()
: this(ServiceLocator.Current.GetInstance<IMessenger>())
{
}
[PreferredConstructor]
protected BaseActivityViewModel(IMessenger messenger)
{
this.MessengerInstance = messenger;
}
public abstract void OnActivityCreated(Bundle bundle);
}
} | 24.5 | 68 | 0.66876 | [
"MIT"
] | jamesmcroft/MS-MVP-Apps | MVP.App.Droid/Common/BaseActivityViewModel.cs | 637 | C# |
// <auto-generated />
namespace SistemaGestionRENI.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")]
public sealed partial class IndicadorValor : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(IndicadorValor));
string IMigrationMetadata.Id
{
get { return "201808200516005_IndicadorValor"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 27.733333 | 97 | 0.627404 | [
"MIT"
] | bleudchanel/ProyectoRENI | SistemaGestionRENI/Migrations/201808200516005_IndicadorValor.Designer.cs | 832 | C# |
using OpenTK;
namespace Minotaur.Graphics.Animation
{
public abstract class BoneAnimationControlerBase : IBoneAnimationController
{
public abstract bool TryGetBoneTransforms(int bone, out Vector3 translation, out Quaternion rotation, out Vector3 scale, out float blendWeight);
public bool TryGetGoneTransforms(int bone, out Matrix4 transform, out float blendWeight)
{
Vector3 translation;
Quaternion rotation;
Vector3 scale;
bool result = TryGetBoneTransforms(bone, out translation, out rotation, out scale, out blendWeight);
transform = Matrix4.Rotate(rotation) * Matrix4.Scale(scale) * Matrix4.Translation(translation);
return result;
}
}
}
| 30.73913 | 148 | 0.745403 | [
"MIT"
] | mlunnay/minotaur | minotaur/src/Graphics/Animation/BoneAnimationControlerBase.cs | 709 | 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("Pdfium.Windows")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pdfium.Windows")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ebe56c76-1ff3-422d-93ac-3f604f2178c0")]
// 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.72973 | 84 | 0.747135 | [
"Apache-2.0"
] | DAVISOL-GmbH/PdfiumViewer | Pdfium.Windows/Properties/AssemblyInfo.cs | 1,399 | C# |
using FootballTeams.Models;
namespace FootballTeams.Services.Contracts
{
public interface IXmlService
{
void WriteTeamToXml(string fileName, Team team);
Team ReadTeamFromXml(string fileName);
}
}
| 18.916667 | 56 | 0.713656 | [
"MIT"
] | SimeonGerginov/Football-Teams | FootballTeams/FootballTeams/Services/Contracts/IXmlService.cs | 229 | C# |
using Schedule.CronExpressionBuilder.Interface;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Schedule.CronExpressionBuilder
{
public class DaysOfWeekExpressionBuilder : CronExpressionBuilder, IDaysOfWeekExpressionBuilder
{
/// <summary>
/// Every N day(s) starting at specified day of a week e.g. 2 days starting from Monday - 2/2 - Monday, Wednesday ...
/// </summary>
/// <returns></returns>
IDaysOfWeekExpressionBuilder IDaysOfWeekExpressionBuilder.EveryNDaysSyartingAtDayOfWeek(DayOfWeek startAtWeekDay, [Range(1, 7)] int interval)
{
base.EveryNDaysSyartingAtDayOfWeek(startAtWeekDay,interval);
return this;
}
/// <summary>
/// Every weekdays - Monday to Friday
/// </summary>
/// <returns></returns>
IDaysOfWeekExpressionBuilder IDaysOfWeekExpressionBuilder.WeekDays()
{
base.WeekDays();
return this;
}
/// <summary>
/// Every weekends - Saturday, Sunday
/// </summary>
/// <returns></returns>
IDaysOfWeekExpressionBuilder IDaysOfWeekExpressionBuilder.WeekEnds()
{
base.WeekEnds();
return this;
}
/// <summary>
/// Every weekends - Saturday, Sunday
/// </summary>
/// <returns></returns>
IDaysOfWeekExpressionBuilder IDaysOfWeekExpressionBuilder.AtSpecifiedDaysOfWeek(IEnumerable<DayOfWeek> daysOfWeek)
{
base.AtSpecifiedDaysOfWeek(daysOfWeek);
return this;
}
/// <summary>
/// Last specified day of week e.g. last monday of the month.
/// </summary>
/// <param name="lastDayOfWeekOfTheMonth"></param>
/// <returns></returns>
IDaysOfWeekExpressionBuilder IDaysOfWeekExpressionBuilder.LastSpecfiedDayOfWeekOfAMonth(DayOfWeek lastDayOfWeekOfTheMonth)
{
base.LastSpecfiedDayOfWeekOfAMonth(lastDayOfWeekOfTheMonth);
return this;
}
/// <summary>
/// Nth day of Week of the month e.g. 2nd Monday of the Month.
/// </summary>
/// <param name="dayOfWeek"></param>
/// <param name="numberN"></param>
/// <returns></returns>
IDaysOfWeekExpressionBuilder IDaysOfWeekExpressionBuilder.NthDayOfWeekOfAMonth(DayOfWeek dayOfWeek,[Range(1, 5)] int numberN)
{
base.NthDayOfWeekOfAMonth(dayOfWeek,numberN);
return this;
}
/// <summary>
/// Between days of the week e.g. Tuesday - Friday
/// </summary>
/// <returns></returns>
IDaysOfWeekExpressionBuilder IDaysOfWeekExpressionBuilder.BetweenDaysOfWeek(DayOfWeek start, DayOfWeek end)
{
base.BetweenDaysOfWeek( start, end);
return this;
}
}
} | 35.6 | 150 | 0.596827 | [
"MIT"
] | quartzidea/cronexpression | src/DaysOfWeekExpressionBuilder.cs | 3,026 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
namespace Anagram.Models
{
[TestClass]
public class ItemTest
{
// public void Dispose()
// {
// Word.ClearAll();
// }
[TestMethod]
public void ItemConstructor_CreatesInstanceOfItem_Item()
{
Word testWord = new Word("test");
Assert.AreEqual(typeof(Word), testWord.GetType());
}
[TestMethod]
public void Properties_ChecksFirstWordPropertiesInputCorrectly_String()
{
//Arrange
string testWord = "TestListString";
Word testWordObj = new Word(testWord);
//Act
string result = testWordObj.GetFirstWord();
//Assert
Assert.AreEqual(testWord, result);
}
[TestMethod]
public void Properties_ChecksInputListPropertyInput_String()
{
//Arrange
List<string> testList = new List<string>{};
string testInputWord = "TestListString";
testList.Add(testInputWord);
Word testWord = new Word(testList);
//Act
List<string> listResult = testWord.GetFirstList();
//Assert
CollectionAssert.AreEqual(testList, listResult);
}
[TestMethod]
public void Properties_ChecksPropertyInput_String()
{
//Arrange
List<string> testList = new List<string>{};
string testInputWord = "TestListString";
testList.Add(testInputWord);
Word testWord = new Word(testInputWord, testList);
//Act
string result = testWord.GetFirstWord();
List<string> listResult = testWord.GetFirstList();
//Assert
Assert.AreEqual(testInputWord, result);
CollectionAssert.AreEqual(testList, listResult);
}
[TestMethod]
public void AddToCompareList_AddEachUserInputToList_List()
{
//Arrange
List<string> testList = new List<string>{};
string testInputWord = "TestListString";
Word testWord = new Word(testInputWord, testList);
testWord.AddToCompareList(testInputWord);
testWord.AddToCompareList("SecondItemAdded");
Word resultWord = new Word(testInputWord, new List<string> (new string[] {"TestListString", "SecondItemAdded"}));
//Act
string result = testWord.GetFirstWord();
List<string> listResult = testWord.GetFirstList();
foreach (string thisWord in resultWord.GetFirstList())
{
Console.WriteLine("Output from resultWord Object compareList: " + thisWord);
}
//Assert
CollectionAssert.AreEqual(testWord.GetFirstList(), resultWord.GetFirstList());
}
}
}
| 25.86 | 119 | 0.664733 | [
"MIT"
] | TanviCodeLife/anagram-csharp | Anagram.Tests/ModelTests/WordTests.cs | 2,586 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace AdaKioskService
{
internal class ApplicationLauncher
{
/// <summary>
/// butbut: for some reason this is not working, the service does not have permission saying
/// "The application-specific permission settings do not grant Local Launch permission..."
/// So we are currently not using this, instead we force a reboot which has the same effect
/// of restarting the Kiosk app and I refuse to mess around with ServiceBroker ACL's.
/// </summary>
public static bool CreateProcessInConsoleSession(ServiceLog log, String commandLine, bool bElevate)
{
PROCESS_INFORMATION pi;
bool bResult = false;
uint dwSessionId, winlogonPid = 0;
IntPtr hUserToken = IntPtr.Zero, hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;
// Log the client on to the local computer.
dwSessionId = WTSGetActiveConsoleSessionId();
// Find the winlogon process
var procEntry = new PROCESSENTRY32();
uint hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE)
{
return false;
}
procEntry.dwSize = (uint)Marshal.SizeOf(procEntry); //sizeof(PROCESSENTRY32);
if (Process32First(hSnap, ref procEntry) == 0)
{
return false;
}
String strCmp = "explorer.exe";
do
{
if (strCmp.IndexOf(procEntry.szExeFile) == 0)
{
// We found a winlogon process...make sure it's running in the console session
uint winlogonSessId = 0;
if (ProcessIdToSessionId(procEntry.th32ProcessID, out winlogonSessId) &&
winlogonSessId == dwSessionId)
{
winlogonPid = procEntry.th32ProcessID;
break;
}
else
{
var hr = Marshal.GetLastWin32Error();
log.WriteMessage(String.Format("ProcessIdToSessionId error: {0}", hr));
}
}
}
while (Process32Next(hSnap, ref procEntry) != 0);
//Get the user token used by DuplicateTokenEx
WTSQueryUserToken(dwSessionId, out hUserToken);
var si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = "winsta0\\default";
var tp = new TOKEN_PRIVILEGES();
var luid = new LUID();
hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);
if (!OpenProcessToken(hProcess,
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY
| TOKEN_ADJUST_SESSIONID | TOKEN_READ | TOKEN_WRITE, ref hPToken))
{
var hr = Marshal.GetLastWin32Error();
log.WriteMessage(String.Format("CreateProcessInConsoleSession OpenProcessToken error: {0}", hr));
}
if (!LookupPrivilegeValue(IntPtr.Zero, SE_TCB_NAME, ref luid))
{
var hr = Marshal.GetLastWin32Error();
log.WriteMessage(String.Format("CreateProcessInConsoleSession LookupPrivilegeValue error: {0}", hr));
}
var sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);
if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa,
(int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary,
ref hUserTokenDup))
{
var hr = Marshal.GetLastWin32Error();
log.WriteMessage("CreateProcessInConsoleSession DuplicateTokenEx error: {0} Token does not have the privilege.", hr);
CloseHandle(hProcess);
CloseHandle(hUserToken);
CloseHandle(hPToken);
return false;
}
if (bElevate)
{
//tp.Privileges[0].Luid = luid;
//tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
tp.PrivilegeCount = 1;
tp.Privileges = new int[3];
tp.Privileges[2] = SE_PRIVILEGE_ENABLED;
tp.Privileges[1] = luid.HighPart;
tp.Privileges[0] = luid.LowPart;
//Adjust Token privilege
if (!SetTokenInformation(hUserTokenDup, TOKEN_INFORMATION_CLASS.TokenSessionId, ref dwSessionId,
(uint)IntPtr.Size))
{
var hr = Marshal.GetLastWin32Error();
log.WriteMessage(
"CreateProcessInConsoleSession SetTokenInformation error: {0} Token does not have the privilege.", hr);
//CloseHandle(hProcess);
//CloseHandle(hUserToken);
//CloseHandle(hPToken);
//CloseHandle(hUserTokenDup);
//return false;
}
if (!AdjustTokenPrivileges(hUserTokenDup, false, ref tp, Marshal.SizeOf(tp), /*(PTOKEN_PRIVILEGES)*/
IntPtr.Zero, IntPtr.Zero))
{
int nErr = Marshal.GetLastWin32Error();
if (nErr == ERROR_NOT_ALL_ASSIGNED)
{
log.WriteMessage(
"CreateProcessInConsoleSession AdjustTokenPrivileges error: {0} Token does not have the privilege.",
nErr);
}
else
{
log.WriteMessage(String.Format("CreateProcessInConsoleSession AdjustTokenPrivileges error: {0}", nErr));
}
}
}
uint dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
IntPtr pEnv = IntPtr.Zero;
if (CreateEnvironmentBlock(ref pEnv, hUserTokenDup, true))
{
dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
}
else
{
pEnv = IntPtr.Zero;
}
// Launch the process in the client's logon session.
bResult = CreateProcessAsUser(hUserTokenDup, // client's access token
null, // file to execute
commandLine, // command line
ref sa, // pointer to process SECURITY_ATTRIBUTES
ref sa, // pointer to thread SECURITY_ATTRIBUTES
false, // handles are not inheritable
(int)dwCreationFlags, // creation flags
pEnv, // pointer to new environment block
null, // name of current directory
ref si, // pointer to STARTUPINFO structure
out pi // receives information about new process
);
// End impersonation of client.
//GetLastError should be 0
int iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
//Close handles task
CloseHandle(hProcess);
CloseHandle(hUserToken);
CloseHandle(hUserTokenDup);
CloseHandle(hPToken);
return (iResultOfCreateProcessAsUser == 0) ? true : false;
}
public static bool TerminateProcessInUserSession(ServiceLog log, String processName, bool bElevate)
{
bool bResult = false;
uint dwSessionId = 0, winlogonPid = 0;
IntPtr hProcess = IntPtr.Zero;
// Log the client on to the local computer.
dwSessionId = WTSGetActiveConsoleSessionId();
IntPtr phToken = IntPtr.Zero;
if (!WTSQueryUserToken(dwSessionId, out phToken))
{
var hr = Marshal.GetLastWin32Error();
log.WriteMessage(String.Format("WTSQueryUserToken error: {0}", hr));
}
// Find the winlogon process
var procEntry = new PROCESSENTRY32();
uint hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE)
{
return false;
}
procEntry.dwSize = (uint)Marshal.SizeOf(procEntry); //sizeof(PROCESSENTRY32);
if (Process32First(hSnap, ref procEntry) == 0)
{
return false;
}
do
{
string filename = System.IO.Path.GetFileName(procEntry.szExeFile);
if (string.Compare(filename, processName, StringComparison.OrdinalIgnoreCase) == 0)
{
// We found a winlogon process...make sure it's running in the console session
uint winlogonSessId = 0;
if (ProcessIdToSessionId(procEntry.th32ProcessID, out winlogonSessId) &&
winlogonSessId == dwSessionId)
{
winlogonPid = procEntry.th32ProcessID;
break;
}
else
{
var hr = Marshal.GetLastWin32Error();
log.WriteMessage(String.Format("ProcessIdToSessionId error: {0}", hr));
}
}
}
while (Process32Next(hSnap, ref procEntry) != 0);
if (winlogonPid == 0)
{
// not found
return false;
}
hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);
if (!TerminateProcess(hProcess, 1))
{
int nErr = Marshal.GetLastWin32Error();
log.WriteMessage(String.Format("TerminateProcess error: {0}", nErr));
bResult = false;
}
else
{
bResult = true;
}
//Close handles task
CloseHandle(hProcess);
return bResult;
}
#region Native Methods
[DllImport("Shell32.dll", EntryPoint = "ShellExecuteW",
SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern int ShellExecute(IntPtr handle, string verb, string file, string args, string dir, int show);
public enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum
}
public const int READ_CONTROL = 0x00020000;
public const int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
public const int STANDARD_RIGHTS_READ = READ_CONTROL;
public const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
public const int STANDARD_RIGHTS_EXECUTE = READ_CONTROL;
public const int STANDARD_RIGHTS_ALL = 0x001F0000;
public const int SPECIFIC_RIGHTS_ALL = 0x0000FFFF;
public const int TOKEN_ASSIGN_PRIMARY = 0x0001;
public const int TOKEN_DUPLICATE = 0x0002;
public const int TOKEN_IMPERSONATE = 0x0004;
public const int TOKEN_QUERY = 0x0008;
public const int TOKEN_QUERY_SOURCE = 0x0010;
public const int TOKEN_ADJUST_PRIVILEGES = 0x0020;
public const int TOKEN_ADJUST_GROUPS = 0x0040;
public const int TOKEN_ADJUST_DEFAULT = 0x0080;
public const int TOKEN_ADJUST_SESSIONID = 0x0100;
public const int TOKEN_ALL_ACCESS_P = (STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT);
public const int TOKEN_ALL_ACCESS = TOKEN_ALL_ACCESS_P | TOKEN_ADJUST_SESSIONID;
public const int TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY;
public const int TOKEN_WRITE = STANDARD_RIGHTS_WRITE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT;
public const int TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE;
public const uint MAXIMUM_ALLOWED = 0x2000000;
public const int CREATE_NEW_PROCESS_GROUP = 0x00000200;
public const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
public const int IDLE_PRIORITY_CLASS = 0x40;
public const int NORMAL_PRIORITY_CLASS = 0x20;
public const int HIGH_PRIORITY_CLASS = 0x80;
public const int REALTIME_PRIORITY_CLASS = 0x100;
public const int CREATE_NEW_CONSOLE = 0x00000010;
public const string SE_TCB_NAME = "SeTcbPrivilege";
public const string SE_DEBUG_NAME = "SeDebugPrivilege";
public const string SE_RESTORE_NAME = "SeRestorePrivilege";
public const string SE_BACKUP_NAME = "SeBackupPrivilege";
public const int SE_PRIVILEGE_ENABLED = 0x0002;
public const int ERROR_NOT_ALL_ASSIGNED = 1300;
private const uint TH32CS_SNAPPROCESS = 0x00000002;
public static int INVALID_HANDLE_VALUE = -1;
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LookupPrivilegeValue(IntPtr lpSystemName, string lpname,
[MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid);
[DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
public static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", EntryPoint = "CreateProcessWithLogon", SetLastError = true, CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
public static extern bool CreateProcessWithLogon(string lpUsername, string lpDomain, string lpPassword, int dwLogonFlags,
String lpApplicationName, String lpCommandLine, int dwCreationFlags, IntPtr lpEnvironment,
String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
[DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
public static extern bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,
ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType,
int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges,
ref TOKEN_PRIVILEGES NewState, int BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool SetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass,
ref uint TokenInformation, uint TokenInformationLength);
[DllImport("userenv.dll", SetLastError = true)]
public static extern bool CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, bool bInherit);
[DllImport("kernel32.dll")]
private static extern int Process32First(uint hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll")]
private static extern int Process32Next(uint hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hSnapshot);
[DllImport("kernel32.dll")]
private static extern uint WTSGetActiveConsoleSessionId();
[DllImport("Wtsapi32.dll")]
private static extern bool WTSQueryUserToken(uint SessionId, out IntPtr phToken);
[DllImport("kernel32.dll")]
private static extern bool ProcessIdToSessionId(uint dwProcessId, out uint pSessionId);
[DllImport("kernel32.dll")]
private static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
[DllImport("advapi32", SetLastError = true)]
[SuppressUnmanagedCodeSecurity]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle);
[DllImport("kernel32.dll")]
private static extern bool TerminateProcess(IntPtr hProcess, uint exitCode);
#region Nested type: LUID
[StructLayout(LayoutKind.Sequential)]
internal struct LUID
{
public int LowPart;
public int HighPart;
}
#endregion
//end struct
#region Nested type: LUID_AND_ATRIBUTES
[StructLayout(LayoutKind.Sequential)]
internal struct LUID_AND_ATRIBUTES
{
public LUID Luid;
public int Attributes;
}
#endregion
#region Nested type: PROCESSENTRY32
[StructLayout(LayoutKind.Sequential)]
private struct PROCESSENTRY32
{
public uint dwSize;
public readonly uint cntUsage;
public readonly uint th32ProcessID;
public readonly IntPtr th32DefaultHeapID;
public readonly uint th32ModuleID;
public readonly uint cntThreads;
public readonly uint th32ParentProcessID;
public readonly int pcPriClassBase;
public readonly uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public readonly string szExeFile;
}
#endregion
#region Nested type: PROCESS_INFORMATION
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
#endregion
#region Nested type: SECURITY_ATTRIBUTES
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
#endregion
#region Nested type: SECURITY_IMPERSONATION_LEVEL
private enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous = 0,
SecurityIdentification = 1,
SecurityImpersonation = 2,
SecurityDelegation = 3,
}
#endregion
#region Nested type: STARTUPINFO
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public int cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
#endregion
#region Nested type: TOKEN_PRIVILEGES
[StructLayout(LayoutKind.Sequential)]
internal struct TOKEN_PRIVILEGES
{
internal int PrivilegeCount;
//LUID_AND_ATRIBUTES
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
internal int[] Privileges;
}
#endregion
#region Nested type: TOKEN_TYPE
private enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation = 2
}
#endregion
#endregion
// handle to open access token
}
}
| 38.57645 | 133 | 0.586515 | [
"MIT"
] | microsoft/ada | AdaKioskService/ApplicationLauncher.cs | 21,952 | C# |
using System;
using System.Threading;
using Xamarin.Forms;
namespace TruthOrDareUI
{
/// <summary>
/// A class that is used for timers.
/// </summary>
public class CustomTimer
{
private readonly TimeSpan _timeSpan;
private readonly Action _action;
private CancellationTokenSource _cancellation = new CancellationTokenSource();
/// <summary>
/// Creates a new instance of a timer.
/// </summary>
/// <param name="interval">The interval of the timer</param>
/// <param name="action">The action to invoke everytime the timer elapses.</param>
public CustomTimer(Action action)
{
_timeSpan = TimeSpan.FromMilliseconds(1000);
_action = action;
}
/// <summary>
/// Starts the timer.
/// </summary>
public void Start()
{
CancellationTokenSource cts = _cancellation;
Device.StartTimer(_timeSpan, () =>
{
if (cts.IsCancellationRequested)
{
return false;
}
_action.Invoke();
return true;
});
}
/// <summary>
/// Stops the timer
/// </summary>
public void Stop()
{
Interlocked.Exchange(ref _cancellation, new CancellationTokenSource()).Cancel();
}
}
} | 26.62963 | 92 | 0.529207 | [
"MIT"
] | reiniellematt/TruthOrDare | TruthOrDareUI/TruthOrDareUI/CustomTimer.cs | 1,440 | C# |
//-----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//-----------------------------------------------------------------------
using System.Collections.Generic;
using System.Runtime.Serialization;
using HR.TA.Common.TalentEntities.Common;
using Newtonsoft.Json;
namespace HR.TA.Talent.TalentContracts.TalentMatch
{
/// <summary>
/// Job Match
/// </summary>
[DataContract]
public class JobMatch
{
/// <summary>Gets or sets Job opening id.</summary>
[DataMember(Name = "jobOpeningId", EmitDefaultValue = false, IsRequired = true)]
public string JobOpeningId { get; set; }
/// <summary>Gets or sets external job opening id.</summary>
[DataMember(Name = "externalJobOpeningId", EmitDefaultValue = false, IsRequired = true)]
public string ExternalJobOpeningId { get; set; }
/// <summary>Gets or sets job opening description.</summary>
[DataMember(Name = "description", EmitDefaultValue = false, IsRequired = false)]
public string Description { get; set; }
/// <summary>Gets or sets job opening Location.</summary>
[DataMember(Name = "jobLocation", EmitDefaultValue = false, IsRequired = false)]
public Address JobLocation { get; set; }
/// <summary>Gets or sets job opening Title.</summary>
[DataMember(Name = "jobTitle", EmitDefaultValue = false, IsRequired = false)]
public string JobTitle { get; set; }
/// <summary>
/// Gets or sets JobOpeningProperties
/// </summary>
[DataMember(Name = "jobOpeningProperties", EmitDefaultValue = false, IsRequired = false)]
public JobOpeningProperties JobOpeningProperties { get; set; }
/// <summary>
/// Gets or sets Job Opening
/// </summary>
[DataMember(Name = "computeResult", EmitDefaultValue = false, IsRequired = false)]
public List<JobSkill> ComputeResult { get; set; }
/// <summary>
/// Gets or sets score
/// </summary>
[DataMember(Name = "score", EmitDefaultValue = false, IsRequired = true)]
public double Score { get; set; }
}
}
| 38.810345 | 97 | 0.596624 | [
"MIT"
] | QPC-database/msrecruit-scheduling-engine | common/HR.TA.CommonLibrary/HR.TA.Talent/TalentContracts/TalentMatch/JobMatch.cs | 2,253 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LNF.PhysicalAccess
{
public enum zStatus
{
Unknown = 0,
Active = 1,
Disabled = 2,
Lost = 3,
Stolen = 4,
Terminated = 5,
Unaccounted = 6,
Void = 7,
Expired = 8,
AutoDisable = 9
}
}
| 16.818182 | 33 | 0.532432 | [
"MIT"
] | lurienanofab/lnf | LNF/PhysicalAccess/Status.cs | 372 | C# |
using System;
namespace Tfvc2Git.Core.Models.BranchIntegrity
{
[Serializable]
public enum FileIntegrityIssueType
{
MissingInTfvc,
MissingInGit,
ContentMismatch,
ShouldBeDeletedInGit
}
} | 18.076923 | 46 | 0.668085 | [
"MIT"
] | Fred-Jacobs/tfvc-2-git | src/Tfvc2Git.Core/Models/BranchIntegrity/FileIntegrityIssueType.cs | 237 | C# |
using System.IO;
using System.Linq;
using KeyValueStore.Cmd.Exceptions;
using KeyValueStore.Cmd.Interfaces;
namespace KeyValueStore.Cmd.Commands
{
public class GetCommand : ICommand
{
private readonly IDictionaryDeserializer _deserializer;
private readonly IConsole _console;
private readonly string _file;
private readonly string _key;
public GetCommand(IDictionaryDeserializer deserializer, IConsole console, string file, string[] remainingArgs)
{
_deserializer = deserializer;
_console = console;
_file = file;
if (!remainingArgs.Any())
{
throw new CommandParseException("Key not provided.");
}
_key = remainingArgs[0];
}
public void Execute()
{
using (var fs = new FileStream(_file, FileMode.Open))
{
_console.Write(_deserializer.GetSingleValue(fs, _key));
}
}
}
} | 27.486486 | 118 | 0.600787 | [
"MIT"
] | jimtonn/kv | src/KeyValueStore.Cmd/Commands/GetCommand.cs | 1,019 | C# |
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class Solution
{
// Complete the sockMerchant function below.
static int sockMerchant(int n, int[] ar)
{
var count = 0;
Dictionary<int, int> countNums = new Dictionary<int, int>();
foreach (var item in ar)
{
if (!countNums.ContainsKey(item))
{
countNums.Add(item, 1);
}
else
{
if(countNums[item]%2!=0)
{
count++;
countNums[item] = 0;
}
else
{
countNums[item]++;
}
}
}
return count ;
}
static void Main(string[] args)
{
//TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int n = Convert.ToInt32(Console.ReadLine());
int[] ar = Array.ConvertAll(Console.ReadLine().Split(' '), arTemp => Convert.ToInt32(arTemp))
;
int result = sockMerchant(n, ar);
Console.WriteLine(result);
//textWriter.Flush();
//textWriter.Close();
}
}
| 23.630769 | 116 | 0.552083 | [
"MIT"
] | tonchevaAleksandra/HackerRank-Problem-Solving | HackerRank/SalesByMatch/Program.cs | 1,538 | C# |
// <auto-generated />
using System;
using Aiursoft.Warpgate.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Aiursoft.Warpgate.Migrations
{
[DbContext(typeof(WarpgateDbContext))]
partial class WarpgateDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.6")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Aiursoft.Warpgate.SDK.Models.WarpRecord", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("AppId")
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("RecordUniqueName")
.HasColumnType("nvarchar(450)");
b.Property<string>("Tags")
.HasColumnType("nvarchar(max)");
b.Property<string>("TargetUrl")
.HasColumnType("nvarchar(max)");
b.Property<int>("Type")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AppId");
b.HasIndex("RecordUniqueName")
.IsUnique()
.HasFilter("[RecordUniqueName] IS NOT NULL");
b.ToTable("Records");
});
modelBuilder.Entity("Aiursoft.Warpgate.SDK.Models.WarpgateApp", b =>
{
b.Property<string>("AppId")
.HasColumnType("nvarchar(450)");
b.HasKey("AppId");
b.ToTable("WarpApps");
});
modelBuilder.Entity("Aiursoft.Warpgate.SDK.Models.WarpRecord", b =>
{
b.HasOne("Aiursoft.Warpgate.SDK.Models.WarpgateApp", "App")
.WithMany("WarpRecords")
.HasForeignKey("AppId");
b.Navigation("App");
});
modelBuilder.Entity("Aiursoft.Warpgate.SDK.Models.WarpgateApp", b =>
{
b.Navigation("WarpRecords");
});
#pragma warning restore 612, 618
}
}
}
| 34.863636 | 125 | 0.519883 | [
"MIT"
] | AiursoftWeb/Infrastructures | src/WebServices/Infrastructure/Warpgate/Migrations/WarpgateDbContextModelSnapshot.cs | 3,070 | 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 pinpoint-2016-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Pinpoint.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Pinpoint.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpdateApnsChannel Request Marshaller
/// </summary>
public class UpdateApnsChannelRequestMarshaller : IMarshaller<IRequest, UpdateApnsChannelRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((UpdateApnsChannelRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(UpdateApnsChannelRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Pinpoint");
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.HttpMethod = "PUT";
string uriResourcePath = "/v1/apps/{application-id}/channels/apns";
if (!publicRequest.IsSetApplicationId())
throw new AmazonPinpointException("Request object does not have required field ApplicationId set");
uriResourcePath = uriResourcePath.Replace("{application-id}", StringUtils.FromStringWithSlashEncoding(publicRequest.ApplicationId));
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
var marshaller = APNSChannelRequestMarshaller.Instance;
marshaller.Marshall(publicRequest.APNSChannelRequest, context);
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static UpdateApnsChannelRequestMarshaller _instance = new UpdateApnsChannelRequestMarshaller();
internal static UpdateApnsChannelRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static UpdateApnsChannelRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.156863 | 149 | 0.655145 | [
"Apache-2.0"
] | DalavanCloud/aws-sdk-net | sdk/src/Services/Pinpoint/Generated/Model/Internal/MarshallTransformations/UpdateApnsChannelRequestMarshaller.cs | 3,790 | C# |
/*************************************************************************************
Extended WPF Toolkit
Copyright (C) 2007-2013 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
For more features, controls, and fast professional support,
pick up the Plus Edition at http://xceed.com/wpf_toolkit
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
***********************************************************************************/
using System;
namespace Xceed.Wpf.DataGrid.Stats
{
internal class StatResult
{
public StatResult( object value )
{
m_value = value;
}
private object m_value;
public object Value
{
get
{
return m_value;
}
}
}
}
| 22.794872 | 87 | 0.542182 | [
"MIT"
] | DavosLi0bnip/daranguizu | Others/Xceed.Wpf/Xceed.Wpf.DataGrid/Stats/StatResult.cs | 891 | C# |
#region using statements
using SolutionShipper.Objects;
using System;
using System.Collections.Generic;
using XmlMirror.Runtime.Objects;
using XmlMirror.Runtime.Util;
using DataJuggler.Core.UltimateHelper;
#endregion
namespace SolutionShipper.Parsers
{
#region class ShipmentParser : ParserBaseClass
/// <summary>
/// This class is used to parse 'Shipment' objects.
/// </summary>
public partial class ShipmentParser : ParserBaseClass
{
#region Private Variables
private string selectedShipmentPath;
#endregion
#region Constructor(string selectedShipmentFolder)
/// <summary>
/// Create a new instance of a ShipmentParser
/// </summary>
/// <param name="selectedShipmentPath"></param>
public ShipmentParser(string selectedShipmentPath)
{
// Store the argument
this.SelectedShipmentPath = selectedShipmentPath;
}
#endregion
#region Events
#region Parsing(XmlNode xmlNode)
/// <summary>
/// This event is fired BEFORE the collection is initialized.
/// An example of this is the shipments (plural) node.
/// </summary>
/// <param name="xmlNode"></param>
/// <returns>True if cancelled else false if not.</returns>
public bool Parsing(XmlNode xmlNode)
{
// initial value
bool cancel = false;
// Add any pre processing code here. Set cancel to true to abort parsing this collection.
// return value
return cancel;
}
#endregion
#region Parsing(XmlNode xmlNode, ref Shipment shipment)
/// <summary>
/// This event is fired when a single object is initialized.
/// An example of this is the shipment (singlular) node.
/// </summary>
/// <param name="xmlNode"></param>
/// <param name="shipment"></param>
/// <returns>True if cancelled else false if not.</returns>
public bool Parsing(XmlNode xmlNode, ref Shipment shipment)
{
// initial value
bool cancel = false;
// Add any pre processing code here. Set cancel to true to abort adding this object.
// return value
return cancel;
}
#endregion
#region Parsed(XmlNode xmlNode, ref Shipment shipment)
/// <summary>
/// This event is fired AFTER the shipment is parsed.
/// </summary>
/// <param name="xmlNode"></param>
/// <param name="shipment"></param>
/// <returns>True if cancelled else false if not.</returns>
public bool Parsed(XmlNode xmlNode, ref Shipment shipment)
{
// initial value
bool cancel = false;
// If the shipment object exists
if (NullHelper.Exists(shipment))
{
// Create a new instance of an 'OptionsParser' object.
OptionsParser parser = new OptionsParser();
// get a copy of the options
Options options = shipment.Options;
// parse the options
parser.ParseOptions(ref options, xmlNode);
// Raise the Parsed event so the Folders get loaded
parser.Parsed(xmlNode, ref options);
}
// return value
return cancel;
}
#endregion
#endregion
#region Properties
#region HasSelectedShipmentPath
/// <summary>
/// This property returns true if the 'SelectedShipmentPath' exists.
/// </summary>
public bool HasSelectedShipmentPath
{
get
{
// initial value
bool hasSelectedShipmentPath = (!String.IsNullOrEmpty(this.SelectedShipmentPath));
// return value
return hasSelectedShipmentPath;
}
}
#endregion
#region SelectedShipmentPath
/// <summary>
/// This property gets or sets the value for 'SelectedShipmentPath'.
/// </summary>
public string SelectedShipmentPath
{
get { return selectedShipmentPath; }
set { selectedShipmentPath = value; }
}
#endregion
#endregion
}
#endregion
}
| 31.519737 | 105 | 0.52536 | [
"MIT"
] | DataJuggler/SolutionShipper | SolutionShipper/Parsers/ShipmentParser.custom.cs | 4,791 | C# |
using System.ComponentModel;
namespace MockHttp.Language.Flow;
[EditorBrowsable(EditorBrowsableState.Never)]
internal sealed class FallbackRequestSetupPhrase : SetupPhrase<IResponseResult, IThrowsResult>, IRespondsThrows, IFluentInterface
{
public FallbackRequestSetupPhrase(HttpCall setup)
: base(setup)
{
}
}
| 25.692308 | 129 | 0.787425 | [
"Apache-2.0"
] | swoog/MockHttp | src/MockHttp/Language/Flow/FallbackRequestSetupPhrase.cs | 336 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CPC.Model
{
using System;
using System.Collections.Generic;
public partial class CPCUnsortedCash
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public CPCUnsortedCash()
{
this.CPCUnsortedCashDetails = new HashSet<CPCUnsortedCashDetail>();
}
public System.Guid Id { get; set; }
public long SerialNumber { get; set; }
public System.DateTime Date { get; set; }
public string Station { get; set; }
public System.Guid ProjectBranchId { get; set; }
public Nullable<int> TotalNumberBundles { get; set; }
public long TotalBalance { get; set; }
public System.DateTime CreatedOn { get; set; }
public System.Guid CreatedBy { get; set; }
public Nullable<System.DateTime> UpdatedOn { get; set; }
public Nullable<System.Guid> UpdatedBy { get; set; }
public Nullable<byte> Status { get; set; }
public bool IsActive { get; set; }
public virtual CPCProjectBranch CPCProjectBranch { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CPCUnsortedCashDetail> CPCUnsortedCashDetails { get; set; }
}
}
| 42.880952 | 128 | 0.610217 | [
"MIT"
] | sherikhanx/CPCApp | CPC/Model/CPCUnsortedCash.cs | 1,801 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.DotNet.UpgradeAssistant
{
public interface ITargetFrameworkMonikerComparer : IComparer<TargetFrameworkMoniker>
{
/// <summary>
/// Returns true if another tfm is compatible with a first tfm. For example, IsCompatible(net45, net40) should return true because
/// net40-targeted dependencies are compatibile with net45.
/// </summary>
/// <param name="tfm">The TFM of the dependent project.</param>
/// <param name="other">The TFM of the dependency.</param>
/// <returns>True if the dependency is compatible with the dependent TFM, false otherwise.</returns>
bool IsCompatible(TargetFrameworkMoniker tfm, TargetFrameworkMoniker other);
/// <summary>
/// Merges two TFMs, while accounting for platforms and version, to a single version that can be targeted by both.
/// </summary>
/// <param name="tfm1">The first TFM.</param>
/// <param name="tfm2">The second TFM.</param>
/// <param name="result">A merged TFM. For example, passing <c>net5.0-windows</c> and <c>net6.0</c> will result in <c>net6.0-windows</c>.</param>
/// <returns>Whether the merge was successful.</returns>
bool TryMerge(TargetFrameworkMoniker tfm1, TargetFrameworkMoniker tfm2, [MaybeNullWhen(false)] out TargetFrameworkMoniker result);
bool TryParse(string input, [MaybeNullWhen(false)] out TargetFrameworkMoniker tfm);
}
}
| 52.375 | 153 | 0.693914 | [
"MIT"
] | IEvangelist/upgrade-assistant | src/common/Microsoft.DotNet.UpgradeAssistant.Abstractions/ITargetFrameworkMonikerComparer.cs | 1,678 | C# |
using DGP.Genshin.Common.Core.DependencyInjection;
using DGP.Genshin.Common.Exceptions;
using DGP.Genshin.Messages;
using DGP.Genshin.MiHoYoAPI.Calculation;
using DGP.Genshin.MiHoYoAPI.GameRole;
using DGP.Genshin.Services.Abstratcions;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using Microsoft.Toolkit.Mvvm.Messaging;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
namespace DGP.Genshin.ViewModels
{
[ViewModel(ViewModelType.Transient)]
public class PromotionCalculateViewModel : ObservableRecipient, IRecipient<CookieChangedMessage>
{
private readonly ICookieService cookieService;
private Calculator calculator;
private UserGameRoleProvider userGameRoleProvider;
private IEnumerable<UserGameRole>? userGameRoles;
private UserGameRole? selectedUserGameRole;
private IEnumerable<Avatar>? avatars;
private Avatar? selectedAvatar;
private AvatarDetailData? avatarDetailData;
private Consumption? consumption = new();
private IAsyncRelayCommand openUICommand;
private IAsyncRelayCommand computeCommand;
public IEnumerable<UserGameRole>? UserGameRoles
{
get => userGameRoles;
set => SetProperty(ref userGameRoles, value);
}
public UserGameRole? SelectedUserGameRole
{
get => selectedUserGameRole;
set
{
SetProperty(ref selectedUserGameRole, value);
UpdateAvatarListAsync();
}
}
private async void UpdateAvatarListAsync()
{
if (SelectedUserGameRole is not null)
{
string uid = SelectedUserGameRole.GameUid ?? throw new UnexceptedNullException("uid 不应为 null");
string region = SelectedUserGameRole.Region ?? throw new UnexceptedNullException("region 不应为 null");
Avatars = await calculator.GetSyncedAvatarListAsync(new(uid, region), true);
SelectedAvatar = Avatars?.FirstOrDefault();
}
}
public IEnumerable<Avatar>? Avatars
{
get => avatars;
set => SetProperty(ref avatars, value);
}
public Avatar? SelectedAvatar
{
get => selectedAvatar;
set
{
SetProperty(ref selectedAvatar, value);
UpdateAvatarDetailDataAsync();
}
}
private async void UpdateAvatarDetailDataAsync()
{
if (SelectedUserGameRole is not null && SelectedAvatar is not null)
{
string uid = SelectedUserGameRole.GameUid ?? throw new UnexceptedNullException("uid 不应为 null");
string region = SelectedUserGameRole.Region ?? throw new UnexceptedNullException("region 不应为 null");
int avatarId = SelectedAvatar.Id;
AvatarDetailData = await calculator.GetSyncedAvatarDetailDataAsync(avatarId, uid, region);
}
if (SelectedAvatar is not null)
{
SelectedAvatar.LevelTarget = SelectedAvatar.MaxLevel;
AvatarDetailData?.SkillList?.ForEach(x => x.LevelTarget = x.MaxLevel);
if (AvatarDetailData?.Weapon is not null)
{
AvatarDetailData.Weapon.LevelTarget = AvatarDetailData.Weapon.MaxLevel;
}
AvatarDetailData?.ReliquaryList?.ForEach(x => x.LevelTarget = x.MaxLevel);
}
}
public AvatarDetailData? AvatarDetailData
{
get => avatarDetailData;
set => SetProperty(ref avatarDetailData, value);
}
public Consumption? Consumption
{
get => consumption;
set => SetProperty(ref consumption, value);
}
public IAsyncRelayCommand OpenUICommand
{
get => openUICommand;
[MemberNotNull(nameof(openUICommand))]
set => SetProperty(ref openUICommand, value);
}
public IAsyncRelayCommand ComputeCommand
{
get => computeCommand;
[MemberNotNull(nameof(computeCommand))]
set => SetProperty(ref computeCommand, value);
}
public PromotionCalculateViewModel(ICookieService cookieService, IMessenger messenger) : base(messenger)
{
this.cookieService = cookieService;
calculator = new(cookieService.CurrentCookie);
userGameRoleProvider = new(cookieService.CurrentCookie);
OpenUICommand = new AsyncRelayCommand(OpenUIAsync);
ComputeCommand = new AsyncRelayCommand(ComputeAsync);
IsActive = true;
}
~PromotionCalculateViewModel()
{
IsActive = false;
}
private async Task OpenUIAsync()
{
UserGameRoles = await userGameRoleProvider.GetUserGameRolesAsync();
SelectedUserGameRole = UserGameRoles?.FirstOrDefault();
}
private async Task ComputeAsync()
{
if (SelectedAvatar is not null)
{
if (AvatarDetailData != null)
{
AvatarPromotionDelta delta = new()
{
AvatarId = SelectedAvatar.Id,
AvatarLevelCurrent = SelectedAvatar.LevelCurrent,
AvatarLevelTarget = SelectedAvatar.LevelTarget,
SkillList = AvatarDetailData.SkillList?.Select(s => s.ToPromotionDelta()) ?? new List<PromotionDelta>(),
Weapon = AvatarDetailData.Weapon?.ToPromotionDelta(),
ReliquaryList = AvatarDetailData.ReliquaryList?.Select(r => r.ToPromotionDelta()) ?? new List<PromotionDelta>()
};
Consumption = await calculator.ComputeAsync(delta);
}
}
}
/// <summary>
/// Cookie 改变
/// </summary>
/// <param name="message"></param>
public async void Receive(CookieChangedMessage message)
{
calculator = new(cookieService.CurrentCookie);
userGameRoleProvider = new(cookieService.CurrentCookie);
UserGameRoles = await userGameRoleProvider.GetUserGameRolesAsync();
SelectedUserGameRole = UserGameRoles?.FirstOrDefault();
}
}
}
| 38.368421 | 135 | 0.604329 | [
"MIT"
] | bo6682/Snap.Genshin | DGP.Genshin/ViewModels/PromotionCalculateViewModel.cs | 6,591 | C# |
namespace Storyteller.Model
{
public enum Lifecycle
{
Acceptance,
Regression,
Any
}
} | 13.444444 | 27 | 0.553719 | [
"MIT"
] | storyteller/StorytellerVNext | csharp/Storyteller/Model/Lifecycle.cs | 121 | C# |
namespace Authentication.Data.Classes
{
public class VendorMaster
{
}
}
| 12.142857 | 38 | 0.670588 | [
"MIT"
] | CatalinCaldararu/Blazor-Real-Estate-Project-Management | Data/Classes/VendorMaster.cs | 87 | C# |
namespace MassTransit.Testing
{
using System;
using Courier;
using Courier.Factories;
public static class ActivityTestHarnessExtensions
{
/// <summary>
/// Creates an activity test harness
/// </summary>
/// <typeparam name="TActivity"></typeparam>
/// <typeparam name="TArguments"></typeparam>
/// <typeparam name="TLog"></typeparam>
/// <param name="harness"></param>
/// <returns></returns>
public static ActivityTestHarness<TActivity, TArguments, TLog> Activity<TActivity, TArguments, TLog>(this BusTestHarness harness)
where TActivity : class, IActivity<TArguments, TLog>, new()
where TArguments : class
where TLog : class
{
var activityFactory = new FactoryMethodActivityFactory<TActivity, TArguments, TLog>(x => new TActivity(), x => new TActivity());
return new ActivityTestHarness<TActivity, TArguments, TLog>(harness, activityFactory, x =>
{
}, x =>
{
});
}
/// <summary>
/// Creates an activity test harness
/// </summary>
/// <typeparam name="TActivity"></typeparam>
/// <typeparam name="TArguments"></typeparam>
/// <typeparam name="TLog"></typeparam>
/// <param name="harness"></param>
/// <param name="executeFactoryMethod"></param>
/// <param name="compensateFactoryMethod"></param>
/// <returns></returns>
public static ActivityTestHarness<TActivity, TArguments, TLog> Activity<TActivity, TArguments, TLog>(this BusTestHarness harness,
Func<TArguments, TActivity> executeFactoryMethod, Func<TLog, TActivity> compensateFactoryMethod)
where TActivity : class, IActivity<TArguments, TLog>
where TArguments : class
where TLog : class
{
var activityFactory = new FactoryMethodActivityFactory<TActivity, TArguments, TLog>(executeFactoryMethod, compensateFactoryMethod);
return new ActivityTestHarness<TActivity, TArguments, TLog>(harness, activityFactory, x =>
{
}, x =>
{
});
}
/// <summary>
/// Creates an execute-only activity test harness
/// </summary>
/// <typeparam name="TActivity"></typeparam>
/// <typeparam name="TArguments"></typeparam>
/// <param name="harness"></param>
/// <returns></returns>
public static ExecuteActivityTestHarness<TActivity, TArguments> ExecuteActivity<TActivity, TArguments>(this BusTestHarness harness)
where TActivity : class, IExecuteActivity<TArguments>, new()
where TArguments : class
{
var activityFactory = new FactoryMethodExecuteActivityFactory<TActivity, TArguments>(x => new TActivity());
return new ExecuteActivityTestHarness<TActivity, TArguments>(harness, activityFactory, x =>
{
});
}
/// <summary>
/// Creates an execute-only activity test harness
/// </summary>
/// <typeparam name="TActivity"></typeparam>
/// <typeparam name="TArguments"></typeparam>
/// <param name="harness"></param>
/// <param name="executeFactoryMethod"></param>
/// <returns></returns>
public static ExecuteActivityTestHarness<TActivity, TArguments> ExecuteActivity<TActivity, TArguments>(this BusTestHarness harness,
Func<TArguments, TActivity> executeFactoryMethod)
where TActivity : class, IExecuteActivity<TArguments>
where TArguments : class
{
var activityFactory = new FactoryMethodExecuteActivityFactory<TActivity, TArguments>(executeFactoryMethod);
return new ExecuteActivityTestHarness<TActivity, TArguments>(harness, activityFactory, x =>
{
});
}
}
}
| 42.40625 | 144 | 0.59494 | [
"ECL-2.0",
"Apache-2.0"
] | Aerodynamite/MassTrans | src/MassTransit/Testing/ActivityTestHarnessExtensions.cs | 4,071 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Urho;
using Urho.Gui;
using Urho.Urho2D;
namespace MHUrho.UserInterface.MouseKeyboard
{
public class CursorTooltips : IDisposable
{
GameUI uiCtl;
MHUrhoApp Game => MHUrhoApp.Instance;
protected UI UI => Game.UI;
protected Urho.Input Input => Game.Input;
readonly Texture2D images;
List<UIElement> elements = new List<UIElement>();
public CursorTooltips(Texture2D images, GameUI uiCtl)
{
this.images = images;
this.uiCtl = uiCtl;
}
public Text AddText()
{
var newElement = UI.Cursor.CreateText();
elements.Add(newElement);
return newElement;
}
public void AddImage(IntRect imageRect)
{
var newElement = UI.Cursor.CreateBorderImage();
newElement.Texture = images;
newElement.ImageRect = imageRect;
newElement.MinSize = new IntVector2(100, 100);
newElement.Position = new IntVector2(10, 50);
}
public void Clear()
{
foreach (var element in elements) {
element.Remove();
}
elements.Clear();
}
public void Dispose()
{
}
}
}
| 18.661017 | 55 | 0.690282 | [
"MIT"
] | MK4H/MHUrho | MHUrho/MHUrho/UserInterface/MouseKeyboard/CursorTooltips.cs | 1,103 | C# |
namespace OpenGLBindings
{
/// <summary>
/// Not used directly.
/// </summary>
public enum ArbInvalidateSubdata
{
}
} | 14.2 | 36 | 0.577465 | [
"MIT"
] | DeKaDeNcE/WoWDatabaseEditor | Rendering/OpenGLBindings/ArbInvalidateSubdata.cs | 142 | 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 sesv2-2019-09-27.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.SimpleEmailV2.Model
{
/// <summary>
/// An object that describes how email sent during the predictive inbox placement test
/// was handled by a certain email provider.
/// </summary>
public partial class IspPlacement
{
private string _ispName;
private PlacementStatistics _placementStatistics;
/// <summary>
/// Gets and sets the property IspName.
/// <para>
/// The name of the email provider that the inbox placement data applies to.
/// </para>
/// </summary>
public string IspName
{
get { return this._ispName; }
set { this._ispName = value; }
}
// Check to see if IspName property is set
internal bool IsSetIspName()
{
return this._ispName != null;
}
/// <summary>
/// Gets and sets the property PlacementStatistics.
/// <para>
/// An object that contains inbox placement metrics for a specific email provider.
/// </para>
/// </summary>
public PlacementStatistics PlacementStatistics
{
get { return this._placementStatistics; }
set { this._placementStatistics = value; }
}
// Check to see if PlacementStatistics property is set
internal bool IsSetPlacementStatistics()
{
return this._placementStatistics != null;
}
}
} | 31.519481 | 104 | 0.618459 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/SimpleEmailV2/Generated/Model/IspPlacement.cs | 2,427 | 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("Time+15")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Time+15")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("681ba17e-a681-4f01-863b-f7488a9265e5")]
// 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.486486 | 84 | 0.741889 | [
"MIT"
] | IvelinMarinov/SoftUni | 01. Programming Basics - Oct2016/3. Simple Conditions/14. Time+15/Properties/AssemblyInfo.cs | 1,390 | C# |
using System;
namespace KH2FM_Toolkit
{
internal class ConsoleProgress
{
private const int width = 80;
private ConsoleColor _ColorBack;
private ConsoleColor _ColorFore;
private int _ConsoleTop;
private double _Multiplier;
private long _Total;
public long Current
{
get;
private set;
}
public long Total
{
get
{
return this._Total;
}
set
{
if (value != this._Total)
{
this._Total = value;
this._Multiplier = 78.0 / (double)value;
if (value < this.Current)
{
this.Current = value;
}
}
}
}
public ConsoleColor Color
{
get
{
return this._ColorBack;
}
set
{
if (value != this._ColorBack)
{
this._ColorBack = value;
switch (this._ColorBack)
{
case ConsoleColor.Black:
case ConsoleColor.DarkBlue:
case ConsoleColor.DarkGreen:
case ConsoleColor.DarkCyan:
case ConsoleColor.DarkRed:
case ConsoleColor.DarkMagenta:
case ConsoleColor.DarkYellow:
case ConsoleColor.DarkGray:
case ConsoleColor.Blue:
this._ColorFore = ConsoleColor.White;
return;
}
this._ColorFore = ConsoleColor.Black;
}
}
}
public string Text
{
get;
set;
}
public ConsoleProgress(long total, string text = null, ConsoleColor color = ConsoleColor.Green, bool activate=true)
{
if(activate)
{
this.Color = color;
this.Text = text;
this.Total = total;
if (Console.CursorLeft > 0)
{
Console.WriteLine();
}
this._ConsoleTop = Console.CursorTop;
Console.WriteLine();
Console.CursorVisible = false;
}
}
~ConsoleProgress()
{
if (this.Current != this.Total)
{
this.Finish();
}
}
public void Increment(long value = 1L)
{
this.Update(this.Current + value);
}
public void ReDraw()
{
Tuple<int, int> tuple = new Tuple<int, int>(Console.CursorLeft, Console.CursorTop);
Console.SetCursorPosition(0, this._ConsoleTop);
Console.Write("[");
Console.BackgroundColor = this._ColorBack;
Console.ForegroundColor = this._ColorFore;
int i = 0;
int num = (int)(this._Multiplier * (double)this.Current);
while (i < 78)
{
if (i == num)
{
Console.ResetColor();
}
Console.Write((this.Text != null && i <= this.Text.Length && i != 0) ? this.Text[i - 1] : ' ');
i++;
}
Console.ResetColor();
Console.Write("]");
Console.SetCursorPosition(tuple.Item1, tuple.Item2);
}
public void Update(long current)
{
this.Current = ((current > this.Total) ? this.Total : current);
this.ReDraw();
}
public void Finish()
{
Console.CursorVisible = true;
this.Update(this.Total);
}
}
}
| 29.984733 | 123 | 0.426935 | [
"MIT"
] | GovanifY/KH2FM_Toolk | Shared/ConsoleProgress.cs | 3,930 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using Azure.Core;
using Azure.ResourceManager.Compute.Models;
namespace Azure.ResourceManager.Compute
{
/// <summary> A class representing the VirtualMachineScaleSetVmExtension data model. </summary>
public partial class VirtualMachineScaleSetVmExtensionData : ComputeSubResourceData
{
/// <summary> Initializes a new instance of VirtualMachineScaleSetVmExtensionData. </summary>
public VirtualMachineScaleSetVmExtensionData()
{
}
/// <summary> Initializes a new instance of VirtualMachineScaleSetVmExtensionData. </summary>
/// <param name="id"> Resource Id. </param>
/// <param name="name"> The name of the extension. </param>
/// <param name="resourceType"> Resource type. </param>
/// <param name="forceUpdateTag"> How the extension handler should be forced to update even if the extension configuration has not changed. </param>
/// <param name="publisher"> The name of the extension handler publisher. </param>
/// <param name="extensionType"> Specifies the type of the extension; an example is "CustomScriptExtension". </param>
/// <param name="typeHandlerVersion"> Specifies the version of the script handler. </param>
/// <param name="autoUpgradeMinorVersion"> Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. </param>
/// <param name="enableAutomaticUpgrade"> Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension available. </param>
/// <param name="settings"> Json formatted public settings for the extension. </param>
/// <param name="protectedSettings"> The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. </param>
/// <param name="provisioningState"> The provisioning state, which only appears in the response. </param>
/// <param name="instanceView"> The virtual machine extension instance view. </param>
/// <param name="suppressFailures"> Indicates whether failures stemming from the extension will be suppressed (Operational failures such as not connecting to the VM will not be suppressed regardless of this value). The default is false. </param>
/// <param name="protectedSettingsFromKeyVault"> The extensions protected settings that are passed by reference, and consumed from key vault. </param>
internal VirtualMachineScaleSetVmExtensionData(ResourceIdentifier id, string name, ResourceType? resourceType, string forceUpdateTag, string publisher, string extensionType, string typeHandlerVersion, bool? autoUpgradeMinorVersion, bool? enableAutomaticUpgrade, BinaryData settings, BinaryData protectedSettings, string provisioningState, VirtualMachineExtensionInstanceView instanceView, bool? suppressFailures, BinaryData protectedSettingsFromKeyVault) : base(id)
{
Name = name;
ResourceType = resourceType;
ForceUpdateTag = forceUpdateTag;
Publisher = publisher;
ExtensionType = extensionType;
TypeHandlerVersion = typeHandlerVersion;
AutoUpgradeMinorVersion = autoUpgradeMinorVersion;
EnableAutomaticUpgrade = enableAutomaticUpgrade;
Settings = settings;
ProtectedSettings = protectedSettings;
ProvisioningState = provisioningState;
InstanceView = instanceView;
SuppressFailures = suppressFailures;
ProtectedSettingsFromKeyVault = protectedSettingsFromKeyVault;
}
/// <summary> The name of the extension. </summary>
public string Name { get; }
/// <summary> Resource type. </summary>
public ResourceType? ResourceType { get; }
/// <summary> How the extension handler should be forced to update even if the extension configuration has not changed. </summary>
public string ForceUpdateTag { get; set; }
/// <summary> The name of the extension handler publisher. </summary>
public string Publisher { get; set; }
/// <summary> Specifies the type of the extension; an example is "CustomScriptExtension". </summary>
public string ExtensionType { get; set; }
/// <summary> Specifies the version of the script handler. </summary>
public string TypeHandlerVersion { get; set; }
/// <summary> Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. </summary>
public bool? AutoUpgradeMinorVersion { get; set; }
/// <summary> Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension available. </summary>
public bool? EnableAutomaticUpgrade { get; set; }
/// <summary> Json formatted public settings for the extension. </summary>
public BinaryData Settings { get; set; }
/// <summary> The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. </summary>
public BinaryData ProtectedSettings { get; set; }
/// <summary> The provisioning state, which only appears in the response. </summary>
public string ProvisioningState { get; }
/// <summary> The virtual machine extension instance view. </summary>
public VirtualMachineExtensionInstanceView InstanceView { get; set; }
/// <summary> Indicates whether failures stemming from the extension will be suppressed (Operational failures such as not connecting to the VM will not be suppressed regardless of this value). The default is false. </summary>
public bool? SuppressFailures { get; set; }
/// <summary> The extensions protected settings that are passed by reference, and consumed from key vault. </summary>
public BinaryData ProtectedSettingsFromKeyVault { get; set; }
}
}
| 74.697674 | 473 | 0.716843 | [
"MIT"
] | v-kaifazhang/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/VirtualMachineScaleSetVmExtensionData.cs | 6,424 | C# |
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Xuey.NET.Framework.Service
{
/// <summary>
/// 用户角色服务
/// </summary>
public class SysUserRoleService : ISysUserRoleService, ITransient
{
private readonly IRepository<SysUserRole> _sysUserRoleRep; // 用户权限表仓储
private readonly ISysRoleService _sysRoleService;
public SysUserRoleService(IRepository<SysUserRole> sysUserRoleRep, ISysRoleService sysRoleService)
{
_sysUserRoleRep = sysUserRoleRep;
_sysRoleService = sysRoleService;
}
/// <summary>
/// 获取用户的角色Id集合
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public async Task<List<long>> GetUserRoleIdList(long userId)
{
return await _sysUserRoleRep.DetachedEntities.Where(u => u.SysUserId == userId).Select(u => u.SysRoleId).ToListAsync();
}
/// <summary>
/// 授权用户角色
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[UnitOfWork]
public async Task GrantRole(UpdateUserRoleDataInput input)
{
var userRoles = await _sysUserRoleRep.Where(u => u.SysUserId == input.Id).ToListAsync();
await _sysUserRoleRep.DeleteAsync(userRoles);
var roles = input.GrantRoleIdList.Select(u => new SysUserRole
{
SysUserId = input.Id,
SysRoleId = u
}).ToList();
await _sysUserRoleRep.InsertAsync(roles);
}
/// <summary>
/// 获取用户所有角色的数据范围(组织机构Id集合)
/// </summary>
/// <param name="userId"></param>
/// <param name="orgId"></param>
/// <returns></returns>
public async Task<List<long>> GetUserRoleDataScopeIdList(long userId, long orgId)
{
var roleIdList = await GetUserRoleIdList(userId);
// 获取这些角色对应的数据范围
if (roleIdList.Count > 0)
return await _sysRoleService.GetUserDataScopeIdList(roleIdList, orgId);
return roleIdList;
}
/// <summary>
/// 根据角色Id删除对应的用户-角色表关联信息
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public async Task DeleteUserRoleListByRoleId(long roleId)
{
var userRoles = await _sysUserRoleRep.Where(u => u.SysRoleId == roleId).ToListAsync();
await _sysUserRoleRep.DeleteAsync(userRoles);
}
/// <summary>
/// 根据用户Id删除对应的用户-角色表关联信息
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public async Task DeleteUserRoleListByUserId(long userId)
{
var userRoles = await _sysUserRoleRep.Where(u => u.SysUserId == userId).ToListAsync();
await _sysUserRoleRep.DeleteAsync(userRoles);
}
}
} | 33.075269 | 131 | 0.589727 | [
"MIT"
] | xueynet/XYP | src/backend/Xuey.NET.Framework/Service/User/SysUserRoleService.cs | 3,274 | C# |
/*
* Copyright 2010-2013 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.
*/
using System.Collections.Generic;
using Amazon.ElasticLoadBalancing.Model;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.ElasticLoadBalancing.Model.Internal.MarshallTransformations
{
/// <summary>
/// PolicyTypeDescription Unmarshaller
/// </summary>
internal class PolicyTypeDescriptionUnmarshaller : IUnmarshaller<PolicyTypeDescription, XmlUnmarshallerContext>, IUnmarshaller<PolicyTypeDescription, JsonUnmarshallerContext>
{
public PolicyTypeDescription Unmarshall(XmlUnmarshallerContext context)
{
PolicyTypeDescription policyTypeDescription = new PolicyTypeDescription();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("PolicyTypeName", targetDepth))
{
policyTypeDescription.PolicyTypeName = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("Description", targetDepth))
{
policyTypeDescription.Description = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("PolicyAttributeTypeDescriptions/member", targetDepth))
{
policyTypeDescription.PolicyAttributeTypeDescriptions.Add(PolicyAttributeTypeDescriptionUnmarshaller.GetInstance().Unmarshall(context));
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return policyTypeDescription;
}
}
return policyTypeDescription;
}
public PolicyTypeDescription Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static PolicyTypeDescriptionUnmarshaller instance;
public static PolicyTypeDescriptionUnmarshaller GetInstance()
{
if (instance == null)
instance = new PolicyTypeDescriptionUnmarshaller();
return instance;
}
}
}
| 37.494253 | 179 | 0.594114 | [
"Apache-2.0"
] | zz0733/aws-sdk-net | AWSSDK_DotNet35/Amazon.ElasticLoadBalancing/Model/Internal/MarshallTransformations/PolicyTypeDescriptionUnmarshaller.cs | 3,262 | C# |
namespace App03
{
public class MyObj
{
public string Name { get; set; }
}
public class MyOptions
{
public string Option1 { get; set; }
public string[] Option2 { get; set; }
public MyObj[] MyObj { get; set; }
}
}
| 19.142857 | 45 | 0.537313 | [
"MIT"
] | bigfont/asp-net-5-beginner | App03Options/MyOptions.cs | 268 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Components.RadioButtons;
namespace osu.Game.Tests.Visual.Editor
{
[TestFixture]
public class TestCaseEditorComposeRadioButtons : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(DrawableRadioButton) };
public TestCaseEditorComposeRadioButtons()
{
RadioButtonCollection collection;
Add(collection = new RadioButtonCollection
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 150,
Items = new[]
{
new RadioButton("Item 1", () => { }),
new RadioButton("Item 2", () => { }),
new RadioButton("Item 3", () => { }),
new RadioButton("Item 4", () => { }),
new RadioButton("Item 5", () => { })
}
});
for (int i = 0; i < collection.Items.Count; i++)
{
int l = i;
AddStep($"Select item {l + 1}", () => collection.Items[l].Select());
AddStep($"Deselect item {l + 1}", () => collection.Items[l].Deselect());
}
}
}
}
| 35.090909 | 100 | 0.509067 | [
"MIT"
] | asd7766zxc/osu | osu.Game.Tests/Visual/Editor/TestCaseEditorComposeRadioButtons.cs | 1,501 | C# |
using System;
using System.Windows.Forms;
namespace CalculatorGUI
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
} | 23.789474 | 65 | 0.581858 | [
"MIT"
] | darksv/calc | Calculator.GUI/Program.cs | 454 | C# |
using System;
using Modular.NET.Core.Tests.TestMaterials.Enums;
using Xunit;
namespace Modular.NET.Core.Tests.Helpers
{
public class EnumHelperTests
{
#region Methods
[Fact]
public void EnumHelper_GetDictionary()
{
var dic = EnumHelper.GetDictionary<EnumGender>();
foreach (var each in Enum.GetValues(typeof(EnumGender)))
{
Assert.True(dic.ContainsKey((int) each));
Assert.Equal(dic[(int) each], each.ToString());
}
}
[Fact]
public void EnumHelper_GetDictionary_WithStructButNonEnum()
{
Assert.Throws<ArgumentException>(() =>
{
var dic = EnumHelper.GetDictionary<int>();
});
}
[Fact]
public void EnumHelper_GetDictionary_WithIgnore()
{
var dic = EnumHelper.GetDictionary(EnumGender.Male);
foreach (var each in Enum.GetValues(typeof(EnumGender)))
{
if ((EnumGender) each == EnumGender.Male)
{
continue;
}
Assert.True(dic.ContainsKey((int) each));
Assert.Equal(dic[(int) each], each.ToString());
}
}
[Fact]
public void EnumHelper_GetDictionary_WithIgnoreWithStructButNonEnum()
{
Assert.Throws<ArgumentException>(() =>
{
var dic = EnumHelper.GetDictionary(1);
});
}
[Fact]
public void EnumHelper_GetDictionaryInDescription()
{
var dic = EnumHelper.GetDictionaryInDescription<EnumGender>();
foreach (var each in Enum.GetValues(typeof(EnumGender)))
{
Assert.True(dic.ContainsKey((int) each));
Assert.Equal(dic[(int) each], ((Enum) each).GetDescription());
}
}
[Fact]
public void EnumHelper_GetDictionaryInDescription_WithStructButNonEnum()
{
Assert.Throws<ArgumentException>(() =>
{
var dic = EnumHelper.GetDictionaryInDescription<int>();
});
}
[Fact]
public void EnumHelper_GetDictionaryInDescription_WithIgnore()
{
var dic = EnumHelper.GetDictionaryInDescription(EnumGender.Male);
foreach (var each in Enum.GetValues(typeof(EnumGender)))
{
if ((EnumGender) each == EnumGender.Male)
{
continue;
}
Assert.True(dic.ContainsKey((int) each));
Assert.Equal(dic[(int) each], ((Enum) each).GetDescription());
}
}
[Fact]
public void EnumHelper_GetDictionaryInDescription_WithIgnoreWithStructButNonEnum()
{
Assert.Throws<ArgumentException>(() =>
{
var dic = EnumHelper.GetDictionaryInDescription(1);
});
}
[Fact]
public void EnumHelper_GetDictionaryInDisplayText()
{
var dic = EnumHelper.GetDictionaryInDisplayText<EnumGender>();
foreach (var each in Enum.GetValues(typeof(EnumGender)))
{
Assert.True(dic.ContainsKey((int) each));
Assert.Equal(dic[(int) each], ((Enum) each).GetDisplayText());
}
}
[Fact]
public void EnumHelper_GetDictionaryInDisplayText_WithStructButNonEnum()
{
Assert.Throws<ArgumentException>(() =>
{
var dic = EnumHelper.GetDictionaryInDisplayText<int>();
});
}
[Fact]
public void EnumHelper_GetDictionaryInDisplayText_WithIgnore()
{
var dic = EnumHelper.GetDictionaryInDisplayText(EnumGender.Male);
foreach (var each in Enum.GetValues(typeof(EnumGender)))
{
if ((EnumGender) each == EnumGender.Male)
{
continue;
}
Assert.True(dic.ContainsKey((int) each));
Assert.Equal(dic[(int) each], ((Enum) each).GetDisplayText());
}
}
[Fact]
public void EnumHelper_GetDictionaryInDisplayText_WithIgnoreWithStructButNonEnum()
{
Assert.Throws<ArgumentException>(() =>
{
var dic = EnumHelper.GetDictionaryInDisplayText(1);
});
}
#endregion
}
}
| 29.483871 | 90 | 0.528009 | [
"MIT"
] | modular-net/Modular.NET | test/Modular.NET.Core.Tests/Helpers/EnumHelperTests.cs | 4,572 | C# |
#region → Usings .
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Windows;
using citPOINT.eNeg.Common;
using citPOINT.eNeg.Data.Web;
using System.ServiceModel.DomainServices.Client;
#endregion
#region → History .
/* Date User Change
*
* 19.09.10 Yousra Reda Creation
*/
# endregion
#region → ToDos .
/*
* Date set by User Description
*
*
*/
# endregion
namespace citPOINT.eNeg.MVVM.Test
{
/// <summary>
/// Mock for Manage Users Model
/// </summary>
[Export(typeof(IUserBaseModel))]
public class MockManageUsers : IUserBaseModel
{
#region → Fields .
private eNegContext mContext;
private List<User> mUsers;
private eNegPaging mUserPager;
private bool mIsFilteredByAlphabet;
private string mFilterLetter;
private string mLastSelectedColumn;
private bool mIsFilteredByKey;
private string mFilterKeyWord;
private List<UserOrganization> mUserOrganizations;
#endregion Fields
#region → Properties .
/// <summary>
/// Gets or sets a value indicating whether this instance is for public profile.
/// this is the main key that sparate the manageUserViewmodel from PublicUserViewModel.
/// </summary>
/// <value>
/// <c>true</c> if this instance is for public profile; otherwise, <c>false</c>.
/// </value>
public bool IsForPublicProfile {get;set;}
/// <summary>
/// Gets the context.
/// </summary>
/// <value>The context.</value>
public eNegContext Context
{
get
{
if (mContext == null)
{
mContext = new eNegContext(new Uri("http://localhost:9000/citPOINT-eNeg-Data-Web-eNegService.svc", UriKind.Absolute));
}
return mContext;
}
}
/// <summary>
/// Gets a value indicating whether this instance has changes.
/// </summary>
/// <value>
/// <c>true</c> if this instance has changes; otherwise, <c>false</c>.
/// </value>
public bool HasChanges
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether this instance is busy.
/// </summary>
/// <value><c>true</c> if this instance is busy; otherwise, <c>false</c>.</value>
public bool IsBusy
{
get { return false; }
}
/// <summary>
/// Gets or sets the users.
/// </summary>
/// <value>The users.</value>
public List<User> Users
{
get
{
if (mUsers == null)
{
mUsers = new List<User>()
{
new User()
{
UserID = Guid.NewGuid(),
EmailAddress = "Test_Test@gmail.com",
Password = "123456A",
NewPassword = string.Empty,
PasswordConfirmation = "123456A",
Locked = false,
IPAddress = "10.0.02.2",
LastLoginDate = DateTime.Now,
CreateDate = DateTime.Now,
AnswerHash = string.Empty,
AnswerSalt = string.Empty,
Online = false,
Disabled = false,
FirstName = string.Empty,
LastName = string.Empty,
CompanyName = string.Empty,
Address = string.Empty,
City = string.Empty,
Phone = string.Empty,
Mobile = string.Empty,
Gender = false,
Reset = false
},
new User()
{
UserID = Guid.NewGuid(),
EmailAddress = "Test_Test2@gmail.com",
Password = "123456A",
NewPassword = string.Empty,
PasswordConfirmation = "123456A",
Locked = false,
IPAddress = "10.0.02.2",
LastLoginDate = DateTime.Now,
CreateDate = DateTime.Now,
AnswerHash = string.Empty,
AnswerSalt = string.Empty,
Online = false,
Disabled = false,
FirstName = string.Empty,
LastName = string.Empty,
CompanyName = string.Empty,
Address = string.Empty,
City = string.Empty,
Phone = string.Empty,
Mobile = string.Empty,
Gender = false,
Reset = false
},
new User()
{
UserID = Guid.NewGuid(),
EmailAddress = "Test_Test3@gmail.com",
Password = "123456A",
NewPassword = string.Empty,
PasswordConfirmation = "123456A",
Locked = false,
IPAddress = "10.0.02.2",
LastLoginDate = DateTime.Now,
CreateDate = DateTime.Now,
AnswerHash = string.Empty,
AnswerSalt = string.Empty,
Online = false,
Disabled = false,
FirstName = string.Empty,
LastName = string.Empty,
CompanyName = string.Empty,
Address = string.Empty,
City = string.Empty,
Phone = string.Empty,
Mobile = string.Empty,
Gender = false,
Reset = false
},
new User()
{
UserID = Guid.NewGuid(),
EmailAddress = "Test_Test4@gmail.com",
Password = "123456A",
NewPassword = string.Empty,
PasswordConfirmation = "123456A",
Locked = false,
IPAddress = "10.0.02.2",
LastLoginDate = DateTime.Now,
CreateDate = DateTime.Now,
AnswerHash = string.Empty,
AnswerSalt = string.Empty,
Online = false,
Disabled = false,
FirstName = string.Empty,
LastName = string.Empty,
CompanyName = string.Empty,
Address = string.Empty,
City = string.Empty,
Phone = string.Empty,
Mobile = string.Empty,
Gender = false,
Reset = false
}
};
}
return mUsers;
}
}
/// <summary>
/// Gets the organization source.
/// </summary>
/// <value>The organization source.</value>
public List<UserOrganization> UserOrganizations
{
get
{
if (mUserOrganizations == null)
{
mUserOrganizations = new List<UserOrganization>()
{
new UserOrganization ()
{
UserOrganizationID = Guid.NewGuid(),
UserID = this.mUsers[0].UserID,
OrganizationID = Guid.NewGuid(),
MemberStatus = 0,
Deleted = false,
DeletedBy = Guid.NewGuid(),
DeletedOn = DateTime.Now
},
new UserOrganization ()
{
UserOrganizationID = Guid.NewGuid(),
UserID = this.mUsers[1].UserID,
OrganizationID = Guid.NewGuid(),
MemberStatus = 3,
Deleted = false,
DeletedBy = Guid.NewGuid(),
DeletedOn = DateTime.Now
}
};
}
return mUserOrganizations;
}
}
/// <summary>
/// Gets the user page.
/// </summary>
/// <value>The user page.</value>
public eNegPaging UserPager
{
get
{
if (mUserPager == null)
{
mUserPager = new eNegPaging();
mUserPager.CurrentPageNumber = 1;
mUserPager.ItemsCount = Users.Count;
mUserPager.ItemsPagesCount = 3;
mUserPager.uxPagePanel = new System.Windows.Controls.StackPanel();
}
return mUserPager;
}
}
/// <summary>
/// Gets a value indicating whether this instance is filtered by alphabet.
/// </summary>
/// <value>
/// <c>true</c> if this instance is filtered by alphabet; otherwise, <c>false</c>.
/// </value>
public bool IsFilteredByAlphabet
{
get
{
return mIsFilteredByAlphabet;
}
set
{
mIsFilteredByAlphabet = value;
}
}
/// <summary>
/// Gets or sets the filter letter.
/// </summary>
/// <value>The filter letter.</value>
public string FilterLetter
{
get
{
return mFilterLetter;
}
set
{
mFilterLetter = value;
}
}
/// <summary>
/// Gets or sets the last selected column.
/// </summary>
/// <value>The last selected column.</value>
public string LastSelectedColumn
{
get
{
return mLastSelectedColumn;
}
set
{
mLastSelectedColumn = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this instance is filtered by key.
/// </summary>
/// <value>
/// <c>true</c> if this instance is filtered by key; otherwise, <c>false</c>.
/// </value>
public bool IsFilteredByKey
{
get
{
return mIsFilteredByKey;
}
set
{
mIsFilteredByKey = value;
}
}
/// <summary>
/// Gets or sets the filter key word.
/// </summary>
/// <value>The filter key word.</value>
public string FilterKeyWord
{
get
{
return mFilterKeyWord;
}
set
{
mFilterKeyWord = value;
}
}
#endregion
#region → Constructor .
/// <summary>
/// Initializes a new instance of the <see cref="MockManageUsers"/> class.
/// </summary>
public MockManageUsers()
{
AppConfigurations.CurrentLoginUser = new LoginUser();
}
#endregion
#region → Events .
/// <summary>
/// Occurs when [find user count complete].
/// </summary>
public event Action<InvokeOperation<int?>> FindUserCountComplete;
/// <summary>
/// Occurs when [get users by alphabet count complete].
/// </summary>
public event Action<InvokeOperation<int>> GetUsersCountByAlphabetComplete;
/// <summary>
/// Occurs when [get users count complete].
/// </summary>
public event Action<InvokeOperation<int>> GetUsersCountComplete;
/// <summary>
/// Occurs when [find user complete].
/// </summary>
public event EventHandler<eNegEntityResultArgs<Data.Web.User>> FindUsersComplete;
/// <summary>
/// Occurs when [get users by alphabet complete].
/// </summary>
public event EventHandler<eNegEntityResultArgs<Data.Web.User>> GetUsersByAlphabetComplete;
/// <summary>
/// Occurs when [get users complete].
/// </summary>
public event EventHandler<eNegEntityResultArgs<Data.Web.User>> GetUsersByPageNumberComplete;
/// <summary>
/// Call back of Geting user organizations for owners users.
/// </summary>
public event EventHandler<eNegEntityResultArgs<UserOrganization>> GetUserOrganizationsForOwnersUsersComplete;
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Occurs when [save changes complete].
/// </summary>
public event EventHandler<SubmitOperationEventArgs> SaveChangesComplete;
#endregion Events
#region → Methods .
#region → Public .
/// <summary>
/// Fins the users count async.
/// </summary>
/// <param name="KeyWord">The key word.</param>
/// <param name="UserID">The user ID.</param>
public void FinUsersCountAsync(string KeyWord, Guid UserID)
{
if (FindUserCountComplete != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
FindUserCountComplete(Context.FindUsersCount(KeyWord, UserID,IsForPublicProfile));
});
}
}
/// <summary>
/// Finds the users async.
/// </summary>
/// <param name="KeyWord">The key word.</param>
public void FindUsersAsync(string KeyWord)
{
if (FindUsersComplete != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
FindUsersComplete(this, new eNegEntityResultArgs<User>(this.Users.Where(s => s.EmailAddress.Contains(KeyWord))));
});
}
}
/// <summary>
/// Gets the user count async.
/// </summary>
public void GetUserCountAsync()
{
if (GetUsersCountComplete != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
GetUsersCountComplete(Context.GetUsersCountExceptCurrentUser(AppConfigurations.CurrentLoginUser.UserID, IsForPublicProfile));
});
}
}
/// <summary>
/// Gets the user by alphabet.
/// </summary>
/// <param name="Alphabet">The alphabet.</param>
/// <param name="ColumnName">Name of the column.</param>
public void GetUserByAlphabetAsync(string Alphabet, string ColumnName)
{
if (GetUsersByAlphabetComplete != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
GetUsersByAlphabetComplete(this, new eNegEntityResultArgs<User>(this.Users));
});
}
}
/// <summary>
/// Gets the users by page number async.
/// </summary>
/// <param name="PageNumber">The page number.</param>
public void GetUsersByPageNumberAsync(int PageNumber)
{
if (GetUsersByPageNumberComplete != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
GetUsersByPageNumberComplete(this, new eNegEntityResultArgs<User>(this.Users));
});
}
}
/// <summary>
/// Gets the user organizations for owners users.
/// </summary>
/// <param name="usersIDs">The users Ids.</param>
public void GetUserOrganizationsForOwnersUsers(List<Guid> usersIDs)
{
GetUserOrganizationsForOwnersUsersComplete(this, new eNegEntityResultArgs<UserOrganization>(this.UserOrganizations));
}
/// <summary>
/// Rejects the changes.
/// </summary>
public void RejectChanges()
{
}
/// <summary>
/// Removes the user.
/// </summary>
/// <param name="user">The user.</param>
public void RemoveUser(User user)
{
this.Users.Remove(user);
}
/// <summary>
/// Save Complete
/// </summary>
public void SaveChangesAsync()
{
if (SaveChangesComplete != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
SaveChangesComplete(this, new SubmitOperationEventArgs(null, null));
});
}
}
/// <summary>
/// Gets the user count by alphabet async.
/// </summary>
/// <param name="Alphabet">The alphabet.</param>
/// <param name="ColumnName">Name of the column.</param>
/// <param name="UserID">The user ID.</param>
public void GetUserCountByAlphabetAsync(string Alphabet, string ColumnName, Guid UserID)
{
if (GetUsersCountByAlphabetComplete != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
GetUsersCountByAlphabetComplete(Context.GetUsersCountByAlphabetExceptCurrentUser(Alphabet, ColumnName, UserID, IsForPublicProfile));
});
}
}
/// <summary>
/// Refreshes the updated user.
/// </summary>
/// <param name="UserID">The user ID.</param>
public void RefreshUpdatedUser(Guid UserID)
{
}
#endregion Methods
#endregion Public
public void CleanUp()
{
throw new NotImplementedException();
}
}
}
| 33.575296 | 152 | 0.439198 | [
"MIT"
] | ivconsult/eNeg | citPOINT.eNeg.Client.Tests/MockManageUsers.cs | 19,863 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Securities;
namespace QuantConnect.Orders.Fees
{
/// <summary>
/// Provides an implementation of <see cref="FeeModel"/> that models FXCM order fees
/// </summary>
public class FxcmFeeModel : FeeModel
{
private readonly HashSet<Symbol> _groupCommissionSchedule1 = new HashSet<Symbol>
{
Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM),
Symbol.Create("GBPUSD", SecurityType.Forex, Market.FXCM),
Symbol.Create("USDJPY", SecurityType.Forex, Market.FXCM),
Symbol.Create("USDCHF", SecurityType.Forex, Market.FXCM),
Symbol.Create("AUDUSD", SecurityType.Forex, Market.FXCM),
Symbol.Create("EURJPY", SecurityType.Forex, Market.FXCM),
Symbol.Create("GBPJPY", SecurityType.Forex, Market.FXCM),
};
/// <summary>
/// Get the fee for this order in units of the account currency
/// </summary>
/// <param name="parameters">A <see cref="OrderFeeParameters"/> object
/// containing the security and order</param>
/// <returns>The cost of the order in units of the account currency</returns>
public override OrderFee GetOrderFee(OrderFeeParameters parameters)
{
// From http://www.fxcm.com/forex/forex-pricing/ (on Oct 6th, 2015)
// Forex: $0.04 per side per 1k lot for EURUSD, GBPUSD, USDJPY, USDCHF, AUDUSD, EURJPY, GBPJPY
// $0.06 per side per 1k lot for other instruments
// From https://www.fxcm.com/uk/markets/cfds/frequently-asked-questions/
// CFD: no commissions
decimal fee = 0;
if (parameters.Security.Type == SecurityType.Forex)
{
var commissionRate = _groupCommissionSchedule1.Contains(parameters.Security.Symbol)
? 0.04m : 0.06m;
fee = Math.Abs(commissionRate * parameters.Order.AbsoluteQuantity / 1000);
}
return new OrderFee(new CashAmount(fee,
parameters.AccountCurrency));
}
}
} | 44.046154 | 106 | 0.65351 | [
"Apache-2.0"
] | arcayi/Lean | Common/Orders/Fees/FxcmFeeModel.cs | 2,863 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using OpenQA.Selenium.Appium.Windows;
namespace UITests.UILibrary
{
public class EventsMode
{
WindowsDriver<WindowsElement> Session;
public EventsMode(WindowsDriver<WindowsElement> session)
{
Session = session;
}
}
}
| 27.5625 | 102 | 0.664399 | [
"MIT"
] | Microsoft/accessibility-insights-windows | src/UITests/UILibrary/EventsMode.cs | 428 | C# |
#pragma checksum "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\Modules\FileUpload\ImageUpload.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "b36c37312774a0f18a99528860a04de3edc03d58"
// <auto-generated/>
#pragma warning disable 1591
#pragma warning disable 0414
#pragma warning disable 0649
#pragma warning disable 0169
namespace YourSpace.Modules.FileUpload
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using Microsoft.AspNetCore.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using Microsoft.AspNetCore.Components.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Shared;
#line default
#line hidden
#nullable disable
#nullable restore
#line 11 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.ModalWindow;
#line default
#line hidden
#nullable disable
#nullable restore
#line 13 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Page;
#line default
#line hidden
#nullable disable
#nullable restore
#line 14 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Page.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 15 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Page.Components;
#line default
#line hidden
#nullable disable
#nullable restore
#line 16 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Page.ModifyComponents;
#line default
#line hidden
#nullable disable
#nullable restore
#line 17 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Blocks.ModifyComponents;
#line default
#line hidden
#nullable disable
#nullable restore
#line 18 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Blocks.Components;
#line default
#line hidden
#nullable disable
#nullable restore
#line 19 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Blocks.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 20 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Blocks;
#line default
#line hidden
#nullable disable
#nullable restore
#line 21 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Groups.ModifyComponents;
#line default
#line hidden
#nullable disable
#nullable restore
#line 22 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Groups.ViewMode;
#line default
#line hidden
#nullable disable
#nullable restore
#line 23 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Pages.Groups.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 25 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.ThingCounter;
#line default
#line hidden
#nullable disable
#nullable restore
#line 26 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.ThingCounter.Components;
#line default
#line hidden
#nullable disable
#nullable restore
#line 28 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.DataWorker;
#line default
#line hidden
#nullable disable
#nullable restore
#line 29 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Cloner;
#line default
#line hidden
#nullable disable
#nullable restore
#line 30 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Gallery;
#line default
#line hidden
#nullable disable
#nullable restore
#line 31 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Gallery.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 32 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.FileUpload;
#line default
#line hidden
#nullable disable
#nullable restore
#line 33 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Inputs;
#line default
#line hidden
#nullable disable
#nullable restore
#line 35 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Moderation;
#line default
#line hidden
#nullable disable
#nullable restore
#line 36 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Moderation.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 38 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.ComponentsView;
#line default
#line hidden
#nullable disable
#nullable restore
#line 39 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Services;
#line default
#line hidden
#nullable disable
#nullable restore
#line 40 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Lister;
#line default
#line hidden
#nullable disable
#nullable restore
#line 41 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Image;
#line default
#line hidden
#nullable disable
#nullable restore
#line 43 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.UserProfile;
#line default
#line hidden
#nullable disable
#nullable restore
#line 44 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.UserProfile.Compoents;
#line default
#line hidden
#nullable disable
#nullable restore
#line 46 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using Microsoft.Extensions.Localization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 47 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Localization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 48 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using YourSpace.Modules.Music;
#line default
#line hidden
#nullable disable
#nullable restore
#line 50 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor"
using BlazorInputFile;
#line default
#line hidden
#nullable disable
public partial class ImageUpload : CFileUpload
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
}
#pragma warning restore 1998
#nullable restore
#line 24 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\Modules\FileUpload\ImageUpload.razor"
public static new int GetDefaultModalId() => 5;
protected override void OnInitialized()
{
_fileType = FileType.Images;
base.OnInitialized();
}
public override void HandleDataType()
{
base.HandleDataType();
_fileType = FileType.Images;
AcceptMimes = new string[]
{
"image/jpeg",
"image/png",
"image/gif"
};
MaxSize = Options.Value.MaxImageSize;
}
public override bool CustomCheckFile(string path)
{
return true;
}
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Components.InjectAttribute] private IStringLocalizer<ImageUpload> L { get; set; }
}
}
#pragma warning restore 1591
| 26.397143 | 194 | 0.789804 | [
"MIT"
] | Invectys/Sites | YourSpaceMDB_4.2_Optimization/YourSpace/obj/Debug/netcoreapp3.1/win-x64/RazorDeclaration/Modules/FileUpload/ImageUpload.razor.g.cs | 9,239 | C# |
using System.Threading;
using CrawlerWave.Utils.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace CrawlerWave.Core.Configurations;
internal static class Initialization
{
private const int MaxAttemptsCreateDriver = 10;
public static (IWebDriver? driver, ChromeDriverService? service) Create(string[] capabilities)
{
IWebDriver? Driver = null;
ChromeDriverService? Service = null;
ChromeOptions? Options = null;
for (var i = 0; i < MaxAttemptsCreateDriver; i++)
{
try
{
if (Options == null) Options = NewOptions(capabilities);
Service = NewService();
Driver = new ChromeDriver(Service, Options);
return (Driver, Service);
}
catch
{
Service?.Dispose();
Driver?.Dispose();
Thread.Sleep(TimeSpan.FromSeconds(3));
}
}
return (null, null);
}
private static ChromeOptions NewOptions(string[] capabilities)
{
var options = new ChromeOptions() {
AcceptInsecureCertificates = true,
UseSpecCompliantProtocol = true
};
options.AddArguments(capabilities);
return options;
}
private static ChromeDriverService NewService()
{
var service = ChromeDriverService.CreateDefaultService(FolderUtils.GetAbsolutePath());
service.HideCommandPromptWindow = true;
service.Port = SocketHelper.GetNewSocketPort();
return service;
}
}
| 27.586207 | 98 | 0.600625 | [
"MIT"
] | afborgesDev/CrawlerWave | src/CrawlerWave.Core/Configurations/Initialization.cs | 1,602 | C# |
using System;
using MGR.CommandLineParser.Extensibility.Converters;
using Xunit;
namespace MGR.CommandLineParser.UnitTests.Extensibility.Converters
{
public class BooleanConverterTests
{
[Fact]
public void TargetType()
{
// Arrange
IConverter converter = new BooleanConverter();
var expectedType = typeof(bool);
// Act
var actual = converter.TargetType;
// Assert
Assert.Equal(expectedType, actual);
}
[Fact]
public void StringEmptyConversion()
{
// Arrange
IConverter converter = new BooleanConverter();
var value = string.Empty;
// Act
var actual = converter.Convert(value, converter.TargetType);
// Assert
Assert.NotNull(actual);
Assert.IsType<bool>(actual);
Assert.True((bool)actual);
}
[Fact]
public void LowerTrueConversion()
{
// Arrange
IConverter converter = new BooleanConverter();
var value = "true";
// Act
var actual = converter.Convert(value, converter.TargetType);
// Assert
Assert.NotNull(actual);
Assert.IsType<bool>(actual);
Assert.True((bool)actual);
}
[Fact]
public void UpperTrueConversion()
{
// Arrange
IConverter converter = new BooleanConverter();
var value = "True";
// Act
var actual = converter.Convert(value, converter.TargetType);
// Assert
Assert.NotNull(actual);
Assert.IsType<bool>(actual);
Assert.True((bool)actual);
}
[Fact]
public void LowerFalseConversion()
{
// Arrange
IConverter converter = new BooleanConverter();
var value = "false";
// Act
var actual = converter.Convert(value, converter.TargetType);
// Assert
Assert.NotNull(actual);
Assert.IsType<bool>(actual);
Assert.False((bool)actual);
}
[Fact]
public void UpperFalseConversion()
{
// Arrange
IConverter converter = new BooleanConverter();
var value = "False";
// Act
var actual = converter.Convert(value, converter.TargetType);
// Assert
Assert.NotNull(actual);
Assert.IsType<bool>(actual);
Assert.False((bool)actual);
}
[Fact]
public void MinusConversion()
{
// Arrange
IConverter converter = new BooleanConverter();
var value = "-";
// Act
var actual = converter.Convert(value, converter.TargetType);
// Assert
Assert.NotNull(actual);
Assert.IsType<bool>(actual);
Assert.False((bool)actual);
}
[Fact]
public void PlusConversion()
{
// Arrange
IConverter converter = new BooleanConverter();
var value = "+";
// Act
var actual = converter.Convert(value, converter.TargetType);
// Assert
Assert.NotNull(actual);
Assert.IsType<bool>(actual);
Assert.True((bool)actual);
}
[Fact]
[Trait(nameof(Exception), nameof(CommandLineParserException))]
public void BadValueConversion()
{
// Arrange
IConverter converter = new BooleanConverter();
var value = "Hello";
var expectedExceptionMessage = Constants.ExceptionMessages.FormatConverterUnableConvert(value, typeof(bool));
#if NET48
var expectedInnerExceptionMessage = "String was not recognized as a valid Boolean.";
#else
var expectedInnerExceptionMessage = "String 'Hello' was not recognized as a valid Boolean.";
#endif
// Act
using (new LangageSwitcher("en-us"))
{
var actualException = Assert.Throws<CommandLineParserException>(() => converter.Convert(value, converter.TargetType));
// Assert
Assert.Equal(expectedExceptionMessage, actualException.Message);
Assert.NotNull(actualException.InnerException);
var actualInnerExecption = Assert.IsAssignableFrom<FormatException>(actualException.InnerException);
Assert.Equal(expectedInnerExceptionMessage, actualInnerExecption.Message);
}
}
}
} | 29.179012 | 134 | 0.543262 | [
"MIT"
] | mgrosperrin/commandlineparser | tests/MGR.CommandLineParser.UnitTests/Extensibility/Converters/BooleanConverterTests.cs | 4,729 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace ArtmisNet.Ha90.Migrations
{
public partial class Upgraded_To_Abp_5_1_0 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "UserNameOrEmailAddress",
table: "AbpUserLoginAttempts",
maxLength: 256,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 255,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Value",
table: "AbpSettings",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 2000,
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "UserNameOrEmailAddress",
table: "AbpUserLoginAttempts",
maxLength: 255,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 256,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Value",
table: "AbpSettings",
maxLength: 2000,
nullable: true,
oldClrType: typeof(string),
oldNullable: true);
}
}
}
| 31.770833 | 71 | 0.523279 | [
"MIT"
] | grandpa22/HA90 | src/ArtmisNet.Ha90.EntityFrameworkCore/Migrations/20191216011543_Upgraded_To_Abp_5_1_0.cs | 1,527 | 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("08.CenterPoint")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("08.CenterPoint")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ba4c5d23-6e47-4387-8743-19b65175b3a2")]
// 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.864865 | 84 | 0.744468 | [
"MIT"
] | V-Uzunov/Soft-Uni-Education | 02.ProgrammingFundamentalsC#/05.MethodsAndDebuggingExercise/08.CenterPoint/Properties/AssemblyInfo.cs | 1,404 | C# |
using StudentSystem.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace StudentSystem.Web.Controllers
{
public class HomeController : Controller
{
private IStudentSystemData data;
public HomeController()
{
this.data = new StudentsSystemData();
}
public ActionResult Index()
{
var students = this.data.Students.All();
return View(students);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | 20.45 | 67 | 0.57335 | [
"MIT"
] | DimitarDKirov/Data-Bases | 13. Entity Framework Code First/StudentSystem/StudentSystem.Web/Controllers/HomeController.cs | 820 | C# |
/*
* Copyright (c) Adam Chapweske
*
* Licensed under MIT (https://github.com/achapweske/silvernote/blob/master/LICENSE)
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DOM.HTML.Internal
{
/// <summary>
/// Root of an HTML document.
/// See the HTML element definition in HTML 4.01.
/// http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-33759296
/// </summary>
public class HTMLHtmlElementBase : HTMLElementBase, HTMLHtmlElement
{
#region Constructors
internal HTMLHtmlElementBase(HTMLDocumentImpl ownerDocument)
: base(HTMLElements.HTML, ownerDocument)
{
}
#endregion
#region HTMLHtmlElement
public string Version
{
get { return GetAttribute(HTMLAttributes.VERSION); }
set { SetAttribute(HTMLAttributes.VERSION, value); }
}
#endregion
}
}
| 22.714286 | 84 | 0.636268 | [
"MIT"
] | achapweske/silvernote | SilverNote.DOM/HTML/Implementation/HTMLHtmlElementBase.cs | 956 | C# |
using System.Windows;
using System.Windows.Media.Media3D;
namespace Surfaces
{
public abstract class Surface : ModelVisual3D
{
public static PropertyHolder<Material, Surface> MaterialProperty =
new PropertyHolder<Material, Surface>("Material", null, OnMaterialChanged);
public static PropertyHolder<Material, Surface> BackMaterialProperty =
new PropertyHolder<Material, Surface>("BackMaterial", null, OnBackMaterialChanged);
public static PropertyHolder<bool, Surface> VisibleProperty =
new PropertyHolder<bool, Surface>("Visible", true, OnVisibleChanged);
private readonly GeometryModel3D _content = new GeometryModel3D();
public Surface()
{
Content = _content;
_content.Geometry = CreateMesh();
}
public Material Material
{
get { return MaterialProperty.Get(this); }
set { MaterialProperty.Set(this, value); }
}
public Material BackMaterial
{
get { return BackMaterialProperty.Get(this); }
set { BackMaterialProperty.Set(this, value); }
}
public bool Visible
{
get { return VisibleProperty.Get(this); }
set { VisibleProperty.Set(this, value); }
}
private static void OnMaterialChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((Surface) sender).OnMaterialChanged();
}
private static void OnBackMaterialChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((Surface) sender).OnBackMaterialChanged();
}
private static void OnVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((Surface) sender).OnVisibleChanged();
}
protected static void OnGeometryChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((Surface) sender).OnGeometryChanged();
}
private void OnMaterialChanged()
{
SetContentMaterial();
}
private void OnBackMaterialChanged()
{
SetContentBackMaterial();
}
private void OnVisibleChanged()
{
SetContentMaterial();
SetContentBackMaterial();
}
private void SetContentMaterial()
{
_content.Material = Visible ? Material : null;
}
private void SetContentBackMaterial()
{
_content.BackMaterial = Visible ? BackMaterial : null;
}
private void OnGeometryChanged()
{
_content.Geometry = CreateMesh();
}
protected abstract Geometry3D CreateMesh();
}
} | 28.9375 | 102 | 0.604392 | [
"MIT"
] | BogdanDimov/HQC-2-HW | Topics/02. Code-Tuning-and-Optimization/homework/Problem1. SolarSystem/Surface.cs | 2,778 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Measure : MonoBehaviour
{
#region Unity Events
void Awake()
{
var x = GetComponent<MeshRenderer>().bounds.extents.x;
var z = GetComponent<MeshRenderer>().bounds.extents.z;
Debug.Log(string.Format("Bounding box: {0} x {1}", x, z));
}
#endregion
}
| 22.647059 | 66 | 0.657143 | [
"MIT"
] | kennebel/HexShip | Assets/B_Scripts/Support/Measure.cs | 387 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FuelSDK;
namespace objsamples
{
partial class Tester
{
static void TestET_ListSubscriber()
{
string NewListName = "CSharpSDKListSubscriber";
string SubscriberTestEmail = "CSharpSDKListSubscriber@bh.exacttarget.com";
Console.WriteLine("--- Testing ListSubscriber ---");
ET_Client myclient = new ET_Client();
Console.WriteLine("\n Create List");
ET_List postList = new ET_List();
postList.AuthStub = myclient;
postList.ListName = NewListName;
PostReturn prList = postList.Post();
if (prList.Status && prList.Results.Length > 0)
{
int newListID = prList.Results[0].Object.ID;
Console.WriteLine("\n Create Subscriber on List");
ET_Subscriber postSub = new ET_Subscriber();
postSub.Lists = new ET_SubscriberList[] { new ET_SubscriberList() { ID = newListID } };
postSub.AuthStub = myclient;
postSub.EmailAddress = SubscriberTestEmail;
postSub.Attributes = new FuelSDK.ET_ProfileAttribute[] { new ET_ProfileAttribute() { Name = "First Name", Value = "ExactTarget Example" } };
PostReturn postResponse = postSub.Post();
Console.WriteLine("Post Status: " + postResponse.Status.ToString());
Console.WriteLine("Message: " + postResponse.Message.ToString());
Console.WriteLine("Code: " + postResponse.Code.ToString());
Console.WriteLine("Results Length: " + postResponse.Results.Length);
if (!postResponse.Status)
{
if (postResponse.Results.Length > 0 && postResponse.Results[0].ErrorCode == 12014)
{
// If the subscriber already exists in the account then we need to do an update.
//Update Subscriber On List
Console.WriteLine("\n Update Subscriber to add to List");
PatchReturn patchResponse = postSub.Patch();
Console.WriteLine("Post Status: " + patchResponse.Status.ToString());
Console.WriteLine("Message: " + patchResponse.Message.ToString());
Console.WriteLine("Code: " + patchResponse.Code.ToString());
Console.WriteLine("Results Length: " + patchResponse.Results.Length);
}
}
Console.WriteLine("\n Retrieve all Subscribers on the List");
ET_List_Subscriber getListSub = new ET_List_Subscriber();
getListSub.AuthStub = myclient;
getListSub.Props = new string[] { "ObjectID", "SubscriberKey", "CreatedDate", "Client.ID", "Client.PartnerClientKey", "ListID", "Status" };
getListSub.SearchFilter = new SimpleFilterPart() { Property = "ListID", SimpleOperator = SimpleOperators.equals, Value = new string[] { newListID.ToString() } };
GetReturn getResponse = getListSub.Get();
Console.WriteLine("Get Status: " + getResponse.Status.ToString());
Console.WriteLine("Message: " + getResponse.Message.ToString());
Console.WriteLine("Code: " + getResponse.Code.ToString());
Console.WriteLine("Results Length: " + getResponse.Results.Length);
foreach (ET_List_Subscriber ResultListSub in getResponse.Results)
{
Console.WriteLine("--ListID: " + ResultListSub.ID + ", SubscriberKey(EmailAddress): " + ResultListSub.SubscriberKey);
}
}
//Console.WriteLine("Retrieve Filtered ListSubscribers with GetMoreResults");
//ET_ListSubscriber oe = new ET_ListSubscriber();
//oe.authStub = myclient;
//oe.SearchFilter = new SimpleFilterPart() { Property = "EventDate", SimpleOperator = SimpleOperators.greaterThan, DateValue = new DateTime[] { filterDate } };
//oe.props = new string[] { "ObjectID", "SubscriberKey", "CreatedDate", "Client.ID", "Client.PartnerClientKey", "ListID", "Status" };
//GetReturn oeGet = oe.Get();
//Console.WriteLine("Get Status: " + oeGet.Status.ToString());
//Console.WriteLine("Message: " + oeGet.Message.ToString());
//Console.WriteLine("Code: " + oeGet.Code.ToString());
//Console.WriteLine("Results Length: " + oeGet.Results.Length);
//Console.WriteLine("MoreResults: " + oeGet.MoreResults.ToString());
//// Since this could potentially return a large number of results, we do not want to print the results
////foreach (ET_ListSubscriber ListSubscriber in oeGet.Results)
////{
//// Console.WriteLine("SubscriberKey: " + ListSubscriber.SubscriberKey + ", EventDate: " + ListSubscriber.EventDate.ToString());
////}
//while (oeGet.MoreResults)
//{
// Console.WriteLine("Continue Retrieve Filtered ListSubscribers with GetMoreResults");
// oeGet = oe.GetMoreResults();
// Console.WriteLine("Get Status: " + oeGet.Status.ToString());
// Console.WriteLine("Message: " + oeGet.Message.ToString());
// Console.WriteLine("Code: " + oeGet.Code.ToString());
// Console.WriteLine("Results Length: " + oeGet.Results.Length);
// Console.WriteLine("MoreResults: " + oeGet.MoreResults.ToString());
//}
//The following request could potentially bring back large amounts of data if run against a production account
//Console.WriteLine("Retrieve All ListSubscribers with GetMoreResults");
//ET_ListSubscriber oe = new ET_ListSubscriber();
//oe.authStub = myclient;
//oe.props = new string[] { "SendID", "SubscriberKey", "EventDate", "Client.ID", "EventType", "BatchID", "TriggeredSendDefinitionObjectID", "PartnerKey" };
//GetResponse oeGetAll = oe.Get();
//Console.WriteLine("Get Status: " + oeGetAll.Status.ToString());
//Console.WriteLine("Message: " + oeGetAll.Message.ToString());
//Console.WriteLine("Code: " + oeGetAll.Code.ToString());
//Console.WriteLine("Results Length: " + oeGetAll.Results.Length);
//Console.WriteLine("MoreResults: " + oeGetAll.MoreResults.ToString());
//// Since this could potentially return a large number of results, we do not want to print the results
////foreach (ET_ListSubscriber ListSubscriber in oeGet.Results)
////{
//// Console.WriteLine("SubscriberKey: " + ListSubscriber.SubscriberKey + ", EventDate: " + ListSubscriber.EventDate.ToString());
////}
//while (oeGetAll.MoreResults)
//{
// oeGetAll = oe.GetMoreResults();
// Console.WriteLine("Get Status: " + oeGetAll.Status.ToString());
// Console.WriteLine("Message: " + oeGetAll.Message.ToString());
// Console.WriteLine("Code: " + oeGetAll.Code.ToString());
// Console.WriteLine("Results Length: " + oeGetAll.Results.Length);
// Console.WriteLine("MoreResults: " + oeGetAll.MoreResults.ToString());
//}
}
}
}
| 56.007407 | 177 | 0.588679 | [
"MIT"
] | Sandviksas/FuelSDK-CSharp | objsamples/Sample_List_Subscriber.cs | 7,563 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace AssetImporter {
public class LstLoader {
public void Load(string sourceFileName, string destinationDirectory) {
// This might not even be a real LST although it has .LST extension. WTF?
// So, we have to do this in two steps.
ushort header;
using (var binaryReader = new BinaryReader(File.Open(sourceFileName, FileMode.Open))) {
header = binaryReader.BE_ReadUInt16();
}
// If it turns out that this is a txt file, use the appropriate loader for that
// (Does that actually ever happen? Would be cool to ditch all this verification shit)
if (header == 0xE7FD) {
new TxtLoader().Load(sourceFileName, destinationDirectory);
return;
}
// Now we're sure it's a LST... or are we?
if (header != 0x204E) {
throw new Exception("Invalid LST file : " + sourceFileName);
}
// Ok now we're REALLY sure! Phew.
using (var binaryReader = new BinaryReader(File.Open(sourceFileName, FileMode.Open))) {
binaryReader.BE_ReadUInt16(); // Skip header, we've just read it
binaryReader.ReadUInt32(); // Skip number of entries, we'll just read until end of file anyway
int numEntry = 0;
string baseName = Path.GetFileNameWithoutExtension(sourceFileName);
while(binaryReader.BaseStream.Position + 1 < binaryReader.BaseStream.Length) {
if ( binaryReader.BE_ReadInt16() != 0x0100) {
continue;
}
var baseFormat = (BaseFormat)binaryReader.ReadInt16();
Loader.LoadBaseFormat(baseFormat, destinationDirectory, baseName + numEntry++, binaryReader);
}
}
}
}
}
| 47.113636 | 115 | 0.563917 | [
"Apache-2.0"
] | asik/Settlers-2-Remake | src/AssetImporter/Loader/LstLoader.cs | 2,075 | C# |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace APIDelays.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "APIDelays.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | 57.424779 | 149 | 0.665742 | [
"MIT"
] | thelittlewozniak/getdelays.be | APIDelays/Areas/HelpPage/App_Start/HelpPageConfig.cs | 6,489 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir & xuri 2021
//
// 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.
// This file was automatically generated and should not be edited directly.
namespace SharpVk.Interop.Google
{
/// <summary>
/// </summary>
public unsafe delegate Result VkSwapchainKHRGetPastPresentationTimingDelegate(Device device, Khronos.Swapchain swapchain, uint* presentationTimingCount, SharpVk.Google.PastPresentationTiming* presentationTimings);
}
| 49.548387 | 217 | 0.769531 | [
"MIT"
] | xuri02/SharpVk | src/SharpVk/Interop/Google/VkSwapchainKHRGetPastPresentationTimingDelegate.gen.cs | 1,536 | C# |
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharePointPnP.ProvisioningApp.DomainModel
{
/// <summary>
/// A First Release Office 365 Tenant
/// </summary>
public class Tenant : BaseModel<String>
{
/// <summary>
/// The name of the First Release Tenant
/// </summary>
[StringLength(100)]
[Required]
public String TenantName { get; set; }
/// <summary>
/// The description/name of the reference owner
/// </summary>
[StringLength(200)]
public String ReferenceOwner { get; set; }
}
}
| 24.363636 | 55 | 0.629353 | [
"MIT"
] | GitTest12345679/sp-provisioning-service | SharePointPnP.ProvisioningApp/SharePointPnP.ProvisioningApp.DomainModel/Tenant.cs | 806 | C# |
using CotorraNode.Common.Base.Schema;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Text;
namespace Cotorra.Schema
{
public static class MinimumSalaryExtension
{
public static MinimunSalary SetData(this MinimunSalary minimunSalary, DateTime expirationDate, decimal zoneA, decimal zoneB,
decimal zoneC)
{
minimunSalary.ZoneA = zoneA;
minimunSalary.ZoneB = zoneB;
minimunSalary.ZoneC = zoneC;
minimunSalary.ExpirationDate = expirationDate;
return minimunSalary;
}
public static MinimunSalary SetOwnerData(this MinimunSalary minimunSalary, Guid companyId, Guid instanceId, Guid userId)
{
minimunSalary.company = companyId;
minimunSalary.InstanceID = instanceId;
minimunSalary.user = userId;
return minimunSalary;
}
}
/// <summary>
/// Salario Mínimo
/// </summary>
[DataContract]
[Serializable]
public class MinimunSalary : IdentityCatalogEntityExt
{
[DataMember]
public DateTime ExpirationDate { get; set; }
[DataMember]
public decimal ZoneA { get; set; }
[DataMember]
public decimal ZoneB { get; set; }
[DataMember]
public decimal ZoneC { get; set; }
}
[DataContract]
public enum ZoneType
{
A = 1,
B = 2,
C = 3,
}
}
| 24.806452 | 132 | 0.622237 | [
"MIT"
] | CotorraProject/Cotorra | Cotorra.Schema/domain/MinimunSalary.cs | 1,541 | C# |
// <copyright file="ElasticsearchClientInstrumentation.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using OpenTelemetry.Contrib.Instrumentation.ElasticsearchClient.Implementation;
using OpenTelemetry.Instrumentation;
using OpenTelemetry.Trace;
namespace OpenTelemetry.Contrib.Instrumentation.ElasticsearchClient
{
/// <summary>
/// Elasticsearch client instrumentation.
/// </summary>
internal class ElasticsearchClientInstrumentation : IDisposable
{
private readonly DiagnosticSourceSubscriber diagnosticSourceSubscriber;
/// <summary>
/// Initializes a new instance of the <see cref="ElasticsearchClientInstrumentation"/> class.
/// </summary>
/// <param name="activitySource">ActivitySource adapter instance.</param>
/// <param name="options">Configuration options for Elasticsearch client instrumentation.</param>
public ElasticsearchClientInstrumentation(ActivitySourceAdapter activitySource, ElasticsearchClientInstrumentationOptions options)
{
if (activitySource == null)
{
throw new ArgumentNullException(nameof(activitySource));
}
this.diagnosticSourceSubscriber = new DiagnosticSourceSubscriber(new ElasticsearchRequestPipelineDiagnosticListener(activitySource, options), null);
this.diagnosticSourceSubscriber.Subscribe();
}
/// <inheritdoc/>
public void Dispose()
{
this.diagnosticSourceSubscriber.Dispose();
}
}
}
| 40.886792 | 160 | 0.719889 | [
"Apache-2.0"
] | alexvaluyskiy/opentelemetry-dotnet-contrib | src/OpenTelemetry.Contrib.Instrumentation.Elasticsearch/ElasticsearchClientInstrumentation.cs | 2,169 | C# |
using global::System;
using NUnit.Framework;
using NUnit.Framework.TUnit;
using Tizen.NUI.Components;
using Tizen.NUI.BaseComponents;
namespace Tizen.NUI.Devel.Tests
{
using tlog = Tizen.Log;
[TestFixture]
[Description("public/WebView/WebView")]
public class PublicWebViewTest
{
private const string tag = "NUITEST";
private string url = Tizen.Applications.Application.Current.DirectoryInfo.Resource + "picture.png";
private static string[] runtimeArgs = { "Tizen.NUI.Devel.Tests", "--enable-dali-window", "--enable-spatial-navigation" };
private const string USER_AGENT = "Mozilla/5.0 (SMART-TV; Linux; Tizen 6.0) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/4.0 Chrome/76.0.3809.146 TV Safari/537.36";
private Tizen.NUI.BaseComponents.WebView webView = null;
private void JsCallback(string arg) { }
private void VideoCallback (bool arg) { }
private void GeolocationCallback (string arg1, string arg2) { }
private void PromptCallback (string arg1, string arg2) { }
internal class MyWebView : Tizen.NUI.BaseComponents.WebView
{
public MyWebView() : base()
{ }
public void OnDispose(DisposeTypes type)
{
base.Dispose(type);
}
}
[SetUp]
public void Init()
{
tlog.Info(tag, "Init() is called!");
webView = new Tizen.NUI.BaseComponents.WebView(runtimeArgs)
{
Size = new Size(500, 200),
UserAgent = USER_AGENT
};
webView.LoadUrl("http://www.baidu.com");
}
[TearDown]
public void Destroy()
{
webView.ClearCache();
webView.ClearCookies();
webView.Dispose();
tlog.Info(tag, "Destroy() is called!");
}
[Test]
[Category("P1")]
[Description("WebView constructor.")]
[Property("SPEC", "Tizen.NUI.WebView.WebView C")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "CONSTR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewConstructor()
{
tlog.Debug(tag, $"WebViewConstructor START");
var testingTarget = new Tizen.NUI.BaseComponents.WebView();
Assert.IsNotNull(testingTarget, "null handle");
Assert.IsInstanceOf<Tizen.NUI.BaseComponents.WebView>(testingTarget, "Should return WebView instance.");
testingTarget?.Dispose();
tlog.Debug(tag, $"WebViewConstructor END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView constructor.")]
[Property("SPEC", "Tizen.NUI.WebView.WebView C")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "CONSTR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewConstructorWithLocaleAndTimezone()
{
tlog.Debug(tag, $"WebViewConstructorWithLocaleAndTimezone START");
var testingTarget = new Tizen.NUI.BaseComponents.WebView("Shanghai", "Asia/Shanghai");
Assert.IsNotNull(testingTarget, "null handle");
Assert.IsInstanceOf<Tizen.NUI.BaseComponents.WebView>(testingTarget, "Should return WebView instance.");
testingTarget?.Dispose();
tlog.Debug(tag, $"WebViewConstructorWithLocaleAndTimezone END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView constructor.")]
[Property("SPEC", "Tizen.NUI.WebView.WebView C")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "CONSTR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewConstructorWithWebView()
{
tlog.Debug(tag, $"WebViewConstructorWithWebView START");
var testingTarget = new Tizen.NUI.BaseComponents.WebView(webView);
Assert.IsNotNull(testingTarget, "null handle");
Assert.IsInstanceOf<Tizen.NUI.BaseComponents.WebView>(testingTarget, "Should return WebView instance.");
testingTarget.ClearCache();
testingTarget.ClearCookies();
testingTarget.Dispose();
tlog.Debug(tag, $"WebViewConstructorWithWebView END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView PageLoadStarted.")]
[Property("SPEC", "Tizen.NUI.WebView.PageLoadStarted A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewPageLoadStarted()
{
tlog.Debug(tag, $"WebViewPageLoadStarted START");
webView.PageLoadStarted += OnLoadStarted;
webView.PageLoadStarted -= OnLoadStarted;
tlog.Debug(tag, $"WebViewPageLoadStarted END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView PageLoading.")]
[Property("SPEC", "Tizen.NUI.WebView.PageLoading A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewPageLoading()
{
tlog.Debug(tag, $"WebViewPageLoading START");
webView.PageLoading += OnLoading;
webView.PageLoading -= OnLoading;
tlog.Debug(tag, $"WebViewPageLoading END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView PageLoadFinished.")]
[Property("SPEC", "Tizen.NUI.WebView.PageLoadFinished A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewPageLoadFinished()
{
tlog.Debug(tag, $"WebViewPageLoadFinished START");
webView.PageLoadFinished += OnLoadFinished;
webView.PageLoadFinished -= OnLoadFinished;
tlog.Debug(tag, $"WebViewPageLoadFinished END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView PageLoadError.")]
[Property("SPEC", "Tizen.NUI.WebView.PageLoadError A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewPageLoadError()
{
tlog.Debug(tag, $"WebViewPageLoadError START");
webView.PageLoadError += OnLoadError;
webView.PageLoadError -= OnLoadError;
tlog.Debug(tag, $"WebViewPageLoadError END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ScrollEdgeReached.")]
[Property("SPEC", "Tizen.NUI.WebView.ScrollEdgeReached A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewScrollEdgeReached()
{
tlog.Debug(tag, $"WebViewScrollEdgeReached START");
webView.ScrollEdgeReached += OnEdgeReached;
webView.ScrollEdgeReached -= OnEdgeReached;
tlog.Debug(tag, $"WebViewPageLoadError END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView UrlChanged.")]
[Property("SPEC", "Tizen.NUI.WebView.UrlChanged A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewUrlChanged()
{
tlog.Debug(tag, $"WebViewUrlChanged START");
webView.UrlChanged += OnUrlChange;
webView.UrlChanged -= OnUrlChange;
tlog.Debug(tag, $"WebViewUrlChanged END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView FormRepostPolicyDecided.")]
[Property("SPEC", "Tizen.NUI.WebView.FormRepostPolicyDecided A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewFormRepostPolicyDecided()
{
tlog.Debug(tag, $"WebViewFormRepostPolicyDecided START");
webView.FormRepostPolicyDecided += OnFormRepostPolicyDecide;
webView.FormRepostPolicyDecided -= OnFormRepostPolicyDecide;
tlog.Debug(tag, $"WebViewFormRepostPolicyDecided END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView FrameRendered.")]
[Property("SPEC", "Tizen.NUI.WebView.FrameRendered A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewFrameRendered()
{
tlog.Debug(tag, $"WebViewFrameRendered START");
webView.FrameRendered += OnFrameRender;
webView.FrameRendered -= OnFrameRender;
tlog.Debug(tag, $"WebViewFrameRendered END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ResponsePolicyDecided.")]
[Property("SPEC", "Tizen.NUI.WebView.ResponsePolicyDecided A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewResponsePolicyDecided()
{
tlog.Debug(tag, $"WebViewResponsePolicyDecided START");
webView.ResponsePolicyDecided += OnResponsePolicyDecide;
webView.ResponsePolicyDecided -= OnResponsePolicyDecide;
tlog.Debug(tag, $"WebViewResponsePolicyDecided END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView CertificateConfirmed.")]
[Property("SPEC", "Tizen.NUI.WebView.CertificateConfirmed A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewCertificateConfirmed()
{
tlog.Debug(tag, $"WebViewCertificateConfirmed START");
webView.CertificateConfirmed += OnCertificateConfirme;
webView.CertificateConfirmed -= OnCertificateConfirme;
tlog.Debug(tag, $"WebViewCertificateConfirmed END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView SslCertificateChanged.")]
[Property("SPEC", "Tizen.NUI.WebView.SslCertificateChanged A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewSslCertificateChanged()
{
tlog.Debug(tag, $"WebViewSslCertificateChanged START");
webView.SslCertificateChanged += OnSslCertificateChange;
webView.SslCertificateChanged -= OnSslCertificateChange;
tlog.Debug(tag, $"WebViewSslCertificateChanged END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView HttpAuthRequested.")]
[Property("SPEC", "Tizen.NUI.WebView.HttpAuthRequested A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewHttpAuthRequested()
{
tlog.Debug(tag, $"WebViewHttpAuthRequested START");
webView.HttpAuthRequested += OnHttpAuthRequeste;
webView.HttpAuthRequested -= OnHttpAuthRequeste;
tlog.Debug(tag, $"WebViewHttpAuthRequested END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ConsoleMessageReceived.")]
[Property("SPEC", "Tizen.NUI.WebView.ConsoleMessageReceived A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewConsoleMessageReceived()
{
tlog.Debug(tag, $"WebViewHttpAuthRequested START");
webView.ConsoleMessageReceived += OnConsoleMessageReceive;
webView.ConsoleMessageReceived -= OnConsoleMessageReceive;
tlog.Debug(tag, $"WebViewConsoleMessageReceived END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView BackForwardList.")]
[Property("SPEC", "Tizen.NUI.WebView.BackForwardList A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewBackForwardList()
{
tlog.Debug(tag, $"WebViewBackForwardList START");
var result = webView.BackForwardList;
tlog.Debug(tag, "ForwardList : " + result);
tlog.Debug(tag, $"WebViewBackForwardList END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView Context.")]
[Property("SPEC", "Tizen.NUI.WebView.Context A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewContext()
{
tlog.Debug(tag, $"WebViewContext START");
var result = webView.Context;
tlog.Debug(tag, "Context : " + result);
tlog.Debug(tag, $"WebViewContext END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView CookieManager.")]
[Property("SPEC", "Tizen.NUI.WebView.CookieManager A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewCookieManager()
{
tlog.Debug(tag, $"WebViewCookieManager START");
var result = webView.CookieManager;
tlog.Debug(tag, "CookieManager : " + result);
tlog.Debug(tag, $"WebViewCookieManager END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView Settings.")]
[Property("SPEC", "Tizen.NUI.WebView.Settings A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewSettings()
{
tlog.Debug(tag, $"WebViewSettings START");
var result = webView.Settings;
tlog.Debug(tag, "Settings : " + result);
tlog.Debug(tag, $"WebViewSettings END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView Url.")]
[Property("SPEC", "Tizen.NUI.WebView.Url A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewUrl()
{
tlog.Debug(tag, $"WebViewUrl START");
webView.Url = url;
tlog.Debug(tag, "Url : " + webView.Url);
tlog.Debug(tag, $"WebViewUrl END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView CacheModel.")]
[Property("SPEC", "Tizen.NUI.WebView.CacheModel A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewCacheModel()
{
tlog.Debug(tag, $"WebViewCacheModel START");
webView.CacheModel = Tizen.NUI.CacheModel.DocumentViewer;
tlog.Debug(tag, "CacheModel : " + webView.CacheModel);
webView.CacheModel = Tizen.NUI.CacheModel.DocumentBrowser;
tlog.Debug(tag, "CacheModel : " + webView.CacheModel);
webView.CacheModel = Tizen.NUI.CacheModel.PrimaryWebBrowser;
tlog.Debug(tag, "CacheModel : " + webView.CacheModel);
tlog.Debug(tag, $"WebViewCacheModel END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView CookieAcceptPolicy.")]
[Property("SPEC", "Tizen.NUI.WebView.CookieAcceptPolicy A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewCookieAcceptPolicy()
{
tlog.Debug(tag, $"WebViewCookieAcceptPolicy START");
webView.CookieAcceptPolicy = (CookieAcceptPolicy)Tizen.NUI.WebCookieManager.CookieAcceptPolicyType.NoThirdParty;
tlog.Debug(tag, "CookieAcceptPolicy : " + webView.CookieAcceptPolicy);
webView.CookieAcceptPolicy = (CookieAcceptPolicy)Tizen.NUI.WebCookieManager.CookieAcceptPolicyType.Always;
tlog.Debug(tag, "CookieAcceptPolicy : " + webView.CookieAcceptPolicy);
webView.CookieAcceptPolicy = (CookieAcceptPolicy)Tizen.NUI.WebCookieManager.CookieAcceptPolicyType.Never;
tlog.Debug(tag, "CookieAcceptPolicy : " + webView.CookieAcceptPolicy);
tlog.Debug(tag, $"WebViewCookieAcceptPolicy END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView UserAgent.")]
[Property("SPEC", "Tizen.NUI.WebView.UserAgent A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewUserAgent()
{
tlog.Debug(tag, $"WebViewUserAgent START");
webView.UserAgent = "Mozilla/5.0 (Linux; Android 4.2.1; M040 Build/JOP40D) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36";
tlog.Debug(tag, "UserAgent : " + webView.UserAgent);
tlog.Debug(tag, $"WebViewUserAgent END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView EnableJavaScript.")]
[Property("SPEC", "Tizen.NUI.WebView.EnableJavaScript A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewEnableJavaScript()
{
tlog.Debug(tag, $"WebViewEnableJavaScript START");
webView.EnableJavaScript = true;
tlog.Debug(tag, "EnableJavaScript : " + webView.EnableJavaScript);
webView.EnableJavaScript = false;
tlog.Debug(tag, "EnableJavaScript : " + webView.EnableJavaScript);
tlog.Debug(tag, $"WebViewEnableJavaScript END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView LoadImagesAutomatically.")]
[Property("SPEC", "Tizen.NUI.WebView.LoadImagesAutomatically A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewLoadImagesAutomatically()
{
tlog.Debug(tag, $"WebViewLoadImagesAutomatically START");
webView.LoadImagesAutomatically = true;
tlog.Debug(tag, "LoadImagesAutomatically : " + webView.LoadImagesAutomatically);
webView.LoadImagesAutomatically = false;
tlog.Debug(tag, "LoadImagesAutomatically : " + webView.LoadImagesAutomatically);
tlog.Debug(tag, $"WebViewLoadImagesAutomatically END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView DefaultTextEncodingName.")]
[Property("SPEC", "Tizen.NUI.WebView.DefaultTextEncodingName A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewDefaultTextEncodingName()
{
tlog.Debug(tag, $"WebViewDefaultTextEncodingName START");
var result = webView.DefaultTextEncodingName;
tlog.Debug(tag, "DefaultTextEncodingName : " + result);
webView.DefaultTextEncodingName = "gbk";
tlog.Debug(tag, "DefaultTextEncodingName : " + result);
tlog.Debug(tag, $"WebViewDefaultTextEncodingName END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView DefaultFontSize.")]
[Property("SPEC", "Tizen.NUI.WebView.DefaultFontSize A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewDefaultFontSize()
{
tlog.Debug(tag, $"WebViewDefaultFontSize START");
var result = webView.DefaultFontSize;
tlog.Debug(tag, "DefaultFontSize : " + result);
webView.DefaultFontSize = 32;
tlog.Debug(tag, "DefaultFontSize : " + result);
tlog.Debug(tag, $"WebViewDefaultFontSize END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ScrollPosition.")]
[Property("SPEC", "Tizen.NUI.WebView.ScrollPosition A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewScrollPosition()
{
tlog.Debug(tag, $"WebViewScrollPosition START");
webView.ScrollPosition = new Position(0.2f, 0.1f);
tlog.Debug(tag, "ScrollPositionX : " + webView.ScrollPosition.X);
tlog.Debug(tag, "ScrollPositionY : " + webView.ScrollPosition.Y);
tlog.Debug(tag, $"WebViewScrollPosition END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ScrollSize.")]
[Property("SPEC", "Tizen.NUI.WebView.ScrollSize A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewScrollSize()
{
tlog.Debug(tag, $"WebViewScrollSize START");
tlog.Debug(tag, "Width : " + webView.ScrollSize.Width);
tlog.Debug(tag, "Height : " + webView.ScrollSize.Height);
tlog.Debug(tag, $"WebViewScrollSize END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ContentSize.")]
[Property("SPEC", "Tizen.NUI.WebView.ContentSize A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewContentSize()
{
tlog.Debug(tag, $"WebViewContentSize START");
tlog.Debug(tag, "Width : " + webView.ContentSize.Width);
tlog.Debug(tag, "Height : " + webView.ContentSize.Height);
tlog.Debug(tag, $"WebViewContentSize END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView VideoHoleEnabled.")]
[Property("SPEC", "Tizen.NUI.WebView.VideoHoleEnabled A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewVideoHoleEnabled()
{
tlog.Debug(tag, $"WebViewVideoHoleEnabled START");
webView.VideoHoleEnabled = true;
tlog.Debug(tag, "VideoHoleEnabled : " + webView.VideoHoleEnabled);
webView.VideoHoleEnabled = false;
tlog.Debug(tag, "VideoHoleEnabled : " + webView.VideoHoleEnabled);
tlog.Debug(tag, $"WebViewVideoHoleEnabled END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView MouseEventsEnabled.")]
[Property("SPEC", "Tizen.NUI.WebView.MouseEventsEnabled A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewMouseEventsEnabled()
{
tlog.Debug(tag, $"WebViewMouseEventsEnabled START");
webView.MouseEventsEnabled = true;
tlog.Debug(tag, "MouseEventsEnabled : " + webView.MouseEventsEnabled);
webView.MouseEventsEnabled = false;
tlog.Debug(tag, "MouseEventsEnabled : " + webView.MouseEventsEnabled);
tlog.Debug(tag, $"WebViewMouseEventsEnabled END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView KeyEventsEnabled.")]
[Property("SPEC", "Tizen.NUI.WebView.KeyEventsEnabled A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewKeyEventsEnabled()
{
tlog.Debug(tag, $"WebViewKeyEventsEnabled START");
webView.KeyEventsEnabled = true;
tlog.Debug(tag, "KeyEventsEnabled : " + webView.KeyEventsEnabled);
webView.KeyEventsEnabled = false;
tlog.Debug(tag, "KeyEventsEnabled : " + webView.KeyEventsEnabled);
tlog.Debug(tag, $"WebViewKeyEventsEnabled END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ContentBackgroundColor.")]
[Property("SPEC", "Tizen.NUI.WebView.ContentBackgroundColor A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewContentBackgroundColor()
{
tlog.Debug(tag, $"WebViewContentBackgroundColor START");
webView.ContentBackgroundColor = new Vector4(0.3f, 0.5f, 1.0f, 0.0f);
tlog.Debug(tag, "ContentBackgroundColor : " + webView.ContentBackgroundColor);
tlog.Debug(tag, $"WebViewContentBackgroundColor END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView TilesClearedWhenHidden.")]
[Property("SPEC", "Tizen.NUI.WebView.TilesClearedWhenHidden A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewTilesClearedWhenHidden()
{
tlog.Debug(tag, $"WebViewTilesClearedWhenHidden START");
webView.TilesClearedWhenHidden = true;
tlog.Debug(tag, "TilesClearedWhenHidden : " + webView.TilesClearedWhenHidden);
webView.TilesClearedWhenHidden = false;
tlog.Debug(tag, "TilesClearedWhenHidden : " + webView.TilesClearedWhenHidden);
tlog.Debug(tag, $"WebViewTilesClearedWhenHidden END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView TileCoverAreaMultiplier.")]
[Property("SPEC", "Tizen.NUI.WebView.TileCoverAreaMultiplier A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewTileCoverAreaMultiplier()
{
tlog.Debug(tag, $"WebViewTileCoverAreaMultiplier START");
webView.TileCoverAreaMultiplier = 0.3f;
tlog.Debug(tag, "TileCoverAreaMultiplier : " + webView.TileCoverAreaMultiplier);
tlog.Debug(tag, $"WebViewTileCoverAreaMultiplier END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView CursorEnabledByClient.")]
[Property("SPEC", "Tizen.NUI.WebView.CursorEnabledByClient A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewCursorEnabledByClient()
{
tlog.Debug(tag, $"WebViewCursorEnabledByClient START");
webView.CursorEnabledByClient = true;
tlog.Debug(tag, "CursorEnabledByClient : " + webView.CursorEnabledByClient);
webView.CursorEnabledByClient = false;
tlog.Debug(tag, "CursorEnabledByClient : " + webView.CursorEnabledByClient);
tlog.Debug(tag, $"WebViewCursorEnabledByClient END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView SelectedText.")]
[Property("SPEC", "Tizen.NUI.WebView.SelectedText A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewSelectedText()
{
tlog.Debug(tag, $"WebViewSelectedText START");
var text = webView.SelectedText;
tlog.Debug(tag, "SelectedText : " + text);
tlog.Debug(tag, $"WebViewSelectedText END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView Title.")]
[Property("SPEC", "Tizen.NUI.WebView.Title A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewTitle()
{
tlog.Debug(tag, $"WebViewTitle START");
var title = webView.Title;
tlog.Debug(tag, "Title : " + title);
tlog.Debug(tag, $"WebViewTitle END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView Favicon.")]
[Property("SPEC", "Tizen.NUI.WebView.Favicon A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewFavicon()
{
tlog.Debug(tag, $"WebViewFavicon START");
var fav = webView.Favicon;
tlog.Debug(tag, "Favicon : " + fav);
tlog.Debug(tag, $"WebViewFavicon END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView PageZoomFactor.")]
[Property("SPEC", "Tizen.NUI.WebView.PageZoomFactor A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewPageZoomFactor()
{
tlog.Debug(tag, $"WebViewPageZoomFactor START");
webView.PageZoomFactor = 0.3f;
tlog.Debug(tag, "PageZoomFactor : " + webView.PageZoomFactor);
tlog.Debug(tag, $"WebViewPageZoomFactor END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView TextZoomFactor.")]
[Property("SPEC", "Tizen.NUI.WebView.TextZoomFactor A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewTextZoomFactor()
{
tlog.Debug(tag, $"WebViewTextZoomFactor START");
webView.TextZoomFactor = 0.2f;
tlog.Debug(tag, "TextZoomFactor : " + webView.TextZoomFactor);
tlog.Debug(tag, $"WebViewTextZoomFactor END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView LoadProgressPercentage.")]
[Property("SPEC", "Tizen.NUI.WebView.LoadProgressPercentage A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRO")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewLoadProgressPercentage()
{
tlog.Debug(tag, $"WebViewLoadProgressPercentage START");
var result = webView.LoadProgressPercentage;
tlog.Debug(tag, "LoadProgressPercentage : " + result);
tlog.Debug(tag, $"WebViewLoadProgressPercentage END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView LoadHtmlString.")]
[Property("SPEC", "Tizen.NUI.WebView.LoadHtmlString M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewLoadHtmlString()
{
tlog.Debug(tag, $"WebViewLoadHtmlString START");
try
{
webView.LoadHtmlString("<html><head lang=\"en\"></head></html>");
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewLoadHtmlString END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView LoadContents.")]
[Property("SPEC", "Tizen.NUI.WebView.LoadContents M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewLoadContents()
{
tlog.Debug(tag, $"WebViewLoadContents START");
try
{
webView.LoadContents("body", 18, " ", "gbk", "http://www.runoob.com/jsref/prop-doc-baseuri.html");
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewLoadContents END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView Reload.")]
[Property("SPEC", "Tizen.NUI.WebView.Reload M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewReload()
{
tlog.Debug(tag, $"WebViewReload START");
try
{
webView.Reload();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewReload END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ReloadWithoutCache.")]
[Property("SPEC", "Tizen.NUI.WebView.ReloadWithoutCache M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewReloadWithoutCache()
{
tlog.Debug(tag, $"WebViewReloadWithoutCache START");
try
{
webView.ReloadWithoutCache();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewReloadWithoutCache END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView StopLoading.")]
[Property("SPEC", "Tizen.NUI.WebView.StopLoading M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewStopLoading()
{
tlog.Debug(tag, $"WebViewStopLoading START");
try
{
webView.StopLoading();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewStopLoading END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView Suspend.")]
[Property("SPEC", "Tizen.NUI.WebView.Suspend M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewSuspend()
{
tlog.Debug(tag, $"WebViewSuspend START");
try
{
webView.Suspend();
webView.Resume();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewSuspend END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView SuspendNetworkLoading.")]
[Property("SPEC", "Tizen.NUI.WebView.SuspendNetworkLoading M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewSuspendNetworkLoading()
{
tlog.Debug(tag, $"WebViewSuspendNetworkLoading START");
try
{
webView.SuspendNetworkLoading();
webView.ResumeNetworkLoading();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewSuspendNetworkLoading END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView AddCustomHeader.")]
[Property("SPEC", "Tizen.NUI.WebView.AddCustomHeader M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewAddCustomHeader()
{
tlog.Debug(tag, $"WebViewAddCustomHeader START");
var result = webView.AddCustomHeader("customHeader_title", "font-size: 32rpx");
tlog.Debug(tag, "AddCustomHeader : " + result);
result = webView.RemoveCustomHeader("customHeader_title");
tlog.Debug(tag, "RemoveCustomHeader : " + result);
tlog.Debug(tag, $"WebViewAddCustomHeader END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ScrollBy.")]
[Property("SPEC", "Tizen.NUI.WebView.ScrollBy M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewScrollBy()
{
tlog.Debug(tag, $"WebViewScrollBy START");
try
{
webView.ScrollBy(1, 1);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewScrollBy END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ScrollEdgeBy.")]
[Property("SPEC", "Tizen.NUI.WebView.ScrollEdgeBy M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewScrollEdgeBy()
{
tlog.Debug(tag, $"WebViewScrollEdgeBy START");
var result = webView.ScrollEdgeBy(1, 1);
tlog.Debug(tag, "ScrollEdgeBy : " + result);
tlog.Debug(tag, $"WebViewScrollEdgeBy END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView GoBack.")]
[Property("SPEC", "Tizen.NUI.WebView.GoBack M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewGoBack()
{
tlog.Debug(tag, $"WebViewGoBack START");
try
{
webView.GoBack();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewGoBack END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView GoForward.")]
[Property("SPEC", "Tizen.NUI.WebView.GoForward M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewGoForward()
{
tlog.Debug(tag, $"WebViewGoForward START");
try
{
webView.GoForward();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewGoForward END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView CanGoBack.")]
[Property("SPEC", "Tizen.NUI.WebView.CanGoBack M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewCanGoBack()
{
tlog.Debug(tag, $"WebViewCanGoBack START");
var result = webView.CanGoBack();
tlog.Debug(tag, "CanGoBack : " + result);
tlog.Debug(tag, $"WebViewCanGoBack END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView CanGoForward.")]
[Property("SPEC", "Tizen.NUI.WebView.CanGoForward M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewCanGoForward()
{
tlog.Debug(tag, $"WebViewCanGoForward START");
var result = webView.CanGoForward();
tlog.Debug(tag, "CanGoForward : " + result);
tlog.Debug(tag, $"WebViewCanGoForward END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView EvaluateJavaScript.")]
[Property("SPEC", "Tizen.NUI.WebView.EvaluateJavaScript M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewEvaluateJavaScript()
{
tlog.Debug(tag, $"WebViewEvaluateJavaScript START");
try
{
webView.EvaluateJavaScript("<script type=\"text / javascript\">document.write(\"page\");</script>");
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewEvaluateJavaScript END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView AddJavaScriptMessageHandler.")]
[Property("SPEC", "Tizen.NUI.WebView.AddJavaScriptMessageHandler M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewAddJavaScriptMessageHandler()
{
tlog.Debug(tag, $"WebViewAddJavaScriptMessageHandler START");
try
{
webView.AddJavaScriptMessageHandler("AllowOrigin", JsCallback);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewAddJavaScriptMessageHandler END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView RegisterJavaScriptAlertCallback.")]
[Property("SPEC", "Tizen.NUI.WebView.RegisterJavaScriptAlertCallback M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewRegisterJavaScriptAlertCallback()
{
tlog.Debug(tag, $"WebViewRegisterJavaScriptAlertCallback START");
try
{
webView.RegisterJavaScriptAlertCallback(JsCallback);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewRegisterJavaScriptAlertCallback END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView RegisterJavaScriptConfirmCallback.")]
[Property("SPEC", "Tizen.NUI.WebView.RegisterJavaScriptConfirmCallback M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewRegisterJavaScriptConfirmCallback()
{
tlog.Debug(tag, $"WebViewRegisterJavaScriptConfirmCallback START");
try
{
webView.RegisterJavaScriptConfirmCallback(JsCallback);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewRegisterJavaScriptConfirmCallback END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView RegisterJavaScriptPromptCallback.")]
[Property("SPEC", "Tizen.NUI.WebView.RegisterJavaScriptPromptCallback M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewRegisterJavaScriptPromptCallback()
{
tlog.Debug(tag, $"WebViewRegisterJavaScriptPromptCallback START");
try
{
webView.RegisterJavaScriptPromptCallback(PromptCallback);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewRegisterJavaScriptPromptCallback END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ClearAllTilesResources.")]
[Property("SPEC", "Tizen.NUI.WebView.ClearAllTilesResources M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewClearAllTilesResources()
{
tlog.Debug(tag, $"WebViewClearAllTilesResources START");
try
{
webView.ClearAllTilesResources();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewClearAllTilesResources END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ClearHistory.")]
[Property("SPEC", "Tizen.NUI.WebView.ClearHistory M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewClearHistory()
{
tlog.Debug(tag, $"WebViewClearHistory START");
try
{
webView.ClearHistory();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewClearHistory END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView SetScaleFactor.")]
[Property("SPEC", "Tizen.NUI.WebView.SetScaleFactor M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewSetScaleFactor()
{
tlog.Debug(tag, $"WebViewSetScaleFactor START");
try
{
using (Vector2 point = new Vector2(1.0f, 1.0f))
{
webView.SetScaleFactor(0.2f, point);
var result = webView.GetScaleFactor();
tlog.Debug(tag, "ScaleFactor : " + result);
}
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewSetScaleFactor END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ActivateAccessibility.")]
[Property("SPEC", "Tizen.NUI.WebView.ActivateAccessibility M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewActivateAccessibility()
{
tlog.Debug(tag, $"WebViewActivateAccessibility START");
try
{
webView.ActivateAccessibility(false);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewActivateAccessibility END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView HighlightText.")]
[Property("SPEC", "Tizen.NUI.WebView.HighlightText M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewHighlightText()
{
tlog.Debug(tag, $"WebViewHighlightText START");
try
{
webView.HighlightText("web", Tizen.NUI.BaseComponents.WebView.FindOption.AtWordStart, 3);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewHighlightText END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView AddDynamicCertificatePath.")]
[Property("SPEC", "Tizen.NUI.WebView.AddDynamicCertificatePath M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewAddDynamicCertificatePath()
{
tlog.Debug(tag, $"WebViewAddDynamicCertificatePath START");
try
{
webView.AddDynamicCertificatePath("127.0.0.0", "/");
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewAddDynamicCertificatePath END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView CheckVideoPlayingAsynchronously.")]
[Property("SPEC", "Tizen.NUI.WebView.CheckVideoPlayingAsynchronously M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewCheckVideoPlayingAsynchronously()
{
tlog.Debug(tag, $"WebViewCheckVideoPlayingAsynchronously START");
try
{
webView.CheckVideoPlayingAsynchronously(VideoCallback);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewCheckVideoPlayingAsynchronously END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView RegisterGeolocationPermissionCallback.")]
[Property("SPEC", "Tizen.NUI.WebView.RegisterGeolocationPermissionCallback M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewRegisterGeolocationPermissionCallback()
{
tlog.Debug(tag, $"WebViewRegisterGeolocationPermissionCallback START");
try
{
webView.RegisterGeolocationPermissionCallback(GeolocationCallback);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewRegisterGeolocationPermissionCallback END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ClearCache.")]
[Property("SPEC", "Tizen.NUI.WebView.ClearCache M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewClearCache()
{
tlog.Debug(tag, $"WebViewClearCache START");
try
{
webView.ClearCache();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewClearCache END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView ClearCookies.")]
[Property("SPEC", "Tizen.NUI.WebView.ClearCookies M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewClearCookies()
{
tlog.Debug(tag, $"WebViewClearCookies START");
try
{
webView.ClearCookies();
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewClearCookies END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView DownCast.")]
[Property("SPEC", "Tizen.NUI.WebView.DownCast M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewDownCast()
{
tlog.Debug(tag, $"WebViewDownCast START");
try
{
Tizen.NUI.BaseComponents.WebView.DownCast(webView);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewDownCast END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView Assign.")]
[Property("SPEC", "Tizen.NUI.WebView.Assign M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewAssign()
{
tlog.Debug(tag, $"WebViewAssign START");
try
{
webView.Assign(webView);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
tlog.Debug(tag, $"WebViewAssign END (OK)");
}
[Test]
[Category("P1")]
[Description("WebView Dispose.")]
[Property("SPEC", "Tizen.NUI.WebView.Dispose M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("COVPARAM", "")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void WebViewDispose()
{
tlog.Debug(tag, $"WebViewDispose START");
var testingTarget = new MyWebView();
Assert.IsNotNull(testingTarget, "null handle");
Assert.IsInstanceOf<Tizen.NUI.BaseComponents.WebView>(testingTarget, "Should return WebView instance.");
testingTarget.OnDispose(DisposeTypes.Explicit);
//disposed
testingTarget.OnDispose(DisposeTypes.Explicit);
tlog.Debug(tag, $"WebViewDispose END (OK)");
}
private void OnLoadStarted(object sender, WebViewPageLoadEventArgs e) { }
private void OnLoading(object sender, WebViewPageLoadEventArgs e) { }
private void OnLoadFinished(object sender, WebViewPageLoadEventArgs e) { }
private void OnLoadError(object sender, WebViewPageLoadErrorEventArgs e) { }
private void OnEdgeReached(object sender, WebViewScrollEdgeReachedEventArgs e) { }
private void OnUrlChange(object sender, WebViewUrlChangedEventArgs e) { }
private void OnFormRepostPolicyDecide(object sender, WebViewFormRepostPolicyDecidedEventArgs e) { }
private void OnFrameRender(object sender, EventArgs e) { }
private void OnResponsePolicyDecide(object sender, WebViewResponsePolicyDecidedEventArgs e) { }
private void OnCertificateConfirme(object sender, WebViewCertificateReceivedEventArgs e) { }
private void OnSslCertificateChange(object sender, WebViewCertificateReceivedEventArgs e) { }
private void OnHttpAuthRequeste(object sender, WebViewHttpAuthRequestedEventArgs e) { }
private void OnConsoleMessageReceive(object sender, WebViewConsoleMessageReceivedEventArgs e) { }
}
} | 35.033608 | 181 | 0.554017 | [
"Apache-2.0",
"MIT"
] | JSUYA/TizenFX | test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/public/WebView/TSWebView.cs | 59,419 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HraveMzdy.Procezor.Service.Interfaces;
using HraveMzdy.Procezor.Payrolex.Registry.Constants;
namespace HraveMzdy.Procezor.Payrolex.Registry.Providers
{
// PaymentBasis PAYMENT_BASIS
public class PaymentBasisResult : PayrolexTermResult
{
public PaymentBasisResult(ITermTarget target, IArticleSpec spec, Int32 value, Int32 basis) : base(target, spec, value, basis)
{
}
public override string ResultMessage()
{
return $"Value: {this.ResultValue}; Basis: {this.ResultBasis}";
}
}
// PaymentFixed PAYMENT_FIXED
public class PaymentFixedResult : PayrolexTermResult
{
public PaymentFixedResult(ITermTarget target, IArticleSpec spec, Int32 value, Int32 basis) : base(target, spec, value, basis)
{
}
public override string ResultMessage()
{
return $"Value: {this.ResultValue}; Basis: {this.ResultBasis}";
}
}
}
| 30.885714 | 133 | 0.680851 | [
"Unlicense"
] | mzdyhrave/payrollcs | proj/Procezor.Payrolex/Registry.Providers/SalaryResults.cs | 1,083 | C# |
using System;
using System.Data.Common;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using NServiceBus.Transport.SqlServerNative;
public class ConsumingLoop
{
string connectionString = null!;
async Task ConsumeLoop()
{
#region ConsumeLoop
static async Task Callback(
DbTransaction transaction,
IncomingMessage message,
CancellationToken cancellation)
{
if (message.Body != null)
{
using var reader = new StreamReader(message.Body);
var bodyText = await reader.ReadToEndAsync();
Console.WriteLine($"Reply received:\r\n{bodyText}");
}
}
Task<DbTransaction> TransactionBuilder(CancellationToken cancellation)
{
return ConnectionHelpers.BeginTransaction(connectionString, cancellation);
}
static void ErrorCallback(Exception exception)
{
Environment.FailFast("Message consuming loop failed", exception);
}
// start consuming
var consumingLoop = new MessageConsumingLoop(
table: "endpointTable",
delay: TimeSpan.FromSeconds(1),
transactionBuilder: TransactionBuilder,
callback: Callback,
errorCallback: ErrorCallback);
consumingLoop.Start();
// stop consuming
await consumingLoop.Stop();
#endregion
}
} | 27.924528 | 86 | 0.614189 | [
"MIT"
] | gbiellem/NServiceBus.SqlNative | src/SqlServer.Native.Tests/Snippets/Main/ConsumingLoop.cs | 1,482 | C# |
namespace PersonInfo
{
using System;
using System.Collections.Generic;
using System.Text;
public interface IPerson
{
string Name { get; }
int Age { get; }
}
}
| 14.428571 | 37 | 0.584158 | [
"MIT"
] | deedeedextor/Software-University | C#Advanced/C#OOP/InterfacesAndAbstractionsLE/PersonsInfo/IPerson.cs | 204 | C# |
// using System;
// using System.Reflection;
// using System.IO;
// using System.Text;
// readonly struct App
// {
// static Assembly EntryAssembly = typeof(App).Assembly;
// static string[] ResourceNames()
// => EntryAssembly.GetManifestResourceNames();
// static StringBuilder FormatBuffer()
// => new StringBuilder(8*1024);
// static Stream ResourceStream(string name)
// => EntryAssembly.GetManifestResourceStream(name);
// static BinaryReader ResourceReader(Stream src)
// => new BinaryReader(src);
// static byte[] ReadBytes(BinaryReader src, long count)
// => src.ReadBytes((int)count);
// static void Show()
// {
// var names = ResourceNames();
// var buffer = FormatBuffer();
// foreach(var name in names)
// {
// buffer.Clear();
// using var stream = ResourceStream(name);
// using var reader = ResourceReader(stream);
// render(name, ReadBytes(reader, stream.Length), buffer);
// Console.WriteLine(buffer.ToString());
// }
// }
// static void EmitFile(string dst)
// {
// var names = ResourceNames();
// var buffer = FormatBuffer();
// var count = names.Length;
// using var writer = new StreamWriter(dst);
// for(var i=0; i<count; i++)
// {
// var name = names[i];
// buffer.Clear();
// using var stream = ResourceStream(name);
// using var reader = ResourceReader(stream);
// var data = ReadBytes(reader, stream.Length);
// buffer.AppendFormat("{0,-10} | {1,-36} | ", i, name);
// RenderHexText(data,buffer);
// writer.WriteLine(buffer.ToString());
// }
// }
// static void RenderHexText(ReadOnlySpan<byte> src, StringBuilder dst)
// {
// var count = src.Length;
// for(var i=0; i<count; i++)
// dst.Append(string.Format("{0} ", src[i].ToString("x")));
// }
// static void render(string name, ReadOnlySpan<byte> src, StringBuilder dst)
// {
// dst.AppendLine(new string('-',120));
// dst.AppendLine(name);
// var length = src.Length;
// for(var i=0; i<length; i++)
// {
// dst.Append(string.Format("{0} ", src[i].ToString("x")));
// if(i != 0 && i % 80 == 0)
// dst.AppendLine();
// }
// }
// static long Show(string resname)
// {
// using var stream = EntryAssembly.GetManifestResourceStream(resname);
// using var reader = new BinaryReader(stream);
// var length = stream.Length;
// var data = reader.ReadBytes((int)length);
// var target = new StringBuilder(data.Length);
// var j = 0;
// target.AppendLine(resname);
// target.AppendLine(new string('-',120));
// for(var i=0; i<length; i++, j++)
// {
// target.Append(string.Format("{0} ", data[i].ToString("x")));
// if(j != 0 && j % 80 == 0)
// {
// target.AppendLine();
// j = 0;
// }
// }
// Console.WriteLine(target.ToString());
// return length;
// }
// public static int Main(string[] args)
// {
// var path = @"J:\database\tables\indices\bytecode.csv";
// EmitFile(path);
// return 0;
// }
// }
| 31.495495 | 81 | 0.51373 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/respack/app/App.cs | 3,496 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using GF.Common;
using GF.Server;
using Ps;
public class CellConfig
{
//-------------------------------------------------------------------------
SharpConfig.Configuration Cfg { get; set; }
// 全局配置
public int GlobalAFKLevelLimit { get; private set; }// 挂机等级限制
// 新手村配置信息
public int BornSceneId { get; private set; }
public float BornPosMin { get; private set; }
public float BornPosMax { get; private set; }
// 地府配置信息
public int ReviveSceneId { get; private set; }
public float RevivePosMin { get; private set; }
public float RevivePosMax { get; private set; }
// 任务配置信息
public List<int> ListTaskStoryStartTaskId { get; private set; }
//-------------------------------------------------------------------------
public CellConfig()
{
SharpConfig.Configuration.ValidCommentChars = new char[] { '#', ';' };
string cfg_file = ServerPath.getPathMediaRoot() + "Fishing\\Config\\CellConfig.cfg";
Cfg = SharpConfig.Configuration.LoadFromFile(cfg_file);
//Cfg.Save(cfg_file);
//foreach (var section in Cfg)
//{
// EbLog.Note("SectionName=" + section.Name);
// foreach (var setting in section)
// {
// EbLog.Note("SettingName=" + setting.Name);
// }
//}
_parse();
}
//-------------------------------------------------------------------------
void _parse()
{
// 全局配置
var global = Cfg["Global"];
GlobalAFKLevelLimit = global["GlobalAFKLevelLimit"].IntValue;
// 新手村场景配置
var born_scene = Cfg["BornScene"];
BornSceneId = born_scene["BornSceneId"].IntValue;
BornPosMin = (float)born_scene["BornPosMin"].DoubleValue;
BornPosMax = (float)born_scene["BornPosMax"].DoubleValue;
// 地府场景配置
var revive_scene = Cfg["ReviveScene"];
ReviveSceneId = revive_scene["ReviveSceneId"].IntValue;
RevivePosMin = (float)revive_scene["RevivePosMin"].DoubleValue;
RevivePosMax = (float)revive_scene["RevivePosMax"].DoubleValue;
// 任务配置信息
var task = Cfg["Task"];
ListTaskStoryStartTaskId = new List<int>();
string[] tasks = task["ListTaskStoryStartTaskId"].StringValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var i in tasks)
{
ListTaskStoryStartTaskId.Add(int.Parse(i));
}
}
}
| 31.987805 | 135 | 0.566908 | [
"MIT"
] | corefan/Fishing | Server/Fishing.Grain/Main/CellConfig.cs | 2,729 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
namespace aoe3wpfg
{
public class Age3KeyboardFocusBorder : Button
{
public Age3KeyboardFocusBorder()
{
}
}
}
| 16.4 | 49 | 0.678862 | [
"Unlicense"
] | tytannial/AOE3wpfg | aoe3wpfg/controls/Age3KeyboardFocusBorder.cs | 248 | C# |
using Antlr4.Runtime;
using Microsoft.Pc.TypeChecker.Types;
namespace Microsoft.Pc.TypeChecker.AST.Expressions
{
public class MapAccessExpr : IPExpr
{
public MapAccessExpr(ParserRuleContext sourceLocation, IPExpr mapExpr, IPExpr indexExpr, PLanguageType type)
{
SourceLocation = sourceLocation;
MapExpr = mapExpr;
IndexExpr = indexExpr;
Type = type;
}
public IPExpr MapExpr { get; }
public IPExpr IndexExpr { get; }
public ParserRuleContext SourceLocation { get; }
public PLanguageType Type { get; }
}
}
| 27.086957 | 116 | 0.642055 | [
"MIT"
] | cristicmf/P | Src/Pc/Compiler/TypeChecker/AST/Expressions/MapAccessExpr.cs | 623 | C# |
using System;
using Content.Client.Cooldown;
using Content.Client.Items.Managers;
using Content.Client.Stylesheets;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.GameObjects;
using Robust.Shared.Input;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
namespace Content.Client.Items.UI
{
public class ItemSlotButton : Control, IEntityEventSubscriber
{
private const string HighlightShader = "SelectionOutlineInrange";
[Dependency] private readonly IItemSlotManager _itemSlotManager = default!;
public EntityUid Entity { get; set; }
public TextureRect Button { get; }
public SpriteView SpriteView { get; }
public SpriteView HoverSpriteView { get; }
public TextureButton StorageButton { get; }
public CooldownGraphic CooldownDisplay { get; }
public Action<GUIBoundKeyEventArgs>? OnPressed { get; set; }
public Action<GUIBoundKeyEventArgs>? OnStoragePressed { get; set; }
public Action<GUIMouseHoverEventArgs>? OnHover { get; set; }
public bool EntityHover => HoverSpriteView.Sprite != null;
public bool MouseIsHovering;
private readonly PanelContainer _highlightRect;
public string TextureName { get; set; }
public ItemSlotButton(Texture texture, Texture storageTexture, string textureName)
{
IoCManager.InjectDependencies(this);
MinSize = (64, 64);
TextureName = textureName;
AddChild(Button = new TextureRect
{
Texture = texture,
TextureScale = (2, 2),
MouseFilter = MouseFilterMode.Stop
});
AddChild(_highlightRect = new PanelContainer
{
StyleClasses = { StyleNano.StyleClassHandSlotHighlight },
MinSize = (32, 32),
Visible = false
});
Button.OnKeyBindDown += OnButtonPressed;
AddChild(SpriteView = new SpriteView
{
Scale = (2, 2),
OverrideDirection = Direction.South
});
AddChild(HoverSpriteView = new SpriteView
{
Scale = (2, 2),
OverrideDirection = Direction.South
});
AddChild(StorageButton = new TextureButton
{
TextureNormal = storageTexture,
Scale = (0.75f, 0.75f),
HorizontalAlignment = HAlignment.Right,
VerticalAlignment = VAlignment.Bottom,
Visible = false,
});
StorageButton.OnKeyBindDown += args =>
{
if (args.Function != EngineKeyFunctions.UIClick)
{
OnButtonPressed(args);
}
};
StorageButton.OnPressed += OnStorageButtonPressed;
Button.OnMouseEntered += _ =>
{
MouseIsHovering = true;
};
Button.OnMouseEntered += OnButtonHover;
Button.OnMouseExited += _ =>
{
MouseIsHovering = false;
ClearHover();
};
AddChild(CooldownDisplay = new CooldownGraphic
{
Visible = false,
});
}
protected override void EnteredTree()
{
base.EnteredTree();
_itemSlotManager.EntityHighlightedUpdated += HandleEntitySlotHighlighted;
UpdateSlotHighlighted();
}
protected override void ExitedTree()
{
base.ExitedTree();
_itemSlotManager.EntityHighlightedUpdated -= HandleEntitySlotHighlighted;
}
private void HandleEntitySlotHighlighted(EntitySlotHighlightedEventArgs entitySlotHighlightedEventArgs)
{
UpdateSlotHighlighted();
}
public void UpdateSlotHighlighted()
{
Highlight(_itemSlotManager.IsHighlighted(Entity));
}
public void ClearHover()
{
if (EntityHover)
{
ISpriteComponent? tempQualifier = HoverSpriteView.Sprite;
if (tempQualifier != null)
{
IoCManager.Resolve<IEntityManager>().DeleteEntity(tempQualifier.Owner);
}
HoverSpriteView.Sprite = null;
}
}
public virtual void Highlight(bool highlight)
{
if (highlight)
{
_highlightRect.Visible = true;
}
else
{
_highlightRect.Visible = false;
}
}
private void OnButtonPressed(GUIBoundKeyEventArgs args)
{
OnPressed?.Invoke(args);
}
private void OnStorageButtonPressed(BaseButton.ButtonEventArgs args)
{
if (args.Event.Function == EngineKeyFunctions.UIClick)
{
OnStoragePressed?.Invoke(args.Event);
}
else
{
OnPressed?.Invoke(args.Event);
}
}
private void OnButtonHover(GUIMouseHoverEventArgs args)
{
OnHover?.Invoke(args);
}
}
}
| 28.967914 | 111 | 0.554366 | [
"MIT"
] | A-Box-12/space-station-14 | Content.Client/Items/UI/ItemSlotButton.cs | 5,419 | C# |
/*
* Copyright 2020 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using NewRelic.Api.Agent;
namespace AspNetCoreMvcAsyncApplication
{
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
[Trace]
public async Task Invoke(HttpContext context)
{
await MiddlewareMethodAsync();
await _next(context);
}
[Trace]
[MethodImpl(MethodImplOptions.NoInlining)]
private async Task MiddlewareMethodAsync()
{
await Task.Delay(1);
}
}
}
| 22 | 60 | 0.635135 | [
"Apache-2.0"
] | Faithlife/newrelic-dotnet-agent | tests/Agent/IntegrationTests/Applications/AspNetCoreMvcAsyncApplication/CustomMiddleware.cs | 814 | C# |
using CleanArchitecture.Core.Entities;
using CleanArchitecture.Core.Interfaces;
using System.Linq;
namespace CleanArchitecture.Core
{
public static class DatabasePopulator
{
public static int PopulateDatabase(IRepository todoRepository)
{
if (todoRepository.List<ToDoItem>().Count() >= 5) return 0;
todoRepository.Add(new ToDoItem
{
Title = "Get Sample Working",
Description = "Try to get the sample to build."
});
todoRepository.Add(new ToDoItem
{
Title = "Review Solution",
Description = "Review the different projects in the solution and how they relate to one another."
});
todoRepository.Add(new ToDoItem
{
Title = "Run and Review Tests",
Description = "Make sure all the tests run and review what they are doing."
});
return todoRepository.List<ToDoItem>().Count;
}
}
}
| 31.636364 | 113 | 0.574713 | [
"MIT"
] | C0d3Freek/CleanArchitecture | src/CleanArchitecture.Core/DatabasePopulator.cs | 1,046 | C# |
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace BackgroundTask
{
public class BackgroundPrinter : IHostedService
{
private readonly ILogger<BackgroundPrinter> logger;
private readonly IWorker worker;
public BackgroundPrinter(ILogger<BackgroundPrinter> logger, IWorker worker)
{
this.logger = logger;
this.worker = worker;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await worker.DoWork(cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
| 25.333333 | 83 | 0.67823 | [
"MIT"
] | dmb-dev87/asp.net-tutorial | BackgroundTask/BackgroundTask/BackgroundPrinter.cs | 838 | C# |
using Chloe.Descriptors;
using Chloe.Exceptions;
using Chloe.Infrastructure;
using Chloe.Mapper;
using Chloe.Mapper.Activators;
using Chloe.Mapper.Binders;
using Chloe.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Chloe.Query.Mapping
{
public class ComplexObjectActivatorCreator : IObjectActivatorCreator
{
public ComplexObjectActivatorCreator(ConstructorDescriptor constructorDescriptor)
{
this.ConstructorDescriptor = constructorDescriptor;
this.ConstructorParameters = new Dictionary<ParameterInfo, int>();
this.ConstructorComplexParameters = new Dictionary<ParameterInfo, IObjectActivatorCreator>();
this.PrimitiveMembers = new Dictionary<MemberInfo, int>();
this.ComplexMembers = new Dictionary<MemberInfo, IObjectActivatorCreator>();
this.CollectionMembers = new Dictionary<MemberInfo, IObjectActivatorCreator>();
}
public Type ObjectType { get { return this.ConstructorDescriptor.ConstructorInfo.DeclaringType; } }
public bool IsRoot { get; set; }
public int? CheckNullOrdinal { get; set; }
public ConstructorDescriptor ConstructorDescriptor { get; private set; }
public Dictionary<ParameterInfo, int> ConstructorParameters { get; private set; }
public Dictionary<ParameterInfo, IObjectActivatorCreator> ConstructorComplexParameters { get; private set; }
/// <summary>
/// 映射成员集合。以 MemberInfo 为 key,读取 DataReader 时的 Ordinal 为 value
/// </summary>
public Dictionary<MemberInfo, int> PrimitiveMembers { get; private set; }
/// <summary>
/// 复杂类型成员集合。
/// </summary>
public Dictionary<MemberInfo, IObjectActivatorCreator> ComplexMembers { get; private set; }
public Dictionary<MemberInfo, IObjectActivatorCreator> CollectionMembers { get; private set; }
public IObjectActivator CreateObjectActivator()
{
return this.CreateObjectActivator(null);
}
public IObjectActivator CreateObjectActivator(IDbContext dbContext)
{
InstanceCreator instanceCreator = this.ConstructorDescriptor.GetInstanceCreator();
List<IObjectActivator> argumentActivators = this.CreateArgumentActivators(dbContext);
List<IMemberBinder> memberBinders = this.CreateMemberBinders(dbContext);
IObjectActivator objectActivator;
if (dbContext != null)
objectActivator = new ObjectActivatorWithTracking(instanceCreator, argumentActivators, memberBinders, this.CheckNullOrdinal, dbContext);
else
objectActivator = new ComplexObjectActivator(instanceCreator, argumentActivators, memberBinders, this.CheckNullOrdinal);
if (this.IsRoot && this.HasMany())
{
TypeDescriptor entityTypeDescriptor = EntityTypeContainer.GetDescriptor(this.ObjectType);
List<Tuple<PropertyDescriptor, int>> keys = new List<Tuple<PropertyDescriptor, int>>(entityTypeDescriptor.PrimaryKeys.Count);
foreach (PrimitivePropertyDescriptor primaryKey in entityTypeDescriptor.PrimaryKeys)
{
keys.Add(new Tuple<PropertyDescriptor, int>(primaryKey, this.PrimitiveMembers[primaryKey.Definition.Property]));
}
IEntityRowComparer entityRowComparer = new EntityRowComparer(keys);
objectActivator = new RootEntityActivator(objectActivator, this.CreateFitter(dbContext), entityRowComparer);
}
return objectActivator;
}
List<IMemberBinder> CreateMemberBinders(IDbContext dbContext)
{
ObjectMemberMapper mapper = this.ConstructorDescriptor.GetEntityMemberMapper();
List<IMemberBinder> memberBinders = new List<IMemberBinder>(this.PrimitiveMembers.Count + this.ComplexMembers.Count + this.CollectionMembers.Count);
foreach (var kv in this.PrimitiveMembers)
{
MRMTuple mrmTuple = mapper.GetMappingMemberMapper(kv.Key);
PrimitiveMemberBinder binder = new PrimitiveMemberBinder(kv.Key, mrmTuple, kv.Value);
memberBinders.Add(binder);
}
foreach (var kv in this.ComplexMembers)
{
MemberValueSetter setter = mapper.GetMemberSetter(kv.Key);
IObjectActivator memberActivtor = kv.Value.CreateObjectActivator(dbContext);
ComplexMemberBinder binder = new ComplexMemberBinder(setter, memberActivtor);
memberBinders.Add(binder);
}
foreach (var kv in this.CollectionMembers)
{
MemberValueSetter setter = mapper.GetMemberSetter(kv.Key);
IObjectActivator memberActivtor = kv.Value.CreateObjectActivator(dbContext);
CollectionMemberBinder binder = new CollectionMemberBinder(setter, memberActivtor);
memberBinders.Add(binder);
}
return memberBinders;
}
List<IObjectActivator> CreateArgumentActivators(IDbContext dbContext)
{
ParameterInfo[] parameters = this.ConstructorDescriptor.ConstructorInfo.GetParameters();
List<IObjectActivator> argumentActivators = new List<IObjectActivator>(parameters.Length);
for (int i = 0; i < parameters.Length; i++)
{
IObjectActivator argumentActivator = null;
ParameterInfo parameter = parameters[i];
if (this.ConstructorParameters.TryGetValue(parameter, out int ordinal))
{
argumentActivator = new PrimitiveObjectActivator(parameter.ParameterType, ordinal);
}
else if (this.ConstructorComplexParameters.TryGetValue(parameter, out IObjectActivatorCreator argumentActivatorCreator))
{
argumentActivator = argumentActivatorCreator.CreateObjectActivator(dbContext);
}
else
{
throw new UnbelievableException();
}
argumentActivators.Add(argumentActivator);
}
return argumentActivators;
}
public IFitter CreateFitter(IDbContext dbContext)
{
List<Tuple<PropertyDescriptor, IFitter>> includings = new List<Tuple<PropertyDescriptor, IFitter>>();
TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(this.ConstructorDescriptor.ConstructorInfo.DeclaringType);
foreach (var item in this.ComplexMembers.Concat(this.CollectionMembers))
{
IFitter propFitter = item.Value.CreateFitter(dbContext);
includings.Add(new Tuple<PropertyDescriptor, IFitter>(typeDescriptor.GetPropertyDescriptor(item.Key), propFitter));
}
ComplexObjectFitter fitter = new ComplexObjectFitter(includings);
return fitter;
}
public bool HasMany()
{
if (this.CollectionMembers.Count > 0)
return true;
foreach (var kv in this.ComplexMembers)
{
ComplexObjectActivatorCreator activatorCreator = kv.Value as ComplexObjectActivatorCreator;
if (activatorCreator.HasMany())
return true;
}
return false;
}
}
}
| 45.793939 | 160 | 0.65577 | [
"MIT"
] | johnnyleecn/Chloe | src/Chloe/Query/Mapping/ComplexObjectActivatorCreator.cs | 7,606 | C# |
using System;
using System.Collections.Generic;
namespace ServiceStack.CacheAccess
{
/// <summary>
/// A common interface implementation that is implemented by most cache providers
/// </summary>
public interface ICacheClient
: IDisposable
{
/// <summary>
/// Removes the specified item from the cache.
/// </summary>
/// <param name="key">The identifier for the item to delete.</param>
/// <returns>
/// true if the item was successfully removed from the cache; false otherwise.
/// </returns>
bool Remove(string key);
/// <summary>
/// Removes the cache for all the keys provided.
/// </summary>
/// <param name="keys">The keys.</param>
void RemoveAll(IEnumerable<string> keys);
/// <summary>
/// Retrieves the specified item from the cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The identifier for the item to retrieve.</param>
/// <returns>
/// The retrieved item, or <value>null</value> if the key was not found.
/// </returns>
T Get<T>(string key);
/// <summary>
/// Increments the value of the specified key by the given amount.
/// The operation is atomic and happens on the server.
/// A non existent value at key starts at 0
/// </summary>
/// <param name="key">The identifier for the item to increment.</param>
/// <param name="amount">The amount by which the client wants to increase the item.</param>
/// <returns>
/// The new value of the item or -1 if not found.
/// </returns>
/// <remarks>The item must be inserted into the cache before it can be changed. The item must be inserted as a <see cref="T:System.String"/>. The operation only works with <see cref="System.UInt32"/> values, so -1 always indicates that the item was not found.</remarks>
long Increment(string key, uint amount);
/// <summary>
/// Increments the value of the specified key by the given amount.
/// The operation is atomic and happens on the server.
/// A non existent value at key starts at 0
/// </summary>
/// <param name="key">The identifier for the item to increment.</param>
/// <param name="amount">The amount by which the client wants to decrease the item.</param>
/// <returns>
/// The new value of the item or -1 if not found.
/// </returns>
/// <remarks>The item must be inserted into the cache before it can be changed. The item must be inserted as a <see cref="T:System.String"/>. The operation only works with <see cref="System.UInt32"/> values, so -1 always indicates that the item was not found.</remarks>
long Decrement(string key, uint amount);
/// <summary>
/// Adds a new item into the cache at the specified cache key only if the cache is empty.
/// </summary>
/// <param name="key">The key used to reference the item.</param>
/// <param name="value">The object to be inserted into the cache.</param>
/// <returns>
/// true if the item was successfully stored in the cache; false otherwise.
/// </returns>
/// <remarks>The item does not expire unless it is removed due memory pressure.</remarks>
bool Add<T>(string key, T value);
/// <summary>
/// Sets an item into the cache at the cache key specified regardless if it already exists or not.
/// </summary>
bool Set<T>(string key, T value);
/// <summary>
/// Replaces the item at the cachekey specified only if an items exists at the location already.
/// </summary>
bool Replace<T>(string key, T value);
bool Add<T>(string key, T value, DateTime expiresAt);
bool Set<T>(string key, T value, DateTime expiresAt);
bool Replace<T>(string key, T value, DateTime expiresAt);
bool Add<T>(string key, T value, TimeSpan expiresIn);
bool Set<T>(string key, T value, TimeSpan expiresIn);
bool Replace<T>(string key, T value, TimeSpan expiresIn);
/// <summary>
/// Invalidates all data on the cache.
/// </summary>
void FlushAll();
/// <summary>
/// Retrieves multiple items from the cache.
/// The default value of T is set for all keys that do not exist.
/// </summary>
/// <param name="keys">The list of identifiers for the items to retrieve.</param>
/// <returns>
/// a Dictionary holding all items indexed by their key.
/// </returns>
IDictionary<string, T> GetAll<T>(IEnumerable<string> keys);
/// <summary>
/// Sets multiple items to the cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="values">The values.</param>
void SetAll<T>(IDictionary<string, T> values);
}
}
| 40.06087 | 272 | 0.655958 | [
"BSD-3-Clause"
] | GSerjo/ServiceStack | src/ServiceStack.Interfaces/CacheAccess/ICacheClient.cs | 4,493 | C# |
/*
* Copyright (c) 2018 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace Algolia.Search.Models.Common
{
/// <summary>
/// Api's copy to response
/// </summary>
public class CopyToResponse : IndexingResponse
{
/// <summary>
/// Date of update
/// </summary>
public DateTime UpdatedAt { get; set; }
}
}
| 36.615385 | 79 | 0.72619 | [
"MIT"
] | DrLeh/algoliasearch-client-csharp | src/Algolia.Search/Models/Common/CopyToResponse.cs | 1,428 | C# |
using System.Threading;
using System.Threading.Tasks;
using Audiochan.API.Extensions;
using Audiochan.API.Models;
using Audiochan.Core.Extensions;
using Audiochan.Core.Services;
using Audiochan.Core.Users.Commands;
using Audiochan.Core.Users.Queries;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
namespace Audiochan.API.Controllers.Me
{
[Area("me")]
[Authorize]
[Route("[area]/favorites/audios")]
[ProducesResponseType(401)]
public class FavoriteAudiosController : ControllerBase
{
private readonly IMediator _mediator;
private readonly long _currentUserId;
private readonly string _currentUsername;
public FavoriteAudiosController(ICurrentUserService currentUserService, IMediator mediator)
{
_mediator = mediator;
currentUserService.User.TryGetUserId(out _currentUserId);
currentUserService.User.TryGetUserName(out _currentUsername);
}
[HttpGet(Name = "YourFavoriteAudios")]
[SwaggerOperation(
Summary = "Get Your favorite audios",
Description = "Requires authentication.",
OperationId = "YourFavoriteAudios",
Tags = new[] {"me"}
)]
public async Task<IActionResult> GetYourFavoriteAudios([FromQuery] OffsetPaginationQueryParams queryParams,
CancellationToken cancellationToken = default)
{
var query = new GetUserFavoriteAudiosQuery
{
Username = _currentUsername,
Offset = queryParams.Offset,
Size = queryParams.Size
};
var result = await _mediator.Send(query, cancellationToken);
return Ok(result);
}
[HttpHead("{audioId:long}", Name="CheckIfUserFavoritedAudio")]
[SwaggerOperation(
Summary = "Check if the authenticated user favorited an audio",
Description = "Requires authentication.",
OperationId = "CheckIfUserFavoritedAudio",
Tags = new[] {"me"}
)]
public async Task<IActionResult> IsFavoriteAudio(long audioId, CancellationToken cancellationToken)
{
var command = new CheckIfAudioFavoritedQuery(audioId, _currentUserId);
return await _mediator.Send(command, cancellationToken)
? Ok()
: NotFound();
}
[HttpPut("{audioId:long}", Name = "FavoriteAudio")]
[SwaggerOperation(
Summary = "Favorite an audio",
Description = "Requires authentication.",
OperationId = "FavoriteAudio",
Tags = new[] {"me"}
)]
public async Task<IActionResult> FavoriteAudio(long audioId, CancellationToken cancellationToken)
{
var command = new SetFavoriteAudioCommand(audioId, _currentUserId, true);
var result = await _mediator.Send(command, cancellationToken);
return result.IsSuccess
? Ok()
: result.ReturnErrorResponse();
}
[HttpDelete("{audioId:long}", Name = "UnFavoriteAudio")]
[SwaggerOperation(
Summary = "UnFavorite an audio",
Description = "Requires authentication.",
OperationId = "UnFavoriteAudio",
Tags = new[] {"me"}
)]
public async Task<IActionResult> UnFavoriteAudio(long audioId, CancellationToken cancellationToken)
{
var command = new SetFavoriteAudioCommand(audioId, _currentUserId, false);
var result = await _mediator.Send(command, cancellationToken);
return result.IsSuccess
? NoContent()
: result.ReturnErrorResponse();
}
}
} | 38.19802 | 115 | 0.625194 | [
"MIT"
] | nollidnosnhoj/Audiochan_old | src/api/src/Audiochan.API/Controllers/Me/FavoriteAudiosController.cs | 3,860 | C# |
// MIT License
// Original work Copyright (c) 2019 InnoGames GmbH
//
// 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.
//
// https://github.com/innogames/ProjectWindowDetails
// Modified for ONI, Copyright (c) Nathan MacAdam, All rights reserved.
// MIT License (See LICENSE file)
using UnityEngine;
namespace Oni.Editor
{
public class GuidDetail : ProjectWindowDetailBase
{
public GuidDetail()
{
Name = "Guid";
ColumnWidth = 230;
}
public override string GetLabel(string guid, string assetPath, Object asset)
{
return guid;
}
}
} | 45.472222 | 177 | 0.724496 | [
"MIT"
] | nmacadam/Oni | Editor/Tools & Windows/Project Window Extensions/GuidDetail.cs | 1,637 | C# |
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
namespace Roslynator
{
/// <summary>
/// Represents consecutive sequence of selected items in a collection.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ISelection<T> : IReadOnlyList<T>
{
/// <summary>
/// Gets an index of the first selected item.
/// </summary>
int FirstIndex { get; }
/// <summary>
/// Gets an index of the last selected item.
/// </summary>
int LastIndex { get; }
/// <summary>
/// Gets the first selected item.
/// </summary>
T First();
/// <summary>
/// Gets the last selected item.
/// </summary>
T Last();
}
}
| 26.764706 | 156 | 0.565934 | [
"Apache-2.0"
] | ProphetLamb-Organistion/Roslynator | src/Core/ISelection`1.cs | 912 | 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 elasticbeanstalk-2010-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.ElasticBeanstalk.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations
{
/// <summary>
/// CreateApplication Request Marshaller
/// </summary>
public class CreateApplicationRequestMarshaller : IMarshaller<IRequest, CreateApplicationRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((CreateApplicationRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(CreateApplicationRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.ElasticBeanstalk");
request.Parameters.Add("Action", "CreateApplication");
request.Parameters.Add("Version", "2010-12-01");
if(publicRequest != null)
{
if(publicRequest.IsSetApplicationName())
{
request.Parameters.Add("ApplicationName", StringUtils.FromString(publicRequest.ApplicationName));
}
if(publicRequest.IsSetDescription())
{
request.Parameters.Add("Description", StringUtils.FromString(publicRequest.Description));
}
}
return request;
}
}
} | 36.972603 | 149 | 0.655798 | [
"Apache-2.0"
] | SaschaHaertel/AmazonAWS | sdk/src/Services/ElasticBeanstalk/Generated/Model/Internal/MarshallTransformations/CreateApplicationRequestMarshaller.cs | 2,699 | C# |
using System;
namespace CoCSharp.Network.Cryptography
{
/// <summary>
/// Implements method to encrypt or decrypt network traffic of the Clash of Clan protocol
/// version 7.x.x. This was ported from Clash of Clans Documentation Project(https://github.com/clanner/cocdp/blob/master/cocutils.py)
/// by clanner to C#. :]
/// </summary>
public class Crypto7 : CoCCrypto
{
private const string InitialKey = "fhsd6f86f67rt8fw78fw789we78r9789wer6re";
private const string InitialNonce = "nonce";
/// <summary>
/// Initializes a new instance of the <see cref="Crypto7"/> class with
/// the default key and nonce.
/// </summary>
public Crypto7()
{
InitializeCiphers(InitialKey + InitialNonce);
}
/// <summary>
/// Initializes a new instance of the <see cref="Crypto7"/> class with
/// the specified key.
/// </summary>
/// <param name="key"></param>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
public Crypto7(string key)
{
if (key == null)
throw new ArgumentNullException("key");
InitializeCiphers(key);
}
/// <summary>
/// Gets the version of the <see cref="CoCCrypto"/>.
/// </summary>
public override int Version
{
get
{
return 7;
}
}
private RC4 Encryptor { get; set; }
private RC4 Decryptor { get; set; }
/// <summary>
/// Encrypts the provided bytes(plain-text).
/// </summary>
/// <param name="data">Bytes to encrypt.</param>
/// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
public override void Encrypt(ref byte[] data)
{
if (data == null)
throw new ArgumentNullException("data");
for (int k = 0; k < data.Length; k++)
data[k] ^= Encryptor.PRGA();
}
/// <summary>
/// Decrypts the provided bytes(cipher-text).
/// </summary>
/// <param name="data">Bytes to decrypt.</param>
/// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
public override void Decrypt(ref byte[] data)
{
if (data == null)
throw new ArgumentNullException("data");
for (int k = 0; k < data.Length; k++)
data[k] ^= Decryptor.PRGA();
}
/// <summary>
/// Update the key with the specified client seed and server nonce.
/// </summary>
/// <param name="clientSeed">Client seed.</param>
/// <param name="serverNonce">Server random nonce.</param>
/// <exception cref="ArgumentNullException"><paramref name="serverNonce"/> is null.</exception>
public void UpdateCiphers(int clientSeed, byte[] serverNonce)
{
if (serverNonce == null)
throw new ArgumentNullException("serverNonce");
var newNonce = ScrambleNonce((ulong)clientSeed, serverNonce);
var key = InitialKey + newNonce;
InitializeCiphers(key);
}
/// <summary>
/// Generates a random byte array of random length between 15 and 25 bytes long.
/// </summary>
/// <returns>The random byte array.</returns>
public static byte[] GenerateNonce()
{
var buffer = new byte[InternalUtils.Random.Next(15, 25)];
InternalUtils.Random.NextBytes(buffer);
return buffer;
}
/// <summary>
/// Initializes the ciphers with the specified key.
/// </summary>
/// <param name="key">The key used to update the cipher.</param>
private void InitializeCiphers(string key)
{
Encryptor = new RC4(key);
Decryptor = new RC4(key);
for (int k = 0; k < key.Length; k++)
{
// skip bytes
Encryptor.PRGA();
Decryptor.PRGA();
}
}
private static string ScrambleNonce(ulong clientSeed, byte[] serverNonce)
{
var scrambler = new Scrambler(clientSeed);
var byte100 = 0;
for (int i = 0; i < 100; i++)
byte100 = scrambler.GetByte();
var scrambled = string.Empty;
for (int i = 0; i < serverNonce.Length; i++)
scrambled += (char)(serverNonce[i] ^ (scrambler.GetByte() & byte100));
return scrambled;
}
private class RC4
{
public RC4(byte[] key)
{
Key = KSA(key);
}
public RC4(string key)
{
Key = KSA(StringToByteArray(key));
}
public byte[] Key { get; set; } // "S"
private byte i { get; set; }
private byte j { get; set; }
public byte PRGA()
{
/* Pseudo-Random Generation Algorithm
*
* The returned value should be XORed with
* the data to encrypt or decrypt it.
*/
var temp = (byte)0;
i = (byte)((i + 1) % 256);
j = (byte)((j + Key[i]) % 256);
// swap S[i] and S[j];
temp = Key[i];
Key[i] = Key[j];
Key[j] = temp;
return Key[(Key[i] + Key[j]) % 256]; // value to XOR with data
}
private static byte[] KSA(byte[] key)
{
/* Key-Scheduling Algorithm
*
* Used to initialize key array.
*/
var keyLength = key.Length;
var S = new byte[256];
for (int i = 0; i != 256; i++) S[i] = (byte)i;
var j = (byte)0;
var temp = (byte)0;
for (int i = 0; i != 256; i++)
{
j = (byte)((j + S[i] + key[i % keyLength]) % 256); // meth is working
// swap S[i] and S[j];
temp = S[i];
S[i] = S[j];
S[j] = temp;
}
return S;
}
private static byte[] StringToByteArray(string str)
{
var bytes = new byte[str.Length];
for (int i = 0; i < str.Length; i++) bytes[i] = (byte)str[i];
return bytes;
}
}
private class Scrambler
{
public Scrambler(ulong seed)
{
IX = 0;
Buffer = SeedBuffer(seed);
}
public int IX { get; set; }
public ulong[] Buffer { get; set; }
private static ulong[] SeedBuffer(ulong seed)
{
var buffer = new ulong[624];
for (int i = 0; i < 624; i++)
{
buffer[i] = seed;
seed = (1812433253 * ((seed ^ RShift(seed, 30)) + 1)) & 0xFFFFFFFF;
}
return buffer;
}
public int GetByte()
{
var x = (ulong)GetInt();
if (IsNeg(x)) x = Negate(x);
return (int)(x % 256);
}
private int GetInt()
{
if (IX == 0) MixBuffer();
var val = Buffer[IX];
IX = (IX + 1) % 624;
val ^= RShift(val, 11) ^ LShift((val ^ RShift(val, 11)), 7) & 0x9D2C5680;
return (int)(RShift((val ^ LShift(val, 15L) & 0xEFC60000), 18L) ^ val ^ LShift(val, 15L) & 0xEFC60000);
}
private void MixBuffer()
{
var i = 0;
var j = 0;
while (i < 624)
{
i += 1;
var v4 = (Buffer[i % 624] & 0x7FFFFFFF) + (Buffer[j] & 0x80000000);
var v6 = RShift(v4, 1) ^ Buffer[(i + 396) % 624];
if ((v4 & 1) != 0) v6 ^= 0x9908B0DF;
Buffer[j] = v6;
j += 1;
}
}
private static ulong RShift(ulong num, ulong n)
{
var highbits = (ulong)0;
if ((num & Pow(2, 31)) != 0) highbits = (Pow(2, n) - 1) * Pow(2, 32 - n);
return (num / Pow(2, n)) | highbits;
}
private static ulong LShift(ulong num, ulong n)
{
return (num * Pow(2, n)) % Pow(2, 32);
}
private static bool IsNeg(ulong num)
{
return (num & (ulong)Math.Pow(2, 31)) != 0;
}
private static ulong Negate(ulong num)
{
return (~num) + 1;
}
private static ulong Pow(ulong x, ulong y)
{
return (ulong)Math.Pow(x, y);
}
}
}
}
| 31.770548 | 138 | 0.448421 | [
"MIT"
] | FICTURE7/CoCSharp | src/CoCSharp/Network/Cryptography/Crypto7.cs | 9,279 | C# |
////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Philippe Leefsma 2012 - ADN/Developer Technical Services
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace ListViewEmbeddedControls
{
public class ListViewEx : ListView
{
#region Interop-Defines
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wPar, IntPtr lPar);
// ListView messages
private const int LVM_FIRST = 0x1000;
private const int LVM_GETCOLUMNORDERARRAY = (LVM_FIRST + 59);
// Windows Messages
private const int WM_PAINT = 0x000F;
#endregion
/// <summary>
/// Structure to hold an embedded control's info
/// </summary>
private struct EmbeddedControl
{
public Control Control;
public int Column;
public int Row;
public DockStyle Dock;
public ListViewItem Item;
}
private ArrayList _embeddedControls = new ArrayList();
public ListViewEx() {}
/// <summary>
/// Retrieve the order in which columns appear
/// </summary>
/// <returns>Current display order of column indices</returns>
protected int[] GetColumnOrder()
{
IntPtr lPar = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Columns.Count);
IntPtr res = SendMessage(Handle, LVM_GETCOLUMNORDERARRAY, new IntPtr(Columns.Count), lPar);
if (res.ToInt32() == 0) // Something went wrong
{
Marshal.FreeHGlobal(lPar);
return null;
}
int [] order = new int[Columns.Count];
Marshal.Copy(lPar, order, 0, Columns.Count);
Marshal.FreeHGlobal(lPar);
return order;
}
/// <summary>
/// Retrieve the bounds of a ListViewSubItem
/// </summary>
/// <param name="Item">The Item containing the SubItem</param>
/// <param name="SubItem">Index of the SubItem</param>
/// <returns>Subitem's bounds</returns>
protected Rectangle GetSubItemBounds(ListViewItem Item, int SubItem)
{
Rectangle subItemRect = Rectangle.Empty;
if (Item == null)
throw new ArgumentNullException("Item");
int[] order = GetColumnOrder();
if (order == null) // No Columns
return subItemRect;
if (SubItem >= order.Length)
throw new IndexOutOfRangeException("SubItem "+SubItem+" out of range");
// Retrieve the bounds of the entire ListViewItem (all subitems)
Rectangle lviBounds = Item.GetBounds(ItemBoundsPortion.Entire);
int subItemX = lviBounds.Left;
// Calculate the X position of the SubItem.
// Because the columns can be reordered we have to use Columns[order[i]] instead of Columns[i] !
ColumnHeader col;
int i;
for (i=0; i<order.Length; i++)
{
col = this.Columns[order[i]];
if (col.Index == SubItem)
break;
subItemX += col.Width;
}
subItemRect = new Rectangle(subItemX, lviBounds.Top, this.Columns[order[i]].Width, lviBounds.Height);
return subItemRect;
}
/// <summary>
/// Add a control to the ListView
/// </summary>
/// <param name="c">Control to be added</param>
/// <param name="col">Index of column</param>
/// <param name="row">Index of row</param>
public void AddEmbeddedControl(Control c, int col, int row)
{
AddEmbeddedControl(c,col,row,DockStyle.Fill);
}
/// <summary>
/// Add a control to the ListView
/// </summary>
/// <param name="c">Control to be added</param>
/// <param name="col">Index of column</param>
/// <param name="row">Index of row</param>
/// <param name="dock">Location and resize behavior of embedded control</param>
public void AddEmbeddedControl(Control c, int col, int row, DockStyle dock)
{
if (c==null)
throw new ArgumentNullException();
if (col>=Columns.Count || row>=Items.Count)
throw new ArgumentOutOfRangeException();
EmbeddedControl ec;
ec.Control = c;
ec.Column = col;
ec.Row = row;
ec.Dock = dock;
ec.Item = Items[row];
_embeddedControls.Add(ec);
// Add a Click event handler to select the ListView row when an embedded control is clicked
c.Click += new EventHandler(_embeddedControl_Click);
this.Controls.Add(c);
}
/// <summary>
/// Remove a control from the ListView
/// </summary>
/// <param name="c">Control to be removed</param>
public void RemoveEmbeddedControl(Control c)
{
if (c == null)
throw new ArgumentNullException();
for (int i=0; i<_embeddedControls.Count; i++)
{
EmbeddedControl ec = (EmbeddedControl)_embeddedControls[i];
if (ec.Control == c)
{
c.Click -= new EventHandler(_embeddedControl_Click);
this.Controls.Remove(c);
_embeddedControls.RemoveAt(i);
return;
}
}
throw new Exception("Control not found!");
}
/// <summary>
/// Retrieve the control embedded at a given location
/// </summary>
/// <param name="col">Index of Column</param>
/// <param name="row">Index of Row</param>
/// <returns>Control found at given location or null if none assigned.</returns>
public Control GetEmbeddedControl(int col, int row)
{
foreach (EmbeddedControl ec in _embeddedControls)
if (ec.Row == row && ec.Column == col)
return ec.Control;
return null;
}
[DefaultValue(View.LargeIcon)]
public new View View
{
get
{
return base.View;
}
set
{
// Embedded controls are rendered only when we're in Details mode
foreach (EmbeddedControl ec in _embeddedControls)
ec.Control.Visible = (value == View.Details);
base.View = value;
}
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_PAINT:
if (View != View.Details)
break;
if (this.View == View.Details && this.Columns.Count > 0)
this.Columns[this.Columns.Count - 1].Width = -2;
// Calculate the position of all embedded controls
foreach (EmbeddedControl ec in _embeddedControls)
{
Rectangle rc = this.GetSubItemBounds(ec.Item, ec.Column);
if ((this.HeaderStyle != ColumnHeaderStyle.None) &&
(rc.Top<this.Font.Height)) // Control overlaps ColumnHeader
{
ec.Control.Visible = false;
continue;
}
else
{
ec.Control.Visible = true;
}
switch (ec.Dock)
{
case DockStyle.Fill:
break;
case DockStyle.Top:
rc.Height = ec.Control.Height;
break;
case DockStyle.Left:
rc.Width = ec.Control.Width;
break;
case DockStyle.Bottom:
rc.Offset(0, rc.Height-ec.Control.Height);
rc.Height = ec.Control.Height;
break;
case DockStyle.Right:
rc.Offset(rc.Width-ec.Control.Width, 0);
rc.Width = ec.Control.Width;
break;
case DockStyle.None:
rc.Size = ec.Control.Size;
break;
}
// Set embedded control's bounds
ec.Control.Bounds = rc;
}
break;
}
base.WndProc (ref m);
}
private void _embeddedControl_Click(object sender, EventArgs e)
{
// When a control is clicked the ListViewItem holding it is selected
foreach (EmbeddedControl ec in _embeddedControls)
{
if (ec.Control == (Control)sender)
{
this.SelectedItems.Clear();
ec.Item.Selected = true;
}
}
}
}
}
| 28.174216 | 104 | 0.645808 | [
"MIT"
] | ADN-DevTech/MaterialProfiler | MaterialProfiler/ListViewEx.cs | 8,086 | C# |
namespace Facebook.ApiClient.Entities.Enumerations
{
/// <summary>
/// The effective status of the ad set, which can be either its own status or caused by its parent campaign.
/// </summary>
public enum AdsetEffectiveStatus
{
/// <summary>
/// ACTIVE
/// </summary>
ACTIVE,
/// <summary>
/// PAUSED
/// </summary>
PAUSED,
/// <summary>
/// DELETED
/// </summary>
DELETED,
/// <summary>
/// PENDING_REVIEW
/// </summary>
PENDING_REVIEW,
/// <summary>
/// DISAPPROVED
/// </summary>
DISAPPROVED,
/// <summary>
/// PREAPPROVED
/// </summary>
PREAPPROVED,
/// <summary>
/// PENDING_BILLING_INFO
/// </summary>
PENDING_BILLING_INFO,
/// <summary>
/// CAMPAIGN_PAUSED
/// </summary>
CAMPAIGN_PAUSED,
/// <summary>
/// ARCHIVED
/// </summary>
ARCHIVED,
/// <summary>
/// ADSET_PAUSED
/// </summary>
ADSET_PAUSED,
}
}
| 19.114754 | 112 | 0.457118 | [
"MIT"
] | ketanjawahire/FacebookClient.Entities | Facebook.ApiClient.Entities/Enumerations/AdsetEffectiveStatus.cs | 1,168 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace EquationSolver
{
public class ExceptionEventArgs: EventArgs
{
public Exception Exception { get; set; }
public ExceptionEventArgs(Exception ex)
{
Exception = ex;
}
}
}
| 17.823529 | 48 | 0.633663 | [
"MIT"
] | JeffBramlett/EquationSolvr | EquationSolver/EquationSolver/ExceptionEventArgs.cs | 305 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
namespace Test
{
using System;
class AA
{
static int Main()
{
bool b = true;
do
{
try
{
b = true;
do
{
while (b)
return 100;
} while (b);
}
catch (Exception) { }
do
{
long local4 = 32L;
do { } while (checked(38L >= local4));
} while (b);
} while (b);
return -1;
}
}
}
| 22.055556 | 71 | 0.329975 | [
"MIT"
] | belav/runtime | src/tests/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b48864/b48864.cs | 794 | 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 UiPath.Web.Client202010
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Account.
/// </summary>
public static partial class AccountExtensions
{
/// <summary>
/// Authenticates the user based on user name and password
/// </summary>
/// <remarks>
/// Authenticates the user based on user name and password.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// The login parameters.
/// </param>
[System.Obsolete("This operation is deprecated. Please do not use it any longer.")]
public static AjaxResponse Authenticate(this IAccount operations, LoginModel body = default(LoginModel))
{
return operations.AuthenticateAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Authenticates the user based on user name and password
/// </summary>
/// <remarks>
/// Authenticates the user based on user name and password.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// The login parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
[System.Obsolete("This operation is deprecated. Please do not use it any longer.")]
public static async Task<AjaxResponse> AuthenticateAsync(this IAccount operations, LoginModel body = default(LoginModel), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AuthenticateWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 38.532258 | 199 | 0.567183 | [
"MIT"
] | AFWberlin/orchestrator-powershell | UiPath.Web.Client/generated202010/AccountExtensions.cs | 2,389 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace Barista.Api.Dto
{
public class AuthenticationMeansDto
{
[Required]
public string Type { get; set; }
public string Label { get; set; }
public DateTimeOffset ValidSince { get; set; } = DateTimeOffset.UtcNow;
public DateTimeOffset? ValidUntil { get; set; }
}
}
| 21.333333 | 79 | 0.653646 | [
"MIT"
] | nesfit/Coffee | Barista.Api/Dto/AuthenticationMeansDto.cs | 386 | 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: EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type ManagedAppRegistrationOperationsCollectionRequest.
/// </summary>
public partial class ManagedAppRegistrationOperationsCollectionRequest : BaseRequest, IManagedAppRegistrationOperationsCollectionRequest
{
/// <summary>
/// Constructs a new ManagedAppRegistrationOperationsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public ManagedAppRegistrationOperationsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified ManagedAppOperation to the collection via POST.
/// </summary>
/// <param name="managedAppOperation">The ManagedAppOperation to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ManagedAppOperation.</returns>
public System.Threading.Tasks.Task<ManagedAppOperation> AddAsync(ManagedAppOperation managedAppOperation, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsync<ManagedAppOperation>(managedAppOperation, cancellationToken);
}
/// <summary>
/// Adds the specified ManagedAppOperation to the collection via POST and returns a <see cref="GraphResponse{ManagedAppOperation}"/> object of the request.
/// </summary>
/// <param name="managedAppOperation">The ManagedAppOperation to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{ManagedAppOperation}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<ManagedAppOperation>> AddResponseAsync(ManagedAppOperation managedAppOperation, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsyncWithGraphResponse<ManagedAppOperation>(managedAppOperation, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IManagedAppRegistrationOperationsCollectionPage> GetAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
var response = await this.SendAsync<ManagedAppRegistrationOperationsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response?.Value?.CurrentPage != null)
{
response.Value.InitializeNextPageRequest(this.Client, response.NextLink);
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
return response.Value;
}
return null;
}
/// <summary>
/// Gets the collection page and returns a <see cref="GraphResponse{ManagedAppRegistrationOperationsCollectionResponse}"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{ManagedAppRegistrationOperationsCollectionResponse}"/> object.</returns>
public System.Threading.Tasks.Task<GraphResponse<ManagedAppRegistrationOperationsCollectionResponse>> GetResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
return this.SendAsyncWithGraphResponse<ManagedAppRegistrationOperationsCollectionResponse>(null, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IManagedAppRegistrationOperationsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IManagedAppRegistrationOperationsCollectionRequest Expand(Expression<Func<ManagedAppOperation, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IManagedAppRegistrationOperationsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IManagedAppRegistrationOperationsCollectionRequest Select(Expression<Func<ManagedAppOperation, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IManagedAppRegistrationOperationsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IManagedAppRegistrationOperationsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IManagedAppRegistrationOperationsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IManagedAppRegistrationOperationsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| 45.808612 | 183 | 0.625757 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/ManagedAppRegistrationOperationsCollectionRequest.cs | 9,574 | C# |
// This example illustrates the manipulation of C++ references in C#.
using System;
public class runme {
public static void Main()
{
Console.WriteLine( "Creating some objects:" );
Vector a = new Vector(3,4,5);
Vector b = new Vector(10,11,12);
Console.WriteLine( " Created " + a.print() );
Console.WriteLine( " Created " + b.print() );
// ----- Call an overloaded operator -----
// This calls the wrapper we placed around
//
// operator+(const Vector &a, const Vector &)
//
// It returns a new allocated object.
Console.WriteLine( "Adding a+b" );
Vector c = example.addv(a,b);
Console.WriteLine( " a+b = " + c.print() );
// Note: Unless we free the result, a memory leak will occur if the -noproxy commandline
// is used as the proxy classes define finalizers which call the Dispose() method. When
// -noproxy is not specified the memory management is controlled by the garbage collector.
// You can still call Dispose(). It will free the c++ memory immediately, but not the
// C# memory! You then must be careful not to call any member functions as it will
// use a NULL c pointer on the underlying c++ object. We set the C# object to null
// which will then throw a C# exception should we attempt to use it again.
c.Dispose();
c = null;
// ----- Create a vector array -----
Console.WriteLine( "Creating an array of vectors" );
VectorArray va = new VectorArray(10);
Console.WriteLine( " va = " + va.ToString() );
// ----- Set some values in the array -----
// These operators copy the value of Vector a and Vector b to the vector array
va.set(0,a);
va.set(1,b);
// This works, but it would cause a memory leak if -noproxy was used!
va.set(2,example.addv(a,b));
// Get some values from the array
Console.WriteLine( "Getting some array values" );
for (int i=0; i<5; i++)
Console.WriteLine( " va(" + i + ") = " + va.get(i).print() );
// Watch under resource meter to check on this
Console.WriteLine( "Making sure we don't leak memory." );
for (int i=0; i<1000000; i++)
c = va.get(i%10);
// ----- Clean up -----
// This could be omitted. The garbage collector would then clean up for us.
Console.WriteLine( "Cleaning up" );
va.Dispose();
a.Dispose();
b.Dispose();
}
}
| 33.364865 | 94 | 0.601863 | [
"Apache-2.0"
] | Arun-Yuvaraj/Pose-Estimation | swigwin-4.0.1/swigwin-4.0.1/Examples/csharp/reference/runme.cs | 2,469 | 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 is1 distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.Record
{
using System;
using System.Collections;
using NUnit.Framework;
using NPOI.HSSF.Record;
using NPOI.Util;
/**
* Tests the serialization and deserialization of the ObjRecord class works correctly.
* Test data taken directly from a real Excel file.
*
* @author Yegor Kozlov
*/
[TestFixture]
public class TestObjRecord
{
/**
* OBJ record data containing two sub-records.
* The data taken directly from a real Excel file.
*
* [OBJ]
* [ftCmo]
* [ftEnd]
*/
private static byte[] recdata = {
0x15, 0x00, 0x12, 0x00, 0x06, 0x00, 0x01, 0x00, 0x11, 0x60,
(byte)0xF4, 0x02, 0x41, 0x01, 0x14, 0x10, 0x1F, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
// TODO - this data seems to require two extra bytes padding. not sure where original file is.
// it's not bug 38607 attachment 17639
};
private static byte[] recdataNeedingPadding = {
21, 0, 18, 0, 0, 0, 1, 0, 17, 96, 0, 0, 0, 0, 56, 111, unchecked((byte)-52), 3, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 0, 0, 0, 0
};
[Test]
public void TestLoad()
{
ObjRecord record = new ObjRecord(TestcaseRecordInputStream.Create(ObjRecord.sid, recdata));
Assert.AreEqual(26, record.RecordSize - 4);
IList subrecords = record.SubRecords;
Assert.AreEqual(2, subrecords.Count);
Assert.IsTrue(subrecords[0] is CommonObjectDataSubRecord);
Assert.IsTrue(subrecords[1] is EndSubRecord);
}
[Test]
public void TestStore()
{
ObjRecord record = new ObjRecord(TestcaseRecordInputStream.Create(ObjRecord.sid, recdata));
byte[] recordBytes = record.Serialize();
Assert.AreEqual(26, recordBytes.Length - 4);
byte[] subData = new byte[recdata.Length];
System.Array.Copy(recordBytes, 4, subData, 0, subData.Length);
Assert.IsTrue(NPOI.Util.Arrays.Equals(recdata, subData));
}
[Test]
public void TestConstruct()
{
ObjRecord record = new ObjRecord();
CommonObjectDataSubRecord ftCmo = new CommonObjectDataSubRecord();
ftCmo.ObjectType = (CommonObjectType.Comment);
ftCmo.ObjectId = ((short)1024);
ftCmo.IsLocked = (true);
ftCmo.IsPrintable = (true);
ftCmo.IsAutoFill = (true);
ftCmo.IsAutoline = (true);
record.AddSubRecord(ftCmo);
EndSubRecord ftEnd = new EndSubRecord();
record.AddSubRecord(ftEnd);
//Serialize and Read again
byte[] recordBytes = record.Serialize();
//cut off the record header
byte[] bytes = new byte[recordBytes.Length - 4];
System.Array.Copy(recordBytes, 4, bytes, 0, bytes.Length);
record = new ObjRecord(TestcaseRecordInputStream.Create(ObjRecord.sid, bytes));
IList subrecords = record.SubRecords;
Assert.AreEqual(2, subrecords.Count);
Assert.IsTrue(subrecords[0] is CommonObjectDataSubRecord);
Assert.IsTrue(subrecords[1] is EndSubRecord);
}
[Test]
public void TestReadWriteWithPadding_bug45133()
{
ObjRecord record = new ObjRecord(TestcaseRecordInputStream.Create(ObjRecord.sid, recdataNeedingPadding));
if (record.RecordSize == 34)
{
throw new AssertionException("Identified bug 45133");
}
Assert.AreEqual(36, record.RecordSize);
IList subrecords = record.SubRecords;
Assert.AreEqual(3, subrecords.Count);
Assert.AreEqual(typeof(CommonObjectDataSubRecord), subrecords[0].GetType());
Assert.AreEqual(typeof(GroupMarkerSubRecord), subrecords[1].GetType());
Assert.AreEqual(typeof(EndSubRecord), subrecords[2].GetType());
}
/**
* Check that ObjRecord tolerates and preserves padding to a 4-byte boundary
* (normally padding is to a 2-byte boundary).
*/
[Test]
public void Test4BytePadding()
{
// actual data from file saved by Excel 2007
byte[] data = HexRead.ReadFromString(""
+ "15 00 12 00 1E 00 01 00 11 60 B4 6D 3C 01 C4 06 "
+ "49 06 00 00 00 00 00 00 00 00 00 00");
// this data seems to have 2 extra bytes of padding more than usual
// the total may have been padded to the nearest quad-byte length
RecordInputStream in1 = TestcaseRecordInputStream.Create(ObjRecord.sid, data);
// check read OK
ObjRecord record = new ObjRecord(in1);
// check that it re-serializes to the same data
byte[] ser = record.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(ObjRecord.sid, data, ser);
}
}
} | 41.847222 | 129 | 0.596747 | [
"Apache-2.0"
] | 0xAAE/npoi | testcases/main/HSSF/Record/TestObjRecord.cs | 6,026 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.Build.Framework;
using NuGet.Common;
using NuGet.ProjectModel;
namespace Microsoft.NET.Build.Tasks
{
internal class LockFileCache
{
private IBuildEngine4 _buildEngine;
public LockFileCache(IBuildEngine4 buildEngine)
{
_buildEngine = buildEngine;
}
public LockFile GetLockFile(string path)
{
if (!Path.IsPathRooted(path))
{
throw new BuildErrorException(Strings.AssetsFilePathNotRooted, path);
}
string lockFileKey = GetTaskObjectKey(path);
LockFile result;
object existingLockFileTaskObject = _buildEngine.GetRegisteredTaskObject(lockFileKey, RegisteredTaskObjectLifetime.Build);
if (existingLockFileTaskObject == null)
{
result = LoadLockFile(path);
_buildEngine.RegisterTaskObject(lockFileKey, result, RegisteredTaskObjectLifetime.Build, true);
}
else
{
result = (LockFile)existingLockFileTaskObject;
}
return result;
}
private static string GetTaskObjectKey(string lockFilePath)
{
return $"{nameof(LockFileCache)}:{lockFilePath}";
}
private LockFile LoadLockFile(string path)
{
if (!File.Exists(path))
{
throw new BuildErrorException(Strings.AssetsFileNotFound, path);
}
// TODO - https://github.com/dotnet/sdk/issues/18 adapt task logger to Nuget Logger
return LockFileUtilities.GetLockFile(path, NullLogger.Instance);
}
}
}
| 30.253968 | 134 | 0.615425 | [
"MIT"
] | 333fred/dotnet-sdk | src/Tasks/Microsoft.NET.Build.Tasks/LockFileCache.cs | 1,908 | C# |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using Dbg = System.Management.Automation.Diagnostics;
using System.Runtime.Serialization;
using System.Collections.Generic;
#if CORECLR
using Environment = System.Management.Automation.Environment;
#endif
namespace System.Management.Automation
{
/// <summary>
///
/// Defines a data structure used to represent informational context destined for the host or user.
///
/// </summary>
/// <remarks>
///
/// InformationRecords are passed to <see cref="System.Management.Automation.Cmdlet.WriteInformation(Object, string[])"/>,
/// which, according to host or user preference, forwards that information on to the host for rendering to the user.
///
/// </remarks>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteInformation(Object, string[])"/>
[DataContract()]
public class InformationRecord
{
/// <summary>
///
/// Initializes a new instance of the InformationRecord class.
///
/// </summary>
/// <param name="messageData">The object to be transmitted to the host.</param>
/// <param name="source">The source of the message (i.e.: script path, function name, etc.)</param>
public InformationRecord(Object messageData, string source)
{
this.MessageData = messageData;
this.Source = source;
this.TimeGenerated = DateTime.Now;
this.Tags = new List<string>();
// domain\user on Windows, just user on Unix
#if UNIX
this.User = Platform.Unix.UserName;
#else
this.User = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
#endif
this.Computer = PsUtils.GetHostName();
this.ProcessId = (uint)System.Diagnostics.Process.GetCurrentProcess().Id;
this.NativeThreadId = PsUtils.GetNativeThreadId();
this.ManagedThreadId = (uint)System.Threading.Thread.CurrentThread.ManagedThreadId;
}
/// <summary>
/// Added to enable ClrFacade.GetUninitializedObject to instantiate an uninitialized version of this class.
/// </summary>
internal InformationRecord() { }
/// <summary>
/// Copy constructor
/// </summary>
internal InformationRecord(InformationRecord baseRecord)
{
this.MessageData = baseRecord.MessageData;
this.Source = baseRecord.Source;
this.TimeGenerated = baseRecord.TimeGenerated;
this.Tags = baseRecord.Tags;
this.User = baseRecord.User;
this.Computer = baseRecord.Computer;
this.ProcessId = baseRecord.ProcessId;
this.NativeThreadId = baseRecord.NativeThreadId;
this.ManagedThreadId = baseRecord.ManagedThreadId;
}
// Some of these setters are internal, while others are public.
// The ones that are public are left that way because systems that proxy
// the events may need to alter them (i.e.: workflow). The ones that remain internal
// are that way because they are fundamental properties of the record itself.
/// <summary>
/// The message data for this informational record
/// </summary>
[DataMember]
public Object MessageData { get; internal set; }
/// <summary>
/// The source of this informational record (script path, function name, etc.)
/// </summary>
[DataMember]
public string Source { get; set; }
/// <summary>
/// The time this informational record was generated.
/// </summary>
[DataMember]
public DateTime TimeGenerated { get; set; }
/// <summary>
/// The tags associated with this informational record (if any)
/// </summary>
[DataMember]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public List<string> Tags { get; internal set; }
/// <summary>
/// The user that generated this informational record
/// </summary>
[DataMember]
public string User { get; set; }
/// <summary>
/// The computer that generated this informational record
/// </summary>
[DataMember]
public string Computer { get; set; }
/// <summary>
/// The process that generated this informational record
/// </summary>
[DataMember]
public uint ProcessId { get; set; }
/// <summary>
/// The native thread that generated this informational record
/// </summary>
public uint NativeThreadId { get; set; }
/// <summary>
/// The managed thread that generated this informational record
/// </summary>
[DataMember]
public uint ManagedThreadId { get; set; }
/// <summary>
/// Converts an InformationRecord to a string-based representation.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (MessageData != null)
{
return MessageData.ToString();
}
else
{
return base.ToString();
}
}
internal static InformationRecord FromPSObjectForRemoting(PSObject inputObject)
{
InformationRecord informationRecord = new InformationRecord();
informationRecord.MessageData = RemotingDecoder.GetPropertyValue<Object>(inputObject, "MessageData");
informationRecord.Source = RemotingDecoder.GetPropertyValue<string>(inputObject, "Source");
informationRecord.TimeGenerated = RemotingDecoder.GetPropertyValue<DateTime>(inputObject, "TimeGenerated");
informationRecord.Tags = new List<string>();
System.Collections.ArrayList tagsArrayList = RemotingDecoder.GetPropertyValue<System.Collections.ArrayList>(inputObject, "Tags");
foreach (string tag in tagsArrayList)
{
informationRecord.Tags.Add(tag);
}
informationRecord.User = RemotingDecoder.GetPropertyValue<string>(inputObject, "User");
informationRecord.Computer = RemotingDecoder.GetPropertyValue<string>(inputObject, "Computer");
informationRecord.ProcessId = RemotingDecoder.GetPropertyValue<uint>(inputObject, "ProcessId");
informationRecord.NativeThreadId = RemotingDecoder.GetPropertyValue<uint>(inputObject, "NativeThreadId");
informationRecord.ManagedThreadId = RemotingDecoder.GetPropertyValue<uint>(inputObject, "ManagedThreadId");
return informationRecord;
}
/// <summary>
/// Returns this object as a PSObject property bag
/// that can be used in a remoting protocol data object.
/// </summary>
/// <returns>This object as a PSObject property bag</returns>
internal PSObject ToPSObjectForRemoting()
{
PSObject informationAsPSObject = RemotingEncoder.CreateEmptyPSObject();
informationAsPSObject.Properties.Add(new PSNoteProperty("MessageData", this.MessageData));
informationAsPSObject.Properties.Add(new PSNoteProperty("Source", this.Source));
informationAsPSObject.Properties.Add(new PSNoteProperty("TimeGenerated", this.TimeGenerated));
informationAsPSObject.Properties.Add(new PSNoteProperty("Tags", this.Tags));
informationAsPSObject.Properties.Add(new PSNoteProperty("User", this.User));
informationAsPSObject.Properties.Add(new PSNoteProperty("Computer", this.Computer));
informationAsPSObject.Properties.Add(new PSNoteProperty("ProcessId", this.ProcessId));
informationAsPSObject.Properties.Add(new PSNoteProperty("NativeThreadId", this.NativeThreadId));
informationAsPSObject.Properties.Add(new PSNoteProperty("ManagedThreadId", this.ManagedThreadId));
return informationAsPSObject;
}
}
/// <summary>
/// Class that holds informational messages to represent output created by the
/// Write-Host cmdlet.
/// </summary>
public class HostInformationMessage
{
/// <summary>
/// The message being output by the host
/// </summary>
public string Message { get; set; }
/// <summary>
/// 'True' if the host should not append a NewLine to the message output
/// </summary>
public bool? NoNewLine { get; set; }
/// <summary>
/// The foreground color of the message
/// </summary>
public ConsoleColor? ForegroundColor { get; set; }
/// <summary>
/// The background color of the message
/// </summary>
public ConsoleColor? BackgroundColor { get; set; }
/// <summary>
/// Returns a string-based representation of the host information message
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Message;
}
}
}
| 39.357143 | 141 | 0.617273 | [
"Apache-2.0",
"MIT"
] | adbertram/PowerShell | src/System.Management.Automation/engine/InformationRecord.cs | 9,367 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MatBlazor.DevUtils
{
public class Config
{
public static Config GetConfig()
{
return new Config();
}
public string Path
{
get { return System.IO.Path.GetFullPath(_path); }
}
private string _path = "../../../..";
public string RepositoryPath
{
get { return System.IO.Path.GetDirectoryName(Path); }
}
public string DemoContainerTag = "DemoContainer";
public string ContentTag = "Content";
public string SourceContentTag = "SourceContent";
public string FileMask = "*.razor";
}
} | 22.5 | 65 | 0.575 | [
"MIT"
] | CSOleson/MatBlazor | src/MatBlazor.DevUtils/Config.cs | 722 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Logging;
namespace Ordering.Application.Behaviors
{
public class UnhandledExceptionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly ILogger<TRequest> _logger;
public UnhandledExceptionBehaviour(ILogger<TRequest> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
RequestHandlerDelegate<TResponse> next)
{
try
{
return await next();
}
catch (Exception ex)
{
var requestName = typeof(TRequest).Name;
_logger.LogError(ex, "Application Request: Unhandled Exception for Request {Name} {@Request}", requestName, request);
throw;
}
}
}
}
| 29.945946 | 133 | 0.637184 | [
"MIT"
] | bgani/dotnet-microservices | src/Services/Ordering/Ordering.Application/Behaviors/UnhandledExceptionBehavior.cs | 1,110 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.