content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankAccounts
{
class Loan : Account
{
public Loan(Customer customer, decimal balance, decimal interestRate)
{
base._customer = customer;
base._balance = balance;
base._interestRate = interestRate;
}
public override void DepositMoney(decimal ammount)
{
base._balance += ammount;
}
public override void WithDraw(decimal ammount)
{
Console.WriteLine("You cannot withdraw money from a loan account!");
}
public override decimal InterestAmmount(int months)
{
decimal ammount = 0;
months -= 2;
string customerType = base._customer.typeOfCustomer();
if (customerType == "individual")
{
months--;
}
if (months > 0)
{
ammount = base._interestRate * months;
}
return ammount;
}
}
}
| 26.069767 | 80 | 0.545049 | [
"MIT"
] | IvayloDamyanov/CSharp-ObjectOrientedProgramming | 05. OOP-Principles-Part-2/BankAccounts/Loan.cs | 1,123 | C# |
using Microsoft.Azure.Devices;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;
using Azure.Core;
namespace IoTEdgeDeployBlobs.Sdk
{
public class DeployBlobs
{
private readonly string _deployBlobsModuleName;
private readonly ServiceClient _serviceClient;
private readonly RegistryManager _registryManager;
private readonly ILogger _logger;
private readonly JobClient _jobClient;
public DeployBlobs(string iotHubConnectionString, string deployBlobsModuleName, ILogger logger = null)
{
_deployBlobsModuleName = deployBlobsModuleName;
_logger = logger;
_serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString, TransportType.Amqp);
_registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
_jobClient = JobClient.CreateFromConnectionString(iotHubConnectionString);
_logger?.LogInformation("Module dependencies Service Client, RegistryManager and JobClient ready.");
}
public DeployBlobs(TokenCredential tokenCredential, string iotHubHostname, string deployBlobsModuleName, ILogger logger = null)
{
_deployBlobsModuleName = deployBlobsModuleName;
_logger = logger;
_serviceClient = ServiceClient.Create(iotHubHostname, tokenCredential, TransportType.Amqp);
_registryManager = RegistryManager.Create(iotHubHostname, tokenCredential);
_jobClient = JobClient.Create(iotHubHostname, tokenCredential);
_logger?.LogInformation("Module dependencies Service Client, RegistryManager and JobClient ready.");
}
public async Task<DownloadBlobsResponse> DeployBlobsAsync(string targetEdgeDeviceId, IEnumerable<BlobInfo> blobs, int methodTimeout = 30)
{
CloudToDeviceMethod methodRequest = PrepareDownloadBlobsDirectMethod(blobs, methodTimeout);
//perform a Direct Method to the remote device to initiate the device stream!
CloudToDeviceMethodResult response = await _serviceClient.InvokeDeviceMethodAsync(targetEdgeDeviceId, _deployBlobsModuleName, methodRequest);
DownloadBlobsResponse responseObj = DownloadBlobsResponse.FromJson(response.GetPayloadAsJson());
return responseObj;
}
/// <summary>
/// Deploy the list of blobs to the IoT Edge Devices executing the deployBlobs module and the query condition. Returns a JobId that can be used to monitor the JobStatus.
/// </summary>
/// <param name="blobs">List of blobs to be downloaded by the deployBlob module at the target devices.</param>
/// <param name="queryCondition">Query condition to filter target devices based on the 'devices.modules' schema.</param>
/// <returns></returns>
public async Task<JobResponse> ScheduleDeployBlobsJobAsync(List<BlobInfo> blobs, string queryCondition = "", int methodTimeout = 30)
{
string jobId = Guid.NewGuid().ToString();
CloudToDeviceMethod downloadMethod = PrepareDownloadBlobsDirectMethod(blobs, methodTimeout);
string deployBlobsModuleCondition = $"FROM devices.modules WHERE devices.modules.moduleId = '{_deployBlobsModuleName}'";
if (!String.IsNullOrWhiteSpace(queryCondition))
{
deployBlobsModuleCondition = $"{ deployBlobsModuleCondition } AND ({queryCondition})";
}
return await StartDownloadJobAsync(jobId, deployBlobsModuleCondition, downloadMethod);
}
/// <summary>
/// Deploy the list of blobs to the IoT Edge Devices executing the deployBlobs module and matching the deviceIds list. Returns a JobId that can be used to monitor the JobStatus.
/// </summary>
/// <param name="blobs">List of blobs to be downloaded by the deployBlob module at the target devices.</param>
/// <param name="devicesIds">List of target devices.</param>
/// <returns></returns>
public async Task<JobResponse> ScheduleDeployBlobsJobAsync(List<BlobInfo> blobs, IEnumerable<string> devicesIds)
{
if (devicesIds is null || !devicesIds.Any())
{
return null;
}
string queryCondition = $"deviceId IN [ '{String.Join("', '", devicesIds)}' ]";
return await ScheduleDeployBlobsJobAsync(blobs, queryCondition);
}
/// <summary>
/// Gets the current status for the scheduled job matching the jobId
/// </summary>
/// <param name="jobId"></param>
/// <returns></returns>
public async Task<string> GetDeployBlobsJobStatusAsync(string jobId)
{
JobResponse result = await _jobClient.GetJobAsync(jobId);
return result?.Status.ToString();
}
/// <summary>
/// Gets all the deatils for the scheduled job matching the jobId
/// </summary>
/// <param name="jobId"></param>
/// <returns></returns>
public async Task<JobResponse> GetDeploymentJobAsync(string jobId)
{
return await _jobClient.GetJobAsync(jobId);
}
/// <summary>
/// Gets all the reponses from all targeted devices by the scheduled job matching the jobId
/// </summary>
/// <param name="jobId"></param>
/// <param name="queryCondition">Optionally, a query condition over the devices.jobs schema can be provided</param>
/// <returns></returns>
public async Task<IEnumerable<DeviceJob>> GetDeploymentJobResponsesAsync(string jobId, string queryCondition="")
{
List<DeviceJob> responses = new();
string queryStr = $"SELECT * FROM devices.jobs where jobId = '{jobId}'";
if (!String.IsNullOrEmpty(queryCondition))
{
queryStr += $" and ({queryCondition})";
}
_logger.LogInformation($"Querying job reponses: {queryStr}");
var query = _registryManager.CreateQuery(queryStr);
while (query.HasMoreResults)
{
var response = await query.GetNextAsDeviceJobAsync();
responses.AddRange(response);
}
_logger.LogInformation($"Found {responses.Count} reponses");
return responses;
}
/// <summary>
/// Gets all the edge devices Ids.
/// </summary>
/// <param name="queryCondition">Optionally, a query condition over the devices schema can be provide to filter the retrieved Ids</param>
/// <returns></returns>
public async Task<IEnumerable<string>> GetEdgeDevicesIdsAsync(string queryCondition = "")
{
List<string> ids = new();
string queryStr = $"SELECT * FROM devices where capabilities.iotEdge = true";
if (!String.IsNullOrEmpty(queryCondition))
{
queryStr += $" and ( {queryCondition} )";
}
_logger.LogInformation($"Gathering Edge DevicesIds: {queryStr}");
var query = _registryManager.CreateQuery(queryStr);
while (query.HasMoreResults)
{
var response = await query.GetNextAsTwinAsync();
ids.AddRange(response.Select(dv => dv.DeviceId));
}
return ids;
}
private static CloudToDeviceMethod PrepareDownloadBlobsDirectMethod(IEnumerable<BlobInfo> blobs, int methodTimeout = 30)
{
DownloadBlobsRequest downloadBlobRequest = new();
downloadBlobRequest.Blobs.AddRange(blobs);
var methodRequest = new CloudToDeviceMethod(
DownloadBlobsDirectMethod.DownloadBlobMethodName,
TimeSpan.FromSeconds(methodTimeout), //It could get a time out if the download takes more than defined seconds
TimeSpan.FromSeconds(5)
);
methodRequest.SetPayloadJson(downloadBlobRequest.ToJson());
return methodRequest;
}
private async Task<JobResponse> StartDownloadJobAsync(string jobId, string queryCondition, CloudToDeviceMethod downloadMethod)
{
JobResponse result = await _jobClient.ScheduleDeviceMethodAsync(jobId,
queryCondition,
downloadMethod,
DateTime.UtcNow,
(long)TimeSpan.FromMinutes(3).TotalSeconds);
_logger?.LogInformation($"Scheduled jobId {jobId} targeting '{queryCondition}'. Job Timeout 3 minutes.");
return result;
}
}
}
| 44.522613 | 185 | 0.647517 | [
"MIT"
] | algorni/iot-edge-deploy-blob | source/IoTEdgeDeployBlobs.Sdk/DeployBlobs.cs | 8,862 | C# |
namespace Stormbot.Bot.Core
{
public enum PermissionLevel : byte
{
User = 0,
ChannelModerator,
ChannelAdmin,
ServerModerator,
ServerAdmin,
ServerOwner,
BotOwner
}
} | 17.923077 | 38 | 0.562232 | [
"MIT"
] | SSStormy/StormBot | Bot.Core/PermissionLevel.cs | 235 | C# |
using System;
using System.Net;
using System.Web.Mvc;
using Sitecore.Diagnostics;
using Sitecore.HabitatHome.Fitness.Feature.Collection.Model;
using Sitecore.HabitatHome.Fitness.Feature.Collection.Services;
using Sitecore.HabitatHome.Fitness.Foundation.Analytics.Filters;
using Sitecore.HabitatHome.Fitness.Foundation.Analytics.Services;
using Sitecore.LayoutService.Mvc.Security;
namespace Sitecore.HabitatHome.Fitness.Feature.Collection.Controllers
{
[RequireSscApiKey]
[ImpersonateApiKeyUser]
[EnableApiKeyCors]
[SuppressFormsAuthenticationRedirect]
public class HabitatFitnessDemographicsController : Controller
{
private IDemographicsService service;
public HabitatFitnessDemographicsController([NotNull]IDemographicsService service)
{
this.service = service;
}
[ActionName("facet")]
[HttpPost]
[CancelCurrentPage]
public ActionResult UpdateFacet([System.Web.Http.FromBody]DemographicsPayload data)
{
try
{
service.UpdateFacet(data);
}
catch (Exception ex)
{
Log.Error($"Error while running UpdateFacet API", ex, this);
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
[ActionName("profile")]
[HttpPost]
[CancelCurrentPage]
public ActionResult UpdateProfile([System.Web.Http.FromBody]DemographicsPayload data)
{
try
{
service.UpdateProfile(data);
}
catch (Exception ex)
{
Log.Error($"Error while running UpdateProfile API", ex, this);
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
} | 32.370968 | 96 | 0.648231 | [
"MPL-2.0"
] | arthurbai/Sitecore.HabitatHome.Omni | fitness/server/src/Feature/Collection/code/Controllers/HabitatFitnessDemographicsController.cs | 2,009 | C# |
namespace PicoTracer
{
public abstract class Renderer : Component
{
public Material material { get; set; }
}
} | 18.714286 | 46 | 0.633588 | [
"MIT"
] | AshkoreDracson/PicoTracer | PicoTracer/Core/Rendering/Renderer.cs | 133 | C# |
using System.Linq;
using Elasticsearch.Net;
using FluentAssertions;
using Nest.Tests.MockData;
using Nest.Tests.MockData.Domain;
using NUnit.Framework;
namespace Nest.Tests.Integration.Search
{
[TestFixture]
public class PercolateTests : IntegrationTests
{
private string _LookFor = NestTestData.Data.First().Followers.First().FirstName;
[Test]
public void RegisterPercolateTest()
{
var name = "mypercolator";
var c = this.Client;
var r = c.RegisterPercolator<ElasticsearchProject>(name, p => p
.Query(q => q
.Term(f => f.Name, "elasticsearch.pm")
)
);
Assert.True(r.IsValid);
Assert.True(r.Created);
Assert.AreEqual(r.Index, ElasticsearchConfiguration.DefaultIndex);
Assert.AreEqual(r.Type, ".percolator");
Assert.AreEqual(r.Id, name);
Assert.Greater(r.Version, 0);
var request = r.ConnectionStatus.Request.Utf8String();
request.Should().NotBeNullOrEmpty().And.NotBe("{}");
}
[Test]
public void UnregisterPercolateTest()
{
var name = "mypercolator";
var c = this.Client;
var r = c.RegisterPercolator<ElasticsearchProject>(name, p => p
.AddMetadata(md=>md.Add("color", "blue"))
.Query(q => q
.Term(f => f.Name, "elasticsearch.pm")
)
);
Assert.True(r.IsValid);
Assert.True(r.Created);
Assert.AreEqual(r.Index, ElasticsearchConfiguration.DefaultIndex);
Assert.AreEqual(r.Id, name);
Assert.Greater(r.Version, 0);
var re = c.UnregisterPercolator<ElasticsearchProject>(name);
Assert.True(re.IsValid);
Assert.True(re.Found);
Assert.AreEqual(re.Index, ElasticsearchConfiguration.DefaultIndex);
Assert.AreEqual(re.Type, ".percolator");
Assert.AreEqual(re.Id, name);
Assert.Greater(re.Version, 0);
re = c.UnregisterPercolator<ElasticsearchProject>(name);
Assert.True(re.IsValid);
Assert.False(re.Found);
}
[Test]
public void PercolateDoc()
{
this.RegisterPercolateTest(); // I feel a little dirty.
var c = this.Client;
var name = "mypercolator";
var document = new ElasticsearchProject()
{
Id = 12,
Name = "elasticsearch.pm",
Country = "netherlands",
LOC = 100000, //Too many :(
};
var r = c.Percolate<ElasticsearchProject>(p=>p.Document(document));
Assert.True(r.IsValid);
Assert.NotNull(r.Matches);
Assert.True(r.Matches.Select(m=>m.Id).Contains(name));
var indexResult = c.Index(document);
r = c.Percolate<ElasticsearchProject>(p=>p.Id(indexResult.Id));
Assert.True(r.IsValid);
Assert.NotNull(r.Matches);
Assert.True(r.Matches.Select(m=>m.Id).Contains(name));
var re = c.UnregisterPercolator<ElasticsearchProject>(name);
}
[Test]
public void PercolateTypedDoc()
{
this.RegisterPercolateTest(); // I feel a little dirty.
var c = this.Client;
var name = "eclecticsearch";
var r = c.RegisterPercolator<ElasticsearchProject>(name, p => p
.Query(q => q
.Term(f => f.Country, "netherlands")
)
);
Assert.True(r.IsValid);
Assert.True(r.Created);
var obj = new ElasticsearchProject()
{
Name = "NEST",
Country = "netherlands",
LOC = 100000, //Too many :(
};
var percolateResponse = this.Client.Percolate<ElasticsearchProject>(p=>p
.Document(obj)
.TrackScores(false)
);
Assert.True(percolateResponse.IsValid);
Assert.NotNull(percolateResponse.Matches);
Assert.True(percolateResponse.Matches.Select(m=>m.Id).Contains(name));
var re = c.UnregisterPercolator<ElasticsearchProject>(name);
}
[Test]
public void PercolateTypedDocWithQuery()
{
var c = this.Client;
var name = "eclecticsearch" + ElasticsearchConfiguration.NewUniqueIndexName();
var re = c.UnregisterPercolator<ElasticsearchProject>(name);
var r = c.RegisterPercolator<ElasticsearchProject>(name, p => p
.AddMetadata(md=>md.Add("color", "blue"))
.Query(q => q
.Term(f => f.Country, "netherlands")
)
);
Assert.True(r.IsValid);
Assert.True(r.Created);
c.Refresh();
var obj = new ElasticsearchProject()
{
Name = "NEST",
Country = "netherlands",
LOC = 100000, //Too many :(
};
var percolateResponse = this.Client.Percolate<ElasticsearchProject>(p => p
.Document(obj)
.Query(q=>q.Match(m=>m.OnField("color").Query("blue")))
);
Assert.True(percolateResponse.IsValid);
Assert.NotNull(percolateResponse.Matches);
Assert.True(percolateResponse.Matches.Select(m=>m.Id).Contains(name));
//should not match since we registered with the color blue
percolateResponse = this.Client.Percolate<ElasticsearchProject>(p => p
.Query(q => q.Term("color", "green"))
.Document(obj)
);
Assert.True(percolateResponse.IsValid);
Assert.NotNull(percolateResponse.Matches);
Assert.False(percolateResponse.Matches.Select(m=>m.Id).Contains(name));
var countPercolateReponse = this.Client.PercolateCount(obj,p => p
.Query(q=>q.Match(m=>m.OnField("color").Query("blue")))
);
countPercolateReponse.IsValid.Should().BeTrue();
countPercolateReponse.Total.Should().Be(1);
re = c.UnregisterPercolator<ElasticsearchProject>(name);
}
}
} | 29.900585 | 82 | 0.680814 | [
"Apache-2.0"
] | Bloomerang/elasticsearch-net | src/Tests/Nest.Tests.Integration/Search/PercolateTests.cs | 5,115 | C# |
// Copyright © 2019 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using AWhewell.Owin.Utility;
using AWhewell.Owin.Utility.Formatters;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test.AWhewell.Owin.Utility
{
[TestClass]
public class TypeFormatterResolverCache_Tests
{
[TestMethod]
public void Find_FormatterList_Returns_Existing_Resolver()
{
var resolver1 = TypeFormatterResolverCache.Find(new DateTime_Iso8601_Formatter());
var resolver2 = TypeFormatterResolverCache.Find(new DateTime_Iso8601_Formatter());
Assert.IsNotNull(resolver1);
Assert.AreSame(resolver1, resolver2);
}
[TestMethod]
public void Find_FormatterList_Ignores_Order_Of_Types()
{
var resolver1 = TypeFormatterResolverCache.Find(new DateTime_Iso8601_Formatter(), new DateTimeOffset_JavaScriptTicks_Formatter());
var resolver2 = TypeFormatterResolverCache.Find(new DateTimeOffset_JavaScriptTicks_Formatter(), new DateTime_Iso8601_Formatter());
Assert.IsNotNull(resolver1);
Assert.AreSame(resolver1, resolver2);
}
[TestMethod]
public void Find_FormatterList_Does_Not_Ignores_Types()
{
var resolver1 = TypeFormatterResolverCache.Find(new DateTime_Iso8601_Formatter());
var resolver2 = TypeFormatterResolverCache.Find(new DateTimeOffset_Iso8601_Formatter());
Assert.AreNotSame(resolver1, resolver2);
}
[TestMethod]
public void Find_FormatterList_Accepts_Null()
{
var resolver1 = TypeFormatterResolverCache.Find((ITypeFormatter[])null);
var resolver2 = TypeFormatterResolverCache.Find((ITypeFormatter[])null);
Assert.IsNotNull(resolver1);
Assert.AreSame(resolver1, resolver2);
}
[TestMethod]
public void Clear_Empties_Cache()
{
var resolver1 = TypeFormatterResolverCache.Find(new DateTime_Iso8601_Formatter());
TypeFormatterResolverCache.Clear();
var resolver2 = TypeFormatterResolverCache.Find(new DateTime_Iso8601_Formatter());
Assert.AreNotSame(resolver1, resolver2);
}
}
}
| 53.342857 | 749 | 0.730852 | [
"BSD-3-Clause"
] | awhewell/owin | Tests/Test.Owin.Utility/TypeFormatterResolverCache_Tests.cs | 3,737 | C# |
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Security.AccessControl;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using LoggerLibrary;
using System.DirectoryServices.AccountManagement;
namespace WindowsLibrary
{
public class WindowsHelper
{
private Logger _logger;
public WindowsHelper(Logger logger)
{
_logger = logger;
}
public bool AddHostFileEntry(string entry)
{
try
{
var hostsWriter = new StreamWriter(Environment.GetEnvironmentVariable("windir") + "\\system32\\drivers\\etc\\hosts", true);
hostsWriter.AutoFlush = true;
hostsWriter.WriteLine(entry);
hostsWriter.Dispose();
}
catch (Exception e)
{
_logger.Log(e, "Failed to add hosts file entry.");
return false;
}
return true;
}
public List<Tuple<string, Bitmap>> CaptureScreen()
{
try
{
var bitmapList = new List<Tuple<string, Bitmap>>();
foreach (Screen s in Screen.AllScreens)
{
string captureFileShortName = s.DeviceName.Substring(s.DeviceName.LastIndexOf("\\") + 1) + "--" + GetTimeStamp();
_logger.Log("Capture screen: " + s.DeviceName +
" [" + s.Bounds.Width + "x" + s.Bounds.Height + "] [" + captureFileShortName + "].");
var bmpScreenshot = new Bitmap(s.Bounds.Width, s.Bounds.Height, PixelFormat.Format32bppArgb);
Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(s.Bounds.X, s.Bounds.Y, 0, 0, s.Bounds.Size, CopyPixelOperation.SourceCopy);
bitmapList.Add(new Tuple<string, Bitmap>(captureFileShortName, bmpScreenshot));
}
return bitmapList;
}
catch (Exception e)
{
_logger.Log(e, "Failed to capture screen.");
}
return null;
}
public bool CaptureScreen(string outputFolder)
{
try
{
foreach (Screen s in Screen.AllScreens)
{
string captureFileShortName = s.DeviceName.Substring(s.DeviceName.LastIndexOf("\\") + 1) + "--" + GetTimeStamp();
_logger.Log("Capture screen: " + s.DeviceName +
" [" + s.Bounds.Width + "x" + s.Bounds.Height + "] [" + captureFileShortName + "].");
Bitmap bmpScreenshot = new Bitmap(s.Bounds.Width, s.Bounds.Height, PixelFormat.Format32bppArgb);
Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(s.Bounds.X, s.Bounds.Y, 0, 0, s.Bounds.Size, CopyPixelOperation.SourceCopy);
_logger.Log("Save: " + outputFolder + "\\" + captureFileShortName + ".png");
bmpScreenshot.Save(outputFolder + "\\" + captureFileShortName + ".png", ImageFormat.Png);
}
return true;
}
catch (Exception e)
{
_logger.Log(e, "Failed to capture screen.");
}
return false;
}
public void CreateShortcut(
string shortcutFileName,
string targetFileName,
string targetArguments = "",
string shortcutDescription = "",
int iconNumber = 2)
{
// Icon index numbers can be referenced at this link:
// https://help4windows.com/windows_7_shell32_dll.shtml
// Define 'Windows Script Host Shell Object' as a type
Type windowsScriptHostShell = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8"));
// Create a shell instance
dynamic wshShellInstance = Activator.CreateInstance(windowsScriptHostShell);
try
{
if (!shortcutFileName.EndsWith(".lnk"))
{
shortcutFileName += ".lnk";
}
var lnk = wshShellInstance.CreateShortcut(shortcutFileName);
try
{
lnk.TargetPath = targetFileName;
lnk.Arguments = targetArguments;
lnk.WorkingDirectory = Path.GetDirectoryName(targetFileName);
lnk.IconLocation = "shell32.dll, " + iconNumber.ToString();
lnk.Description = shortcutDescription;
lnk.Save();
}
finally
{
Marshal.FinalReleaseComObject(lnk);
}
}
finally
{
Marshal.FinalReleaseComObject(wshShellInstance);
}
}
public bool ConfigureAutomaticLogon(string logonUser, string logonPwd)
{
try
{
_logger.Log("Configure automatic logon user: " + logonUser);
RegistryHelper reg = new RegistryHelper(_logger);
RegistryKey winLogonKey = reg.OpenKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", true, RegistryHive.LocalMachine);
winLogonKey.SetValue("AutoAdminLogon", "1", RegistryValueKind.String);
winLogonKey.SetValue("DefaultUserName", logonUser, RegistryValueKind.String);
winLogonKey.SetValue("DefaultPassword", logonPwd, RegistryValueKind.String);
winLogonKey.SetValue("DisableCAD", "1", RegistryValueKind.DWord);
winLogonKey.DeleteValue("AutoLogonCount", false);
winLogonKey.DeleteValue("DefaultDomainName", false);
winLogonKey.Dispose();
RegistryKey policiesKey = reg.OpenKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true, RegistryHive.LocalMachine);
policiesKey.SetValue("EnableFirstLogonAnimation", "0", RegistryValueKind.DWord);
policiesKey.Dispose();
return true;
}
catch (Exception e)
{
_logger.Log(e, "Failed to configure automatic logon.");
return false;
}
}
public DateTime ConvertBinaryDateTime(Byte[] bytes)
{
long filedate = (((((((
(long)bytes[7] * 256 +
(long)bytes[6]) * 256 +
(long)bytes[5]) * 256 +
(long)bytes[4]) * 256 +
(long)bytes[3]) * 256 +
(long)bytes[2]) * 256 +
(long)bytes[1]) * 256 +
(long)bytes[0]);
DateTime returnDate = DateTime.FromFileTime(filedate);
return returnDate;
}
public bool DeleteEnvironmentVariable(string variableName)
{
if (Environment.GetEnvironmentVariable(variableName, EnvironmentVariableTarget.Machine) != null)
{
Environment.SetEnvironmentVariable(variableName, null, EnvironmentVariableTarget.Machine);
return true;
}
return false;
}
public void DetachConsole()
{
IntPtr cw = NativeMethods.GetConsoleWindow();
NativeMethods.FreeConsole();
NativeMethods.SendMessage(cw, 0x0102, 13, IntPtr.Zero);
}
public IntPtr DuplicateToken(IntPtr hUserToken, uint sessionId = 65536)
{
IntPtr hTokenToDup = hUserToken; // this may be replaced by a linked/elevated token if UAC is turned ON/enabled.
IntPtr hDuplicateToken = IntPtr.Zero;
int cbSize = 0;
try
{
NativeMethods.SECURITY_ATTRIBUTES sa = new NativeMethods.SECURITY_ATTRIBUTES();
sa.nLength = Marshal.SizeOf(sa);
if (hUserToken == IntPtr.Zero)
{
_logger.Log("No token was provided.", Logger.MsgType.ERROR);
return IntPtr.Zero;
}
if (Environment.OSVersion.Version.Major >= 6)
{
// Is the provided token NOT elevated?
if (!IsTokenElevated(hUserToken))
{
cbSize = IntPtr.Size;
IntPtr pLinkedToken = Marshal.AllocHGlobal(cbSize);
if (pLinkedToken == IntPtr.Zero)
{
_logger.Log("Failed to allocate memory for linked token check.", Logger.MsgType.ERROR);
return IntPtr.Zero;
}
// Are we NOT able to query the linked token? [Note: If the user is an admin, the linked token will be the elevation token!!!!!]
if (!NativeMethods.GetTokenInformation(hUserToken,
NativeMethods.TOKEN_INFORMATION_CLASS.TokenLinkedToken,
pLinkedToken,
cbSize,
out cbSize))
{
_logger.Log("Failed to query LINKED token [GetTokenInformation=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(pLinkedToken);
return IntPtr.Zero;
}
if (pLinkedToken != IntPtr.Zero)
{
_logger.Log("Token has a LINKED token.");
// Is the linked token an elevated token?
if (IsTokenElevated(Marshal.ReadIntPtr(pLinkedToken)))
{
_logger.Log("LINKED token is ELEVATED, assign for duplication...");
hTokenToDup = Marshal.ReadIntPtr(pLinkedToken);
}
else
{
_logger.Log("LINKED token is not elevated.");
}
Marshal.FreeHGlobal(pLinkedToken);
}
else
{
_logger.Log("Token does NOT have a LINKED token.");
}
}
}
if (!NativeMethods.DuplicateTokenEx(hTokenToDup,
NativeMethods.TOKEN_MAXIMUM_ALLOWED,
ref sa,
NativeMethods.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
NativeMethods.TOKEN_TYPE.TokenPrimary,
ref hDuplicateToken))
{
_logger.Log("Failed to duplicate token [DuplicateTokenEx=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hTokenToDup);
return IntPtr.Zero;
}
Marshal.FreeHGlobal(hTokenToDup);
cbSize = IntPtr.Size;
IntPtr pSessionId = Marshal.AllocHGlobal(cbSize);
if (!NativeMethods.GetTokenInformation(hDuplicateToken, NativeMethods.TOKEN_INFORMATION_CLASS.TokenSessionId, pSessionId, cbSize, out cbSize))
{
_logger.Log("Failed to token's session id [GetTokenInformation=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(pSessionId);
return IntPtr.Zero;
}
else
{
_logger.Log("Duplicated token is configured for session id [" +
Marshal.ReadInt32(pSessionId).ToString() + "].");
}
if (sessionId >= 0 && sessionId <= 65535 && sessionId != Marshal.ReadInt32(pSessionId))
{
_logger.Log("Adjust token session: " + sessionId.ToString());
if (!NativeMethods.SetTokenInformation(hDuplicateToken, NativeMethods.TOKEN_INFORMATION_CLASS.TokenSessionId, ref sessionId, (uint)Marshal.SizeOf(sessionId)))
{
_logger.Log("Failed to assign token session [SetTokenInformation=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
return hDuplicateToken;
}
}
Marshal.FreeHGlobal(pSessionId);
}
catch (Exception e)
{
_logger.Log(e, "Failed duplicating or elevating user token.");
}
return hDuplicateToken;
}
public List<Tuple<uint, string>> GetUserSessions()
{
var userSessions = new List<Tuple<uint, string>>();
try
{
IntPtr hServer = NativeMethods.WTSOpenServer(Environment.MachineName);
IntPtr hSessionInfo = IntPtr.Zero;
if (!NativeMethods.WTSEnumerateSessions(hServer, 0, 1, ref hSessionInfo, out UInt32 sessionCount))
{
_logger.Log("Failed to enumerate user sessions [WTSEnumerateSessions=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
}
else
{
Int32 sessionSize = Marshal.SizeOf(typeof(NativeMethods.WTS_SESSION_INFO));
IntPtr hCurSession = hSessionInfo;
for (int i = 1; i < sessionCount; i++)
{
NativeMethods.WTS_SESSION_INFO si = (NativeMethods.WTS_SESSION_INFO)Marshal.PtrToStructure(hCurSession, typeof(NativeMethods.WTS_SESSION_INFO));
if (!NativeMethods.WTSQueryUserToken(si.SessionID, out IntPtr hUserToken))
{
_logger.Log("Failed to query terminal user token [WTSQueryUserToken=" +
Marshal.GetLastWin32Error().ToString() + "] in session [" + si.SessionID.ToString() + "].", Logger.MsgType.ERROR);
}
else
{
WindowsIdentity userId = new WindowsIdentity(hUserToken);
_logger.Log("Found session: " + si.SessionID.ToString() + "/" + userId.Name);
userSessions.Add(new Tuple<uint, string>(si.SessionID, userId.Name));
userId.Dispose();
}
hCurSession += sessionSize;
}
NativeMethods.WTSFreeMemory(hSessionInfo);
}
NativeMethods.WTSCloseServer(hServer);
}
catch (Exception e)
{
_logger.Log(e, "Failed to query terminal user sessions.");
}
return userSessions;
}
public bool EnablePrivilege(IntPtr hToken, string privilege)
{
_logger.Log("Enable: " + privilege);
NativeMethods.LUID luid = new NativeMethods.LUID();
NativeMethods.TOKEN_PRIVILEGES newState;
newState.PrivilegeCount = 1;
newState.Privileges = new NativeMethods.LUID_AND_ATTRIBUTES[1];
if (!NativeMethods.LookupPrivilegeValue(null, privilege, ref luid))
{
_logger.Log("Unable to lookup privilege (LookupPrivilegeValue=" +
Marshal.GetLastWin32Error().ToString() + ").", Logger.MsgType.ERROR);
return false;
}
newState.Privileges[0].Luid = luid;
newState.Privileges[0].Attributes = NativeMethods.SE_PRIVILEGE_ENABLED;
if (!NativeMethods.AdjustTokenPrivileges(hToken, false, ref newState, (UInt32)Marshal.SizeOf(newState), out NativeMethods.TOKEN_PRIVILEGES oldState, out UInt32 outBytes))
{
_logger.Log("Unable to adjust token privileges (AdjustTokenPrivileges=" +
Marshal.GetLastWin32Error().ToString() + ").", Logger.MsgType.ERROR);
return false;
}
return true;
}
public IntPtr GetAdminUserToken()
{
try
{
uint consoleSessionId = NativeMethods.WTSGetActiveConsoleSessionId();
if (consoleSessionId != 0xFFFFFFFF)
{
_logger.Log("Found console session: " + consoleSessionId.ToString());
if (!NativeMethods.WTSQueryUserToken(consoleSessionId, out IntPtr hUserToken))
{
_logger.Log("Failed to query console user token [WTSQueryUserToken=" + Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
}
else
{
WindowsIdentity userId = new WindowsIdentity(hUserToken);
_logger.Log("Console user: " + userId.Name);
userId.Dispose();
if (!IsUserInAdminGroup(hUserToken))
{
_logger.Log("Console user is not an administrator.", Logger.MsgType.WARN);
}
else
{
_logger.Log("Console user is an administrator.");
return hUserToken;
}
}
}
}
catch (Exception e)
{
_logger.Log(e, "Failed to query console user session.");
}
try
{
IntPtr hServer = NativeMethods.WTSOpenServer(Environment.MachineName);
IntPtr hSessionInfo = IntPtr.Zero;
if (!NativeMethods.WTSEnumerateSessions(hServer, 0, 1, ref hSessionInfo, out UInt32 sessionCount))
{
_logger.Log("Failed to enumerate user sessions [WTSEnumerateSessions=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
}
else
{
Int32 sessionSize = Marshal.SizeOf(typeof(NativeMethods.WTS_SESSION_INFO));
IntPtr hCurSession = hSessionInfo;
for (int i = 0; i < sessionCount; i++)
{
NativeMethods.WTS_SESSION_INFO si = (NativeMethods.WTS_SESSION_INFO)Marshal.PtrToStructure(hCurSession, typeof(NativeMethods.WTS_SESSION_INFO));
_logger.Log("Found session: " + si.SessionID.ToString());
if (!NativeMethods.WTSQueryUserToken(si.SessionID, out IntPtr hUserToken))
{
_logger.Log("Failed to query terminal user token [WTSQueryUserToken=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
}
else
{
WindowsIdentity userId = new WindowsIdentity(hUserToken);
_logger.Log("Terminal user: " + userId.Name);
userId.Dispose();
if (!IsUserInAdminGroup(hUserToken))
{
_logger.Log("Terminal user is not an administrator.", Logger.MsgType.WARN);
}
else
{
_logger.Log("Terminal user is an administrator");
return hUserToken;
}
}
hCurSession += sessionSize;
}
NativeMethods.WTSFreeMemory(hSessionInfo);
}
NativeMethods.WTSCloseServer(hServer);
}
catch (Exception e)
{
_logger.Log(e, "Failed to query terminal user sessions.");
}
return IntPtr.Zero;
}
public IntPtr GetConsoleUserToken()
{
try
{
uint consoleSessionId = NativeMethods.WTSGetActiveConsoleSessionId();
if (consoleSessionId != 0xFFFFFFFF)
{
_logger.Log("Found console session: " + consoleSessionId.ToString());
if (!NativeMethods.WTSQueryUserToken(consoleSessionId, out IntPtr hUserToken))
{
_logger.Log("Failed to query console user token [WTSQueryUserToken=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
}
else
{
WindowsIdentity userId = new WindowsIdentity(hUserToken);
_logger.Log("Console user: " + userId.Name);
userId.Dispose();
return hUserToken;
}
}
}
catch (Exception e)
{
_logger.Log(e, "Failed to query console user session.");
}
return IntPtr.Zero;
}
public string GetTimeStamp()
{
return DateTime.Now.ToString("yyyy-MM-dd--HH.mm.ss");
}
public string GetUninstallReg(string displayName)
{
if (Environment.Is64BitOperatingSystem)
{
RegistryKey localMachine64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey uninstallKey64 = localMachine64.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false);
foreach (string subKeyName in uninstallKey64.GetSubKeyNames())
{
try
{
RegistryKey productKey = uninstallKey64.OpenSubKey(subKeyName, false);
var displayNameValue = productKey.GetValue("DisplayName");
if (displayNameValue != null)
{
if (displayNameValue.ToString().ToLower().Equals(displayName.ToLower()))
{
uninstallKey64.Dispose();
localMachine64.Dispose();
return "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + subKeyName;
}
}
productKey.Dispose();
}
catch (Exception e)
{
_logger.Log(e, "Failed to open product key [" + subKeyName + "].");
continue;
}
}
uninstallKey64.Dispose();
localMachine64.Dispose();
}
RegistryKey localMachine32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
RegistryKey uninstallKey32 = localMachine32.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false);
foreach (string subKeyName in uninstallKey32.GetSubKeyNames())
{
try
{
RegistryKey productKey = uninstallKey32.OpenSubKey(subKeyName, false);
var displayNameValue = productKey.GetValue("DisplayName");
if (displayNameValue != null)
{
if (displayNameValue.ToString().ToLower().Equals(displayName.ToLower()))
{
uninstallKey32.Dispose();
localMachine32.Dispose();
return "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + subKeyName;
}
}
productKey.Dispose();
}
catch (Exception e)
{
_logger.Log(e, "Failed to open product key [" + subKeyName + "].");
continue;
}
}
uninstallKey32.Dispose();
localMachine32.Dispose();
return null;
}
public string GetUninstallString(string displayName)
{
bool foundApp = false;
string returnString = null;
if (Environment.Is64BitOperatingSystem)
{
RegistryKey localMachine64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey uninstallKey64 = localMachine64.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false);
foreach (string subKeyName in uninstallKey64.GetSubKeyNames())
{
try
{
RegistryKey productKey = uninstallKey64.OpenSubKey(subKeyName, false);
var displayNameValue = productKey.GetValue("DisplayName");
if (displayNameValue != null)
{
if (displayNameValue.ToString().ToLower().Equals(displayName.ToLower()))
{
foundApp = true;
var uninstStringValue = productKey.GetValue("UninstallString");
if (uninstStringValue != null)
{
returnString = uninstStringValue.ToString();
}
break;
}
}
productKey.Dispose();
}
catch (Exception e)
{
_logger.Log(e, "Failed to open product key [" + subKeyName + "].");
continue;
}
}
uninstallKey64.Dispose();
localMachine64.Dispose();
if (foundApp)
{
return returnString;
}
}
RegistryKey localMachine32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
RegistryKey uninstallKey32 = localMachine32.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false);
foreach (string subKeyName in uninstallKey32.GetSubKeyNames())
{
try
{
RegistryKey productKey = uninstallKey32.OpenSubKey(subKeyName, false);
var displayNameValue = productKey.GetValue("DisplayName");
if (displayNameValue != null)
{
if (displayNameValue.ToString().ToLower().Equals(displayName.ToLower()))
{
foundApp = true;
var uninstStringValue = productKey.GetValue("UninstallString");
if (uninstStringValue != null)
{
returnString = uninstStringValue.ToString();
}
break;
}
}
productKey.Dispose();
}
catch (Exception e)
{
_logger.Log(e, "Failed to open product key [" + subKeyName + "].");
continue;
}
}
uninstallKey32.Dispose();
localMachine32.Dispose();
if (foundApp)
{
return returnString;
}
else
{
return returnString;
}
}
private static void GrantAccess(string username, IntPtr handle, int accessMask)
{
SafeHandle safeHandle = new NativeMethods.NoopSafeHandle(handle);
NativeMethods.GenericSecurity security = new NativeMethods.GenericSecurity(false, ResourceType.WindowObject, safeHandle, AccessControlSections.Access);
security.AddAccessRule(new NativeMethods.GenericAccessRule(new NTAccount(username), accessMask, AccessControlType.Allow));
security.Persist(safeHandle, AccessControlSections.Access);
}
public void GrantAccessToWindowStationAndDesktop(string username)
{
IntPtr handle;
const int WindowStationAllAccess = 0x000f037f;
handle = NativeMethods.GetProcessWindowStation();
GrantAccess(username, handle, WindowStationAllAccess);
const int DesktopRightsAllAccess = 0x000f01ff;
handle = NativeMethods.GetThreadDesktop(NativeMethods.GetCurrentThreadId());
GrantAccess(username, handle, DesktopRightsAllAccess);
}
public bool ImportCertificate(
string certFilename,
string certPassword = "",
StoreName certStore = StoreName.My,
StoreLocation certLocation = StoreLocation.CurrentUser)
{
try
{
if (!File.Exists(certFilename))
{
_logger.Log("Specified certifcate file does not exist [" + certFilename + "].", Logger.MsgType.ERROR);
return false;
}
X509Certificate2 importCert = null;
if (certPassword != "")
{
importCert = new X509Certificate2(certFilename, certPassword);
}
else
{
importCert = new X509Certificate2(certFilename);
}
var store = new X509Store(certStore, certLocation);
store.Open(OpenFlags.ReadWrite);
if (!store.Certificates.Contains(importCert))
{
_logger.Log("Import certificate...");
store.Add(importCert);
_logger.Log("Certifcate imported successfully.");
}
else
{
_logger.Log("Certificate already imported.");
}
store.Dispose();
return true;
}
catch (Exception e)
{
_logger.Log(e, "Failed to import certificate.");
return false;
}
}
public bool IncreaseProcessPrivileges(Process targetProcess)
{
IntPtr hProcess = targetProcess.Handle;
if (!NativeMethods.OpenProcessToken(hProcess, NativeMethods.TOKEN_ALL_ACCESS, out IntPtr hToken))
{
_logger.Log("Unable to open specified process token [OpenProcessToken=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
return false;
}
return IncreaseTokenPrivileges(hToken);
}
public bool IncreaseTokenPrivileges(IntPtr hToken)
{
if (!EnablePrivilege(hToken, NativeMethods.SE_INCREASE_QUOTA_NAME))
{
_logger.Log("Failed to enable privilege [SeIncreaseQuotaPrivilege].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
if (!EnablePrivilege(hToken, NativeMethods.SE_ASSIGNPRIMARYTOKEN_NAME))
{
_logger.Log("Failed to enable privilege [SeAssignPrimaryTokenPrivilege].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
if (!EnablePrivilege(hToken, NativeMethods.SE_TCB_NAME))
{
_logger.Log("Failed to enable privilege [SeTcbPrivilege].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
if (!EnablePrivilege(hToken, NativeMethods.SE_DEBUG_NAME))
{
_logger.Log("Failed to enable privilege [SeDebugPrivilege].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
if (!EnablePrivilege(hToken, NativeMethods.SE_IMPERSONATE_NAME))
{
_logger.Log("Failed to enable privilege [SeImpersonatePrivilege].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
if (!EnablePrivilege(hToken, NativeMethods.SE_TIME_ZONE_NAME))
{
_logger.Log("Failed to enable privilege [SeTimeZonePrivilege].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
if (!EnablePrivilege(hToken, NativeMethods.SE_SYSTEMTIME_NAME))
{
_logger.Log("Failed to enable privilege [SeSystemtimePrivilege].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
if (!EnablePrivilege(hToken, NativeMethods.SE_SHUTDOWN_NAME))
{
_logger.Log("Failed to enable privilege [SeShutdownPrivilege].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
if (!EnablePrivilege(hToken, NativeMethods.SE_TAKE_OWNERSHIP_NAME))
{
_logger.Log("Failed to enable privilege [SeTakeOwnershipPrivilege].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
Marshal.FreeHGlobal(hToken);
return true;
}
public bool IsAppInstalled(string displayName)
{
bool foundApp = false;
if (Environment.Is64BitOperatingSystem)
{
RegistryKey localMachine64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey uninstallKey64 = localMachine64.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false);
foreach (string subKeyName in uninstallKey64.GetSubKeyNames())
{
try
{
RegistryKey productKey = uninstallKey64.OpenSubKey(subKeyName, false);
var displayNameValue = productKey.GetValue("DisplayName");
if (displayNameValue != null)
{
if (displayNameValue.ToString().ToLower().Equals(displayName.ToLower()))
{
foundApp = true;
break;
}
}
productKey.Dispose();
}
catch (Exception e)
{
_logger.Log(e, "Failed to open product key [" + subKeyName + "].");
continue;
}
}
uninstallKey64.Dispose();
localMachine64.Dispose();
if (foundApp)
{
return true;
}
}
RegistryKey localMachine32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
RegistryKey uninstallKey32 = localMachine32.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false);
foreach (string subKeyName in uninstallKey32.GetSubKeyNames())
{
try
{
RegistryKey productKey = uninstallKey32.OpenSubKey(subKeyName, false);
var displayNameValue = productKey.GetValue("DisplayName");
if (displayNameValue != null)
{
if (displayNameValue.ToString().ToLower().Equals(displayName.ToLower()))
{
foundApp = true;
break;
}
}
productKey.Dispose();
}
catch (Exception e)
{
_logger.Log(e, "Failed to open product key [" + subKeyName + "].");
continue;
}
}
uninstallKey32.Dispose();
localMachine32.Dispose();
if (foundApp)
{
return true;
}
else
{
return false;
}
}
public bool IsAutoLogonConfigred(out string logonUser, out string logonPwd)
{
int autoAdminLogon = -1;
logonUser = null;
logonPwd = null;
try
{
_logger.Log("Read logon configuration...");
RegistryKey winLogonKey = new RegistryHelper(_logger)
.OpenKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", true, RegistryHive.LocalMachine);
var curAutoAdminLogon = winLogonKey.GetValue("AutoAdminLogon");
var curAutoLogonCount = winLogonKey.GetValue("AutoLogonCount");
var curDefaultUserName = winLogonKey.GetValue("DefaultUserName");
var curDefaultPassword = winLogonKey.GetValue("DefaultPassword");
var curDisableCAD = winLogonKey.GetValue("DisableCAD");
if (curAutoAdminLogon != null)
{
if (!int.TryParse(curAutoAdminLogon.ToString(), out autoAdminLogon))
{
autoAdminLogon = -1;
}
_logger.Log(" AutoAdminLogon: " + autoAdminLogon.ToString());
}
else
{
_logger.Log(" AutoAdminLogon: <Not Available>");
}
if (curAutoLogonCount != null)
{
if (!int.TryParse(curAutoLogonCount.ToString(), out int autoLogonCount))
{
autoLogonCount = -1;
}
_logger.Log(" AutoLogonCount: " + autoLogonCount.ToString());
}
else
{
_logger.Log(" AutoLogonCount: <Not Available>");
}
if (curDefaultUserName != null)
{
logonUser = curDefaultUserName.ToString();
_logger.Log(" DefaultUserName: " + logonUser);
}
else
{
_logger.Log(" DefaultUserName: <Not Available>");
}
if (curDefaultPassword != null)
{
logonPwd = curDefaultPassword.ToString();
_logger.Log(" DefaultPassword: <Not Displayed>");
}
else
{
_logger.Log(" DefaultPassword: <Not Available>");
}
if (curDisableCAD != null)
{
if (!int.TryParse(curDisableCAD.ToString(), out int disableCAD))
{
disableCAD = -1;
}
_logger.Log(" DisableCAD: " + disableCAD.ToString());
}
else
{
_logger.Log(" DisableCAD: <Not Available>");
}
if (autoAdminLogon == 1 && !logonUser.Equals(""))
{
_logger.Log("Automatic logon: CONFIGURED");
return true;
}
else
{
_logger.Log("Automatic logon: NOT CONFIGURED");
return false;
}
}
catch (Exception e)
{
_logger.Log(e, "Failed to inspect automatic logon configuration.");
return false;
}
}
public bool IsDomainUser(string userName, string domainName)
{
bool userExists = false;
try
{
using (var domainContext = new PrincipalContext(ContextType.Domain, domainName))
{
using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
{
if (foundUser != null)
{
userExists = true;
}
}
}
}
catch (Exception e)
{
_logger.Log(e, "Failed to validate domain user credentials.");
}
return userExists;
}
public bool IsLocalUser(string userName)
{
bool userExists = false;
try
{
using (var localContext = new PrincipalContext(ContextType.Machine))
{
using (var foundUser = UserPrincipal.FindByIdentity(localContext, IdentityType.SamAccountName, userName))
{
if (foundUser != null)
{
userExists = true;
}
}
}
}
catch (Exception e)
{
_logger.Log(e, "Failed to validate local user credentials.");
}
return userExists;
}
public bool IsTokenElevated(IntPtr hToken)
{
if (Environment.OSVersion.Version.Major >= 6)
{
int cbSize = sizeof(NativeMethods.TOKEN_ELEVATION_TYPE);
IntPtr pElevationType = Marshal.AllocHGlobal(cbSize);
if (pElevationType == IntPtr.Zero)
{
_logger.Log("Failed to allocate memory for token elevation check.", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
return false;
}
if (!NativeMethods.GetTokenInformation(hToken,
NativeMethods.TOKEN_INFORMATION_CLASS.TokenElevationType,
pElevationType,
cbSize,
out cbSize))
{
_logger.Log("Failed to query user-token elevation type [GetTokenInformation=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hToken);
Marshal.FreeHGlobal(pElevationType);
return false;
}
NativeMethods.TOKEN_ELEVATION_TYPE elevType = (NativeMethods.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(pElevationType);
if (elevType == NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
{
/* Type 3 is a limited token with administrative privileges removed
* and administrative groups disabled. The limited token is used when
* User Account Control is enabled, the application does not require
* administrative privilege, and the user does not choose to start
* the program using Run as administrator.*/
_logger.Log("Token elevation type: Limited.");
Marshal.FreeHGlobal(hToken);
Marshal.FreeHGlobal(pElevationType);
return false;
}
else if (elevType == NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault)
{
/* Type 1 is a full token with no privileges removed or groups disabled.
* A full token is only used if User Account Control is disabled or if
* the user is the built -in Administrator account (for which UAC
* disabled by default), service account or local system account.*/
_logger.Log("Token elevation type: Default.");
Marshal.FreeHGlobal(hToken);
Marshal.FreeHGlobal(pElevationType);
return true;
}
else if (elevType == NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull)
{
/* Type 2 is an elevated token with no privileges removed or groups
* disabled. An elevated token is used when User Account Control is
* enabled and the user chooses to start the program using Run as
* administrator. An elevated token is also used when an application
* is configured to always require administrative privilege or to
* always require maximum privilege, and the user is a member of the
* Administrators group.*/
_logger.Log("Token elevation type: Full.");
Marshal.FreeHGlobal(hToken);
Marshal.FreeHGlobal(pElevationType);
return true;
}
else
{
_logger.Log("Token elevation type: Unknown.");
Marshal.FreeHGlobal(hToken);
Marshal.FreeHGlobal(pElevationType);
return false;
}
}
else
{
Marshal.FreeHGlobal(hToken);
return true;
}
}
public bool IsUACEnabled()
{
bool isUserAccountControlEnabled = false;
try
{
if (Environment.Is64BitOperatingSystem)
{
RegistryKey localMachine64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey systemPolicies = localMachine64.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
if (systemPolicies != null)
{
int enableLua = int.Parse(systemPolicies.GetValue("EnableLUA").ToString());
if (enableLua == 1)
{
_logger.Log("User account control (UAC): Enabled");
isUserAccountControlEnabled = true;
}
else
{
_logger.Log("User account control (UAC): Disabled");
isUserAccountControlEnabled = false;
}
}
localMachine64.Dispose();
}
else
{
RegistryKey localMachine32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
RegistryKey systemPolicies = localMachine32.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
if (systemPolicies != null)
{
int enableLua = int.Parse(systemPolicies.GetValue("EnableLUA").ToString());
if (enableLua == 1)
{
_logger.Log("User account control (UAC): Enabled");
isUserAccountControlEnabled = true;
}
else
{
_logger.Log("User account control (UAC): Disabled");
isUserAccountControlEnabled = false;
}
}
localMachine32.Dispose();
}
}
catch (Exception e)
{
_logger.Log(e, "Failed to determine if UAC is enabled.");
return isUserAccountControlEnabled;
}
return isUserAccountControlEnabled;
}
public bool IsUserInAdminGroup(IntPtr hToken)
{
// Is UAC enabled?
/*
* Note: In Windows Vista and newer, one cannot simply check if the user account is in
* the administrators group. It depends on whether or not the user possesses an
* elevated token. To do this, we must query the user's access token, and check
* for a linked token that indicates they have elevation privileges or not.
* Otherwise, you may get a false negative, e.g. the user is an admin, but
* UserPrincipal.IsInRole() returns false. Ohh the simpler times. We miss them.
* I feel like .NET needs a native library for this. I dislike having to user
* unmanaged code.
*/
if (IsUACEnabled())
{
bool fInAdminGroup = false;
IntPtr hTokenToCheck = IntPtr.Zero;
IntPtr pElevationType = IntPtr.Zero;
IntPtr pLinkedToken = IntPtr.Zero;
int cbSize = 0;
try
{
if (Environment.OSVersion.Version.Major >= 6)
{
cbSize = sizeof(NativeMethods.TOKEN_ELEVATION_TYPE);
pElevationType = Marshal.AllocHGlobal(cbSize);
if (pElevationType == IntPtr.Zero)
{
_logger.Log("Failed to allocate memory for token elevation check.", Logger.MsgType.ERROR);
return false;
}
if (!NativeMethods.GetTokenInformation(hToken, NativeMethods.TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType, cbSize, out cbSize))
{
_logger.Log("Failed to query token elevation type [GetTokenInformation=" + Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
return false;
}
NativeMethods.TOKEN_ELEVATION_TYPE elevType = (NativeMethods.TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(pElevationType);
if (elevType == NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
{
_logger.Log("Token elevation type: Limited.");
cbSize = IntPtr.Size;
pLinkedToken = Marshal.AllocHGlobal(cbSize);
if (pLinkedToken == IntPtr.Zero)
{
_logger.Log("Failed to allocate memory for linked token check.", Logger.MsgType.ERROR);
return false;
}
if (!NativeMethods.GetTokenInformation(hToken, NativeMethods.TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken, cbSize, out cbSize))
{
_logger.Log("Failed to query LINKED token [GetTokenInformation=" + Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
return false;
}
else
{
_logger.Log("Token has a Linked token.", Logger.MsgType.DEBUG);
}
hTokenToCheck = Marshal.ReadIntPtr(pLinkedToken);
}
else if (elevType == NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault)
{
_logger.Log("Token elevation type: Default.", Logger.MsgType.DEBUG);
}
else if (elevType == NativeMethods.TOKEN_ELEVATION_TYPE.TokenElevationTypeFull)
{
_logger.Log("Token elevation type: Full.", Logger.MsgType.DEBUG);
}
else
{
_logger.Log("Token elevation type: Unknown.", Logger.MsgType.DEBUG);
}
}
if (hTokenToCheck == IntPtr.Zero)
{
if (!NativeMethods.DuplicateToken(hToken, NativeMethods.SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, out hTokenToCheck))
{
_logger.Log("Failed to duplicate ORIGNAL access token [DuplicateToken=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
return false;
}
}
WindowsIdentity id = new WindowsIdentity(hTokenToCheck);
WindowsPrincipal principal = new WindowsPrincipal(id);
fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator);
id.Dispose();
}
catch (Exception e)
{
_logger.Log(e, "Failed to verify if user token is in admin group.");
return false;
}
finally
{
if (hToken != IntPtr.Zero)
{
hToken = IntPtr.Zero;
}
if (hTokenToCheck != IntPtr.Zero)
{
hTokenToCheck = IntPtr.Zero;
}
if (pElevationType != IntPtr.Zero)
{
Marshal.FreeHGlobal(pElevationType);
pElevationType = IntPtr.Zero;
}
if (pLinkedToken != IntPtr.Zero)
{
Marshal.FreeHGlobal(pLinkedToken);
pLinkedToken = IntPtr.Zero;
}
}
return fInAdminGroup;
}
else
{
WindowsIdentity userId = new WindowsIdentity(hToken);
WindowsPrincipal userPrincipal = new WindowsPrincipal(userId);
if (userPrincipal.IsInRole("Administrators") || userPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
userId.Dispose();
return true;
}
else
{
userId.Dispose();
return false;
}
}
}
public bool IsUserInAdminGroup(WindowsIdentity userToCheck)
{
if (new WindowsPrincipal(userToCheck).IsInRole(WindowsBuiltInRole.Administrator))
{
return true;
}
try
{
uint entriesRead = 0, totalEntries = 0;
unsafe
{
int LOCALGROUP_INFO_1_SIZE = sizeof(NativeMethods.LOCALGROUP_INFO_1);
int LOCALGROUP_MEMBERS_INFO_1_SIZE = sizeof(NativeMethods.LOCALGROUP_MEMBERS_INFO_1);
IntPtr groupInfoPtr, userInfoPtr;
groupInfoPtr = IntPtr.Zero;
userInfoPtr = IntPtr.Zero;
NativeMethods.NetLocalGroupEnum(IntPtr.Zero, 1, ref groupInfoPtr, 0xFFFFFFFF, ref entriesRead, ref totalEntries, IntPtr.Zero);
for (int i = 0; i < totalEntries; i++)
{
int newOffset = 0;
long newOffset64 = 0;
NativeMethods.LOCALGROUP_INFO_1 groupInfo;
if (Environment.Is64BitOperatingSystem)
{
newOffset64 = groupInfoPtr.ToInt64() + LOCALGROUP_INFO_1_SIZE * i;
groupInfo = (NativeMethods.LOCALGROUP_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset64), typeof(NativeMethods.LOCALGROUP_INFO_1));
}
else
{
newOffset = groupInfoPtr.ToInt32() + LOCALGROUP_INFO_1_SIZE * i;
groupInfo = (NativeMethods.LOCALGROUP_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset), typeof(NativeMethods.LOCALGROUP_INFO_1));
}
string currentGroupName = Marshal.PtrToStringAuto(groupInfo.lpszGroupName);
_logger.Log("Group: " + currentGroupName, Logger.MsgType.DEBUG);
if (currentGroupName.ToLower().Equals("administrators"))
{
uint entriesRead1 = 0, totalEntries1 = 0;
NativeMethods.NetLocalGroupGetMembers(IntPtr.Zero, groupInfo.lpszGroupName, 1, ref userInfoPtr, 0xFFFFFFFF, ref entriesRead1, ref totalEntries1, IntPtr.Zero);
for (int j = 0; j < totalEntries1; j++)
{
NativeMethods.LOCALGROUP_MEMBERS_INFO_1 memberInfo;
int newOffset1 = 0;
long newOffset1_64 = 0;
if (Environment.Is64BitOperatingSystem)
{
newOffset1_64 = userInfoPtr.ToInt64() + LOCALGROUP_MEMBERS_INFO_1_SIZE * j;
memberInfo = (NativeMethods.LOCALGROUP_MEMBERS_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset1_64), typeof(NativeMethods.LOCALGROUP_MEMBERS_INFO_1));
}
else
{
newOffset1 = userInfoPtr.ToInt32() + LOCALGROUP_MEMBERS_INFO_1_SIZE * j;
memberInfo = (NativeMethods.LOCALGROUP_MEMBERS_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset1), typeof(NativeMethods.LOCALGROUP_MEMBERS_INFO_1));
}
string currentUserName = Marshal.PtrToStringAuto(memberInfo.lgrmi1_name);
_logger.Log(" Member: " + currentUserName, Logger.MsgType.DEBUG);
if (currentUserName.ToLower().Equals(userToCheck.Name.ToLower()) ||
(userToCheck.Name.Contains("\\") && currentUserName.ToLower().Equals(
userToCheck.Name.ToLower().Substring(userToCheck.Name.IndexOf("\\") + 1))))
{
NativeMethods.NetApiBufferFree(userInfoPtr);
NativeMethods.NetApiBufferFree(groupInfoPtr);
return true;
}
}
NativeMethods.NetApiBufferFree(userInfoPtr);
break;
}
}
NativeMethods.NetApiBufferFree(groupInfoPtr);
}
}
catch (Exception e)
{
_logger.Log(e, "Failed to determine admin group membership [NativeMethods.method].");
}
return false;
}
public bool IsUserInAdminGroup(string userName)
{
try
{
uint entriesRead = 0, totalEntries = 0;
unsafe
{
int LOCALGROUP_INFO_1_SIZE = sizeof(NativeMethods.LOCALGROUP_INFO_1);
int LOCALGROUP_MEMBERS_INFO_1_SIZE = sizeof(NativeMethods.LOCALGROUP_MEMBERS_INFO_1);
IntPtr groupInfoPtr, userInfoPtr;
groupInfoPtr = IntPtr.Zero;
userInfoPtr = IntPtr.Zero;
NativeMethods.NetLocalGroupEnum(IntPtr.Zero, 1, ref groupInfoPtr, 0xFFFFFFFF, ref entriesRead, ref totalEntries, IntPtr.Zero);
for (int i = 0; i < totalEntries; i++)
{
int newOffset = 0;
long newOffset64 = 0;
NativeMethods.LOCALGROUP_INFO_1 groupInfo;
if (Environment.Is64BitOperatingSystem)
{
newOffset64 = groupInfoPtr.ToInt64() + LOCALGROUP_INFO_1_SIZE * i;
groupInfo = (NativeMethods.LOCALGROUP_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset64), typeof(NativeMethods.LOCALGROUP_INFO_1));
}
else
{
newOffset = groupInfoPtr.ToInt32() + LOCALGROUP_INFO_1_SIZE * i;
groupInfo = (NativeMethods.LOCALGROUP_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset), typeof(NativeMethods.LOCALGROUP_INFO_1));
}
string currentGroupName = Marshal.PtrToStringAuto(groupInfo.lpszGroupName);
_logger.Log("Group: " + currentGroupName, Logger.MsgType.DEBUG);
if (currentGroupName.ToLower().Equals("administrators"))
{
uint entriesRead1 = 0, totalEntries1 = 0;
NativeMethods.NetLocalGroupGetMembers(IntPtr.Zero, groupInfo.lpszGroupName, 1, ref userInfoPtr, 0xFFFFFFFF, ref entriesRead1, ref totalEntries1, IntPtr.Zero);
for (int j = 0; j < totalEntries1; j++)
{
NativeMethods.LOCALGROUP_MEMBERS_INFO_1 memberInfo;
int newOffset1 = 0;
long newOffset1_64 = 0;
if (Environment.Is64BitOperatingSystem)
{
newOffset1_64 = userInfoPtr.ToInt64() + LOCALGROUP_MEMBERS_INFO_1_SIZE * j;
memberInfo = (NativeMethods.LOCALGROUP_MEMBERS_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset1_64), typeof(NativeMethods.LOCALGROUP_MEMBERS_INFO_1));
}
else
{
newOffset1 = userInfoPtr.ToInt32() + LOCALGROUP_MEMBERS_INFO_1_SIZE * j;
memberInfo = (NativeMethods.LOCALGROUP_MEMBERS_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset1), typeof(NativeMethods.LOCALGROUP_MEMBERS_INFO_1));
}
string currentUserName = Marshal.PtrToStringAuto(memberInfo.lgrmi1_name);
_logger.Log(" Member: " + currentUserName, Logger.MsgType.DEBUG);
if (currentUserName.ToLower().Equals(userName.ToLower()) ||
(userName.Contains("\\") && currentUserName.ToLower().Equals(
userName.ToLower().Substring(userName.IndexOf("\\") + 1))))
{
NativeMethods.NetApiBufferFree(userInfoPtr);
NativeMethods.NetApiBufferFree(groupInfoPtr);
return true;
}
}
NativeMethods.NetApiBufferFree(userInfoPtr);
break;
}
}
NativeMethods.NetApiBufferFree(groupInfoPtr);
}
}
catch (Exception e)
{
_logger.Log(e, "Failed to determine admin group membership [NativeMethods.method].");
}
return false;
}
public bool RebootSystem(
uint delaySeconds = 10,
string comment = null,
NativeMethods.ShutdownReason shutdownReason =
NativeMethods.ShutdownReason.MajorOther |
NativeMethods.ShutdownReason.MinorOther)
{
IntPtr hProcess = Process.GetCurrentProcess().Handle;
if (!NativeMethods.OpenProcessToken(hProcess, NativeMethods.TOKEN_ALL_ACCESS, out IntPtr hToken))
{
_logger.Log("Unable to open specified process token [OpenProcessToken=" + Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
Marshal.FreeHGlobal(hProcess);
return false;
}
if (!EnablePrivilege(hToken, NativeMethods.SE_SHUTDOWN_NAME))
{
_logger.Log("Failed to enable privilege [SeShutdownPrivilege].", Logger.MsgType.WARN);
Marshal.FreeHGlobal(hProcess);
Marshal.FreeHGlobal(hToken);
return false;
}
Marshal.FreeHGlobal(hProcess);
Marshal.FreeHGlobal(hToken);
if (comment == null || comment == "")
{
string processName = Process.GetCurrentProcess().MainModule.FileName;
string shortName = processName.Substring(processName.LastIndexOf("\\") + 1);
string friendlyName = shortName.Substring(0, shortName.LastIndexOf("."));
comment = friendlyName + " initiated a reboot of the system.";
}
_logger.Log($"Windows reboot [{comment}]");
if (!NativeMethods.InitiateSystemShutdownEx(null, comment, delaySeconds, true, true, shutdownReason))
{
int lastError = Marshal.GetLastWin32Error();
/* Is this an unexpected error code?
1115/0x45B --> A system shutdown is in progress.
1190/0x4A6 --> A system shutdown has already been scheduled.
*/
if (lastError != 1115 && lastError != 1190)
{
_logger.Log("Failed to initiate reboot [InitiateSystemShutdownEx=" +
Marshal.GetLastWin32Error().ToString() + "].", Logger.MsgType.ERROR);
return false;
}
else if (lastError == 1115)
{
_logger.Log("REBOOT: A system shutdown is in progress.");
}
else if (lastError == 1190)
{
_logger.Log("REBOOT: A system shutdown has already been scheduled.");
}
}
else
{
_logger.Log($"REBOOT: System will restart in ({delaySeconds}) seconds.");
}
return true;
}
public string[] SynthesizeCommandLineArgs()
{
StringBuilder argCrawler = new StringBuilder(Environment.CommandLine);
char nextChar = '\0';
char currentChar = '\0';
char previousChar = '\0';
int quoteLevel = 0;
bool inQuote = false;
for (int i = 0; i < argCrawler.Length; i++)
{
// Ternary character scope
previousChar = currentChar;
currentChar = argCrawler[i];
// Are we near end of string?
if (i < argCrawler.Length - 1)
{
// Scope next character
nextChar = argCrawler[i + 1];
}
else
{
// Stub null char
nextChar = '\0';
}
// Is this a START QUOTE?
if ((previousChar == '\0' && currentChar == '\"' && nextChar != '\0') || (previousChar == ' ' && currentChar == '\"' && nextChar != '\0'))
{
inQuote = true;
quoteLevel += 1;
}
// Is this an END QUOTE?
if (inQuote && ((currentChar == '\"' && nextChar == ' ') || (currentChar == '\"' && nextChar == '\0')))
{
quoteLevel -= 1;
if (quoteLevel == 0)
{
inQuote = false;
}
}
// Is this a space character, outside of quoted text?
if (argCrawler[i].Equals(' ') && !inQuote)
{
argCrawler[i] = '\n';
}
}
string[] synthArgs = argCrawler.ToString().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (synthArgs.Length > 1)
{
for (int i = 1; i < synthArgs.Length; i++)
{
// If quoted, unquote the argument
// Note: Quotes were needed to distinctly identify the argument from other arguments, but otherwise serve no purpose.
// Note: Carful not to trim quotes-- we only want to trim a single/outer mathcing pair.
if (synthArgs[i].StartsWith("\"") && synthArgs[i].EndsWith("\""))
{
synthArgs[i] = synthArgs[i].Substring(1, synthArgs[i].Length - 2);
}
_logger.Log("Argument [" + i.ToString() + "]: " + synthArgs[i]);
}
}
else
{
_logger.Log("Arguments: <None>");
}
return synthArgs;
}
}
} | 41.619825 | 189 | 0.484869 | [
"MIT"
] | CodeFontana/WindowsHelpers-Net-Framework | WindowsNative/WindowsHelper.cs | 71,380 | C# |
using Paramore.Brighter;
using System;
namespace Greetings.Ports.Events
{
public class GreetingEvent : Event
{
public GreetingEvent() : base(Guid.NewGuid()) { }
public GreetingEvent(string greeting) : base(Guid.NewGuid())
{
Greeting = greeting;
}
public string Greeting { get; set; }
}
}
| 19.777778 | 68 | 0.601124 | [
"MIT"
] | BrighterCommand/Brighter | samples/ASBTaskQueue/Greetings/Ports/Events/GreetingEvent.cs | 358 | C# |
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using Server.Packets;
namespace Server.Protocols.Data {
[ADataProtocol("json")]
sealed class DataProtocolJSON : IDataProtocol {
static private IDataProtocol instance = new DataProtocolJSON();
private string name;
private DataProtocolJSON() {
}
public DataPacket Read(byte[] data) {
string dataJSON = Encoding.UTF8.GetString(data).Replace(@"\""", """).Replace(@"<", "<").Replace(@"<", ">");
string packetName = this.GetName(dataJSON);
if(!string.IsNullOrEmpty(packetName)) {
PacketType packet = PacketFactory.Get(packetName);
if(packet != null) {
DataPacket dataPacket = new DataPacket(packet);
foreach(PacketField field in packet.Fields) {
string value = string.Empty;
if(field.DataType != null) {
IPacketDataTypeParser parser = field.DataType.GetParser(this.name);
if(parser != null) {
switch(field.DataType.Name) {
case "bool":
value = this.GetValueBool(dataJSON, field.Name);
break;
case "byte":
case "sbyte":
case "short":
case "ushort":
case "int":
case "uint":
case "long":
case "ulong":
case "float":
case "double":
case "timespan":
value = this.GetValueNumber(dataJSON, field.Name);
break;
case "string":
value = this.GetValueString(dataJSON, field.Name);
break;
default:
Log.Add("unknown data type: " + field.DataType.Name);
break;
}
if(!string.IsNullOrEmpty(value)) {
dataPacket[field] = field.DataType.GetParser(this.name).Read(value);
}
} else {
Log.Add("no data type (" + field.DataType.Name + ") parser for " + this.name + " protocol");
}
} else {
Log.Add("unknown data type, field: " + field.Name);
}
}
return dataPacket;
} else {
Log.Add("unknown packet: " + packetName);
return null;
}
} else {
Log.Add("wrong packet (no type)");
return null;
}
}
private string GetName(string dataJSON) {
Match result = Regex.Match(dataJSON, @"^{\s?""type""\s?:\s?""(?<value>[a-zA-Z_]+)""\s?", RegexOptions.ExplicitCapture | RegexOptions.Multiline);
if(result.Success && result.Groups["value"] != null) {
return result.Groups["value"].Value;
} else {
return string.Empty;
}
}
private string GetValueBool(string dataJSON, string fieldName) {
Match result = Regex.Match(dataJSON, @"""" + fieldName + @"""\s?:\s?(?<value>(true|false))", RegexOptions.ExplicitCapture | RegexOptions.Multiline);
if(result.Success && result.Groups["value"] != null) {
return result.Groups["value"].Value;
} else {
return string.Empty;
}
}
private string GetValueNumber(string dataJSON, string fieldName) {
Match result = Regex.Match(dataJSON, @"""" + fieldName + @"""\s?:\s?(?<value>(-|\+)?[\d.]+(e\+[\d.]+)?|null)?", RegexOptions.ExplicitCapture | RegexOptions.Multiline);
if(result.Success && result.Groups["value"] != null) {
return result.Groups["value"].Value;
} else {
return string.Empty;
}
}
private string GetValueString(string dataJSON, string fieldName) {
Match result = Regex.Match(dataJSON, @"""" + fieldName + @"""\s?:\s?""(?<value>[^""]*)?""", RegexOptions.ExplicitCapture | RegexOptions.Multiline);
if(result.Success && result.Groups["value"] != null) {
return result.Groups["value"].Value;
} else {
return string.Empty;
}
}
public byte[] Write(DataPacket data) {
StringBuilder dataJSON = new StringBuilder(@"{""type"":""");
dataJSON.Append(data.Name);
dataJSON.Append(@"""");
foreach(KeyValuePair<PacketField, FieldData> pair in data.Enumerator) {
if(pair.Key.DataType != null) {
IPacketDataTypeParser parser = pair.Key.DataType.GetParser(this.name);
if(parser != null) {
if(pair.Value.Value != null) {
dataJSON.Append(@",""");
dataJSON.Append(pair.Key.Name);
dataJSON.Append(@""":");
dataJSON.Append(parser.Write(pair.Value.Value));
}
} else {
Log.Add("no data type (" + pair.Key.DataType.Name + ") parser for " + this.name + " protocol");
}
} else {
Log.Add("unknown data type, field " + pair.Key.Name);
}
}
dataJSON.Append(@"}");
return Encoding.UTF8.GetBytes(dataJSON.ToString());
}
public string Name {
set {
if(string.IsNullOrEmpty(this.name)) {
this.name = value;
}
}
}
}
} | 42.757962 | 180 | 0.423507 | [
"MIT"
] | Maksims/gh12-server | Protocols/Data/DataProtocolJSON.cs | 6,713 | C# |
using ConsoleIntroduction.Game;
using SFML.Graphics;
namespace ConsoleIntroduction
{
class Shapes
{
public const string CONSOLE_FONT_PATH = "./fonts/arial.ttf";
public Positions positions;
Sprite spriteFromFile;
Font consoleFont;
public void LoadContent()
{
consoleFont = new Font(CONSOLE_FONT_PATH);
positions = new Positions();
Texture texture;
texture = new Texture("./Images/image1.png");
spriteFromFile = new Sprite(texture);
}
public void Draw(GameLoop gameLoop)
{
uint fontSize = 14;
if (consoleFont != null)
{
string strTotalTimeElapsed = gameLoop.GameTime.TotalTimeElapsed.ToString("0.0000");
string strDeltaTime = gameLoop.GameTime.DeltaTime.ToString("0.00000");
float fps = 1 / gameLoop.GameTime.DeltaTime;
string strFps = fps.ToString();
Utils.DrawText(gameLoop, strTotalTimeElapsed, consoleFont, Color.White,
fontSize, 4, 8);
Utils.DrawText(gameLoop, strFps, consoleFont, Color.White,
fontSize, positions.Fps.X, positions.Fps.Y);
}
Utils.DrawText(gameLoop, "press arrows to move text", consoleFont,
Color.Red, fontSize, 100, 4);
Utils.DrawText(gameLoop, "click mouse to move circle and change shape direction", consoleFont,
Color.Red, fontSize, 100, 24);
Utils.DrawCircle(gameLoop, positions.CircleRadius, Color.Red,
positions.CircleCenter.X, positions.CircleCenter.Y);
Utils.DrawTexture(gameLoop, spriteFromFile,
positions.Sprite.X, positions.Sprite.Y + positions.OffsetY);
}
public void Update()
{
if (positions.Up)
{
positions.OffsetY--;
}
else
{
positions.OffsetY++;
}
}
}
}
| 30.720588 | 106 | 0.554811 | [
"MIT"
] | NathanKr/SfmlPlayground | ConsoleIntroduction/ConsoleIntroduction/Game/Shapes.cs | 2,091 | C# |
// =======================================================================================================
//
// ,uEZGZX LG Eu iJ vi
// BB7. .: uM 8F 0BN Bq S:
// @X LO rJLYi : i iYLL XJ Xu7@ Mu 7LjL; rBOii 7LJ7 .vYUi
// ,@ LG 7Br...SB vB B B1...7BL 0S i@, OU :@7. ,u@ @u.. :@: ;B LB. ::
// v@ LO B Z0 i@ @ BU @Y qq .@L Oj @ 5@ Oi @. MB U@
// .@ JZ :@ :@ rB B @ 5U Eq @0 Xj ,B .B Br ,B:rv777i :0ZU
// @M LO @ Mk :@ .@ BL @J EZ GZML @ XM B; @ Y@
// ZBFi::vu 1B ;B7..:qO BS..iGB BJ..:vB2 BM rBj :@7,.:5B qM.. i@r..i5. ir. UB
// iuU1vi , ;LLv, iYvi , ;LLr . ., . rvY7: rLi 7LLr, ,uvv:
//
//
// Copyright 2014-2015 daxnet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =======================================================================================================
namespace CloudNotes.DesktopClient.Extensibility.Data
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Represents that the inherited classes are data access proxies that
/// can provide the data source to the desktop client.
/// </summary>
internal abstract class DataAccessProxy : IDisposable
{
#region Private Fields
private readonly ClientCredential credential;
#endregion
#region Cctor
/// <summary>
/// Finalizes an instance of the <see cref="DataAccessProxy"/> class.
/// </summary>
~DataAccessProxy()
{
this.Dispose(false);
}
#endregion
#region Ctor
/// <summary>
/// Initializes a new instance of the <see cref="DataAccessProxy"/> class.
/// </summary>
/// <param name="credential">The client credential used for consuming the data access functionalities.</param>
public DataAccessProxy(ClientCredential credential)
{
this.credential = credential;
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the client credential used for consuming the data access functionalities.
/// </summary>
protected ClientCredential Credential
{
get { return this.credential; }
}
#endregion
#region Protected Methods
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected abstract void Dispose(bool disposing);
#endregion
#region Public Methods
/// <summary>
/// Gets the notes asynchronously.
/// </summary>
/// <param name="deleted">True if the method should return the notes that are marked as deleted. False will return all the
/// notes available.</param>
/// <returns>The <see cref="Task"/> that returns a list of retrieved notes.</returns>
public abstract Task<IEnumerable<Note>> GetNotesAsync(bool deleted = false);
/// <summary>
/// Creates the note asynchronously.
/// </summary>
/// <param name="note">The note object to be created.</param>
/// <returns>The <see cref="Task"/> that returns the <see cref="Guid"/> value which represents the ID of the note that is newly created.</returns>
public abstract Task<Guid> CreateNoteAsync(Note note);
/// <summary>
/// Updates the note asynchronously.
/// </summary>
/// <param name="note">The note to be updated.</param>
/// <returns>The <see cref="Task"/> that is responsible for updating the note.</returns>
public abstract Task UpdateNoteAsync(Note note);
/// <summary>
/// Marks the note as deleted asynchronously.
/// </summary>
/// <param name="id">The ID of the note to be marked as deleted.</param>
/// <returns>The <see cref="Task"/> that is responsible for marking the note as deleted.</returns>
public abstract Task MarkDeleteAsync(Guid id);
/// <summary>
/// Deletes the note asynchronously.
/// </summary>
/// <param name="id">The ID of the note to be deleted.</param>
/// <returns>The <see cref="Task"/> that is responsible for deleting the note.</returns>
public abstract Task DeleteAsync(Guid id);
/// <summary>
/// Empties the trash bin asynchronously.
/// </summary>
/// <returns>The <see cref="Task"/> that is responsible for empty the trash bin.</returns>
public abstract Task EmptyTrashAsync();
/// <summary>
/// Restores the note from the trash bin asynchronously.
/// </summary>
/// <param name="id">The ID of the note to be restored.</param>
/// <returns>The <see cref="Task"/> that is responsible for restoring the note from the trash bin.</returns>
public abstract Task RestoreAsync(Guid id);
/// <summary>
/// Gets the note asynchronously.
/// </summary>
/// <param name="id">The ID of the note to be retrieved.</param>
/// <returns>The <see cref="Task"/> that returns the retrieved note.</returns>
public abstract Task<Note> GetNoteAsync(Guid id);
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| 44.476821 | 154 | 0.538267 | [
"Apache-2.0"
] | daxnet/CloudNotes | CloudNotes.DesktopClient.Extensibility/Data/DataAccessProxy.cs | 6,718 | C# |
// <auto-generated />
namespace AdminLteMvc.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class ConVanNo1 : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(ConVanNo1));
string IMigrationMetadata.Id
{
get { return "202009010831306_ConVanNo1"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 27 | 92 | 0.617284 | [
"MIT"
] | ataharasystemsolutions/KTI_TEST | AdminLteMvc/AdminLteMvc/Migrations/202009010831306_ConVanNo1.Designer.cs | 810 | C# |
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neu.Core;
using Neu.IO.Json;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Neu.UnitTests
{
[TestClass]
public class UT_TransactionOutput
{
TransactionOutput uut;
[TestInitialize]
public void TestSetup()
{
uut = new TransactionOutput();
}
[TestMethod]
public void AssetId_Get()
{
uut.AssetId.Should().BeNull();
}
[TestMethod]
public void AssetId_Set()
{
UInt256 val = new UInt256(TestUtils.GetByteArray(32, 0x42));
uut.AssetId = val;
uut.AssetId.Should().Be(val);
}
[TestMethod]
public void Value_Get()
{
uut.Value.Should().Be(Fixed8.Zero);
}
[TestMethod]
public void Value_Set()
{
Fixed8 val = Fixed8.FromDecimal(42);
uut.Value = val;
uut.Value.Should().Be(val);
}
[TestMethod]
public void ScriptHash_Get()
{
uut.ScriptHash.Should().BeNull();
}
[TestMethod]
public void ScriptHash_Set()
{
UInt160 val = new UInt160(TestUtils.GetByteArray(20, 0x42));
uut.ScriptHash = val;
uut.ScriptHash.Should().Be(val);
}
[TestMethod]
public void Size_Get()
{
uut.AssetId = new UInt256(TestUtils.GetByteArray(32, 0x42));
uut.Value = Fixed8.FromDecimal(42);
uut.ScriptHash = new UInt160(TestUtils.GetByteArray(20, 0x42));
uut.Size.Should().Be(60); // 32 + 8 + 20
}
[TestMethod]
public void ToJson()
{
uut.AssetId = new UInt256(TestUtils.GetByteArray(32, 0x42));
uut.Value = Fixed8.FromDecimal(42);
uut.ScriptHash = new UInt160(TestUtils.GetByteArray(20, 0x42));
JObject jObj = uut.ToJson(36);
jObj.Should().NotBeNull();
jObj["n"].AsNumber().Should().Be(36);
jObj["asset"].AsString().Should().Be("0x2020202020202020202020202020202020202020202020202020202020202042");
jObj["value"].AsString().Should().Be("42");
jObj["address"].AsString().Should().Be("AMoWjH3BDwMY7j8FEAovPJdq8XEuyJynwN");
}
}
}
| 26.714286 | 119 | 0.551625 | [
"MIT"
] | NeuBlockchain/NEU | neu.UnitTests/UT_TransactionOutput.cs | 2,431 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BHackerOverhaul.FileHandler;
using BHackerOverhaul._3DData;
using System.Windows;
namespace BHackerOverhaul.DLHandling
{
public class DLParser
{
public string[] GetParsedObject(byte[] Data)
{
List<string> V = new List<string>();
List<string> F = new List<string>();
List<string> OutPut = new List<string>();
int[] Headers = new HeaderReader().ReadOffsets(Data);
int AdditionalOffset = 1;
List<DLObject> Temp = new List<DLObject>();
try
{
foreach (int Offset in Headers)
{
int CurOffset = Offset;
DLObject Buf = new DLObject();
try
{
while (Data[CurOffset] != 0xB8)
{
if (Data[CurOffset] == 0x04)
{
Temp.Add(Buf);
Buf = new DLObject();
byte[] Pos = new byte[4];
Array.Copy(Data, CurOffset + 4, Pos, 0, 4);
Pos[0] = 0;
if(BitConverter.IsLittleEndian)
{
Array.Reverse(Pos);
}
Buf.DataOffset = BitConverter.ToInt32(Pos, 0);
string Length = Convert.ToString(Data[CurOffset + 2], 2).PadLeft(8, '0');
Length = Length.Substring(0, 6);
Buf.Length = Convert.ToInt32(Length, 2);
}
else if (Data[CurOffset] == 0xB1)
{
Connection c = new Connection();
c.Connection1 = Data[CurOffset + 1] / 2;
c.Connection2 = Data[CurOffset + 2] / 2;
c.Connection3 = Data[CurOffset + 3] / 2;
Buf.connections.Add(c);
c = new Connection();
c.Connection1 = Data[CurOffset + 5] / 2;
c.Connection2 = Data[CurOffset + 6] / 2;
c.Connection3 = Data[CurOffset + 7] / 2;
Buf.connections.Add(c);
}
else if (Data[CurOffset] == 0xBF)
{
Connection c = new Connection();
c.Connection1 = Data[CurOffset + 5] / 2;
c.Connection2 = Data[CurOffset + 6] / 2;
c.Connection3 = Data[CurOffset + 7] / 2;
Buf.connections.Add(c);
}
CurOffset += 0x08;
}
Temp.Add(Buf);
}
catch(Exception ex)
{
}
}
foreach (DLObject obj in Temp)
{
foreach (Connection connection in obj.connections)
{
string builder = "f ";
builder += $"{connection.Connection1 + AdditionalOffset} {connection.Connection2 + AdditionalOffset} {connection.Connection3 + AdditionalOffset}";
F.Add(builder);
}
int CurOffset = obj.DataOffset;
for (int i = 0; i < obj.Length; i++)
{
Vector3 buf = new Vector3();
byte[] temp = new byte[2];
Array.Copy(Data, CurOffset, temp, 0, 2);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(temp);
}
buf.X = (float)BitConverter.ToInt16(temp, 0);
temp = new byte[2];
Array.Copy(Data, CurOffset + 2, temp, 0, 2);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(temp);
}
buf.Y = (float)BitConverter.ToInt16(temp, 0);
temp = new byte[2];
Array.Copy(Data, CurOffset + 4, temp, 0, 2);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(temp);
}
buf.Z = (float)BitConverter.ToInt16(temp, 0);
string Builder = "v ";
Builder += buf.ToString();
V.Add(Builder);
AdditionalOffset++;
CurOffset += 0x10;
}
}
}
catch (Exception ex)
{
}
OutPut.AddRange(V);
OutPut.AddRange(F);
return OutPut.ToArray();
}
public string[] GetParsedObject2(byte[] Data, List<int> imageOffset, List<string> imageNames, string fileName)
{
int i;
int cCount;
List<string> V = new List<string>();
List<string> VT = new List<string>();
List<string> F = new List<string>();
List<string> OutPut = new List<string>();
//List<string> ImgName = new List<string>();
List<int> StartOff = new List<int>();
List<int> EndOff = new List<int>();
List<int> Groupst = new List<int>();
List<int> Groupend = new List<int>();
int[] Headers = new HeaderReader().ReadOffsets(Data);
int AdditionalOffset = 1;
List<DLObject> Temp = new List<DLObject>();
try
{
i = -1;
cCount = -1;
foreach (int Offset in Headers)
{
int CurOffset = Offset;
DLObject Buf = new DLObject();
try
{
while (Data[CurOffset] != 0xB8)
{
if (Data[CurOffset] == 0x04)
{
i++;
Temp.Add(Buf);
StartOff.Add(0);
EndOff.Add(0);
Groupst.Add(cCount + 1);
Groupend.Add(0);
//Groupst[i] = Temp.con;
Buf = new DLObject();
byte[] Pos = new byte[4];
Array.Copy(Data, CurOffset + 4, Pos, 0, 4);
Pos[0] = 0;
if (BitConverter.IsLittleEndian)
{
Array.Reverse(Pos);
}
Buf.DataOffset = BitConverter.ToInt32(Pos, 0);
string Length = Convert.ToString(Data[CurOffset + 2], 2).PadLeft(8, '0');
Length = Length.Substring(0, 6);
Buf.Length = Convert.ToInt32(Length, 2);
}
else if (Data[CurOffset] == 0xB1)
{
Connection c = new Connection();
c.Connection1 = Data[CurOffset + 1] / 2;
c.Connection2 = Data[CurOffset + 2] / 2;
c.Connection3 = Data[CurOffset + 3] / 2;
Buf.connections.Add(c);
cCount++;
c = new Connection();
c.Connection1 = Data[CurOffset + 5] / 2;
c.Connection2 = Data[CurOffset + 6] / 2;
c.Connection3 = Data[CurOffset + 7] / 2;
Buf.connections.Add(c);
cCount++;
}
else if (Data[CurOffset] == 0xBF)
{
Connection c = new Connection();
c.Connection1 = Data[CurOffset + 5] / 2;
c.Connection2 = Data[CurOffset + 6] / 2;
c.Connection3 = Data[CurOffset + 7] / 2;
Buf.connections.Add(c);
cCount++;
}
else if (Data[CurOffset] == 0xFD)
{
if (EndOff[i] == 0)
{
EndOff[i] = Data[CurOffset + 5] * 65536 + Data[CurOffset + 6] * 256 + Data[CurOffset + 7];
}
else
{
StartOff[i] = Data[CurOffset + 5] * 65536 + Data[CurOffset + 6] * 256 + Data[CurOffset + 7];
}
}
CurOffset += 0x08;
Groupend[i] = cCount;
}
Temp.Add(Buf);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
foreach (DLObject obj in Temp)
{
int CurOffset = obj.DataOffset;
for (i = 0; i < obj.Length; i++)
{
Vector3 buf = new Vector3();
byte[] temp = new byte[2];
Array.Copy(Data, CurOffset, temp, 0, 2);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(temp);
}
buf.X = (float)BitConverter.ToInt16(temp, 0);
temp = new byte[2];
Array.Copy(Data, CurOffset + 2, temp, 0, 2);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(temp);
}
buf.Y = (float)BitConverter.ToInt16(temp, 0);
temp = new byte[2];
Array.Copy(Data, CurOffset + 4, temp, 0, 2);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(temp);
}
buf.Z = (float)BitConverter.ToInt16(temp, 0);
string Builder = "v ";
Builder += buf.ToString();
V.Add(Builder);
//new
Vector3 VertexTexture = new Vector3();
temp = new byte[2];
Array.Copy(Data, CurOffset + 8, temp, 0, 2);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(temp);
}
//VertexTexture.X = (float)temp[1]/4;
//VertexTexture.X = (float)temp[1] / (float)4;
VertexTexture.X = (float)BitConverter.ToInt16(temp, 0) / 1024;
temp = new byte[2];
Array.Copy(Data, CurOffset + 10, temp, 0, 2);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(temp);
}
//VertexTexture.Y = (float)temp[1] / (float)4;
VertexTexture.Y = (float)BitConverter.ToInt16(temp, 0) / 1024;
VT.Add("vt " + VertexTexture.X.ToString() + " " + VertexTexture.Y.ToString());
AdditionalOffset++;
CurOffset += 0x10;
}
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
try
{
AdditionalOffset = 1;
foreach (DLObject obj in Temp)
{
foreach (Connection connection in obj.connections)
{
if (connection.Connection1 + AdditionalOffset <= V.Count && connection.Connection2 + AdditionalOffset <= V.Count && connection.Connection3 + AdditionalOffset <= V.Count)
{
string builder = "f ";
builder += $"{connection.Connection1 + AdditionalOffset}{"/"}{connection.Connection1 + AdditionalOffset} {connection.Connection2 + AdditionalOffset}{"/"}{connection.Connection2 + AdditionalOffset} {connection.Connection3 + AdditionalOffset}{"/"}{connection.Connection3 + AdditionalOffset}";
F.Add(builder);
}
}
AdditionalOffset+= obj.Length;
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
OutPut.Add("mtllib " + fileName + ".mtl");
OutPut.AddRange(V);
OutPut.AddRange(VT);
for (int group = 0; group < Groupst.Count; group++)
{
if(Groupst[group] != Groupend[group] + 1)
{
OutPut.Add("o " + group);
for(int j = 0; j < imageOffset.Count; j++)
{
if (StartOff[group] == imageOffset[j])
{
OutPut.Add("usemtl " + j);
break;
}
}
for (int j = Groupst[group]; j <= Groupend[group]; j++)
{
if(j < F.Count) OutPut.Add(F[j]);
}
}
}
return OutPut.ToArray();
}
}
}
| 39.65873 | 318 | 0.355347 | [
"BSD-3-Clause"
] | Coockie1173/BomberHacker2.0 | BHackerOverhaul.DLHandling/DLParser.cs | 14,993 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using UnityEditor;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class PolygonMesh : MonoBehaviour
{
private Mesh mesh;
// Start is called before the first frame update
void Start()
{
mesh = GetComponent<MeshFilter>().mesh = new Mesh();
GenerateVertices(8);
}
void GenerateVertices(int edgeCount)
{
mesh.Clear();
var vertices = new Vector3[edgeCount];
var triangles = new int[(edgeCount - 2) * 3];
for (var i = 0; i < edgeCount; i++)
{
var angle = 360.0f / edgeCount * i;
vertices[i] = Quaternion.Euler(0, 0, angle) * Vector3.right;
}
for (var i = 0; i < edgeCount - 2; i++)
{
triangles[i * 3] = 0;
triangles[i * 3 + 1] = i + 1;
triangles[i * 3 + 2] = i + 2;
}
mesh.vertices = vertices;
mesh.triangles = triangles;
}
}
| 24 | 72 | 0.571296 | [
"MIT"
] | Ownfos/Shrewd | Shrewd/Assets/Scripts/PolygonMesh.cs | 1,082 | C# |
// SPDX-FileCopyrightText: © 2021-2022 MONAI Consortium
// SPDX-License-Identifier: Apache License 2.0
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FellowOakDicom.Network;
using Microsoft.Extensions.Logging;
using Monai.Deploy.InformaticsGateway.Api;
using Monai.Deploy.InformaticsGateway.Api.Storage;
using Monai.Deploy.InformaticsGateway.Common;
using Monai.Deploy.InformaticsGateway.Logging;
using Monai.Deploy.InformaticsGateway.Services.Connectors;
using Monai.Deploy.InformaticsGateway.Services.Storage;
namespace Monai.Deploy.InformaticsGateway.Services.Scp
{
internal class ApplicationEntityHandler
{
private readonly MonaiApplicationEntity _configuration;
private readonly IPayloadAssembler _payloadAssembler;
private readonly ITemporaryFileStore _fileStore;
private readonly ILogger<ApplicationEntityHandler> _logger;
public ApplicationEntityHandler(
MonaiApplicationEntity monaiApplicationEntity,
IPayloadAssembler payloadAssembler,
ITemporaryFileStore fileStore,
ILogger<ApplicationEntityHandler> logger)
{
_configuration = monaiApplicationEntity ?? throw new ArgumentNullException(nameof(monaiApplicationEntity));
_payloadAssembler = payloadAssembler ?? throw new ArgumentNullException(nameof(payloadAssembler));
_fileStore = fileStore ?? throw new ArgumentNullException(nameof(fileStore));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
internal async Task HandleInstance(DicomCStoreRequest request, string calledAeTitle, string callingAeTitle, Guid associationId, StudySerieSopUids uids)
{
if (_configuration.IgnoredSopClasses.Contains(request.SOPClassUID.UID))
{
_logger.InstanceIgnoredWIthMatchingSopClassUid(request.SOPClassUID.UID);
return;
}
var paths = await _fileStore.SaveDicomInstance(associationId.ToString(), request.File, CancellationToken.None).ConfigureAwait(false);
var dicomInfo = new DicomFileStorageInfo
{
CalledAeTitle = calledAeTitle,
CorrelationId = associationId.ToString(),
FilePath = paths.FilePath,
JsonFilePath = paths.DicomMetadataFilePath,
Id = uids.Identifier,
Source = callingAeTitle,
StudyInstanceUid = uids.StudyInstanceUid,
SeriesInstanceUid = uids.SeriesInstanceUid,
SopInstanceUid = uids.SopInstanceUid,
};
if (_configuration.Workflows.Any())
{
dicomInfo.SetWorkflows(_configuration.Workflows.ToArray());
}
var dicomTag = FellowOakDicom.DicomTag.Parse(_configuration.Grouping);
_logger.QueueInstanceUsingDicomTag(dicomTag);
var key = request.Dataset.GetSingleValue<string>(dicomTag);
await _payloadAssembler.Queue(key, dicomInfo, _configuration.Timeout).ConfigureAwait(false);
}
}
}
| 43.888889 | 159 | 0.696835 | [
"Apache-2.0"
] | Project-MONAI/monai-deploy-informatics-gateway | src/InformaticsGateway/Services/Scp/ApplicationEntityHandler.cs | 3,161 | C# |
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour {
// Update is called once per frame
void FixedUpdate () {
float getHor = Input.GetAxis ("Horizontal");
float getVer = Input.GetAxis ("Vertical");
rigidbody.AddForce (getHor, 0.0f, getVer);
}
}
| 16.277778 | 46 | 0.696246 | [
"MIT"
] | scarlethammergames/showcase | Assets/Scripts/ai/Mover.cs | 295 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Relay
{
using System.Globalization;
class SR : Strings
{
public static string GetString(string format, params object[] args)
{
if (args != null && args.Length != 0)
{
for (int i = 0; i < args.Length; i++)
{
string text = args[i] as string;
if (text != null && text.Length > 1024)
{
args[i] = text.Substring(0, 1021) + "...";
}
}
return string.Format(CultureInfo.CurrentUICulture, format, args);
}
return format;
}
public static new string ArgumentOutOfRange(object low, object high)
{
return SR.GetString(Strings.ArgumentOutOfRange, low, high);
}
}
} | 30.147059 | 101 | 0.510244 | [
"MIT"
] | Azure/azure-relay-dotnet | src/Microsoft.Azure.Relay/SR.cs | 1,027 | C# |
using System;
namespace TryNBootLoader.Program.Exceptions
{
public class ProcessNotStartableException : Exception
{
public override string Message { get; }
public ProcessNotStartableException(string processName)
{
Message = $"Unable to start process '{processName}'!";
}
}
}
namespace Ruffo324.Toolbox.Exceptions
{
}
| 17.631579 | 57 | 0.752239 | [
"Apache-2.0"
] | Ruffo324/BruteForceBootloaderUnlock | TryNBootLoader/TryNBootLoader.Program/Exceptions/ProcessNotStartableException.cs | 337 | C# |
using System;
using System.Security;
namespace RED4ext.NET.Runtime
{
/// <summary>
/// The binding wrapper is used for binding the native functions to
/// managed C# delegates.
/// </summary>
[SuppressUnmanagedCodeSecurity]
internal unsafe class BindingWrapper : IDisposable
{
private bool _isDisposed;
private int _currentHead;
private int _currentPosition;
private IntPtr* _currentArea;
private readonly IntPtr* _areas;
internal BindingWrapper(IntPtr pointer)
{
_areas = (IntPtr*)pointer;
}
/// <summary>
/// Fetches a new area of the area array from the native side.
/// The opposite of NewArea on the native side.
/// </summary>
public void FetchArea()
{
if (_isDisposed) return;
_currentArea = (IntPtr*)_areas[_currentPosition++];
_currentHead = 0;
}
/// <summary>
/// Gets the function on the current position in the current area
/// and returns the pointer to it.
/// </summary>
/// <returns>The pointer to the current function</returns>
public IntPtr GetFunction()
{
return _isDisposed ? IntPtr.Zero : _currentArea[_currentHead++];
}
/// <summary>
/// Disposes the wrapper.
/// </summary>
public void Dispose()
{
if (_isDisposed) return;
_isDisposed = true;
}
}
}
| 27.25 | 76 | 0.566841 | [
"MIT"
] | DasDarki/RED4ext.NET | managed/Runtime/BindingWrapper.cs | 1,526 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Blazor.Browser.Interop;
using Microsoft.AspNetCore.Blazor.Components;
using Microsoft.AspNetCore.Blazor.Rendering;
using Microsoft.AspNetCore.Blazor.RenderTree;
using System;
using System.Collections.Generic;
namespace Microsoft.AspNetCore.Blazor.Browser.Rendering
{
/// <summary>
/// Provides mechanisms for rendering <see cref="IComponent"/> instances in a
/// web browser, dispatching events to them, and refreshing the UI as required.
/// </summary>
public class BrowserRenderer : Renderer, IDisposable
{
private readonly int _browserRendererId;
/// <summary>
/// Constructs an instance of <see cref="BrowserRenderer"/>.
/// </summary>
public BrowserRenderer()
{
_browserRendererId = BrowserRendererRegistry.Add(this);
}
internal void DispatchBrowserEvent(int componentId, int eventHandlerId, UIEventArgs eventArgs)
=> DispatchEvent(componentId, eventHandlerId, eventArgs);
internal void RenderNewBatchInternal(int componentId)
=> RenderNewBatch(componentId);
/// <summary>
/// Attaches a new root component to the renderer,
/// causing it to be displayed in the specified DOM element.
/// </summary>
/// <typeparam name="TComponent">The type of the component.</typeparam>
/// <param name="domElementSelector">A CSS selector that uniquely identifies a DOM element.</param>
public void AddComponent<TComponent>(string domElementSelector)
where TComponent: IComponent
{
AddComponent(typeof(TComponent), domElementSelector);
}
/// <summary>
/// Associates the <see cref="IComponent"/> with the <see cref="BrowserRenderer"/>,
/// causing it to be displayed in the specified DOM element.
/// </summary>
/// <param name="componentType">The type of the component.</param>
/// <param name="domElementSelector">A CSS selector that uniquely identifies a DOM element.</param>
public void AddComponent(Type componentType, string domElementSelector)
{
var component = InstantiateComponent(componentType);
var componentId = AssignComponentId(component);
RegisteredFunction.InvokeUnmarshalled<int, string, int, object>(
"attachComponentToElement",
_browserRendererId,
domElementSelector,
componentId);
RenderNewBatch(componentId);
}
/// <summary>
/// Disposes the instance.
/// </summary>
public void Dispose()
{
BrowserRendererRegistry.TryRemove(_browserRendererId);
}
/// <inheritdoc />
protected override void UpdateDisplay(RenderBatch batch)
{
RegisteredFunction.InvokeUnmarshalled<int, RenderBatch, object>(
"renderBatch",
_browserRendererId,
batch);
}
}
}
| 38.831325 | 111 | 0.64319 | [
"Apache-2.0"
] | ebekker/Blazor-OLD | src/Microsoft.AspNetCore.Blazor.Browser/Rendering/BrowserRenderer.cs | 3,225 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Knightware.Threading.Tasks
{
[TestClass]
public class AsyncAutoResetEventTests
{
[TestMethod]
public async Task IntervalTest()
{
var tcs = new TaskCompletionSource<bool>();
var resetEvent = new AsyncAutoResetEvent();
//Timeout in 100ms
Task timeoutTask = resetEvent.WaitAsync(TimeSpan.FromMilliseconds(100)).ContinueWith((r) => tcs.TrySetResult(true));
Task testTimeoutTask = Task.Delay(1000).ContinueWith((r) => tcs.TrySetResult(false));
bool success = await tcs.Task;
Assert.IsTrue(success, "Timeout for async reset event failed to fire");
}
}
}
| 30.785714 | 128 | 0.665893 | [
"Apache-2.0"
] | dsmithson/KnightwareCore | src/KnightwareCoreTests/Threading/Tasks/AsyncAutoResetEventTests.cs | 864 | C# |
using System;
using System.Windows.Forms;
namespace ThreadModeler
{
public partial class FrmSplash : Form
{
public FrmSplash()
{
InitializeComponent();
}
public void CloseDialog()
{
if (InvokeRequired)
Invoke(new MethodInvoker(Dispose));
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape && closeBtn.Visible)
{
Exit();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void closeBtn_Click(object sender, EventArgs e)
{
Exit();
}
private void Exit()
{
DialogResult = DialogResult.Cancel;
Close();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// Specify that the link was visited.
this.linkLabel1.LinkVisited = true;
// Navigate to a URL.
System.Diagnostics.Process.Start("http://www.coolorange.com");
}
}
}
| 18.730769 | 91 | 0.641684 | [
"MIT"
] | coolOrangeLabs/inventor-thread-modeler | ThreadModeler/frmSplash.cs | 976 | C# |
using System;
using System.Threading.Tasks;
using Super.Model.Selection;
using Super.Model.Selection.Adapters;
namespace Super.Operations
{
public class TaskSelector<_, T> : Selector<_, Task<T>>
{
public TaskSelector(ISelect<_, Task<T>> subject) : base(subject) {}
public OperationSelector<_, T> Promote()
=> new OperationSelector<_, T>(Get().Select(SelectOperation<T>.Default));
public TaskSelector<_, TTo> Then<TTo>(ISelect<T, TTo> select) => Then(select.Get);
public TaskSelector<_, TTo> Then<TTo>(Func<T, TTo> select)
=> new TaskSelector<_, TTo>(Get().Select(new Selection<T, TTo>(select)));
}
} | 31.05 | 84 | 0.711755 | [
"MIT"
] | SuperDotNet/Super.NET | Super/Operations/TaskSelector.cs | 623 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Maui.Controls.CustomAttributes;
using Microsoft.Maui.Controls.Internals;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
using Microsoft.Maui.Controls.Compatibility.UITests;
#endif
namespace Microsoft.Maui.Controls.Compatibility.ControlGallery.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Github, 11333,
"[Bug] SwipeView does not work on Android if child has TapGestureRecognizer",
PlatformAffected.Android)]
public partial class Issue11333 : TestContentPage
{
const string SwipeViewId = "SwipeViewId";
public Issue11333()
{
#if APP
InitializeComponent();
#endif
}
protected override void Init()
{
}
#if APP
void OnTapGestureRecognizerOnTapped(object sender, EventArgs e)
{
Debug.WriteLine("Tapped");
}
void OnSwipeViewSwipeEnded(object sender, SwipeEndedEventArgs e)
{
ResultLabel.Text = e.IsOpen ? "Open" : "Close";
}
#endif
#if UITEST && __ANDROID__
[Test]
[Category(UITestCategories.SwipeView)]
public void SwipeWithChildGestureRecognizer()
{
RunningApp.WaitForElement(SwipeViewId);
RunningApp.SwipeRightToLeft();
RunningApp.Tap(SwipeViewId);
RunningApp.WaitForElement(q => q.Marked("Open"));
}
#endif
}
[Preserve(AllMembers = true)]
public class Issue11333Model
{
public string Title { get; set; }
public string Description { get; set; }
}
} | 21.848485 | 79 | 0.746186 | [
"MIT"
] | 10088/maui | src/Compatibility/ControlGallery/src/Issues.Shared/Issue11333.xaml.cs | 1,444 | C# |
/**************************************************************************
* *
* Website: https://github.com/florinleon/ActressMas *
* Description: Iterated Prisoner's Dilemma using ActressMas framework *
* Copyright: (c) 2018, Florin Leon *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation. This program is distributed in the *
* hope that it will be useful, but WITHOUT ANY WARRANTY; without even *
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR *
* PURPOSE. See the GNU General Public License for more details. *
* *
**************************************************************************/
using System;
namespace IteratedPrisonersDilemma
{
public class RandomPrisonerAgent : PrisonerAgent
{
private Random _rand = new Random();
protected override string ChooseAction(int lastOutcome)
{
if (_rand.NextDouble() < 0.5)
return "confess";
else
return "deny";
}
}
} | 44.96875 | 76 | 0.459347 | [
"Apache-2.0"
] | dimven/ActressMas | ActressMas Examples/Turn-Based Examples/T10 Iterated Prisoner Dilemma/RandomPrisonerAgent.cs | 1,441 | C# |
// Copyright © .NET Foundation and Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace PInvoke
{
using System;
using System.IO;
using System.Runtime.InteropServices;
/// <content>
/// Exported functions from the SetupApi.dll Windows library
/// that are available to Desktop apps only.
/// </content>
[OfferFriendlyOverloads]
public static partial class Cabinet
{
/// <summary>
/// The <see cref="FNALLOC"/> provides the declaration for the application-defined callback function to allocate memory in an FDI context.
/// </summary>
/// <param name="cb">
/// The number of bytes to allocate.
/// </param>
/// <returns>
/// A pointer to the allocated memory.
/// </returns>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate IntPtr FNALLOC(int cb);
/// <summary>
/// The <see cref="FNFREE"/> macro provides the declaration for the application-defined callback function to free previously allocated memory in an FDI context.
/// </summary>
/// <param name="pv">
/// Pointer to the allocated memory block to free.
/// </param>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void FNFREE(IntPtr pv);
/// <summary>
/// The <see cref="FNOPEN"/> macro provides the declaration for the application-defined callback function to open a file in an FDI context.
/// </summary>
/// <param name="path">
/// The name of the file.
/// </param>
/// <param name="oflag">
/// File name.
/// </param>
/// <param name="pmode">
/// The kind of operations allowed.
/// </param>
/// <returns>
/// Permission mode.
/// </returns>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int FNOPEN(string path, int oflag, int pmode);
/// <summary>
/// The <see cref="FNREAD"/> macro provides the declaration for the application-defined callback function to read data from a file in an FDI context.
/// </summary>
/// <param name="hf">
/// An application-defined value used to identify the open file.
/// </param>
/// <param name="pv">
/// Storage location for data.
/// </param>
/// <param name="cb">
/// Maximum number of bytes to read.
/// </param>
/// <returns>
/// The number of bytes read.
/// </returns>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int FNREAD(int hf, byte* pv, int cb);
/// <summary>
/// The <see cref="FNWRITE"/> macro provides the declaration for the application-defined callback function to write data to a file in an FDI context.
/// </summary>
/// <param name="hf">
/// An application-defined value used to identify the open file.
/// </param>
/// <param name="pv">
/// Data to be written.
/// </param>
/// <param name="cb">
/// Number of bytes.
/// </param>
/// <returns>
/// If successful, _write returns the number of bytes written.
/// </returns>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int FNWRITE(int hf, byte* pv, int cb);
/// <summary>
/// The <see cref="FNCLOSE"/> macro provides the declaration for the application-defined callback function to close a file in an FDI context.
/// </summary>
/// <param name="hf">
/// An application-defined value used to identify the open file.
/// </param>
/// <returns>
/// 0 if the file was successfully closed. A return value of -1 indicates an error.
/// </returns>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate uint FNCLOSE(int hf);
/// <summary>
/// The <see cref="FNSEEK"/> macro provides the declaration for the application-defined callback function to move a file pointer to the specified location in an FDI context.
/// </summary>
/// <param name="hf">
/// An application-defined value used to identify the open file.
/// </param>
/// <param name="dist">
/// Number of bytes from origin.
/// </param>
/// <param name="seektype">
/// Initial position.
/// </param>
/// <returns>
/// The offset, in bytes, of the new position from the beginning of the file.
/// </returns>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate uint FNSEEK(int hf, int dist, SeekOrigin seektype);
/// <summary>
/// The <see cref="FNFDINOTIFY"/> macro provides the declaration for the application-defined callback notification function to update the application on the status of the decoder.
/// </summary>
/// <param name="fdint">
/// The type of notification.
/// </param>
/// <param name="fdin">
/// The notification.
/// </param>
/// <returns>
/// The return value, which is passed from the application to the Cabinet API.
/// </returns>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int FNFDINOTIFY(NOTIFICATIONTYPE fdint, NOTIFICATION* fdin);
/// <summary>
/// The FDICreate function creates an FDI context.
/// </summary>
/// <param name="pfnalloc">
/// Pointer to an application-defined callback function to allocate memory. The function should be declared using the FNALLOC macro.
/// </param>
/// <param name="pfnfree">
/// Pointer to an application-defined callback function to free previously allocated memory. The function should be declared using the FNFREE macro.
/// </param>
/// <param name="pfnopen">
/// Pointer to an application-defined callback function to open a file. The function should be declared using the FNOPEN macro.
/// </param>
/// <param name="pfnread">
/// Pointer to an application-defined callback function to read data from a file. The function should be declared using the FNREAD macro.
/// </param>
/// <param name="pfnwrite">
/// Pointer to an application-defined callback function to write data to a file. The function should be declared using the FNWRITE macro.
/// </param>
/// <param name="pfnclose">
/// Pointer to an application-defined callback function to close a file. The function should be declared using the FNCLOSE macro.
/// </param>
/// <param name="pfnseek">
/// Pointer to an application-defined callback function to move a file pointer to the specified location. The function should be declared using the FNSEEK macro.
/// </param>
/// <param name="cpuType">
/// In the 16-bit version of FDI, specifies the CPU type and can be any of the following values.
/// </param>
/// <param name="perf">
/// Pointer to an ERF structure that receives the error information.
/// </param>
/// <returns>
/// If the function succeeds, it returns a non-<see cref="IntPtr.Zero"/> HFDI context pointer; otherwise, it returns <see cref="IntPtr.Zero"/>.
/// </returns>
[DllImport(nameof(Cabinet), CallingConvention = CallingConvention.Cdecl)]
public static unsafe extern FdiHandle FDICreate(
FNALLOC pfnalloc,
FNFREE pfnfree,
FNOPEN pfnopen,
FNREAD pfnread,
FNWRITE pfnwrite,
FNCLOSE pfnclose,
FNSEEK pfnseek,
CpuType cpuType,
[Friendly(FriendlyFlags.Out)] ERF* perf);
/// <summary>
/// The FDICopy function extracts files from cabinets.
/// </summary>
/// <param name="hfdi">
/// A valid FDI context handle returned by the FDICreate function.
/// </param>
/// <param name="pszCabinet">
/// The name of the cabinet file, excluding any path information, from which to extract files.
/// If a file is split over multiple cabinets, FDICopy allows for subsequent cabinets to be opened.
/// </param>
/// <param name="pszCabPath">
/// The pathname of the cabinet file, but not including the name of the file itself. For example, "C:\MyCabs".
/// The contents of pszCabinet are appended to pszCabPath to create the full pathname of the cabinet.
/// </param>
/// <param name="flags">
/// No flags are currently defined and this parameter should be set to zero.
/// </param>
/// <param name="pfnfdin">
/// An application-defined callback notification function to update the application on the status of the decoder.
/// </param>
/// <param name="pfnfdid">
/// Not currently used by FDI. This parameter should be set to <see langword="null"/>.
/// </param>
/// <param name="pvUser">
/// Pointer to an application-specified value to pass to the notification function.
/// </param>
/// <returns>
/// If the function succeeds, it returns <see langword="true"/>; otherwise, <see langword="false"/>.
/// </returns>
[DllImport(nameof(Cabinet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static unsafe extern bool FDICopy(
FdiHandle hfdi,
string pszCabinet,
string pszCabPath,
int flags,
FNFDINOTIFY pfnfdin,
void* pfnfdid,
void* pvUser);
/// <summary>
/// The FDIDestroy function deletes an open FDI context.
/// </summary>
/// <param name="hfdi">
/// A valid FDI context handle returned by the FDICreate function.
/// </param>
/// <returns>
/// If the function succeeds, it returns <see langword="true"/>; otherwise, <see langword="false"/>.
/// </returns>
[DllImport(nameof(Cabinet), CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FDIDestroy(IntPtr hfdi);
}
}
| 44.949153 | 187 | 0.598322 | [
"MIT"
] | AArnott/pinvoke | src/Cabinet/Cabinet.cs | 10,611 | C# |
using System;
namespace _1.Train
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[] peopleInWagon = new int[n];
int sum = 0;
for(int i = 0; i < n; i++)
{
peopleInWagon[i] = int.Parse(Console.ReadLine());
sum += peopleInWagon[i];
}
for(int y = 0; y < n; y++)
{
Console.Write(peopleInWagon[y] + " ");
}
Console.WriteLine();
Console.WriteLine(sum);
}
}
}
| 22.851852 | 65 | 0.416532 | [
"MIT"
] | VinsantSavov/SoftUni-Software-Engineering | CSharp-Fundamentals/Fundamentals - 2018/Arrays/Arrays - Excercise/ArraysExcercise/1.Train/Program.cs | 619 | C# |
using Content.Server.Light.EntitySystems;
using Content.Shared.Damage;
using Content.Shared.Light;
using Content.Shared.Sound;
using Robust.Shared.Containers;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
using Robust.Shared.Prototypes;
using Content.Shared.MachineLinking;
using System.Threading;
namespace Content.Server.Light.Components
{
/// <summary>
/// Component that represents a wall light. It has a light bulb that can be replaced when broken.
/// </summary>
[RegisterComponent, Access(typeof(PoweredLightSystem))]
public sealed class PoweredLightComponent : Component
{
[DataField("burnHandSound")]
public SoundSpecifier BurnHandSound = new SoundPathSpecifier("/Audio/Effects/lightburn.ogg");
[DataField("turnOnSound")]
public SoundSpecifier TurnOnSound = new SoundPathSpecifier("/Audio/Machines/light_tube_on.ogg");
[DataField("hasLampOnSpawn", customTypeSerializer: typeof(PrototypeIdSerializer<EntityPrototype>))]
public string? HasLampOnSpawn = null;
[DataField("bulb")]
public LightBulbType BulbType;
[ViewVariables]
[DataField("on")]
public bool On = true;
[DataField("damage", required: true)]
[ViewVariables(VVAccess.ReadWrite)]
public DamageSpecifier Damage = default!;
[ViewVariables]
[DataField("ignoreGhostsBoo")]
public bool IgnoreGhostsBoo;
[ViewVariables]
[DataField("ghostBlinkingTime")]
public TimeSpan GhostBlinkingTime = TimeSpan.FromSeconds(10);
[ViewVariables]
[DataField("ghostBlinkingCooldown")]
public TimeSpan GhostBlinkingCooldown = TimeSpan.FromSeconds(60);
[ViewVariables]
public ContainerSlot LightBulbContainer = default!;
[ViewVariables]
public bool CurrentLit;
[ViewVariables]
public bool IsBlinking;
[ViewVariables]
public TimeSpan LastThunk;
[ViewVariables]
public TimeSpan? LastGhostBlink;
[DataField("onPort", customTypeSerializer: typeof(PrototypeIdSerializer<ReceiverPortPrototype>))]
public string OnPort = "On";
[DataField("offPort", customTypeSerializer: typeof(PrototypeIdSerializer<ReceiverPortPrototype>))]
public string OffPort = "Off";
[DataField("togglePort", customTypeSerializer: typeof(PrototypeIdSerializer<ReceiverPortPrototype>))]
public string TogglePort = "Toggle";
public CancellationTokenSource? CancelToken;
/// <summary>
/// How long it takes to eject a bulb from this
/// </summary>
[DataField("ejectBulbDelay")]
public float EjectBulbDelay = 2;
}
}
| 34.575 | 109 | 0.689443 | [
"MIT"
] | EmoGarbage404/space-station-14 | Content.Server/Light/Components/PoweredLightComponent.cs | 2,766 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using TinyFactory.Exceptions;
namespace TinyFactory.Background
{
public abstract class LoopService : IHostedService, IDisposable
{
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource();
protected abstract TimeSpan LoopDelay { get; set; }
public bool FirstDelay { get; private set; } = true;
protected abstract Task<bool> ExecuteAsync(CancellationToken stoppingToken);
protected async Task TakeFirstDelay(int ms) =>
await TakeFirstDelay(TimeSpan.FromMilliseconds(ms));
protected async Task TakeFirstDelay(TimeSpan time)
{
if (FirstDelay)
{
await Task.Delay(time).ConfigureAwait(false);
FirstDelay = false;
}
}
private async Task StartLoop(CancellationToken cancellationToken)
{
var token = _stoppingCts.Token;
while (!cancellationToken.IsCancellationRequested && !token.IsCancellationRequested)
{
if (!await ExecuteAsync(token).ConfigureAwait(false))
break;
await Task.Delay(LoopDelay).ConfigureAwait(false);
}
}
public virtual Task StartAsync(CancellationToken cancellationToken)
{
cancellationToken.Register(async () => { await StopAsync(default); });
_executingTask = StartLoop(_stoppingCts.Token);
_executingTask.ConfigureAwait(false);
_executingTask.ContinueWith(tsk =>
{
if (tsk.IsFaulted)
throw new ExecutingBackgroundException(tsk.Exception.Message,
tsk.Exception.InnerException);
});
if (_executingTask.IsCompleted)
return _executingTask;
return Task.CompletedTask;
}
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
if (_executingTask == null) return;
try
{
_stoppingCts.Cancel();
}
finally
{
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken)).ConfigureAwait(false);
}
}
public virtual void Dispose()
{
_stoppingCts.Cancel();
}
}
} | 33.743243 | 122 | 0.592311 | [
"MIT"
] | gkurbesov/TinyFactory | TinyFactory/Background/LoopService.cs | 2,499 | C# |
//
// Copyright 2013-2014 Hans Wolff
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
namespace RedFoxMQ
{
public interface IMessage
{
ushort MessageTypeId { get; }
}
}
| 29.5 | 75 | 0.711864 | [
"Apache-2.0"
] | hanswolff/redfoxmq | RedFoxMQ/IMessage.cs | 710 | C# |
//-----------------------------------------------------------------------
// <copyright file="FormatterLocationStep.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// 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>
//-----------------------------------------------------------------------
namespace Databox.OdinSerializer
{
public enum FormatterLocationStep
{
BeforeRegisteredFormatters,
AfterRegisteredFormatters
}
} | 37.769231 | 75 | 0.625255 | [
"MIT"
] | zach-v/Deeper | top-down-shooter/Assets/Packages/Databox/Core/Serializers/OdinSerializer/Core/Misc/FormatterLocationStep.cs | 982 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("AppBar.Sample.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AppBar.Sample.Android")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 36.290323 | 77 | 0.766222 | [
"MIT"
] | jsuarezruiz/Xamarin.Forms.AppBar | src/AppBar.Sample.Android/Properties/AssemblyInfo.cs | 1,128 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
namespace Common
{
public abstract class CSingleton<T> where T : CSingleton<T>
{
protected static T s_instance;
protected CSingleton(){}
public static T Instance(){
if(s_instance == null){
ConstructorInfo[] ctors =
typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
ConstructorInfo ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
if (ctor == null){
Debug.LogError("Canot find non-public constructor in " + typeof(T) + "!");
}
s_instance = ctor.Invoke(null) as T;
}
return s_instance;
}
}
} | 31.074074 | 94 | 0.578069 | [
"MIT"
] | Relinke/2D_Horror_Adventure_Game | UnityProject/Assets/Game/Script/Common/CSingleton.cs | 841 | C# |
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Tellma.Api.Base;
using Tellma.Api.Behaviors;
using Tellma.Api.Dto;
using Tellma.Api.ImportExport;
using Tellma.Api.Metadata;
using Tellma.Model.Application;
using Tellma.Model.Common;
using Tellma.Repository.Admin;
using Tellma.Repository.Common;
using Tellma.Utilities.Blobs;
using Tellma.Utilities.Common;
using Tellma.Utilities.Email;
using Tellma.Utilities.Sms;
namespace Tellma.Api
{
public class UsersService : CrudServiceBase<UserForSave, User, int>
{
private static readonly PhoneAttribute phoneAtt = new();
private static readonly EmailAddressAttribute emailAtt = new();
private readonly ApplicationFactServiceBehavior _behavior;
private readonly IStringLocalizer _localizer;
private readonly AdminRepository _adminRepo;
private readonly IClientProxy _client;
private readonly IIdentityProxy _identity;
private readonly IBlobService _blobService;
private readonly IUserSettingsCache _userSettingsCache;
private readonly MetadataProvider _metadataProvider;
// These are created and used across multiple methods
private List<string> _blobsToDelete;
private List<(string, byte[])> _blobsToSave;
protected override string View => "users";
protected override IFactServiceBehavior FactBehavior => _behavior;
public UsersService(
ApplicationFactServiceBehavior behavior,
CrudServiceDependencies deps,
IStringLocalizer<Strings> localizer,
AdminRepository adminRepo,
IClientProxy client,
IIdentityProxy identity,
IBlobService blobService,
IUserSettingsCache userSettingsCache,
MetadataProvider metadataProvider) : base(deps)
{
_behavior = behavior;
_localizer = localizer;
_adminRepo = adminRepo;
_client = client;
_identity = identity;
_blobService = blobService;
_userSettingsCache = userSettingsCache;
_metadataProvider = metadataProvider;
}
public async Task<Versioned<UserSettingsForClient>> SaveUserSetting(SaveUserSettingsArguments args)
{
await Initialize();
// Retrieve the arguments
var key = args.Key;
var value = args.Value;
// Validation
int maxKey = 255;
int maxValue = 2048;
if (string.IsNullOrWhiteSpace(key))
{
// Key is required
throw new ServiceException(_localizer[ErrorMessages.Error_Field0IsRequired, nameof(args.Key)]);
}
else if (key.Length > maxKey)
{
// Key cannot be too big
throw new ServiceException(_localizer[ErrorMessages.Error_Field0LengthMaximumOf1, nameof(args.Key), maxKey]);
}
if (value != null && value.Length > maxValue)
{
throw new ServiceException(_localizer[ErrorMessages.Error_Field0LengthMaximumOf1, nameof(args.Value), maxValue]);
}
// Save and return
await _behavior.Repository.Users__SaveSettings(key, value, UserId);
return await UserSettingsForClientImpl("fresh", cancellation: default);
}
public async Task<Versioned<UserSettingsForClient>> SaveUserPreferredLanguage(string preferredLanguage, CancellationToken cancellation)
{
await Initialize(cancellation);
if (string.IsNullOrWhiteSpace(preferredLanguage))
{
throw new ServiceException(_localizer[ErrorMessages.Error_Field0IsRequired, "PreferredLanguage"]);
}
var settings = await _behavior.Settings(cancellation);
if (settings.PrimaryLanguageId != preferredLanguage &&
settings.SecondaryLanguageId != preferredLanguage &&
settings.TernaryLanguageId != preferredLanguage)
{
// Not one of the languages supported by this company
throw new ServiceException(_localizer["Error_Language0IsNotSupported", preferredLanguage]);
}
// Save and return
await _behavior.Repository.Users__SavePreferredLanguage(preferredLanguage, UserId, cancellation);
return await UserSettingsForClientImpl("fresh", cancellation);
}
public async Task<Versioned<UserSettingsForClient>> SaveUserPreferredCalendar(string preferredCalendar, CancellationToken cancellation)
{
await Initialize(cancellation);
if (string.IsNullOrWhiteSpace(preferredCalendar))
{
throw new ServiceException(_localizer[ErrorMessages.Error_Field0IsRequired, "PreferredCalendar"]);
}
var settings = await _behavior.Settings(cancellation);
if (settings.PrimaryCalendar != preferredCalendar &&
settings.SecondaryCalendar != preferredCalendar)
{
// Not one of the Calendars supported by this company
throw new ServiceException(_localizer["Error_Calendar0IsNotSupported", preferredCalendar]);
}
// Save and return
await _behavior.Repository.Users__SavePreferredCalendar(preferredCalendar, UserId, cancellation);
return await UserSettingsForClientImpl("fresh", cancellation);
}
public async Task<Versioned<UserSettingsForClient>> UserSettingsForClient(CancellationToken cancellation)
{
await Initialize(cancellation);
return await UserSettingsForClientImpl(_behavior.UserSettingsVersion, cancellation);
}
private async Task<Versioned<UserSettingsForClient>> UserSettingsForClientImpl(string version, CancellationToken cancellation)
{
return await _userSettingsCache.GetUserSettings(UserId, _behavior.TenantId, version, cancellation);
}
public async Task<EntitiesResult<User>> SendInvitation(List<int> ids, ActionArguments args)
{
await Initialize();
if (!_client.EmailEnabled)
{
throw new ServiceException("Email is not enabled in this installation.");
}
if (!_identity.CanInviteUsers)
{
throw new ServiceException("Identity server in this installation does not support user invitation.");
}
// Check if the user has permission
var action = "SendInvitationEmail";
var actionFilter = await UserPermissionsFilter(action, cancellation: default);
ids = await CheckActionPermissionsBefore(actionFilter, ids);
// Execute and return
using var trx = TransactionFactory.ReadCommitted();
var (output, dbUsers) = await _behavior.Repository.Users__Invite(
ids: ids,
validateOnly: ModelState.IsError,
top: ModelState.RemainingErrors,
userId: UserId);
AddErrorsAndThrowIfInvalid(output.Errors);
// Prepare result
var result = (args.ReturnEntities ?? false) ?
await GetByIds(ids, args, action, cancellation: default) :
EntitiesResult<User>.Empty();
// Check user permissions again
await CheckActionPermissionsAfter(actionFilter, ids, result.Data);
#region Non-Transactional Side-Effects
// Send invitation emails
var settings = await _behavior.Settings();
var userSettings = await _behavior.UserSettings();
IEnumerable<UserForInvitation> usersToInvite = dbUsers.Select(dbUser =>
{
var preferredCulture = GetCulture(dbUser.PreferredLanguage);
using var _ = new CultureScope(preferredCulture);
// Localize the names in the user's preferred language
return new UserForInvitation
{
Email = dbUser.Email,
Name = settings.Localize(dbUser.Name, dbUser.Name2, dbUser.Name3),
PreferredLanguage = dbUser.PreferredLanguage,
InviterName = settings.Localize(userSettings.Name, userSettings.Name2, userSettings.Name3),
CompanyName = settings.Localize(settings.ShortCompanyName, settings.ShortCompanyName2, settings.ShortCompanyName3),
};
});
// Start a fresh transaction otherwise MSDTC error is raised.
using var identityTrx = TransactionFactory.ReadCommitted(TransactionScopeOption.RequiresNew);
await _identity.InviteUsersToTenant(_behavior.TenantId, usersToInvite);
identityTrx.Complete();
#endregion
trx.Complete();
return result;
}
public async Task<User> GetMyUser(CancellationToken cancellation)
{
await Initialize(cancellation);
var myIdSingleton = new List<int> { UserId };
var me = await _behavior
.Repository
.Users
.FilterByIds(myIdSingleton)
.FirstOrDefaultAsync(QueryContext, cancellation);
return me;
}
public async Task<User> SaveMyUser(MyUserForSave me)
{
await Initialize();
var userIdSingleton = new List<int> { UserId };
var user = await _behavior.Repository
.Users
.Expand("Roles")
.FilterByIds(userIdSingleton).FirstOrDefaultAsync(QueryContext, cancellation: default);
// Create a user for save
var userForSave = new UserForSave
{
Id = user.Id,
Email = user.Email,
ClientId = user.ClientId,
Name = me.Name?.Trim(),
Name2 = me.Name2?.Trim(),
Name3 = me.Name3?.Trim(),
PreferredLanguage = me.PreferredLanguage?.Trim(),
Image = me.Image,
ContactEmail = user.ContactEmail,
ContactMobile = user.ContactMobile,
EmailNewInboxItem = user.EmailNewInboxItem,
SmsNewInboxItem = user.SmsNewInboxItem,
PushNewInboxItem = user.PushNewInboxItem,
NormalizedContactMobile = user.NormalizedContactMobile,
PreferredChannel = user.PreferredChannel,
PreferredCalendar = user.PreferredCalendar,
EntityMetadata = new EntityMetadata
{
[nameof(UserForSave.Id)] = FieldMetadata.Loaded,
[nameof(UserForSave.Email)] = FieldMetadata.Loaded,
[nameof(UserForSave.Name)] = FieldMetadata.Loaded,
[nameof(UserForSave.Name2)] = FieldMetadata.Loaded,
[nameof(UserForSave.Name3)] = FieldMetadata.Loaded,
[nameof(UserForSave.PreferredLanguage)] = FieldMetadata.Loaded,
[nameof(UserForSave.Image)] = FieldMetadata.Loaded,
[nameof(UserForSave.ContactEmail)] = FieldMetadata.Loaded,
[nameof(UserForSave.ContactMobile)] = FieldMetadata.Loaded,
[nameof(UserForSave.EmailNewInboxItem)] = FieldMetadata.Loaded,
[nameof(UserForSave.SmsNewInboxItem)] = FieldMetadata.Loaded,
[nameof(UserForSave.PushNewInboxItem)] = FieldMetadata.Loaded,
[nameof(UserForSave.NormalizedContactMobile)] = FieldMetadata.Loaded,
[nameof(UserForSave.PreferredChannel)] = FieldMetadata.Loaded,
},
// The roles must remain the way they are
Roles = user.Roles?.Select(e => new RoleMembershipForSave
{
Id = e.Id,
Memo = e.Memo,
RoleId = e.RoleId,
UserId = e.UserId,
EntityMetadata = new EntityMetadata
{
[nameof(RoleMembershipForSave.Id)] = FieldMetadata.Loaded,
[nameof(RoleMembershipForSave.Memo)] = FieldMetadata.Loaded,
[nameof(RoleMembershipForSave.RoleId)] = FieldMetadata.Loaded,
[nameof(RoleMembershipForSave.UserId)] = FieldMetadata.Loaded
},
})
.ToList()
};
// Structural Validation
var overrides = await FactBehavior.GetMetadataOverridesProvider(cancellation: default);
var meta = _metadataProvider.GetMetadata(_behavior.TenantId, typeof(UserForSave), null, overrides);
ValidateEntity(userForSave, meta);
ModelState.ThrowIfInvalid();
var entities = new List<UserForSave>() { userForSave };
// Start a transaction scope for save since it causes data modifications
using var trx = TransactionFactory.ReadCommitted();
// Preprocess the entities
entities = await SavePreprocessAsync(entities);
// Save and retrieve Ids
await SaveExecuteAsync(entities, returnIds: false);
// Load response
var response = await GetMyUser(cancellation: default);
// Perform side effects of save that are not transactional, just before committing the transaction
await NonTransactionalSideEffectsForSave(entities, new List<User> { response });
// Commit and return
trx.Complete();
return response;
}
public async Task<ImageResult> GetImage(int id, CancellationToken cancellation)
{
await Initialize(cancellation);
string imageId;
if (id == UserId)
{
// A user can always view their own image, so we bypass read permissions
User me = await _behavior
.Repository
.Users
.Filter("Id eq me")
.Select(nameof(User.ImageId))
.FirstOrDefaultAsync(QueryContext, cancellation);
imageId = me.ImageId;
}
else
{
// This enforces read permissions
var result = await GetById(id, new GetByIdArguments { Select = nameof(User.ImageId) }, cancellation);
imageId = result.Entity.ImageId;
}
// Get the blob name
if (imageId != null)
{
try
{
// Get the bytes
string blobName = ImageBlobName(imageId);
var imageBytes = await _blobService.LoadBlob(_behavior.TenantId, blobName, cancellation);
return new ImageResult(imageId, imageBytes);
}
catch (BlobNotFoundException)
{
throw new NotFoundException<int>(id);
}
}
else
{
throw new NotFoundException<int>(id);
}
}
public Task<EntitiesResult<User>> Activate(List<int> ids, ActionArguments args)
{
return SetIsActive(ids, args, isActive: true);
}
public Task<EntitiesResult<User>> Deactivate(List<int> ids, ActionArguments args)
{
return SetIsActive(ids, args, isActive: false);
}
private async Task<EntitiesResult<User>> SetIsActive(List<int> ids, ActionArguments args, bool isActive)
{
await Initialize();
// Check user permissions
var action = "IsActive";
var actionFilter = await UserPermissionsFilter(action, cancellation: default);
ids = await CheckActionPermissionsBefore(actionFilter, ids);
// C# Validation
foreach (var (id, index) in ids.Select((id, index) => (id, index)))
{
if (id == UserId)
{
ModelState.AddError($"[{index}]", _localizer["Error_CannotDeactivateYourOwnUser"].Value);
}
}
// Execute and return
using var trx = TransactionFactory.ReadCommitted();
OperationOutput output = await _behavior.Repository.Users__Activate(
ids: ids,
isActive: isActive,
validateOnly: ModelState.IsError,
top: ModelState.RemainingErrors,
userId: UserId);
AddErrorsAndThrowIfInvalid(output.Errors);
// Prepare result
var result = (args.ReturnEntities ?? false) ?
await GetByIds(ids, args, action, cancellation: default) :
EntitiesResult<User>.Empty();
// Check user permissions again
await CheckActionPermissionsAfter(actionFilter, ids, result.Data);
trx.Complete();
return result;
}
protected override Task<EntityQuery<User>> Search(EntityQuery<User> query, GetArguments args, CancellationToken _)
{
string search = args.Search;
if (!string.IsNullOrWhiteSpace(search))
{
search = search.Replace("'", "''"); // escape quotes by repeating them
var email = nameof(User.Email);
var clientId = nameof(User.ClientId);
var name = nameof(User.Name);
var name2 = nameof(User.Name2);
var name3 = nameof(User.Name3);
string filter = $"{name} contains '{search}' or {name2} contains '{search}' or {name3} contains '{search}' or {email} contains '{search}' or {clientId} eq '{search}'";
// If the search term looks like an email, include the contact email in the search
if (emailAtt.IsValid(search))
{
var contactEmail = nameof(User.ContactEmail);
filter += $" or {contactEmail} eq '{search}'";
}
// If the search term looks like a phone number, include the contact mobile in the search
if (phoneAtt.IsValid(search))
{
var e164 = BaseUtil.ToE164(search);
var normalizedContactMobile = nameof(User.NormalizedContactMobile);
filter += $" or {normalizedContactMobile} eq '{e164}'";
}
query = query.Filter(filter);
}
return Task.FromResult(query);
}
protected override Task<List<UserForSave>> SavePreprocessAsync(List<UserForSave> entities)
{
foreach (var entity in entities)
{
entity.Email = entity.Email?.ToLower();
entity.EmailNewInboxItem ??= false;
entity.SmsNewInboxItem ??= false;
entity.PushNewInboxItem ??= false;
entity.IsService ??= false;
entity.PreferredChannel ??= "Email";
if (entity.IsService.Value)
{
// Service accounts do not have emails
entity.Email = null;
}
else
{
// human accounts do not have a client ID
entity.ClientId = null;
}
if (string.IsNullOrWhiteSpace(entity.ContactEmail))
{
entity.ContactEmail = null;
}
else
{
entity.ContactEmail = entity.ContactEmail.ToLower();
}
if (string.IsNullOrWhiteSpace(entity.ContactMobile))
{
entity.ContactMobile = null;
}
// Normalized the contact mobile
entity.NormalizedContactMobile = BaseUtil.ToE164(entity.ContactMobile);
// Make sure the role memberships are not referring to the wrong user
// (RoleMembership is a semi-weak entity, used by both User and Role)
entity.Roles?.ForEach(role =>
{
role.UserId = entity.Id;
});
}
return base.SavePreprocessAsync(entities);
}
protected override async Task<List<int>> SaveExecuteAsync(List<UserForSave> entities, bool returnIds)
{
#region Validate
// Check that line ids are unique and that they have supplied a RoleId
var duplicateLineIds = entities
.SelectMany(e => e.Roles) // All lines
.Where(e => e.Id != 0)
.GroupBy(e => e.Id)
.Where(g => g.Count() > 1) // Duplicate Ids
.SelectMany(g => g)
.ToDictionary(e => e, e => e.Id); // to dictionary
TypeMetadata meta = null;
foreach (var (entity, index) in entities.Select((e, i) => (e, i)))
{
if (entity.IsService.Value)
{
// For service accounts, the ClientId is required
if (string.IsNullOrWhiteSpace(entity.ClientId))
{
meta ??= await GetMetadataForSave(cancellation: default);
var prop = meta.Property(nameof(entity.ClientId));
ModelState.AddError($"[{index}]{nameof(entity.ClientId)}",
_localizer[ErrorMessages.Error_Field0IsRequired, prop.Display()]);
}
}
else
{
// For human accounts, the Email is required
if (string.IsNullOrWhiteSpace(entity.Email))
{
meta ??= await GetMetadataForSave(cancellation: default);
var prop = meta.Property(nameof(entity.Email));
ModelState.AddError($"[{index}]{nameof(entity.Email)}",
_localizer[ErrorMessages.Error_Field0IsRequired, prop.Display()]);
}
}
var lineIndices = entity.Roles.ToIndexDictionary();
foreach (var line in entity.Roles)
{
if (duplicateLineIds.ContainsKey(line))
{
// This error indicates a bug
var lineIndex = lineIndices[line];
var id = duplicateLineIds[line];
ModelState.AddError($"[{index}].{nameof(entity.Roles)}[{lineIndex}].{nameof(entity.Id)}",
_localizer["Error_TheEntityWithId0IsSpecifiedMoreThanOnce", id]);
}
if (line.RoleId == null)
{
var lineIndex = lineIndices[line];
meta ??= await GetMetadataForSave(cancellation: default);
var roleProp = meta.CollectionProperty(nameof(UserForSave.Roles)).CollectionTargetTypeMetadata.Property(nameof(RoleMembershipForSave.RoleId)) ??
throw new InvalidOperationException($"Bug: Could not retrieve metadata for role Id property");
ModelState.AddError($"[{index}].{nameof(entity.Roles)}[{lineIndex}].{nameof(RoleMembershipForSave.RoleId)}",
_localizer[ErrorMessages.Error_Field0IsRequired, roleProp.Display()]);
}
}
}
#endregion
#region Save
// Step (1): Extract the images
_blobsToSave = BaseUtil.ExtractImages(entities, ImageBlobName).ToList();
// Step (2): Save users in the application database
var result = await _behavior.Repository.Users__Save(
entities: entities,
returnIds: returnIds,
validateOnly: ModelState.IsError,
top: ModelState.RemainingErrors,
userId: UserId);
AddErrorsAndThrowIfInvalid(result.Errors);
_blobsToDelete = result.DeletedImageIds.Select(ImageBlobName).ToList();
// Return the new Ids
return result.Ids;
#endregion
}
protected override async Task NonTransactionalSideEffectsForSave(List<UserForSave> entities, IReadOnlyList<User> data)
{
// Step (3): Delete old images from the blob storage
if (_blobsToDelete.Any())
{
await _blobService.DeleteBlobsAsync(_behavior.TenantId, _blobsToDelete);
}
// Step (4): Add new images to the blob storage
if (_blobsToSave.Any())
{
await _blobService.SaveBlobsAsync(_behavior.TenantId, _blobsToSave);
}
// Step (5): Create the identity users
using var identityTrx = TransactionFactory.ReadCommitted(TransactionScopeOption.RequiresNew);
if (_identity.CanCreateUsers)
{
// Make sure to filter out null emails (service accounts)
var emails = entities.Where(e => e.Email != null).Select(e => e.Email);
await _identity.CreateUsersIfNotExist(emails);
}
// Step (6) Update the directory users in the admin database
using var adminTrx = TransactionFactory.ReadCommitted(TransactionScopeOption.RequiresNew);
var oldEmails = new List<string>(); // Emails are readonly after the first save
var newEmails = entities.Where(e => e.Id == 0).Where(e => e.Email != null).Select(e => e.Email);
await _adminRepo.DirectoryUsers__Save(newEmails, oldEmails, _behavior.TenantId);
identityTrx.Complete();
adminTrx.Complete();
}
protected override async Task DeleteExecuteAsync(List<int> ids)
{
#region Validate
// Make sure the user is not deleting his/her own account
foreach (var (id, index) in ids.Select((id, index) => (id, index)))
{
if (id == UserId)
{
ModelState.AddError($"[{index}]", _localizer["Error_CannotDeleteYourOwnUser"].Value);
}
}
#endregion
#region Delete
IEnumerable<string> oldEmails;
IEnumerable<string> newEmails = new List<string>();
List<string> blobsToDelete;
var (result, emails) = await _behavior.Repository.Users__Delete(
ids: ids,
validateOnly: ModelState.IsError,
top: ModelState.RemainingErrors,
userId: UserId);
AddErrorsAndThrowIfInvalid(result.Errors);
oldEmails = emails.Where(e => e != null);
blobsToDelete = result.DeletedImageIds.Select(ImageBlobName).ToList();
#endregion
#region Non-Transactional Effects
// It's unfortunate that EF Core does not support distributed transactions, so there is no
// guarantee that deletes to both the application and the admin will not complete one without the other
using var adminTrx = TransactionFactory.ReadCommitted(TransactionScopeOption.RequiresNew);
// Delete from directory
await _adminRepo.DirectoryUsers__Save(newEmails, oldEmails, _behavior.TenantId);
// Delete user images
await _blobService.DeleteBlobsAsync(_behavior.TenantId, blobsToDelete);
adminTrx.Complete();
#endregion
}
private string ImageBlobName(string guid)
{
return $"Users/{guid}";
}
protected override MappingInfo ProcessDefaultMapping(MappingInfo mapping)
{
// Remove the UserId property from the template, it's supposed to be hidden
var roleMemberships = mapping.CollectionPropertyByName(nameof(User.Roles));
var userProp = roleMemberships.SimplePropertyByName(nameof(RoleMembership.UserId));
roleMemberships.SimpleProperties = roleMemberships.SimpleProperties.Where(p => p != userProp);
mapping.NormalizeIndices(); // Fix the gap we created in the previous line
return base.ProcessDefaultMapping(mapping);
}
public async Task<string> TestEmail(string emailAddress)
{
await Initialize();
// This sequence checks for all potential problems that could occur locally
if (string.IsNullOrWhiteSpace(emailAddress))
{
var errorMsg = _localizer[ErrorMessages.Error_Field0IsRequired, _localizer["Entity_ContactEmail"]];
throw new ServiceException(errorMsg);
}
if (!emailAtt.IsValid(emailAddress))
{
var errorMsg = _localizer[ErrorMessages.Error_Field0IsNotValidEmail, _localizer["Entity_ContactEmail"]];
throw new ServiceException(errorMsg);
}
if (emailAddress.Length > EmailValidation.MaximumEmailAddressLength)
{
var errorMsg = _localizer[ErrorMessages.Error_Field0LengthMaximumOf1, _localizer["Entity_ContactEmail"], EmailValidation.MaximumEmailAddressLength];
throw new ServiceException(errorMsg);
}
var subject = await _client.TestEmailAddress(_behavior.TenantId, emailAddress);
string successMsg = _localizer["TestEmailSentTo0WithSubject1", emailAddress, subject];
return successMsg;
}
public async Task<string> TestPhone(string phone)
{
await Initialize();
if (!_client.SmsEnabled)
{
throw new ServiceException("Email is not enabled in this ERP installation.");
}
var settings = await _behavior.Settings();
if (!settings.SmsEnabled)
{
throw new ServiceException("Email is not enabled for this company.");
}
// This sequence checks for all potential problems that could occur locally
if (string.IsNullOrWhiteSpace(phone))
{
var errorMsg = _localizer[ErrorMessages.Error_Field0IsRequired, _localizer["Entity_ContactMobile"]];
throw new ServiceException(errorMsg);
}
if (!phoneAtt.IsValid(phone))
{
var errorMsg = _localizer[ErrorMessages.Error_Field0IsNotValidPhone, _localizer["Entity_ContactMobile"]];
throw new ServiceException(errorMsg);
}
var normalizedPhone = BaseUtil.ToE164(phone);
if (normalizedPhone.Length > SmsValidation.MaximumPhoneNumberLength)
{
var errorMsg = _localizer[ErrorMessages.Error_Field0LengthMaximumOf1, _localizer["Entity_ContactMobile"], SmsValidation.MaximumPhoneNumberLength];
throw new ServiceException(errorMsg);
}
var message = await _client.TestPhoneNumber(_behavior.TenantId, normalizedPhone);
string successMsg = _localizer["TestSmsSentTo0WithMessage1", normalizedPhone, message];
return successMsg;
}
}
}
| 40.412879 | 183 | 0.576374 | [
"Apache-2.0"
] | mohanad1213/tellma | Tellma.Api/UsersService.cs | 32,009 | C# |
using DaikinController.Serializers;
using DaikinSerializers.Test.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DaikinSerializers.Test
{
[TestClass]
public class DaikinSerializerSerializeTests
{
[TestMethod]
public void Serialize()
{
var serializer = new DaikinSerializer<BasicInfo>();
var serializedData = serializer.Serialize(new BasicInfo
{
Mode = 5,
Name = "Test",
Pow = Power.On,
Stemp = 23.5,
Enabled = true
});
Assert.AreEqual("ret=null&pow=1&mode=5&stemp=23.5&adv=null&name=%54%65%73%74&enabled=1&boolnullabe=null", serializedData);
}
}
} | 29.230769 | 134 | 0.584211 | [
"MIT"
] | d-georgiev-91/Daikin-Controller | DaikinSerializers.Test/DaikinSerializerSerializeTests.cs | 762 | C# |
using J2N.Numerics;
using J2N.Text;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Methods for manipulating strings.
/// <para/>
/// @lucene.internal
/// </summary>
public abstract class StringHelper
{
/// <summary>
/// Pass this as the seed to <see cref="Murmurhash3_x86_32(byte[], int, int, int)"/>. </summary>
//Singleton-esque member. Only created once
public static readonly int GOOD_FAST_HASH_SEED = InitializeHashSeed();
// Poached from Guava: set a different salt/seed
// for each JVM instance, to frustrate hash key collision
// denial of service attacks, and to catch any places that
// somehow rely on hash function/order across JVM
// instances:
private static int InitializeHashSeed()
{
// LUCENENET specific - reformatted with :
string prop = SystemProperties.GetProperty("tests:seed", null);
if (prop != null)
{
// So if there is a test failure that relied on hash
// order, we remain reproducible based on the test seed:
if (prop.Length > 8)
{
prop = prop.Substring(prop.Length - 8);
}
return Convert.ToInt32(prop, 16);
}
else
{
return (int)J2N.Time.CurrentTimeMilliseconds();
}
}
/// <summary>
/// Compares two <see cref="BytesRef"/>, element by element, and returns the
/// number of elements common to both arrays.
/// </summary>
/// <param name="left"> The first <see cref="BytesRef"/> to compare. </param>
/// <param name="right"> The second <see cref="BytesRef"/> to compare. </param>
/// <returns> The number of common elements. </returns>
public static int BytesDifference(BytesRef left, BytesRef right)
{
int len = left.Length < right.Length ? left.Length : right.Length;
var bytesLeft = left.Bytes;
int offLeft = left.Offset;
var bytesRight = right.Bytes;
int offRight = right.Offset;
for (int i = 0; i < len; i++)
{
if (bytesLeft[i + offLeft] != bytesRight[i + offRight])
{
return i;
}
}
return len;
}
private StringHelper()
{
}
/// <summary> Returns a <see cref="T:IComparer{string}"/> over versioned strings such as X.YY.Z
/// <para/>
/// @lucene.internal
/// </summary>
public static IComparer<string> VersionComparer => versionComparer;
private static readonly IComparer<string> versionComparer = Comparer<string>.Create((a, b) =>
{
var aTokens = new StringTokenizer(a, ".");
var bTokens = new StringTokenizer(b, ".");
while (aTokens.MoveNext())
{
int aToken = Convert.ToInt32(aTokens.Current, CultureInfo.InvariantCulture);
if (bTokens.MoveNext())
{
int bToken = Convert.ToInt32(bTokens.Current, CultureInfo.InvariantCulture);
if (aToken != bToken)
{
return aToken < bToken ? -1 : 1;
}
}
else
{
// a has some extra trailing tokens. if these are all zeroes, thats ok.
if (aToken != 0)
{
return 1;
}
}
}
// b has some extra trailing tokens. if these are all zeroes, thats ok.
while (bTokens.MoveNext())
{
if (Convert.ToInt32(bTokens.Current, CultureInfo.InvariantCulture) != 0)
{
return -1;
}
}
return 0;
});
public static bool Equals(string s1, string s2)
{
if (s1 == null)
{
return s2 == null;
}
else
{
return s1.Equals(s2, StringComparison.Ordinal);
}
}
/// <summary>
/// Returns <c>true</c> if the <paramref name="ref"/> starts with the given <paramref name="prefix"/>.
/// Otherwise <c>false</c>.
/// </summary>
/// <param name="ref">
/// The <see cref="BytesRef"/> to test. </param>
/// <param name="prefix">
/// The expected prefix </param>
/// <returns> Returns <c>true</c> if the <paramref name="ref"/> starts with the given <paramref name="prefix"/>.
/// Otherwise <c>false</c>. </returns>
public static bool StartsWith(BytesRef @ref, BytesRef prefix) // LUCENENET TODO: API - convert to extension method
{
return SliceEquals(@ref, prefix, 0);
}
/// <summary>
/// Returns <c>true</c> if the <paramref name="ref"/> ends with the given <paramref name="suffix"/>. Otherwise
/// <c>false</c>.
/// </summary>
/// <param name="ref">
/// The <see cref="BytesRef"/> to test. </param>
/// <param name="suffix">
/// The expected suffix </param>
/// <returns> Returns <c>true</c> if the <paramref name="ref"/> ends with the given <paramref name="suffix"/>.
/// Otherwise <c>false</c>. </returns>
public static bool EndsWith(BytesRef @ref, BytesRef suffix) // LUCENENET TODO: API - convert to extension method
{
return SliceEquals(@ref, suffix, @ref.Length - suffix.Length);
}
private static bool SliceEquals(BytesRef sliceToTest, BytesRef other, int pos)
{
if (pos < 0 || sliceToTest.Length - pos < other.Length)
{
return false;
}
int i = sliceToTest.Offset + pos;
int j = other.Offset;
int k = other.Offset + other.Length;
while (j < k)
{
if (sliceToTest.Bytes[i++] != other.Bytes[j++])
{
return false;
}
}
return true;
}
/// <summary>
/// Returns the MurmurHash3_x86_32 hash.
/// Original source/tests at <a href="https://github.com/yonik/java_util/">https://github.com/yonik/java_util/</a>.
/// </summary>
public static int Murmurhash3_x86_32(byte[] data, int offset, int len, int seed)
{
const int c1 = unchecked((int)0xcc9e2d51);
const int c2 = 0x1b873593;
int h1 = seed;
int roundedEnd = offset + (len & unchecked((int)0xfffffffc)); // round down to 4 byte block
for (int i = offset; i < roundedEnd; i += 4)
{
// little endian load order
int k1 = (((sbyte)data[i]) & 0xff) | ((((sbyte)data[i + 1]) & 0xff) << 8) | ((((sbyte)data[i + 2]) & 0xff) << 16) | (((sbyte)data[i + 3]) << 24);
k1 *= c1;
k1 = BitOperation.RotateLeft(k1, 15);
k1 *= c2;
h1 ^= k1;
h1 = BitOperation.RotateLeft(h1, 13);
h1 = h1 * 5 + unchecked((int)0xe6546b64);
}
// tail
int k2 = 0;
switch (len & 0x03)
{
case 3:
k2 = (((sbyte)data[roundedEnd + 2]) & 0xff) << 16;
// fallthrough
goto case 2;
case 2:
k2 |= (((sbyte)data[roundedEnd + 1]) & 0xff) << 8;
// fallthrough
goto case 1;
case 1:
k2 |= (((sbyte)data[roundedEnd]) & 0xff);
k2 *= c1;
k2 = BitOperation.RotateLeft(k2, 15);
k2 *= c2;
h1 ^= k2;
break;
}
// finalization
h1 ^= len;
// fmix(h1);
h1 ^= (int)((uint)h1 >> 16);
h1 *= unchecked((int)0x85ebca6b);
h1 ^= (int)((uint)h1 >> 13);
h1 *= unchecked((int)0xc2b2ae35);
h1 ^= (int)((uint)h1 >> 16);
return h1;
}
/// <summary>
/// Returns the MurmurHash3_x86_32 hash.
/// Original source/tests at <a href="https://github.com/yonik/java_util/">https://github.com/yonik/java_util/</a>.
/// </summary>
public static int Murmurhash3_x86_32(BytesRef bytes, int seed)
{
return Murmurhash3_x86_32(bytes.Bytes, bytes.Offset, bytes.Length, seed);
}
}
} | 36.618519 | 161 | 0.499444 | [
"Apache-2.0"
] | Ref12/lucenenet | src/Lucene.Net/Util/StringHelper.cs | 9,887 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Web.V20180201
{
public static class ListWebAppSitePushSettingsSlot
{
/// <summary>
/// Push settings for the App.
/// </summary>
public static Task<ListWebAppSitePushSettingsSlotResult> InvokeAsync(ListWebAppSitePushSettingsSlotArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<ListWebAppSitePushSettingsSlotResult>("azure-native:web/v20180201:listWebAppSitePushSettingsSlot", args ?? new ListWebAppSitePushSettingsSlotArgs(), options.WithVersion());
}
public sealed class ListWebAppSitePushSettingsSlotArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Name of web app.
/// </summary>
[Input("name", required: true)]
public string Name { get; set; } = null!;
/// <summary>
/// Name of the resource group to which the resource belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// Name of web app slot. If not specified then will default to production slot.
/// </summary>
[Input("slot", required: true)]
public string Slot { get; set; } = null!;
public ListWebAppSitePushSettingsSlotArgs()
{
}
}
[OutputType]
public sealed class ListWebAppSitePushSettingsSlotResult
{
/// <summary>
/// Gets or sets a JSON string containing a list of dynamic tags that will be evaluated from user claims in the push registration endpoint.
/// </summary>
public readonly string? DynamicTagsJson;
/// <summary>
/// Resource Id.
/// </summary>
public readonly string Id;
/// <summary>
/// Gets or sets a flag indicating whether the Push endpoint is enabled.
/// </summary>
public readonly bool IsPushEnabled;
/// <summary>
/// Kind of resource.
/// </summary>
public readonly string? Kind;
/// <summary>
/// Resource Name.
/// </summary>
public readonly string Name;
/// <summary>
/// Gets or sets a JSON string containing a list of tags that are whitelisted for use by the push registration endpoint.
/// </summary>
public readonly string? TagWhitelistJson;
/// <summary>
/// Gets or sets a JSON string containing a list of tags that require user authentication to be used in the push registration endpoint.
/// Tags can consist of alphanumeric characters and the following:
/// '_', '@', '#', '.', ':', '-'.
/// Validation should be performed at the PushRequestHandler.
/// </summary>
public readonly string? TagsRequiringAuth;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
[OutputConstructor]
private ListWebAppSitePushSettingsSlotResult(
string? dynamicTagsJson,
string id,
bool isPushEnabled,
string? kind,
string name,
string? tagWhitelistJson,
string? tagsRequiringAuth,
string type)
{
DynamicTagsJson = dynamicTagsJson;
Id = id;
IsPushEnabled = isPushEnabled;
Kind = kind;
Name = name;
TagWhitelistJson = tagWhitelistJson;
TagsRequiringAuth = tagsRequiringAuth;
Type = type;
}
}
}
| 33.560345 | 226 | 0.603648 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Web/V20180201/ListWebAppSitePushSettingsSlot.cs | 3,893 | C# |
using UnityEngine;
using System.Collections;
using Alps.Model;
using System;
using MatchmoreUtils;
using System.Threading;
namespace MatchmoreLocation
{
public enum LocationServiceType
{
threaded, coroutine
}
public static class LocationServiceStarter
{
public static IEnumerator Start(Action callback)
{
// First, check if user has location service enabled
if (!Input.location.isEnabledByUser)
{
MatchmoreLogger.Debug("Location service disabled by user");
#if !UNITY_IOS
//https://docs.unity3d.com/ScriptReference/LocationService-isEnabledByUser.html
//if it is IOS we do not break here
yield break;
#endif
}
// Start service before querying location
Input.location.Start();
// Wait until service initializes
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
maxWait--;
}
// Service didn't initialize in 20 seconds
if (maxWait < 1)
{
yield break;
}
// Connection has failed
if (Input.location.status == LocationServiceStatus.Failed)
{
yield break;
}
callback();
}
}
public interface ILocationService
{
Location MockLocation { get; set; }
Action<Location> OnUpdateLocation { get; }
void Start();
void Stop();
}
public class ThreadedLocationSercixe : ThreadedJob, ILocationService
{
private Action<Location> _onUpdate;
private CoroutineWrapper _coroutine;
private LocationInfo _locationInfo;
private LocationServiceStatus _status;
private bool _running;
public Location MockLocation { get; set; }
public Action<Location> OnUpdateLocation { get { return _onUpdate; } }
public ThreadedLocationSercixe(CoroutineWrapper coroutine, Action<Location> onUpdate)
{
this._coroutine = coroutine;
this._onUpdate = onUpdate;
}
public override void Start()
{
if (MockLocation != null)
{
_running = true;
base.Start();
}
else
_coroutine.RunOnce("location_service_start", LocationServiceStarter.Start(() =>
{
//setup a coroutine which will just copy data to this object so the thread actually can take it and send to matchmore
_coroutine.SetupContinuousRoutine("data_update", () =>
{
_status = Input.location.status;
_locationInfo = Input.location.lastData;
});
_running = true;
base.Start();
}));
}
protected override void ThreadFunction()
{
while (_running)
{
try
{
if (MockLocation != null)
OnUpdateLocation(MockLocation);
else
if (_status == LocationServiceStatus.Running)
{
var location = _locationInfo;
OnUpdateLocation(new Location
{
Latitude = location.latitude,
Longitude = location.longitude,
Altitude = location.altitude
});
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
Thread.Sleep(6000);
}
}
public void Stop()
{
_running = false;
}
}
public class CoroutinedLocationService : ILocationService
{
private CoroutineWrapper _coroutine;
private Action<Location> _onUpdate;
public Location MockLocation { get; set; }
public Action<Location> OnUpdateLocation { get { return _onUpdate; } }
public CoroutinedLocationService(CoroutineWrapper coroutine, Action<Location> onUpdate)
{
this._coroutine = coroutine;
this._onUpdate = onUpdate;
}
public void Start()
{
_coroutine.RunOnce("location_service_start", StartLocationServiceCoroutine());
}
public void Stop()
{
_coroutine.StopContinuousRoutine("location_service");
}
IEnumerator StartLocationServiceCoroutine()
{
if (MockLocation != null)
{
_coroutine.SetupContinuousRoutine("location_service", MockLocationUpdate);
yield break;
}
_coroutine.RunOnce("location_service_start",
LocationServiceStarter.Start(
() => _coroutine.SetupContinuousRoutine("location_service", UpdateLocation)));
}
private void MockLocationUpdate()
{
OnUpdateLocation(MockLocation);
}
private void UpdateLocation()
{
if (Input.location.status == LocationServiceStatus.Running)
{
var location = Input.location.lastData;
OnUpdateLocation(new Location
{
Latitude = location.latitude,
Longitude = location.longitude,
Altitude = location.altitude
});
}
}
}
} | 29.375 | 133 | 0.515915 | [
"MIT"
] | matchmore/alps-unity-sdk | Assets/Matchmore/Alps/LocationProviders.cs | 5,875 | C# |
using System;
class Program
{
static void Main(string[] args)
{
int goal = 10_000;
string input;
int currentStepsCount = 0;
while (currentStepsCount < goal)
{
input = Console.ReadLine();
if (input == "Going home")
{
int stepsToHome = int.Parse(Console.ReadLine());
currentStepsCount = currentStepsCount + stepsToHome;
break;
}
else
{
int stepsMade = int.Parse(input);
currentStepsCount = currentStepsCount + stepsMade;
}
}
if (currentStepsCount >= goal)
{
Console.WriteLine("Goal reached! Good job!");
}
else
{
int stepsLeft = goal - currentStepsCount;
Console.WriteLine($"{stepsLeft} more steps to reach goal.");
}
}
}
| 24.526316 | 72 | 0.484979 | [
"MIT"
] | stanislavstoyanov99/SoftUni-Software-Engineering | Programming-Basics-with-C#/Labs-And-Homeworks/WhileLoopLab/Walking/Program.cs | 934 | C# |
using System.Threading.Tasks;
using Abp.Web.Security.AntiForgery;
using Microsoft.AspNetCore.Antiforgery;
using Clase7.Controllers;
using Microsoft.AspNetCore.Mvc;
namespace Clase7.Web.Host.Controllers
{
public class AntiForgeryController : Clase7ControllerBase
{
private readonly IAntiforgery _antiforgery;
private readonly IAbpAntiForgeryManager _antiForgeryManager;
public AntiForgeryController(IAntiforgery antiforgery, IAbpAntiForgeryManager antiForgeryManager)
{
_antiforgery = antiforgery;
_antiForgeryManager = antiForgeryManager;
}
public void GetToken()
{
_antiforgery.SetCookieTokenAndHeader(HttpContext);
}
public void SetCookie()
{
_antiForgeryManager.SetCookie(HttpContext);
}
}
}
| 27.322581 | 105 | 0.697757 | [
"MIT"
] | REL1980/Clase7 | aspnet-core/src/Clase7.Web.Host/Controllers/AntiForgeryController.cs | 847 | C# |
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using System;
namespace EcoMundi.Data
{
[CreateAssetMenu(fileName ="MundiData", menuName = "EcoMundi/Data/MundiData", order = 50)]
public class GameData : ScriptableObject
{
[Header("Game Configs")]
private E_DifficultyType _difficultyType;
public E_Province province;
public bool IsDifficultySet { get { return _difficultyType != E_DifficultyType.None; } }
[Header("Mundi Values")]
public string mundiName;
[Header("Points")]
public int gamePoints;
public int shopPoints;
[Space]
public float difficultyModifier;
[Space]
public int MAX_HEALTH;
public int currentHealth;
public bool IsAlive { get { return currentHealth > 0; } }
[Space]
public DateTime birthDate;// = new DateTime();
public DateTime logOutDate;// = new DateTime();
[Space]
// Ecofootprints values
public int ecofootprintCityValue;
public int ecofootprintCropsValue;
public int ecofootprintForestValue;
public int ecofootprintFarmingValue;
public int ecofootprintFisheriesValue;
public int ecofootprintCarbonValue;
// Achievements values
public int ecologicalActionsDone = 0;
// Events
public delegate void VoidDelegate();
public static event VoidDelegate OnGamePointsModified;
public static event VoidDelegate OnShopPointsModified;
public static event VoidDelegate OnHealthModified;
#region [----- GAME BEHAVIOURS -----]
public void SetNewGameData(string p_mundiName, E_Province p_provinceType)
{
mundiName = p_mundiName;
province = p_provinceType;
currentHealth = 0;
gamePoints = 0;
shopPoints = 0;
ecofootprintCityValue = 0;
ecofootprintCropsValue = 0;
ecofootprintForestValue = 0;
ecofootprintFarmingValue = 0;
ecofootprintFisheriesValue = 0;
ecofootprintCarbonValue = 0;
MAX_HEALTH = 100;
}
public void SetDifficultyType(E_DifficultyType p_difficultyType)
{
if (p_difficultyType == E_DifficultyType.Easy)
difficultyModifier = 1f;
else
difficultyModifier = 3f;
_difficultyType = p_difficultyType;
}
public E_DifficultyType GetDifficulty()
{
return _difficultyType;
}
// GAME POINTS
public void ModifyGamePoints(int p_value)
{
gamePoints += Mathf.CeilToInt(p_value * difficultyModifier);
if (gamePoints < 0)
gamePoints = 0;
OnGamePointsModified?.Invoke();
}
public string GetGamePoints()
{
return gamePoints == 0 ? " 0" : gamePoints.ToString("### ###");
}
// SHOP POINTS
public void ModifyShopPoints(int p_value)
{
shopPoints += Mathf.CeilToInt(p_value * difficultyModifier);
if (shopPoints < 0)
shopPoints = 0;
OnShopPointsModified?.Invoke();
}
public string GetShopPoints()
{
return shopPoints == 0 ? " 0" : shopPoints.ToString("### ###");
}
public void ModifyMundiHealth(int p_value)
{
currentHealth += p_value;
if (currentHealth > MAX_HEALTH)
currentHealth = MAX_HEALTH;
else if (currentHealth < 0)
currentHealth = 0;
OnHealthModified?.Invoke();
}
#endregion
#region [----- SAVE & LOAD -----]
public void UpdateLeaderboardsValue()
{
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Ecuador, gamePoints);
switch (province)
{
case E_Province.Galapagos:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Galapagos, gamePoints);
break;
case E_Province.Esmeraldas:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Esmeraldas, gamePoints);
break;
case E_Province.Manabi:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Manabi, gamePoints);
break;
case E_Province.SantaElena:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.SantaElena, gamePoints);
break;
case E_Province.LosRios:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.LosRios, gamePoints);
break;
case E_Province.Guayas:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Guayas, gamePoints);
break;
case E_Province.ElOro:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.ElOro, gamePoints);
break;
case E_Province.SantoDomingo:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.SantoDomingo, gamePoints);
break;
case E_Province.Pichincha:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Pichincha, gamePoints);
break;
case E_Province.Tungurahua:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Tungurahua, gamePoints);
break;
case E_Province.Cotopaxi:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Cotopaxi, gamePoints);
break;
case E_Province.Carchi:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Carchi, gamePoints);
break;
case E_Province.Chimborazo:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Chimborazo, gamePoints);
break;
case E_Province.Imbabura:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Imbabura, gamePoints);
break;
case E_Province.Loja:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Loja, gamePoints);
break;
case E_Province.Bolivar:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Bolivar, gamePoints);
break;
case E_Province.Azuay:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Azuay, gamePoints);
break;
case E_Province.Cañar:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Cañar, gamePoints);
break;
case E_Province.Sucumbios:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Sucumbios, gamePoints);
break;
case E_Province.MoronaSantiago:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.MoronaSantiago, gamePoints);
break;
case E_Province.Napo:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Napo, gamePoints);
break;
case E_Province.ZamoraChinchipe:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.ZamoraChinchipe, gamePoints);
break;
case E_Province.Orellana:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Orellana, gamePoints);
break;
case E_Province.Pastaza:
PlayServices.Instance.UpdateLeaderBoardScore(E_LeaderboardType.Pastaza, gamePoints);
break;
}
}
#endregion
}
}
| 38.16129 | 112 | 0.585678 | [
"MIT"
] | GameDevArena/Planetoide | Assets/_ROOT/_Code/Managers/Mundi/MundiData/BaseCode/GameData.cs | 8,285 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DataMigration.Outputs
{
[OutputType]
public sealed class ProjectFilePropertiesResponse
{
/// <summary>
/// Optional File extension. If submitted it should not have a leading period and must match the extension from filePath.
/// </summary>
public readonly string? Extension;
/// <summary>
/// Relative path of this file resource. This property can be set when creating or updating the file resource.
/// </summary>
public readonly string? FilePath;
/// <summary>
/// Modification DateTime.
/// </summary>
public readonly string LastModified;
/// <summary>
/// File content type. This property can be modified to reflect the file content type.
/// </summary>
public readonly string? MediaType;
/// <summary>
/// File size.
/// </summary>
public readonly double Size;
[OutputConstructor]
private ProjectFilePropertiesResponse(
string? extension,
string? filePath,
string lastModified,
string? mediaType,
double size)
{
Extension = extension;
FilePath = filePath;
LastModified = lastModified;
MediaType = mediaType;
Size = size;
}
}
}
| 29.719298 | 129 | 0.606257 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/DataMigration/Outputs/ProjectFilePropertiesResponse.cs | 1,694 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Dolittle. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System.Collections.Generic;
using Grpc.Core;
using Machine.Specifications;
namespace Dolittle.Services.for_Endpoints.when_starting
{
public class with_one_service_type_and_two_binders : given.one_service_type_with_two_binders
{
static Endpoints endpoints;
Establish context = () =>
{
configuration.Enabled = true;
endpoints = new Endpoints(service_types, endpoints_configuration, type_finder.Object, container.Object, bound_services.Object, logger);
};
Because of = () => endpoints.Start();
It should_start_endpoint_once = () => endpoint.Verify(_ => _.Start(EndpointVisibility.Public, configuration, Moq.It.IsAny<IEnumerable<Service>>()), Moq.Times.Once);
}
} | 45.791667 | 179 | 0.583258 | [
"MIT"
] | joelhoisko/DotNET.Fundamentals | Specifications/Services/for_Endpoints/when_starting/with_one_service_type_and_two_binders.cs | 1,099 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;
namespace Samples.AzureServiceBus
{
public class Program
{
public static void Main(string[] args)
{
var factory = MessagingFactory.Create("sb://localhost:5672", new MessagingFactorySettings
{
TransportType = TransportType.Amqp,
AmqpTransportSettings = new Microsoft.ServiceBus.Messaging.Amqp.AmqpTransportSettings()
{
UseSslStreamSecurity = false
}
});
Thread.Sleep(1000);
var sender = factory.CreateMessageSender("event_queue");
for (int i = 0; i < 15; i++)
{
sender.Send(new BrokeredMessage(new SampleCommandMessage()
{
Data = i + " " + DateTime.UtcNow.ToString(),
}));
Thread.Sleep(50);
}
sender.Close();
Thread.Sleep(2000);
var client = factory.CreateQueueClient("event_queue", ReceiveMode.PeekLock);
client.PrefetchCount = 6;
client.OnMessage(m =>
{
m.Abandon();
}, new OnMessageOptions() { MaxConcurrentCalls = 7 });
Thread.Sleep(2000);
if ("".Length == 0)
return;
for (int i = 0; i < 15; i++)
{
client.Send(new BrokeredMessage(new SampleCommandMessage()
{
Data = i + " " + DateTime.UtcNow.ToString(),
}));
Thread.Sleep(50);
}
Thread.Sleep(2000);
var msg = client.Receive(TimeSpan.FromSeconds(2));
Thread.Sleep(2000);
client.Close();
Thread.Sleep(2000);
factory.Close();
}
}
public class SampleCommandMessage
{
public string Data { get; set; }
}
}
| 29.943662 | 104 | 0.484948 | [
"MIT"
] | jdaigle/LightRail | src/Samples/Samples.AzureServiceBus/Program.cs | 2,128 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Giselle.Imaging.IO;
namespace Giselle.Imaging.Scan
{
public class InterlacePassProcessor
{
public ScanData ScanData { get; private set; }
public int PassIndex { get; private set; }
public InterlacePassInformation PassInfo { get; private set; }
public InterlacePassProcessor(ScanData scanData)
{
this.ScanData = scanData;
this.PassIndex = -1;
}
public (int X, int Y) GetPosition(int xi, int yi)
{
var scanData = this.ScanData;
if (scanData.InterlacePasses.Length == 0)
{
return (xi, yi);
}
else
{
var pass = scanData.InterlacePasses[this.PassIndex];
var x = pass.OffsetX + pass.IntervalX * xi;
var y = pass.OffsetY + pass.IntervalY * yi;
return (x, y);
}
}
public bool NextPass()
{
var scanData = this.ScanData;
if (scanData.InterlacePasses.Length == 0)
{
if (this.PassIndex >= 0)
{
return false;
}
else
{
this.PassIndex++;
this.PassInfo = new InterlacePassInformation() { PixelsX = scanData.Width, PixelsY = scanData.Height, Stride = scanData.Stride };
return true;
}
}
else
{
if (this.PassIndex + 1 >= scanData.InterlacePasses.Length)
{
return false;
}
else
{
this.PassIndex++;
this.PassInfo = scanData.GetInterlacePassInformation(this.PassIndex);
return true;
}
}
}
}
}
| 26.141026 | 149 | 0.470819 | [
"MIT"
] | gisellevonbingen/Giselle.Imaging | Giselle.Imaging/Scan/InterlacePassProcessor.cs | 2,041 | C# |
using System;
using UnityEngine;
namespace ET
{
public class OperaComponentAwakeSystem : AwakeSystem<OperaComponent>
{
public override void Awake(OperaComponent self)
{
self.mapMask = LayerMask.GetMask("Map");
}
}
public class OperaComponentUpdateSystem : UpdateSystem<OperaComponent>
{
public override void Update(OperaComponent self)
{
self.Update();
}
}
public static class OperaComponentSystem
{
public static void Update(this OperaComponent self)
{
if (Input.GetMouseButtonDown(1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000, self.mapMask))
{
self.ClickPoint = hit.point;
self.frameClickMap.X = self.ClickPoint.x;
self.frameClickMap.Y = self.ClickPoint.y;
self.frameClickMap.Z = self.ClickPoint.z;
self.DomainScene().GetComponent<SessionComponent>().Session.Send(self.frameClickMap);
}
}
if (Input.GetKeyDown(KeyCode.R))
{
CodeLoader.Instance.LoadHotfix();
Game.EventSystem.Add(CodeLoader.Instance.GetTypes());
Game.EventSystem.Load();
Log.Debug("hot reload success!");
}
}
}
} | 30.877551 | 105 | 0.546596 | [
"MIT"
] | klhalu1/ET | Unity/Codes/HotfixView/Demo/Opera/OperaComponentSystem.cs | 1,513 | 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("DesktopProjectDataHandler")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DesktopProjectDataHandler")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("e488dec9-bf37-4d60-8910-4a0d6fca37d5")]
// 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")]
| 39.297297 | 85 | 0.733838 | [
"MIT"
] | fischgeek/AutoToggl | DesktopProjectDataHandler/Properties/AssemblyInfo.cs | 1,457 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Charlotte.GameCommons;
using Charlotte.Games.Enemies;
using Charlotte.Games.Walls;
using Charlotte.Commons;
namespace Charlotte.Games.Scripts
{
public class Script_ステージ0001 : Script
{
protected override IEnumerable<bool> E_EachFrame()
{
return ScriptCommon.Wrapper(SCommon.Supplier(this.E_EachFrame2()));
}
private IEnumerable<int> E_EachFrame2()
{
DDRandom rand = new DDRandom(1);
//Ground.I.Music.Stage_01.Play();
Game.I.Walls.Add(new Wall_Dark());
Game.I.Walls.Add(new Wall_B0001());
yield return 100;
Game.I.Enemies.Add(new Enemy_B0001(DDConsts.Screen_W + 50, DDConsts.Screen_H / 2));
yield return 100;
Game.I.Enemies.Add(new Enemy_B0002(DDConsts.Screen_W + 50, DDConsts.Screen_H / 2));
yield return 300;
// ---- ここからボス ----
//Ground.I.Music.Boss_01.Play();
Game.I.Enemies.Add(new Enemy_Bボス0001());
for (; ; )
yield return 1; // 以降何もしない。
}
}
}
| 22 | 86 | 0.702569 | [
"MIT"
] | soleil-taruto/Elsa | e20201122_YokoShootSp/Elsa20200001/Elsa20200001/Games/Scripts/Script_30b930c630fc30b80001.cs | 1,054 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TwitterRead
{
static class Program
{
/// <summary>
/// アプリケーションのメイン エントリ ポイントです。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 21.384615 | 65 | 0.627698 | [
"MIT"
] | Yukiho-YOSHIEDA/twitter_read | TwitterRead/Program.cs | 604 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.ContainerRegistry.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An object that represents a container registry.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class Registry : Resource
{
/// <summary>
/// Initializes a new instance of the Registry class.
/// </summary>
public Registry()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Registry class.
/// </summary>
/// <param name="location">The location of the resource. This cannot be
/// changed after the resource is created.</param>
/// <param name="sku">The SKU of the container registry.</param>
/// <param name="id">The resource ID.</param>
/// <param name="name">The name of the resource.</param>
/// <param name="type">The type of the resource.</param>
/// <param name="tags">The tags of the resource.</param>
/// <param name="loginServer">The URL that can be used to log into the
/// container registry.</param>
/// <param name="creationDate">The creation date of the container
/// registry in ISO8601 format.</param>
/// <param name="provisioningState">The provisioning state of the
/// container registry at the time the operation was called. Possible
/// values include: 'Creating', 'Updating', 'Deleting', 'Succeeded',
/// 'Failed', 'Canceled'</param>
/// <param name="status">The status of the container registry at the
/// time the operation was called.</param>
/// <param name="adminUserEnabled">The value that indicates whether the
/// admin user is enabled.</param>
/// <param name="storageAccount">The properties of the storage account
/// for the container registry. Only applicable to Classic SKU.</param>
/// <param name="networkRuleSet">The network rule set for a container
/// registry.</param>
/// <param name="policies">The policies for a container
/// registry.</param>
public Registry(string location, Sku sku, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string loginServer = default(string), System.DateTime? creationDate = default(System.DateTime?), string provisioningState = default(string), Status status = default(Status), bool? adminUserEnabled = default(bool?), StorageAccountProperties storageAccount = default(StorageAccountProperties), NetworkRuleSet networkRuleSet = default(NetworkRuleSet), Policies policies = default(Policies))
: base(location, id, name, type, tags)
{
Sku = sku;
LoginServer = loginServer;
CreationDate = creationDate;
ProvisioningState = provisioningState;
Status = status;
AdminUserEnabled = adminUserEnabled;
StorageAccount = storageAccount;
NetworkRuleSet = networkRuleSet;
Policies = policies;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the SKU of the container registry.
/// </summary>
[JsonProperty(PropertyName = "sku")]
public Sku Sku { get; set; }
/// <summary>
/// Gets the URL that can be used to log into the container registry.
/// </summary>
[JsonProperty(PropertyName = "properties.loginServer")]
public string LoginServer { get; private set; }
/// <summary>
/// Gets the creation date of the container registry in ISO8601 format.
/// </summary>
[JsonProperty(PropertyName = "properties.creationDate")]
public System.DateTime? CreationDate { get; private set; }
/// <summary>
/// Gets the provisioning state of the container registry at the time
/// the operation was called. Possible values include: 'Creating',
/// 'Updating', 'Deleting', 'Succeeded', 'Failed', 'Canceled'
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; private set; }
/// <summary>
/// Gets the status of the container registry at the time the operation
/// was called.
/// </summary>
[JsonProperty(PropertyName = "properties.status")]
public Status Status { get; private set; }
/// <summary>
/// Gets or sets the value that indicates whether the admin user is
/// enabled.
/// </summary>
[JsonProperty(PropertyName = "properties.adminUserEnabled")]
public bool? AdminUserEnabled { get; set; }
/// <summary>
/// Gets or sets the properties of the storage account for the
/// container registry. Only applicable to Classic SKU.
/// </summary>
[JsonProperty(PropertyName = "properties.storageAccount")]
public StorageAccountProperties StorageAccount { get; set; }
/// <summary>
/// Gets or sets the network rule set for a container registry.
/// </summary>
[JsonProperty(PropertyName = "properties.networkRuleSet")]
public NetworkRuleSet NetworkRuleSet { get; set; }
/// <summary>
/// Gets or sets the policies for a container registry.
/// </summary>
[JsonProperty(PropertyName = "properties.policies")]
public Policies Policies { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (Sku == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Sku");
}
if (Sku != null)
{
Sku.Validate();
}
if (StorageAccount != null)
{
StorageAccount.Validate();
}
if (NetworkRuleSet != null)
{
NetworkRuleSet.Validate();
}
}
}
}
| 41.56213 | 601 | 0.60635 | [
"MIT"
] | Azkel/azure-sdk-for-net | sdk/containerregistry/Microsoft.Azure.Management.ContainerRegistry/src/Generated/Models/Registry.cs | 7,024 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using SmartAdmin.Domain.Models;
using SmartAdmin.Application.Customers.Commands;
using SmartAdmin.Service;
using URF.Core.Abstractions;
using Mapster;
namespace SmartAdmin.Application.Customers.Handlers
{
public class CreateOrEditCustomerHandler : IRequestHandler<CreateOrEditCustomerCommand, Customer>
{
private readonly IUnitOfWork unitOfWork;
private readonly ICustomerService customerService;
public CreateOrEditCustomerHandler(
IUnitOfWork unitOfWork,
ICustomerService customerService
)
{
this.unitOfWork = unitOfWork;
this.customerService = customerService;
}
public async Task<Customer> Handle(CreateOrEditCustomerCommand request, CancellationToken cancellationToken) {
var customer = request.Adapt<Customer>();
var response =await this.customerService.CreateOrEdit(customer);
await this.unitOfWork.SaveChangesAsync();
return customer;
}
}
}
| 29.648649 | 114 | 0.772106 | [
"Apache-2.0"
] | neozhu/smartadmin.core.urf | smartadmin-core-urf/src/SmartAdmin.Domain/Customers/Handlers/CreateOrEditCustomerHandler.cs | 1,099 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Serialization.Objects;
using JsonApiDotNetCoreExampleTests.Startups;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreExampleTests.IntegrationTests.QueryStrings.SparseFieldSets
{
public sealed class SparseFieldSetTests
: IClassFixture<ExampleIntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext>>
{
private readonly ExampleIntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> _testContext;
private readonly QueryStringFakers _fakers = new QueryStringFakers();
public SparseFieldSetTests(ExampleIntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> testContext)
{
_testContext = testContext;
testContext.ConfigureServicesAfterStartup(services =>
{
services.AddSingleton<ResourceCaptureStore>();
services.AddResourceRepository<ResultCapturingRepository<Blog>>();
services.AddResourceRepository<ResultCapturingRepository<BlogPost>>();
services.AddResourceRepository<ResultCapturingRepository<WebAccount>>();
});
}
[Fact]
public async Task Can_select_fields_in_primary_resources()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var post = _fakers.BlogPost.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?fields[blogPosts]=caption,author";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.ManyData.Should().HaveCount(1);
responseDocument.ManyData[0].Id.Should().Be(post.StringId);
responseDocument.ManyData[0].Attributes.Should().HaveCount(1);
responseDocument.ManyData[0].Attributes["caption"].Should().Be(post.Caption);
responseDocument.ManyData[0].Relationships.Should().HaveCount(1);
responseDocument.ManyData[0].Relationships["author"].Data.Should().BeNull();
responseDocument.ManyData[0].Relationships["author"].Links.Self.Should().NotBeNull();
responseDocument.ManyData[0].Relationships["author"].Links.Related.Should().NotBeNull();
var postCaptured = (BlogPost) store.Resources.Should().ContainSingle(x => x is BlogPost).And.Subject.Single();
postCaptured.Caption.Should().Be(post.Caption);
postCaptured.Url.Should().BeNull();
}
[Fact]
public async Task Can_select_attribute_in_primary_resources()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var post = _fakers.BlogPost.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?fields[blogPosts]=caption";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.ManyData.Should().HaveCount(1);
responseDocument.ManyData[0].Id.Should().Be(post.StringId);
responseDocument.ManyData[0].Attributes.Should().HaveCount(1);
responseDocument.ManyData[0].Attributes["caption"].Should().Be(post.Caption);
responseDocument.ManyData[0].Relationships.Should().BeNull();
var postCaptured = (BlogPost) store.Resources.Should().ContainSingle(x => x is BlogPost).And.Subject.Single();
postCaptured.Caption.Should().Be(post.Caption);
postCaptured.Url.Should().BeNull();
}
[Fact]
public async Task Can_select_relationship_in_primary_resources()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var post = _fakers.BlogPost.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?fields[blogPosts]=author";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.ManyData.Should().HaveCount(1);
responseDocument.ManyData[0].Id.Should().Be(post.StringId);
responseDocument.ManyData[0].Attributes.Should().BeNull();
responseDocument.ManyData[0].Relationships.Should().HaveCount(1);
responseDocument.ManyData[0].Relationships["author"].Data.Should().BeNull();
responseDocument.ManyData[0].Relationships["author"].Links.Self.Should().NotBeNull();
responseDocument.ManyData[0].Relationships["author"].Links.Related.Should().NotBeNull();
var postCaptured = (BlogPost) store.Resources.Should().ContainSingle(x => x is BlogPost).And.Subject.Single();
postCaptured.Caption.Should().BeNull();
postCaptured.Url.Should().BeNull();
}
[Fact]
public async Task Can_select_fields_in_primary_resource_by_ID()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var post = _fakers.BlogPost.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
var route = $"/blogPosts/{post.StringId}?fields[blogPosts]=url,author";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(post.StringId);
responseDocument.SingleData.Attributes.Should().HaveCount(1);
responseDocument.SingleData.Attributes["url"].Should().Be(post.Url);
responseDocument.SingleData.Relationships.Should().HaveCount(1);
responseDocument.SingleData.Relationships["author"].Data.Should().BeNull();
responseDocument.SingleData.Relationships["author"].Links.Self.Should().NotBeNull();
responseDocument.SingleData.Relationships["author"].Links.Related.Should().NotBeNull();
var postCaptured = (BlogPost) store.Resources.Should().ContainSingle(x => x is BlogPost).And.Subject.Single();
postCaptured.Url.Should().Be(post.Url);
postCaptured.Caption.Should().BeNull();
}
[Fact]
public async Task Can_select_fields_in_secondary_resources()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var blog = _fakers.Blog.Generate();
blog.Posts = _fakers.BlogPost.Generate(1);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Blogs.Add(blog);
await dbContext.SaveChangesAsync();
});
var route = $"/blogs/{blog.StringId}/posts?fields[blogPosts]=caption,labels";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.ManyData.Should().HaveCount(1);
responseDocument.ManyData[0].Id.Should().Be(blog.Posts[0].StringId);
responseDocument.ManyData[0].Attributes.Should().HaveCount(1);
responseDocument.ManyData[0].Attributes["caption"].Should().Be(blog.Posts[0].Caption);
responseDocument.ManyData[0].Relationships.Should().HaveCount(1);
responseDocument.ManyData[0].Relationships["labels"].Data.Should().BeNull();
responseDocument.ManyData[0].Relationships["labels"].Links.Self.Should().NotBeNull();
responseDocument.ManyData[0].Relationships["labels"].Links.Related.Should().NotBeNull();
var blogCaptured = (Blog) store.Resources.Should().ContainSingle(x => x is Blog).And.Subject.Single();
blogCaptured.Id.Should().Be(blog.Id);
blogCaptured.Title.Should().BeNull();
blogCaptured.Posts.Should().HaveCount(1);
blogCaptured.Posts[0].Caption.Should().Be(blog.Posts[0].Caption);
blogCaptured.Posts[0].Url.Should().BeNull();
}
[Fact]
public async Task Can_select_fields_of_HasOne_relationship()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var post = _fakers.BlogPost.Generate();
post.Author = _fakers.WebAccount.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
var route = $"/blogPosts/{post.StringId}?include=author&fields[webAccounts]=displayName,emailAddress,preferences";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(post.StringId);
responseDocument.SingleData.Attributes["caption"].Should().Be(post.Caption);
responseDocument.SingleData.Relationships["author"].SingleData.Id.Should().Be(post.Author.StringId);
responseDocument.SingleData.Relationships["author"].Links.Self.Should().NotBeNull();
responseDocument.SingleData.Relationships["author"].Links.Related.Should().NotBeNull();
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Attributes.Should().HaveCount(2);
responseDocument.Included[0].Attributes["displayName"].Should().Be(post.Author.DisplayName);
responseDocument.Included[0].Attributes["emailAddress"].Should().Be(post.Author.EmailAddress);
responseDocument.Included[0].Relationships.Should().HaveCount(1);
responseDocument.Included[0].Relationships["preferences"].Data.Should().BeNull();
responseDocument.Included[0].Relationships["preferences"].Links.Self.Should().NotBeNull();
responseDocument.Included[0].Relationships["preferences"].Links.Related.Should().NotBeNull();
var postCaptured = (BlogPost) store.Resources.Should().ContainSingle(x => x is BlogPost).And.Subject.Single();
postCaptured.Id.Should().Be(post.Id);
postCaptured.Caption.Should().Be(post.Caption);
postCaptured.Author.DisplayName.Should().Be(post.Author.DisplayName);
postCaptured.Author.EmailAddress.Should().Be(post.Author.EmailAddress);
postCaptured.Author.UserName.Should().BeNull();
}
[Fact]
public async Task Can_select_fields_of_HasMany_relationship()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var account = _fakers.WebAccount.Generate();
account.Posts = _fakers.BlogPost.Generate(1);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Accounts.Add(account);
await dbContext.SaveChangesAsync();
});
var route = $"/webAccounts/{account.StringId}?include=posts&fields[blogPosts]=caption,labels";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(account.StringId);
responseDocument.SingleData.Attributes["displayName"].Should().Be(account.DisplayName);
responseDocument.SingleData.Relationships["posts"].ManyData.Should().HaveCount(1);
responseDocument.SingleData.Relationships["posts"].ManyData[0].Id.Should().Be(account.Posts[0].StringId);
responseDocument.SingleData.Relationships["posts"].Links.Self.Should().NotBeNull();
responseDocument.SingleData.Relationships["posts"].Links.Related.Should().NotBeNull();
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Attributes.Should().HaveCount(1);
responseDocument.Included[0].Attributes["caption"].Should().Be(account.Posts[0].Caption);
responseDocument.Included[0].Relationships.Should().HaveCount(1);
responseDocument.Included[0].Relationships["labels"].Data.Should().BeNull();
responseDocument.Included[0].Relationships["labels"].Links.Self.Should().NotBeNull();
responseDocument.Included[0].Relationships["labels"].Links.Related.Should().NotBeNull();
var accountCaptured = (WebAccount) store.Resources.Should().ContainSingle(x => x is WebAccount).And.Subject.Single();
accountCaptured.Id.Should().Be(account.Id);
accountCaptured.DisplayName.Should().Be(account.DisplayName);
accountCaptured.Posts.Should().HaveCount(1);
accountCaptured.Posts[0].Caption.Should().Be(account.Posts[0].Caption);
accountCaptured.Posts[0].Url.Should().BeNull();
}
[Fact]
public async Task Can_select_fields_of_HasMany_relationship_on_secondary_resource()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var blog = _fakers.Blog.Generate();
blog.Owner = _fakers.WebAccount.Generate();
blog.Owner.Posts = _fakers.BlogPost.Generate(1);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Blogs.Add(blog);
await dbContext.SaveChangesAsync();
});
var route = $"/blogs/{blog.StringId}/owner?include=posts&fields[blogPosts]=caption,comments";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(blog.Owner.StringId);
responseDocument.SingleData.Attributes["displayName"].Should().Be(blog.Owner.DisplayName);
responseDocument.SingleData.Relationships["posts"].ManyData.Should().HaveCount(1);
responseDocument.SingleData.Relationships["posts"].ManyData[0].Id.Should().Be(blog.Owner.Posts[0].StringId);
responseDocument.SingleData.Relationships["posts"].Links.Self.Should().NotBeNull();
responseDocument.SingleData.Relationships["posts"].Links.Related.Should().NotBeNull();
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Attributes.Should().HaveCount(1);
responseDocument.Included[0].Attributes["caption"].Should().Be(blog.Owner.Posts[0].Caption);
responseDocument.Included[0].Relationships.Should().HaveCount(1);
responseDocument.Included[0].Relationships["comments"].Data.Should().BeNull();
responseDocument.Included[0].Relationships["comments"].Links.Self.Should().NotBeNull();
responseDocument.Included[0].Relationships["comments"].Links.Related.Should().NotBeNull();
var blogCaptured = (Blog) store.Resources.Should().ContainSingle(x => x is Blog).And.Subject.Single();
blogCaptured.Id.Should().Be(blog.Id);
blogCaptured.Owner.Should().NotBeNull();
blogCaptured.Owner.DisplayName.Should().Be(blog.Owner.DisplayName);
blogCaptured.Owner.Posts.Should().HaveCount(1);
blogCaptured.Owner.Posts[0].Caption.Should().Be(blog.Owner.Posts[0].Caption);
blogCaptured.Owner.Posts[0].Url.Should().BeNull();
}
[Fact]
public async Task Can_select_fields_of_HasManyThrough_relationship()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var post = _fakers.BlogPost.Generate();
post.BlogPostLabels = new HashSet<BlogPostLabel>
{
new BlogPostLabel
{
Label = _fakers.Label.Generate()
}
};
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
var route = $"/blogPosts/{post.StringId}?include=labels&fields[labels]=color";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(post.StringId);
responseDocument.SingleData.Attributes["caption"].Should().Be(post.Caption);
responseDocument.SingleData.Relationships["labels"].ManyData.Should().HaveCount(1);
responseDocument.SingleData.Relationships["labels"].ManyData[0].Id.Should().Be(post.BlogPostLabels.ElementAt(0).Label.StringId);
responseDocument.SingleData.Relationships["labels"].Links.Self.Should().NotBeNull();
responseDocument.SingleData.Relationships["labels"].Links.Related.Should().NotBeNull();
responseDocument.Included.Should().HaveCount(1);
responseDocument.Included[0].Attributes.Should().HaveCount(1);
responseDocument.Included[0].Attributes["color"].Should().Be(post.BlogPostLabels.Single().Label.Color.ToString("G"));
responseDocument.Included[0].Relationships.Should().BeNull();
var postCaptured = (BlogPost) store.Resources.Should().ContainSingle(x => x is BlogPost).And.Subject.Single();
postCaptured.Id.Should().Be(post.Id);
postCaptured.Caption.Should().Be(post.Caption);
postCaptured.BlogPostLabels.Should().HaveCount(1);
postCaptured.BlogPostLabels.Single().Label.Color.Should().Be(post.BlogPostLabels.Single().Label.Color);
postCaptured.BlogPostLabels.Single().Label.Name.Should().BeNull();
}
[Fact]
public async Task Can_select_attributes_in_multiple_resource_types()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var blog = _fakers.Blog.Generate();
blog.Owner = _fakers.WebAccount.Generate();
blog.Owner.Posts = _fakers.BlogPost.Generate(1);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Blogs.Add(blog);
await dbContext.SaveChangesAsync();
});
var route = $"/blogs/{blog.StringId}?include=owner.posts&fields[blogs]=title&fields[webAccounts]=userName,displayName&fields[blogPosts]=caption";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(blog.StringId);
responseDocument.SingleData.Attributes.Should().HaveCount(1);
responseDocument.SingleData.Attributes["title"].Should().Be(blog.Title);
responseDocument.SingleData.Relationships.Should().BeNull();
responseDocument.Included.Should().HaveCount(2);
responseDocument.Included[0].Id.Should().Be(blog.Owner.StringId);
responseDocument.Included[0].Attributes.Should().HaveCount(2);
responseDocument.Included[0].Attributes["userName"].Should().Be(blog.Owner.UserName);
responseDocument.Included[0].Attributes["displayName"].Should().Be(blog.Owner.DisplayName);
responseDocument.Included[0].Relationships.Should().BeNull();
responseDocument.Included[1].Id.Should().Be(blog.Owner.Posts[0].StringId);
responseDocument.Included[1].Attributes.Should().HaveCount(1);
responseDocument.Included[1].Attributes["caption"].Should().Be(blog.Owner.Posts[0].Caption);
responseDocument.Included[1].Relationships.Should().BeNull();
var blogCaptured = (Blog) store.Resources.Should().ContainSingle(x => x is Blog).And.Subject.Single();
blogCaptured.Id.Should().Be(blog.Id);
blogCaptured.Title.Should().Be(blog.Title);
blogCaptured.PlatformName.Should().BeNull();
blogCaptured.Owner.UserName.Should().Be(blog.Owner.UserName);
blogCaptured.Owner.DisplayName.Should().Be(blog.Owner.DisplayName);
blogCaptured.Owner.DateOfBirth.Should().BeNull();
blogCaptured.Owner.Posts.Should().HaveCount(1);
blogCaptured.Owner.Posts[0].Caption.Should().Be(blog.Owner.Posts[0].Caption);
blogCaptured.Owner.Posts[0].Url.Should().BeNull();
}
[Fact]
public async Task Can_select_only_top_level_fields_with_multiple_includes()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var blog = _fakers.Blog.Generate();
blog.Owner = _fakers.WebAccount.Generate();
blog.Owner.Posts = _fakers.BlogPost.Generate(1);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Blogs.Add(blog);
await dbContext.SaveChangesAsync();
});
var route = $"/blogs/{blog.StringId}?include=owner.posts&fields[blogs]=title,owner";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(blog.StringId);
responseDocument.SingleData.Attributes.Should().HaveCount(1);
responseDocument.SingleData.Attributes["title"].Should().Be(blog.Title);
responseDocument.SingleData.Relationships.Should().HaveCount(1);
responseDocument.SingleData.Relationships["owner"].SingleData.Id.Should().Be(blog.Owner.StringId);
responseDocument.SingleData.Relationships["owner"].Links.Self.Should().NotBeNull();
responseDocument.SingleData.Relationships["owner"].Links.Related.Should().NotBeNull();
responseDocument.Included.Should().HaveCount(2);
responseDocument.Included[0].Id.Should().Be(blog.Owner.StringId);
responseDocument.Included[0].Attributes["userName"].Should().Be(blog.Owner.UserName);
responseDocument.Included[0].Attributes["displayName"].Should().Be(blog.Owner.DisplayName);
responseDocument.Included[0].Attributes["dateOfBirth"].Should().BeCloseTo(blog.Owner.DateOfBirth);
responseDocument.Included[0].Relationships["posts"].ManyData.Should().HaveCount(1);
responseDocument.Included[0].Relationships["posts"].ManyData[0].Id.Should().Be(blog.Owner.Posts[0].StringId);
responseDocument.Included[0].Relationships["posts"].Links.Self.Should().NotBeNull();
responseDocument.Included[0].Relationships["posts"].Links.Related.Should().NotBeNull();
responseDocument.Included[1].Id.Should().Be(blog.Owner.Posts[0].StringId);
responseDocument.Included[1].Attributes["caption"].Should().Be(blog.Owner.Posts[0].Caption);
responseDocument.Included[1].Attributes["url"].Should().Be(blog.Owner.Posts[0].Url);
responseDocument.Included[1].Relationships["labels"].Data.Should().BeNull();
responseDocument.Included[1].Relationships["labels"].Links.Self.Should().NotBeNull();
responseDocument.Included[1].Relationships["labels"].Links.Related.Should().NotBeNull();
var blogCaptured = (Blog) store.Resources.Should().ContainSingle(x => x is Blog).And.Subject.Single();
blogCaptured.Id.Should().Be(blog.Id);
blogCaptured.Title.Should().Be(blog.Title);
blogCaptured.PlatformName.Should().BeNull();
}
[Fact]
public async Task Can_select_ID()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var post = _fakers.BlogPost.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?fields[blogPosts]=id,caption";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.ManyData.Should().HaveCount(1);
responseDocument.ManyData[0].Id.Should().Be(post.StringId);
responseDocument.ManyData[0].Attributes.Should().HaveCount(1);
responseDocument.ManyData[0].Attributes["caption"].Should().Be(post.Caption);
responseDocument.ManyData[0].Relationships.Should().BeNull();
var postCaptured = (BlogPost) store.Resources.Should().ContainSingle(x => x is BlogPost).And.Subject.Single();
postCaptured.Id.Should().Be(post.Id);
postCaptured.Caption.Should().Be(post.Caption);
postCaptured.Url.Should().BeNull();
}
[Fact]
public async Task Cannot_select_on_unknown_resource_type()
{
// Arrange
const string route = "/webAccounts?fields[doesNotExist]=id";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<ErrorDocument>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
var error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("The specified fieldset is invalid.");
error.Detail.Should().Be("Resource type 'doesNotExist' does not exist.");
error.Source.Parameter.Should().Be("fields[doesNotExist]");
}
[Fact]
public async Task Cannot_select_attribute_with_blocked_capability()
{
// Arrange
var account = _fakers.WebAccount.Generate();
var route = $"/webAccounts/{account.Id}?fields[webAccounts]=password";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<ErrorDocument>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
var error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("Retrieving the requested attribute is not allowed.");
error.Detail.Should().Be("Retrieving the attribute 'password' is not allowed.");
error.Source.Parameter.Should().Be("fields[webAccounts]");
}
[Fact]
public async Task Retrieves_all_properties_when_fieldset_contains_readonly_attribute()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var blog = _fakers.Blog.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Blogs.Add(blog);
await dbContext.SaveChangesAsync();
});
var route = $"/blogs/{blog.StringId}?fields[blogs]=showAdvertisements";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(blog.StringId);
responseDocument.SingleData.Attributes.Should().HaveCount(1);
responseDocument.SingleData.Attributes["showAdvertisements"].Should().Be(blog.ShowAdvertisements);
responseDocument.SingleData.Relationships.Should().BeNull();
var blogCaptured = (Blog) store.Resources.Should().ContainSingle(x => x is Blog).And.Subject.Single();
blogCaptured.ShowAdvertisements.Should().Be(blogCaptured.ShowAdvertisements);
blogCaptured.Title.Should().Be(blog.Title);
}
[Fact]
public async Task Can_select_fields_on_resource_type_multiple_times()
{
// Arrange
var store = _testContext.Factory.Services.GetRequiredService<ResourceCaptureStore>();
store.Clear();
var post = _fakers.BlogPost.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Posts.Add(post);
await dbContext.SaveChangesAsync();
});
var route = $"/blogPosts/{post.StringId}?fields[blogPosts]=url&fields[blogPosts]=caption,url&fields[blogPosts]=caption,author";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(post.StringId);
responseDocument.SingleData.Attributes.Should().HaveCount(2);
responseDocument.SingleData.Attributes["caption"].Should().Be(post.Caption);
responseDocument.SingleData.Attributes["url"].Should().Be(post.Url);
responseDocument.SingleData.Relationships.Should().HaveCount(1);
responseDocument.SingleData.Relationships["author"].Data.Should().BeNull();
responseDocument.SingleData.Relationships["author"].Links.Self.Should().NotBeNull();
responseDocument.SingleData.Relationships["author"].Links.Related.Should().NotBeNull();
var postCaptured = (BlogPost) store.Resources.Should().ContainSingle(x => x is BlogPost).And.Subject.Single();
postCaptured.Id.Should().Be(post.Id);
postCaptured.Caption.Should().Be(post.Caption);
postCaptured.Url.Should().Be(postCaptured.Url);
}
}
}
| 47.948201 | 157 | 0.64419 | [
"MIT"
] | jlits/JsonApiDotNetCore | test/JsonApiDotNetCoreExampleTests/IntegrationTests/QueryStrings/SparseFieldSets/SparseFieldSetTests.cs | 33,324 | 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 voice-id-2021-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.VoiceID.Model
{
/// <summary>
/// Container for the parameters to the ListSpeakers operation.
/// Lists all speakers in a specified domain.
/// </summary>
public partial class ListSpeakersRequest : AmazonVoiceIDRequest
{
private string _domainId;
private int? _maxResults;
private string _nextToken;
/// <summary>
/// Gets and sets the property DomainId.
/// <para>
/// The identifier of the domain.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=22, Max=22)]
public string DomainId
{
get { return this._domainId; }
set { this._domainId = value; }
}
// Check to see if DomainId property is set
internal bool IsSetDomainId()
{
return this._domainId != null;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of results that are returned per call. You can use <code>NextToken</code>
/// to obtain further pages of results. The default is 100; the maximum allowed page size
/// is also 100.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=100)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// If <code>NextToken</code> is returned, there are more results available. The value
/// of <code>NextToken</code> is a unique pagination token for each page. Make the call
/// again using the returned token to retrieve the next page. Keep all other arguments
/// unchanged. Each pagination token expires after 24 hours.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=8192)]
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 32.048077 | 106 | 0.608461 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/VoiceID/Generated/Model/ListSpeakersRequest.cs | 3,333 | C# |
namespace Blazorise
{
/// <summary>
/// Defines the text transformation.
/// </summary>
public enum TextTransform
{
/// <summary>
/// No capitalization. The text renders as it is. This is default.
/// </summary>
None,
/// <summary>
/// Transforms all characters to lowercase.
/// </summary>
Lowercase,
/// <summary>
/// Transforms all characters to uppercase.
/// </summary>
Uppercase,
/// <summary>
/// Transforms the first character of each word to uppercase.
/// </summary>
Capitalize,
}
}
| 22.37931 | 74 | 0.51772 | [
"Apache-2.0"
] | Luk164/Blazorise | Source/Blazorise/Enums/TextTransform.cs | 651 | C# |
// Copyright (c) Microsoft Corporation
// All rights reserved
namespace Microsoft.VisualStudio.Language.Intellisense
{
/// <summary>
/// Represents a collection of <see cref="IPeekResult"/>s populated by content-type specific <see cref="IPeekResultSource"/>
/// implementations when they are being queried for <see cref="IPeekResult"/>s.
/// </summary>
public interface IPeekResultCollection
{
/// <summary>
/// Gets the number of elements contained in the <see cref="IPeekResultCollection"/>.
/// </summary>
int Count { get; }
/// <summary>
/// Adds an item to the <see cref="IPeekResultCollection"/>.
/// </summary>
/// <param name="peekResult">The object to add to the <see cref="IPeekResultCollection"/>.</param>
void Add(IPeekResult peekResult);
/// <summary>
/// Removes all results from the <see cref="IPeekResultCollection"/>.
/// </summary>
void Clear();
/// <summary>
/// Determines whether the <see cref="IPeekResultCollection"/> contains a specific result.
/// </summary>
/// <param name="peekResult">The object to locate in the <see cref="IPeekResultCollection"/>.</param>
/// <returns><c>true</c> if the result is found in the <see cref="IPeekResultCollection"/>; <c>false</c> otherwise.</returns>
bool Contains(IPeekResult peekResult);
/// <summary>
/// Inserts a result into the collection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which the result should be inserted.</param>
/// <param name="peekResult">The result to insert.</param>
void Insert(int index, IPeekResult peekResult);
/// <summary>
/// Finds the index of the result or returns -1 if the result was not found.
/// </summary>
/// <param name="peekResult">The result to search for in the list.</param>
/// <param name="startAt">The start index for the search.</param>
/// <returns>The index of the result in the list, or -1 if the result was not found.</returns>
int IndexOf(IPeekResult peekResult, int startAt);
/// <summary>
/// Moves the result at the specified index to a new location in the collection.
/// </summary>
/// <param name="oldIndex">The zero-based index specifying the location of the result to be moved.</param>
/// <param name="newIndex">The zero-based index specifying the new location of the result.</param>
/// <remarks>This method inserts the result in the new location.</remarks>
void Move(int oldIndex, int newIndex);
/// <summary>
/// Removes the first occurrence of a specific result from the <see cref="IPeekResultCollection"/>.
/// </summary>
/// <param name="item">The result to remove from the <see cref="IPeekResultCollection"/></param>
/// <returns><c>true</c> if the result was successfully removed from the <see cref="IPeekResultCollection"/>; <c>false</c> otherwise.
/// This method also returns <c>false</c> if the result is not found in the <see cref="IPeekResultCollection"/>.</returns>
bool Remove(IPeekResult item);
/// <summary>
/// Removes the result at the specified index of the collection.
/// </summary>
/// <param name="index">The zero-based index of the result to remove.</param>
void RemoveAt(int index);
/// <summary>
/// Gets or sets the result at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <returns>The result at the specified index.</returns>
IPeekResult this[int index] { get; set; }
}
}
| 48.0375 | 141 | 0.624512 | [
"MIT"
] | AmadeusW/vs-editor-api | src/Editor/Language/Def/Intellisense/Peek/IPeekResultCollection.cs | 3,845 | C# |
using System;
using Hurricane.Shared.Objects.Interfaces;
namespace Hurricane.Shared.Networking.IPC.Interfaces
{
public interface IIPCInterface : IHurricaneObject
{
Boolean Startup();
Boolean Shutdown();
Boolean SendIPCMessage(IIPCMessage message);
event EventHandler<IPCEventArgs> OnReceiveData;
}
} | 23.133333 | 55 | 0.717579 | [
"ISC"
] | Evairfairy/Hurricane | Hurricane.Shared/Networking/IPC/Interfaces/IIPCInterface.cs | 349 | C# |
using Feature.CookieWarning.Application;
using Foundation.SimpleNavigation.Application;
using Foundation.UserInterfaceSupport.Model;
using OpenQA.Selenium;
using Project.UserInterfaceTests.Model;
using ExpectedConditions = SeleniumExtras.WaitHelpers.ExpectedConditions;
namespace Project.UserInterfaceTests.Application
{
class PreparePageService : PageObjects
{
private readonly UserInterfaceBase _userInterface;
public PreparePageService(UserInterfaceBase userInterface) : base(userInterface.WebDriver)
{
_userInterface = userInterface;
}
public void PreparePage()
{
new PageNavigationService(_userInterface).GotoFrontPage();
var test = new CookieWarningService(_userInterface);
test.AcceptCookiesWithoutFail();
}
}
}
| 31.074074 | 98 | 0.731824 | [
"MIT"
] | jsurland/TestFramework | Project/UserInterfaceTests/Application/PreparePageService.cs | 841 | C# |
using UnityEngine;
using System.Collections;
public static class GameObjectHelper
{
#region Setters
public static void SetX(this GameObject gameObject, float x)
{
gameObject.transform.position = new Vector3(x, gameObject.transform.position.y, gameObject.transform.position.z);
}
public static void SetY(this GameObject gameObject, float y)
{
gameObject.transform.position = new Vector3(gameObject.transform.position.x, y, gameObject.transform.position.z);
}
public static void SetZ(this GameObject gameObject, float z)
{
gameObject.transform.position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, z);
}
public static void SetPosition(this GameObject gameObject, float x, float y, float z)
{
gameObject.transform.position = new Vector3(x, y, z);
}
#endregion
#region Getters
public static Vector3 Position(this GameObject gameObject)
{
return gameObject.transform.position;
}
public static float XPos(this GameObject gameObject)
{
return gameObject.transform.position.x;
}
public static float YPos(this GameObject gameObject)
{
return gameObject.transform.position.y;
}
public static float ZPos(this GameObject gameObject)
{
return gameObject.transform.position.z;
}
#endregion
#region Helpers
public static Vector3 PositionWithOverrideX(this GameObject gameObject, float xOverride)
{
return new Vector3(xOverride, gameObject.transform.position.y, gameObject.transform.position.z);
}
public static Vector3 PositionWithOverrideY(this GameObject gameObject, float yOverride)
{
return new Vector3(gameObject.transform.position.x, yOverride, gameObject.transform.position.z);
}
public static Vector3 PositionWithOverrideZ(this GameObject gameObject, float zOverride)
{
return new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, zOverride);
}
#endregion
}
| 27.852941 | 115 | 0.779303 | [
"MIT"
] | mystaticself/unity-extensions | extensions/GameObjectHelper.cs | 1,894 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System.Text;
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json
{
internal static class StringBuilderExtensions
{
/// <summary>
/// Extracts the buffered value and resets the buffer
/// </summary>
internal static string Extract(this StringBuilder builder)
{
var text = builder.ToString();
builder.Clear();
return text;
}
}
} | 35.608696 | 97 | 0.474969 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Migrate/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs | 799 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_NativeInteger : CSharpTestBase
{
private static readonly SymbolDisplayFormat FormatWithSpecialTypes = SymbolDisplayFormat.TestFormat.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
[Fact]
public void EmptyProject()
{
var source = @"";
var comp = CreateCompilation(source);
var expected =
@"";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void ExplicitAttribute_FromSource()
{
var source =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(new[] { NativeIntegerAttributeDefinition, source }, parseOptions: TestOptions.RegularPreview);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger] System.UIntPtr[] F2
";
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute");
Assert.NotNull(attributeType);
AssertNativeIntegerAttributes(module, expected);
});
}
[Fact]
public void ExplicitAttribute_FromMetadata()
{
var comp = CreateCompilation(NativeIntegerAttributeDefinition);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
comp = CreateCompilation(source, references: new[] { ref0 }, parseOptions: TestOptions.RegularPreview);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger] System.UIntPtr[] F2
";
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute");
Assert.Null(attributeType);
AssertNativeIntegerAttributes(module, expected);
});
}
[Fact]
public void ExplicitAttribute_MissingEmptyConstructor()
{
var source1 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NativeIntegerAttribute : Attribute
{
public NativeIntegerAttribute(bool[] flags) { }
}
}";
var source2 =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nint F1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17),
// (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nuint[] F2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20));
}
[Fact]
public void ExplicitAttribute_MissingConstructor()
{
var source1 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NativeIntegerAttribute : Attribute
{
}
}";
var source2 =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nint F1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17),
// (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nuint[] F2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20));
}
[Fact]
public void ExplicitAttribute_ReferencedInSource()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NativeIntegerAttribute : Attribute
{
internal NativeIntegerAttribute() { }
internal NativeIntegerAttribute(bool[] flags) { }
}
}";
var source =
@"#pragma warning disable 67
#pragma warning disable 169
using System;
using System.Runtime.CompilerServices;
[NativeInteger] class Program
{
[NativeInteger] IntPtr F;
[NativeInteger] event EventHandler E;
[NativeInteger] object P { get; }
[NativeInteger(new[] { false, true })] static UIntPtr[] M1() => throw null;
[return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null;
static void M3([NativeInteger]object arg) { }
}";
var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular8);
verifyDiagnostics(comp);
comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.RegularPreview);
verifyDiagnostics(comp);
static void verifyDiagnostics(CSharpCompilation comp)
{
comp.VerifyDiagnostics(
// (5,2): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] class Program
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 2),
// (7,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] IntPtr F;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 6),
// (8,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] event EventHandler E;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(8, 6),
// (9,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] object P { get; }
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(9, 6),
// (11,14): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger(new[] { false, true })").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(11, 14),
// (12,21): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// static void M3([NativeInteger]object arg) { }
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(12, 21));
}
}
[Fact]
public void MissingAttributeUsageAttribute()
{
var source =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void Metadata_ZeroElements()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0]
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0]
ret
}
.method public static void F1(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0]
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<System.IntPtr, System.UIntPtr>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language
// B.F0(default, default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(new A<System.IntPtr, System.UIntPtr>());
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11));
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language
// B.F0(default, default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(new A<System.IntPtr, System.UIntPtr>());
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11));
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0( x, y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(? x, ? y)
[NativeInteger({ })] ? x
[NativeInteger({ })] ? y
void F1(? a)
[NativeInteger({ })] ? a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_OneElementFalse()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F1(class A<int32, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F2(class A<native int, uint32> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<int, System.UIntPtr>());
B.F2(new A<System.IntPtr, uint>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<System.IntPtr, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(System.IntPtr x, System.UIntPtr y)
[NativeInteger({ False })] System.IntPtr x
[NativeInteger({ False })] System.UIntPtr y
void F1(A<System.Int32, System.UIntPtr> a)
[NativeInteger({ False })] A<System.Int32, System.UIntPtr> a
void F2(A<System.IntPtr, System.UInt32> a)
[NativeInteger({ False })] A<System.IntPtr, System.UInt32> a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_OneElementTrue()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
ret
}
.method public static void F1(class A<int32, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
ret
}
.method public static void F2(class A<native int, uint32> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<int, nuint>());
B.F2(new A<nint, uint>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (6,25): error CS8652: The feature 'native-sized integers' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
// B.F1(new A<int, nuint>());
Diagnostic(ErrorCode.ERR_FeatureInPreview, "nuint").WithArguments("native-sized integers").WithLocation(6, 25),
// (7,20): error CS8652: The feature 'native-sized integers' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
// B.F2(new A<nint, uint>());
Diagnostic(ErrorCode.ERR_FeatureInPreview, "nint").WithArguments("native-sized integers").WithLocation(7, 20));
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0(nint x, nuint y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1(A<int, nuint> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<nint, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(System.IntPtr x, System.UIntPtr y)
[NativeInteger({ True })] System.IntPtr x
[NativeInteger({ True })] System.UIntPtr y
void F1(A<System.Int32, System.UIntPtr> a)
[NativeInteger({ True })] A<System.Int32, System.UIntPtr> a
void F2(A<System.IntPtr, System.UInt32> a)
[NativeInteger({ True })] A<System.IntPtr, System.UInt32> a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_AllFalse()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F1(class A<int32, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F2(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 00 00 00 ) // new[] { false, false }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<int, System.UIntPtr>());
B.F2(new A<System.IntPtr, System.UIntPtr>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<System.IntPtr, System.UIntPtr> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(System.IntPtr x, System.UIntPtr y)
[NativeInteger({ False })] System.IntPtr x
[NativeInteger({ False })] System.UIntPtr y
void F1(A<System.Int32, System.UIntPtr> a)
[NativeInteger({ False })] A<System.Int32, System.UIntPtr> a
void F2(A<System.IntPtr, System.UIntPtr> a)
[NativeInteger({ False, False })] A<System.IntPtr, System.UIntPtr> a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_TooFewAndTooManyTransformFlags()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
}
.class public B
{
.method public static void F(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 ) // no array, too few
ret
}
.method public static void F0(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0], too few
ret
}
.method public static void F1(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }, too few
ret
}
.method public static void F2(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }, valid
ret
}
.method public static void F3(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 01 01 00 00 ) // new[] { false, true, true }, too many
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F(A<nint, nuint> a)
{
B.F(a);
B.F0(a);
B.F1(a);
B.F2(a);
B.F3(a);
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (3,21): error CS8652: The feature 'native-sized integers' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
// static void F(A<nint, nuint> a)
Diagnostic(ErrorCode.ERR_FeatureInPreview, "nint").WithArguments("native-sized integers").WithLocation(3, 21),
// (3,27): error CS8652: The feature 'native-sized integers' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
// static void F(A<nint, nuint> a)
Diagnostic(ErrorCode.ERR_FeatureInPreview, "nuint").WithArguments("native-sized integers").WithLocation(3, 27),
// (5,11): error CS0570: 'B.F(?)' is not supported by the language
// B.F(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F0(?)' is not supported by the language
// B.F0(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11),
// (9,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11));
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F(?)' is not supported by the language
// B.F(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F0(?)' is not supported by the language
// B.F0(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11),
// (9,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11));
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F( a)", type.GetMember("F").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F0( a)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<System.IntPtr, nuint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F3( a)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F(? a)
[NativeInteger] ? a
void F0(? a)
[NativeInteger({ })] ? a
void F1(? a)
[NativeInteger({ True })] ? a
void F2(A<System.IntPtr, System.UIntPtr> a)
[NativeInteger({ False, True })] A<System.IntPtr, System.UIntPtr> a
void F3(? a)
[NativeInteger({ False, True, True })] ? a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_UnexpectedTarget()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class A<T>
{
}
.class public B
{
.method public static void F1(int32 w)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 )
ret
}
.method public static void F2(object[] x)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }
ret
}
.method public static void F3(class A<class B> y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }
ret
}
.method public static void F4(native int[] z)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 01 01 00 00 ) // new[] { true, true }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F1(default);
B.F2(default);
B.F3(default);
B.F4(default);
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F2(?)' is not supported by the language
// B.F2(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11),
// (8,11): error CS0570: 'B.F4(?)' is not supported by the language
// B.F4(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11)
);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F2(?)' is not supported by the language
// B.F2(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11),
// (8,11): error CS0570: 'B.F4(?)' is not supported by the language
// B.F4(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11)
);
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F1( w)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2( x)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F3( y)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F4( z)", type.GetMember("F4").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"
B
void F1(? w)
[NativeInteger] ? w
void F2(? x)
[NativeInteger({ False, True })] ? x
void F3(? y)
[NativeInteger({ False, True })] ? y
void F4(? z)
[NativeInteger({ True, True })] ? z
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
[Fact]
public void EmitAttribute_BaseClass()
{
var source =
@"public class A<T, U>
{
}
public class B : A<nint, nuint[]>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"[NativeInteger({ True, True })] B
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Interface()
{
var source =
@"public interface I<T>
{
}
public class A : I<(nint, nuint[])>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "A");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])");
});
}
[Fact]
public void EmitAttribute_AllTypes()
{
var source =
@"public enum E { }
public class C<T>
{
public delegate void D<T>();
public enum F { }
public struct S<U> { }
public interface I<U> { }
public C<T>.S<nint> F1;
public C<nuint>.I<T> F2;
public C<E>.D<nint> F3;
public C<nuint>.D<dynamic> F4;
public C<C<nuint>.D<System.IntPtr>>.F F5;
public C<C<System.UIntPtr>.F>.D<nint> F6;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"C<T>
[NativeInteger] C<T>.S<System.IntPtr> F1
[NativeInteger] C<System.UIntPtr>.I<T> F2
[NativeInteger] C<E>.D<System.IntPtr> F3
[NativeInteger] C<System.UIntPtr>.D<dynamic> F4
[NativeInteger({ True, False })] C<C<System.UIntPtr>.D<System.IntPtr>>.F F5
[NativeInteger({ False, True })] C<C<System.UIntPtr>.F>.D<System.IntPtr> F6
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ErrorType()
{
var source1 =
@"public class A { }
public class B<T> { }";
var comp = CreateCompilation(source1, assemblyName: "95d36b13-f2e1-495d-9ab6-62e8cc63ac22");
var ref1 = comp.EmitToImageReference();
var source2 =
@"public class C<T, U> { }
public class D
{
public B<nint> F1;
public C<nint, A> F2;
}";
comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.RegularPreview);
var ref2 = comp.EmitToImageReference();
var source3 =
@"class Program
{
static void Main()
{
var d = new D();
_ = d.F1;
_ = d.F2;
}
}";
comp = CreateCompilation(source3, references: new[] { ref2 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (6,15): error CS0012: The type 'B<>' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// _ = d.F1;
Diagnostic(ErrorCode.ERR_NoTypeDef, "F1").WithArguments("B<>", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 15),
// (7,15): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// _ = d.F2;
Diagnostic(ErrorCode.ERR_NoTypeDef, "F2").WithArguments("A", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 15));
}
[Fact]
public void EmitAttribute_Fields()
{
var source =
@"public class Program
{
public nint F1;
public (System.IntPtr, nuint[]) F2;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F2
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodReturnType()
{
var source =
@"public class Program
{
public (System.IntPtr, nuint[]) F() => default;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"Program
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F()
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodParameters()
{
var source =
@"public class Program
{
public void F(nint x, nuint y) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"Program
void F(System.IntPtr x, System.UIntPtr y)
[NativeInteger] System.IntPtr x
[NativeInteger] System.UIntPtr y
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyType()
{
var source =
@"public class Program
{
public (System.IntPtr, nuint[]) P => default;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"Program
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P { get; }
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P.get
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyParameters()
{
var source =
@"public class Program
{
public object this[nint x, (nuint[], System.IntPtr) y] => null;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"Program
System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y] { get; }
[NativeInteger] System.IntPtr x
[NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y
System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y].get
[NativeInteger] System.IntPtr x
[NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_EventType()
{
var source =
@"using System;
public class Program
{
public event EventHandler<nuint[]> E;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"Program
[NativeInteger] event System.EventHandler<System.UIntPtr[]> E
void E.add
[NativeInteger] System.EventHandler<System.UIntPtr[]> value
void E.remove
[NativeInteger] System.EventHandler<System.UIntPtr[]> value
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorReturnType()
{
var source =
@"public class C
{
public static nint operator+(C a, C b) => 0;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"C
[NativeInteger] System.IntPtr operator +(C a, C b)
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorParameters()
{
var source =
@"public class C
{
public static C operator+(C a, nuint[] b) => a;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"C
C operator +(C a, System.UIntPtr[] b)
[NativeInteger] System.UIntPtr[] b
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateReturnType()
{
var source =
@"public delegate nint D();";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"D
[NativeInteger] System.IntPtr Invoke()
[NativeInteger] System.IntPtr EndInvoke(System.IAsyncResult result)
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateParameters()
{
var source =
@"public delegate void D(nint x, nuint[] y);";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var expected =
@"D
void Invoke(System.IntPtr x, System.UIntPtr[] y)
[NativeInteger] System.IntPtr x
[NativeInteger] System.UIntPtr[] y
System.IAsyncResult BeginInvoke(System.IntPtr x, System.UIntPtr[] y, System.AsyncCallback callback, System.Object @object)
[NativeInteger] System.IntPtr x
[NativeInteger] System.UIntPtr[] y
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Constraint()
{
var source =
@"public class A<T>
{
}
public class B<T> where T : A<nint>
{
}
public class C<T> where T : A<nuint[]>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
var type = comp.GetMember<NamedTypeSymbol>("B");
Assert.Equal("A<nint>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes));
type = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal("A<nuint[]>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes));
static TypeWithAnnotations getConstraintType(NamedTypeSymbol type) => type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0];
}
[Fact]
public void EmitAttribute_LambdaReturnType()
{
var source =
@"using System;
class Program
{
static object M()
{
Func<nint> f = () => (nint)2;
return f();
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
AssertNoNativeIntegerAttributes(comp);
}
[Fact]
public void EmitAttribute_LambdaParameters()
{
var source =
@"using System;
class Program
{
static void M()
{
Action<nuint[]> a = (nuint[] n) => { };
a(null);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
AssertNoNativeIntegerAttributes(comp);
}
[Fact]
public void EmitAttribute_LocalFunctionReturnType()
{
var source =
@"class Program
{
static object M()
{
nint L() => (nint)2;
return L();
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.RegularPreview,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0");
AssertNativeIntegerAttribute(method.GetReturnTypeAttributes());
AssertAttributes(method.GetAttributes(), "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
});
}
[Fact]
public void EmitAttribute_LocalFunctionParameters()
{
var source =
@"class Program
{
static void M()
{
void L(nuint[] n) { }
L(null);
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.RegularPreview,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0");
AssertNativeIntegerAttribute(method.Parameters[0].GetAttributes());
});
}
[Fact]
public void EmitAttribute_LocalFunctionConstraints()
{
var source =
@"interface I<T>
{
}
class Program
{
static void M()
{
void L<T>() where T : I<nint> { }
L<I<nint>>();
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NativeIntegerAttribute"));
});
}
[Fact]
public void EmitAttribute_Nested()
{
var source =
@"public class A<T>
{
public class B<U> { }
}
unsafe public class Program
{
public nint F1;
public nuint[] F2;
public nint* F3;
public A<nint>.B<nuint> F4;
public (nint, nuint) F5;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseDll);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger] System.UIntPtr[] F2
[NativeInteger] System.IntPtr* F3
[NativeInteger({ True, True })] A<System.IntPtr>.B<System.UIntPtr> F4
[NativeInteger({ True, True })] (System.IntPtr, System.UIntPtr) F5
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_LongTuples_01()
{
var source =
@"public class A<T>
{
}
unsafe public class B
{
public A<(object, (nint, nuint, nint[], nuint, nint, nuint*[], nint, System.UIntPtr))> F1;
public A<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)> F2;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseDll);
var expected =
@"B
[NativeInteger({ True, True, True, True, True, True, True, False })] A<(System.Object, (System.IntPtr, System.UIntPtr, System.IntPtr[], System.UIntPtr, System.IntPtr, System.UIntPtr*[], System.IntPtr, System.UIntPtr))> F1
[NativeInteger({ True, True, True, False, True, True })] A<(System.IntPtr, System.Object, System.UIntPtr[], System.Object, System.IntPtr, System.Object, (System.IntPtr, System.UIntPtr), System.Object, System.UIntPtr)> F2
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_LongTuples_02()
{
var source1 =
@"public interface IA { }
public interface IB<T> { }
public class C : IA, IB<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)>
{
}";
var comp = CreateCompilation(source1, parseOptions: TestOptions.RegularPreview);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().ElementAt(1));
var customAttributes = interfaceImpl.GetCustomAttributes();
AssertAttributes(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])");
var customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])");
AssertEx.Equal(ImmutableArray.Create(true, true, true, false, true, true), reader.ReadBoolArray(customAttribute.Value));
});
var ref1 = comp.EmitToImageReference();
var source2 =
@"class Program
{
static void Main()
{
IA a = new C();
_ = a;
}
}";
comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
}
[Fact]
public void EmitAttribute_PartialMethods()
{
var source =
@"public partial class Program
{
static partial void F1(System.IntPtr x);
static partial void F2(System.UIntPtr x) { }
static partial void F1(nint x) { }
static partial void F2(nuint x);
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.RegularPreview);
// Ideally should not emit any attributes. Compare with dynamic/object.
var expected =
@"Program
void F2(System.UIntPtr x)
[NativeInteger] System.UIntPtr x
";
AssertNativeIntegerAttributes(comp, expected);
}
// Shouldn't depend on [NullablePublicOnly].
[Fact]
public void NoPublicMembers()
{
var source =
@"class A<T, U>
{
}
class B : A<System.UIntPtr, nint>
{
}";
var comp = CreateCompilation(
source,
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.RegularPreview.WithNullablePublicOnly());
var expected =
@"[NativeInteger({ False, True })] B
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void AttributeUsage()
{
var source =
@"public class Program
{
public nint F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute");
AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo();
Assert.False(attributeUsage.Inherited);
Assert.False(attributeUsage.AllowMultiple);
Assert.True(attributeUsage.HasValidAttributeTargets);
var expectedTargets =
AttributeTargets.Class |
AttributeTargets.Event |
AttributeTargets.Field |
AttributeTargets.GenericParameter |
AttributeTargets.Parameter |
AttributeTargets.Property |
AttributeTargets.ReturnValue;
Assert.Equal(expectedTargets, attributeUsage.ValidTargets);
});
}
[Fact]
public void AttributeFieldExists()
{
var source =
@"public class Program
{
public nint F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
CompileAndVerify(comp, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Program");
var member = type.GetMembers("F").Single();
var attributes = member.GetAttributes();
AssertNativeIntegerAttribute(attributes);
var attribute = GetNativeIntegerAttribute(attributes);
var field = attribute.AttributeClass.GetField("TransformFlags");
Assert.Equal("System.Boolean[]", field.TypeWithAnnotations.ToTestDisplayString());
});
}
[Fact]
public void NestedNativeIntegerWithPrecedingType()
{
var comp = CompileAndVerify(@"
class C<T, U, V>
{
public C<dynamic, T, nint> F0;
public C<dynamic, nint, System.IntPtr> F1;
public C<dynamic, nuint, System.UIntPtr> F2;
public C<T, nint, System.IntPtr> F3;
public C<T, nuint, System.UIntPtr> F4;
}
", options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator);
static void symbolValidator(ModuleSymbol module)
{
var expectedAttributes = @"
C<T, U, V>
[NativeInteger] C<dynamic, T, System.IntPtr> F0
[NativeInteger({ True, False })] C<dynamic, System.IntPtr, System.IntPtr> F1
[NativeInteger({ True, False })] C<dynamic, System.UIntPtr, System.UIntPtr> F2
[NativeInteger({ True, False })] C<T, System.IntPtr, System.IntPtr> F3
[NativeInteger({ True, False })] C<T, System.UIntPtr, System.UIntPtr> F4
";
AssertNativeIntegerAttributes(module, expectedAttributes);
var c = module.GlobalNamespace.GetTypeMember("C");
assert("C<dynamic, T, nint>", "F0");
assert("C<dynamic, nint, System.IntPtr>", "F1");
assert("C<dynamic, nuint, System.UIntPtr>", "F2");
assert("C<T, nint, System.IntPtr>", "F3");
assert("C<T, nuint, System.UIntPtr>", "F4");
void assert(string expectedType, string fieldName)
{
Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString());
}
}
}
[Fact]
public void FunctionPointersWithNativeIntegerTypes()
{
var comp = CompileAndVerify(@"
unsafe class C
{
public delegate*<nint, object, object> F0;
public delegate*<nint, nint, nint> F1;
public delegate*<System.IntPtr, System.IntPtr, nint> F2;
public delegate*<nint, System.IntPtr, System.IntPtr> F3;
public delegate*<System.IntPtr, nint, System.IntPtr> F4;
public delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint> F5;
public delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6;
public delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr> F7;
public delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>> F8;
}
", options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator);
static void symbolValidator(ModuleSymbol module)
{
var expectedAttributes = @"
C
[NativeInteger] delegate*<System.IntPtr, System.Object, System.Object> F0
[NativeInteger({ True, True, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F1
[NativeInteger({ True, False, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F2
[NativeInteger({ False, True, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F3
[NativeInteger({ False, False, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F4
[NativeInteger({ True, False, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F5
[NativeInteger({ False, False, False, True })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6
[NativeInteger({ False, True, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F7
[NativeInteger({ False, False, True, False })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F8
";
AssertNativeIntegerAttributes(module, expectedAttributes);
var c = module.GlobalNamespace.GetTypeMember("C");
assert("delegate*<nint, System.Object, System.Object>", "F0");
assert("delegate*<nint, nint, nint>", "F1");
assert("delegate*<System.IntPtr, System.IntPtr, nint>", "F2");
assert("delegate*<nint, System.IntPtr, System.IntPtr>", "F3");
assert("delegate*<System.IntPtr, nint, System.IntPtr>", "F4");
assert("delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint>", "F5");
assert("delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>>", "F6");
assert("delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr>", "F7");
assert("delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>>", "F8");
void assert(string expectedType, string fieldName)
{
var field = c.GetField(fieldName);
FunctionPointerUtilities.CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)field.Type);
Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString());
}
}
}
private static TypeDefinition GetTypeDefinitionByName(MetadataReader reader, string name)
{
return reader.GetTypeDefinition(reader.TypeDefinitions.Single(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name)));
}
private static string GetAttributeConstructorName(MetadataReader reader, CustomAttributeHandle handle)
{
return reader.Dump(reader.GetCustomAttribute(handle).Constructor);
}
private static CustomAttribute GetAttributeByConstructorName(MetadataReader reader, CustomAttributeHandleCollection handles, string name)
{
return reader.GetCustomAttribute(handles.FirstOrDefault(h => GetAttributeConstructorName(reader, h) == name));
}
private static void AssertAttributes(MetadataReader reader, CustomAttributeHandleCollection handles, params string[] expectedNames)
{
var actualNames = handles.Select(h => GetAttributeConstructorName(reader, h)).ToArray();
AssertEx.Equal(actualNames, expectedNames);
}
private static void AssertNoNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes);
}
private static void AssertNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes, "System.Runtime.CompilerServices.NativeIntegerAttribute");
}
private static void AssertAttributes(ImmutableArray<CSharpAttributeData> attributes, params string[] expectedNames)
{
var actualNames = attributes.Select(a => a.AttributeClass.ToTestDisplayString()).ToArray();
AssertEx.Equal(actualNames, expectedNames);
}
private static void AssertNoNativeIntegerAttributes(CSharpCompilation comp)
{
var image = comp.EmitToArray();
using (var reader = new PEReader(image))
{
var metadataReader = reader.GetMetadataReader();
var attributes = metadataReader.GetCustomAttributeRows().Select(metadataReader.GetCustomAttributeName).ToArray();
Assert.False(attributes.Contains("NativeIntegerAttribute"));
}
}
private void AssertNativeIntegerAttributes(CSharpCompilation comp, string expected)
{
CompileAndVerify(comp, symbolValidator: module => AssertNativeIntegerAttributes(module, expected));
}
private static void AssertNativeIntegerAttributes(ModuleSymbol module, string expected)
{
var actual = NativeIntegerAttributesVisitor.GetString((PEModuleSymbol)module);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual);
}
private static CSharpAttributeData GetNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
return attributes.Single(a => a.AttributeClass.ToTestDisplayString() == "System.Runtime.CompilerServices.NativeIntegerAttribute");
}
}
}
| 41.477046 | 237 | 0.625249 | [
"MIT"
] | bilsaboob/roslyn | src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_NativeInteger.cs | 62,342 | C# |
using System;
using EasyCommands;
using EasyCommands.Commands;
using Example;
using System.IO;
namespace EasyCommands.Test.Commands
{
class CallbackSyntaxTest1 : CommandCallbacks<User>
{
// Registration should fail because the command has the wrong return value
[Command("test")]
public int Test(int num1)
{
Console.WriteLine("Hello!");
Console.WriteLine(num1);
return num1;
}
}
}
| 22.428571 | 82 | 0.632696 | [
"MIT"
] | ZakFahey/easy-commands | EasyCommands/Test/Commands/CallbackSyntaxTest1.cs | 473 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support
{
/// <summary>A state of a server that is visible to user.</summary>
[System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support.ServerStateTypeConverter))]
public partial struct ServerState :
System.Management.Automation.IArgumentCompleter
{
/// <summary>
/// Implementations of this function are called by PowerShell to complete arguments.
/// </summary>
/// <param name="commandName">The name of the command that needs argument completion.</param>
/// <param name="parameterName">The name of the parameter that needs argument completion.</param>
/// <param name="wordToComplete">The (possibly empty) word being completed.</param>
/// <param name="commandAst">The command ast in case it is needed for completion.</param>
/// <param name="fakeBoundParameters">This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot
/// or will not attempt to evaluate an argument, in which case you may need to use commandAst.</param>
/// <returns>
/// A collection of completion results, most like with ResultType set to ParameterValue.
/// </returns>
public global::System.Collections.Generic.IEnumerable<global::System.Management.Automation.CompletionResult> CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters)
{
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Ready".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Ready'", "Ready", global::System.Management.Automation.CompletionResultType.ParameterValue, "Ready");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Dropping".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Dropping'", "Dropping", global::System.Management.Automation.CompletionResultType.ParameterValue, "Dropping");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Disabled".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Disabled'", "Disabled", global::System.Management.Automation.CompletionResultType.ParameterValue, "Disabled");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Inaccessible".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Inaccessible'", "Inaccessible", global::System.Management.Automation.CompletionResultType.ParameterValue, "Inaccessible");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Starting".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Starting'", "Starting", global::System.Management.Automation.CompletionResultType.ParameterValue, "Starting");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Stopping".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Stopping'", "Stopping", global::System.Management.Automation.CompletionResultType.ParameterValue, "Stopping");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Stopped".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Stopped'", "Stopped", global::System.Management.Automation.CompletionResultType.ParameterValue, "Stopped");
}
if (global::System.String.IsNullOrEmpty(wordToComplete) || "Updating".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase))
{
yield return new global::System.Management.Automation.CompletionResult("'Updating'", "Updating", global::System.Management.Automation.CompletionResultType.ParameterValue, "Updating");
}
}
}
} | 83.253968 | 373 | 0.714013 | [
"MIT"
] | Agazoth/azure-powershell | src/PostgreSql/generated/api/Support/ServerState.Completer.cs | 5,183 | C# |
using System.Threading.Tasks;
using LambdaCore.Adapters;
namespace SecretManagement.Adapter.InMemory
{
internal sealed class InMemorySecretManagementService : ISecretManagementService
{
public Task<string> DecryptString(string value)
{
return Task.FromResult(value);
}
}
} | 23 | 84 | 0.704969 | [
"MIT"
] | evilpilaf/LambdaTest | src/Adapters/SecretManagement.Adapter/InMemory/InMemorySecretManagementService.cs | 322 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리의 일반 정보는 다음 특성 집합을 통해 제어됩니다.
// 어셈블리와 관련된 정보를 수정하려면
// 이 특성 값을 변경하십시오.
[assembly: AssemblyTitle("ClouDeveloper.Log4net.CallerInfo.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ClouDeveloper.Log4net.CallerInfo.Test")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하십시오.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("d23b2d5a-2802-4af4-b383-8eb9ae661668")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 버전이 자동으로
// 지정되도록 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 29.918919 | 68 | 0.707317 | [
"Apache-2.0"
] | rkttu/Log4net-with-Caller-Info | Log4netWithCallerInfo/ClouDeveloper.Log4net.CallerInfo.Test/Properties/AssemblyInfo.cs | 1,544 | C# |
namespace Contensive.Processor.Models.Domain {
//
//====================================================================================================
//
public class StylesheetContextModel {
public int templateId { get; set; }
public int emailId { get; set; }
public string styleSheet { get; set; }
}
} | 31.909091 | 106 | 0.421652 | [
"Apache-2.0"
] | contensive/Contensive5 | source/Processor/Models/Domain/StylesheetContextModel.cs | 353 | C# |
/*!
* (c) 2016-2018 EntIT Software LLC, a Micro Focus company
*
* 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;
namespace MicroFocus.Adm.Octane.Api.Core.Connector
{
/// <summary>
/// POCO class for connection data that is sent to NGA server during calling to <see cref="Connect"/> method.
/// Uses the user/password method
/// </summary>
public class UserPassConnectionInfo : ConnectionInfo
{
public string user { get; set; }
public string password { get; set; }
/* public string enable_csrf
{
get
{
return "true";
}
}*/
public UserPassConnectionInfo()
{
}
public UserPassConnectionInfo(String user, string password)
{
this.user = user;
this.password = password;
}
}
}
| 27.22 | 110 | 0.645114 | [
"Apache-2.0"
] | MicroFocus/alm-octane-csharp-rest-sdk | OctaneSdk/Connector/UserPassConnectionInfo.cs | 1,363 | C# |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: MiniParameterInfo
**
** Purpose: Represents a method parameter.
**
===========================================================*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.AddIn.MiniReflection.MetadataReader;
using System.Diagnostics.Contracts;
namespace System.AddIn.MiniReflection
{
[Serializable]
internal sealed class MiniCustomAttributeInfo
{
private String _typeName;
private MiniCustomAttributeFixedArgInfo[] _fixedArgs;
private MiniCustomAttributeNamedArgInfo[] _namedArgs;
public MiniCustomAttributeInfo(String typeName, MiniCustomAttributeFixedArgInfo[] fixedArgs,
MiniCustomAttributeNamedArgInfo[] namedArgs)
{
_typeName = typeName;
_fixedArgs = fixedArgs;
_namedArgs = namedArgs;
}
/*
public String TypeName
{
get { return _typeName; }
}
*/
public MiniCustomAttributeFixedArgInfo[] FixedArgs {
get { return _fixedArgs; }
}
public MiniCustomAttributeNamedArgInfo[] NamedArgs {
get { return _namedArgs; }
}
}
[Serializable]
internal sealed class MiniCustomAttributeNamedArgInfo
{
private String _argName;
private CorElementType _type;
private Object _value;
public MiniCustomAttributeNamedArgInfo(CorElementType type, String name, Object value)
{
_argName = name;
_type = type;
_value = value;
}
public Object Value {
get { return _value; }
}
public String Name
{
get {return _argName; }
}
/*
public CorElementType CorElementType
{
get { return _type; }
}
*/
}
[Serializable]
internal sealed class MiniCustomAttributeFixedArgInfo
{
private Object _value;
public MiniCustomAttributeFixedArgInfo(Object value)
{
_value = value;
}
public Object Value {
get { return _value; }
}
}
}
| 23.313725 | 101 | 0.562658 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/fx/src/AddIn/AddIn/System/Addin/MiniReflection/MiniCustomAttributeInfo.cs | 2,378 | C# |
/******************************************************************************/
/*
Project - Unity Ray Marching
https://github.com/TheAllenChou/unity-ray-marching
Author - Ming-Lun "Allen" Chou
Web - http://AllenChou.net
Twitter - @TheAllenChou
*/
/******************************************************************************/
using UnityEngine;
[RequireComponent(typeof(Camera))]
[ExecuteInEditMode]
public class PostProcessingCompute : PostProcessingBase
{
public ComputeShader Compute;
private ComputeShader m_compute;
private RenderTexture m_renderTarget;
protected virtual void Init(ComputeShader compute) { }
protected virtual void Dispose(ComputeShader compute) { }
protected virtual void OnPreRenderImage(ComputeShader compute, RenderTexture src, RenderTexture dst) { }
protected virtual void Dispatch(ComputeShader compute, RenderTexture src, RenderTexture dst) { }
protected virtual void OnPostRenderImage(ComputeShader compute, RenderTexture src, RenderTexture dst) { }
private void OnDisable()
{
if (m_compute == null)
return;
Dispose(m_compute);
m_compute = null;
}
private void OnRenderImage(RenderTexture src, RenderTexture dst)
{
if (Compute != m_compute)
{
if (m_compute != null)
{
Dispose(m_compute);
m_compute = null;
}
if (Compute != null)
{
m_compute = Compute;
Init(m_compute);
}
}
if (m_compute == null)
{
Debug.LogWarning("Compute shader is not assigned for post processing.");
return;
}
if (m_renderTarget == null
|| m_renderTarget.width != src.width
|| m_renderTarget.height != src.height)
{
if (m_renderTarget != null)
{
DestroyImmediate(m_renderTarget);
m_renderTarget = null;
}
m_renderTarget = new RenderTexture(src.width, src.height, 0);
m_renderTarget.enableRandomWrite = true;
m_renderTarget.Create();
}
OnPreRenderImage(m_compute, src, m_renderTarget);
Dispatch(m_compute, src, m_renderTarget);
Graphics.Blit(m_renderTarget, dst);
OnPostRenderImage(m_compute, src, m_renderTarget);
}
}
| 27.296296 | 107 | 0.622795 | [
"MIT"
] | TheAllenChou/unity-ray-marching | unity-ray-marching/Assets/Script/PostProcessingCompute.cs | 2,213 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by SpecFlow (http://www.specflow.org/).
// SpecFlow Version:1.9.0.77
// SpecFlow Generator Version:1.9.0.0
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#region Designer generated code
#pragma warning disable
namespace Orchard.Specs
{
using TechTalk.SpecFlow;
[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[NUnit.Framework.TestFixtureAttribute()]
[NUnit.Framework.DescriptionAttribute("Pages")]
public partial class PagesFeature
{
private static TechTalk.SpecFlow.ITestRunner testRunner;
#line 1 "Pages.feature"
#line hidden
[NUnit.Framework.TestFixtureSetUpAttribute()]
public virtual void FeatureSetup()
{
testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Pages", " In order to add content pages to my site\r\n As an author\r\n I want to create, p" +
"ublish and edit pages", ProgrammingLanguage.CSharp, ((string[])(null)));
testRunner.OnFeatureStart(featureInfo);
}
[NUnit.Framework.TestFixtureTearDownAttribute()]
public virtual void FeatureTearDown()
{
testRunner.OnFeatureEnd();
testRunner = null;
}
[NUnit.Framework.SetUpAttribute()]
public virtual void TestInitialize()
{
}
[NUnit.Framework.TearDownAttribute()]
public virtual void ScenarioTearDown()
{
testRunner.OnScenarioEnd();
}
public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
{
testRunner.OnScenarioStart(scenarioInfo);
}
public virtual void ScenarioCleanup()
{
testRunner.CollectScenarioErrors();
}
[NUnit.Framework.TestAttribute()]
[NUnit.Framework.DescriptionAttribute("In the admin (menu) there is a link to create a Page")]
public virtual void InTheAdminMenuThereIsALinkToCreateAPage()
{
TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("In the admin (menu) there is a link to create a Page", ((string[])(null)));
#line 6
this.ScenarioSetup(scenarioInfo);
#line 7
testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given ");
#line 9
testRunner.When("I go to \"Admin\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 10
testRunner.Then("I should see \"<a href=\"/Admin/Contents/Create/Page\"[^>]*>Page</a>\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 13
testRunner.When("I go to \"Admin/Contents/Create/Page\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table1.AddRow(new string[] {
"Title.Title",
"Super Duper"});
table1.AddRow(new string[] {
"LayoutPart.State",
"{ \"elements\": [ { \"typeName\": \"Orchard.Layouts.Elements.Text\", \"state\": \"Content=" +
"This+is+super.\"} ] }"});
#line 14
testRunner.And("I fill in", ((string)(null)), table1, "And ");
#line 18
testRunner.And("I hit \"Publish Now\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 19
testRunner.And("I go to \"super-duper\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 20
testRunner.Then("I should see \"<h1[^>]*>.*?Super Duper.*?</h1>\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 21
testRunner.And("I should see \"This is super.\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 24
testRunner.When("I go to \"Admin/Contents/Create/Page\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table2.AddRow(new string[] {
"Title.Title",
"Super Duper"});
table2.AddRow(new string[] {
"LayoutPart.State",
"{ \"elements\": [ { \"typeName\": \"Orchard.Layouts.Elements.Text\", \"state\": \"Content=" +
"This+is+super+number+two.\"} ] }"});
#line 25
testRunner.And("I fill in", ((string)(null)), table2, "And ");
#line 29
testRunner.And("I hit \"Publish Now\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 30
testRunner.And("I go to \"super-duper-2\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 31
testRunner.Then("I should see \"<h1[^>]*>.*?Super Duper.*?</h1>\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 32
testRunner.And("I should see \"This is super number two.\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 35
testRunner.When("I go to \"Admin/Contents/Create/Page\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table3.AddRow(new string[] {
"Title.Title",
"Another"});
table3.AddRow(new string[] {
"LayoutPart.State",
"{ \"elements\": [ { \"typeName\": \"Orchard.Layouts.Elements.Text\", \"state\": \"Content=" +
"This+is+the+draft+of+a+new+homepage.\"} ] }"});
table3.AddRow(new string[] {
"Autoroute.PromoteToHomePage",
"true"});
#line 36
testRunner.And("I fill in", ((string)(null)), table3, "And ");
#line 41
testRunner.And("I hit \"Publish Now\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 42
testRunner.And("I go to \"/\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 43
testRunner.Then("I should see \"<h1>Another</h1>\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 44
testRunner.When("I go to \"another\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 45
testRunner.Then("the status should be 404 \"Not Found\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 48
testRunner.When("I go to \"Admin/Contents/Create/Page\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table4.AddRow(new string[] {
"Title.Title",
"Drafty"});
table4.AddRow(new string[] {
"LayoutPart.State",
"{ \"elements\": [ { \"typeName\": \"Orchard.Layouts.Elements.Text\", \"state\": \"Content=" +
"This+is+the+draft+of+a+new+homepage.\"} ] }"});
table4.AddRow(new string[] {
"Autoroute.PromoteToHomePage",
"true"});
#line 49
testRunner.And("I fill in", ((string)(null)), table4, "And ");
#line 54
testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 55
testRunner.And("I go to \"/\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 56
testRunner.Then("I should see \"<h1>Another</h1>\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line hidden
this.ScenarioCleanup();
}
}
}
#pragma warning restore
#endregion
| 46.811828 | 235 | 0.549673 | [
"BSD-3-Clause"
] | bill-cooper/catc-cms | src/Orchard.Specs/Pages.feature.cs | 8,709 | C# |
[CompilerGeneratedAttribute] // RVA: 0x12AD90 Offset: 0x12AE91 VA: 0x12AD90
private sealed class TimelineAsset.<get_outputs>d__27 : IEnumerable<PlayableBinding>, IEnumerable, IEnumerator<PlayableBinding>, IEnumerator, IDisposable // TypeDefIndex: 4557
{
// Fields
private int <>1__state; // 0x10
private PlayableBinding <>2__current; // 0x18
private int <>l__initialThreadId; // 0x38
public TimelineAsset <>4__this; // 0x40
private IEnumerator<TrackAsset> <>7__wrap1; // 0x48
private IEnumerator<PlayableBinding> <>7__wrap2; // 0x50
// Properties
private PlayableBinding System.Collections.Generic.IEnumerator<UnityEngine.Playables.PlayableBinding>.Current { get; }
private object System.Collections.IEnumerator.Current { get; }
// Methods
[DebuggerHiddenAttribute] // RVA: 0x12C5A0 Offset: 0x12C6A1 VA: 0x12C5A0
// RVA: 0x17E9A80 Offset: 0x17E9B81 VA: 0x17E9A80
public void .ctor(int <>1__state) { }
[DebuggerHiddenAttribute] // RVA: 0x12C5B0 Offset: 0x12C6B1 VA: 0x12C5B0
// RVA: 0x17EC530 Offset: 0x17EC631 VA: 0x17EC530 Slot: 7
private void System.IDisposable.Dispose() { }
// RVA: 0x17EC890 Offset: 0x17EC991 VA: 0x17EC890 Slot: 8
private bool MoveNext() { }
// RVA: 0x17EC7D0 Offset: 0x17EC8D1 VA: 0x17EC7D0
private void <>m__Finally1() { }
// RVA: 0x17EC710 Offset: 0x17EC811 VA: 0x17EC710
private void <>m__Finally2() { }
[DebuggerHiddenAttribute] // RVA: 0x12C5C0 Offset: 0x12C6C1 VA: 0x12C5C0
// RVA: 0x17ECEA0 Offset: 0x17ECFA1 VA: 0x17ECEA0 Slot: 6
private PlayableBinding System.Collections.Generic.IEnumerator<UnityEngine.Playables.PlayableBinding>.get_Current() { }
[DebuggerHiddenAttribute] // RVA: 0x12C5D0 Offset: 0x12C6D1 VA: 0x12C5D0
// RVA: 0x17ECEC0 Offset: 0x17ECFC1 VA: 0x17ECEC0 Slot: 10
private void System.Collections.IEnumerator.Reset() { }
[DebuggerHiddenAttribute] // RVA: 0x12C5E0 Offset: 0x12C6E1 VA: 0x12C5E0
// RVA: 0x17ECF20 Offset: 0x17ED021 VA: 0x17ECF20 Slot: 9
private object System.Collections.IEnumerator.get_Current() { }
[DebuggerHiddenAttribute] // RVA: 0x12C5F0 Offset: 0x12C6F1 VA: 0x12C5F0
// RVA: 0x17ECF90 Offset: 0x17ED091 VA: 0x17ECF90 Slot: 4
private IEnumerator<PlayableBinding> System.Collections.Generic.IEnumerable<UnityEngine.Playables.PlayableBinding>.GetEnumerator() { }
[DebuggerHiddenAttribute] // RVA: 0x12C600 Offset: 0x12C701 VA: 0x12C600
// RVA: 0x17ED050 Offset: 0x17ED151 VA: 0x17ED050 Slot: 5
private IEnumerator System.Collections.IEnumerable.GetEnumerator() { }
}
| 44.375 | 175 | 0.768209 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | _no_namespace/TimelineAsset.--get_outputs--d__27.cs | 2,485 | C# |
using System;
using System.IO;
using UnityEditor;
using UnityLocalize.DataStorage;
namespace UnityLocalize.Editor
{
[InitializeOnLoad]
internal static class LocalizationEditorEnvironmentManager
{
private const string TEMP_FOLDER_NAME = "~localizationTemp";
private const string EDITOR_RESOURCES_PATH = "Assets/Plugins/UnityLocalize/Editor/Resources";
static LocalizationEditorEnvironmentManager()
{
string projectDir = Environment.CurrentDirectory;
TempFolder = Path.Combine(projectDir, TEMP_FOLDER_NAME);
CheckEnvironmentFolders();
CheckTranslationStorageExist();
}
[MenuItem("Window/UnityLocalize/Localization Config")]
public static void ShowConfigWindow()
{
var configRepository = new EditorConfigRepository();
var defaultExportUnit = new DefaultLocalizationExportUnit(new DefaultLocalizationRepository(), configRepository, new InlineStringsRepository());
new LocalizationConfigPresenter(
configRepository, defaultExportUnit)
.Run();
}
[MenuItem("Window/UnityLocalize/Translations")]
public static void ShowTranslationsWindow()
{
var config = new EditorConfigRepository().GetInternalConfig();
var defaultLocalizationRepository = new DefaultLocalizationRepository();
var editorTranslationIORepository = new EditorTranslationIORepository(new TranslationStorageProvider());
var ioUnit = new TranslationIOUnit(config, defaultLocalizationRepository, editorTranslationIORepository);
new TranslationInfoPresenter(
new EditorTranslationInfoRepository(), ioUnit)
.Run();
}
[MenuItem("Window/UnityLocalize/Inline strings")]
public static void ShowInlineStringsWindow()
{
new InlineStringsPresenter(
new InlineStringsRepository())
.Run();
}
public static string TempFolder { get; }
public static string DataStoragePath { get; private set; }
private static void CheckEnvironmentFolders()
{
DataStoragePath = new TranslationStorageProvider().GetStoragePath();
if (!Directory.Exists(TempFolder))
{
Directory.CreateDirectory(TempFolder);
}
if (!Directory.Exists(DataStoragePath))
{
Directory.CreateDirectory(DataStoragePath);
}
if (!Directory.Exists(EDITOR_RESOURCES_PATH))
{
Directory.CreateDirectory(EDITOR_RESOURCES_PATH);
}
}
private static void CheckTranslationStorageExist()
{
var translationRepo = new EditorTranslationInfoRepository();
TranslationInfoSet set = translationRepo.Get();
if (set == null)
{
translationRepo.CreateModel();
}
}
}
}
| 32.670213 | 156 | 0.630414 | [
"MIT"
] | anvoro/ULocalize | Assets/Plugins/UnityLocalize/Editor/EditorCore/LocalizationEditorEnvironmentManager.cs | 3,073 | C# |
using PNet;
namespace PNetR
{
public interface INetComponentProxy
{
/// <summary>
/// The current thread's rpc mode.
/// </summary>
RpcMode CurrentRpcMode { get; set; }
Player CurrentSendTo { get; set; }
NetworkView NetworkView { get; set; }
}
} | 21.928571 | 45 | 0.566775 | [
"MIT"
] | Ignis34Rus/LoE-Ghost.Server | libs/PNet2Room/Proxy/INetComponentProxy.cs | 309 | C# |
using System;
using System.Collections.Generic;
using DataStructures.HashTable;
using DataStructures.Trees;
using Xunit;
namespace DataStructures.Tests.HashTests
{
//public class IntersectionTests
//{
// [Fact]
// public void Bianary_tree_repeat()
// {
// BinaryTree<int> tree1 = new BinaryTree<int>();
// BinaryTree<int> tree2 = new BinaryTree<int>();
// tree1.Root = new BinaryTree<int>.Node(1);
// tree2.Root = new BinaryTree<int>.Node(1);
// tree1.Root.Left = new BinaryTree<int>.Node(2);
// tree2.Root.Left = new BinaryTree<int>.Node(2);
// tree1.Root.Right = new BinaryTree<int>.Node(3);
// tree2.Root.Right = new BinaryTree<int>.Node(4);
// List<int> value = Intersection<int>.TreeIntersection(tree1, tree2);
// List<int> expected = new List<int>();
// expected.Add(1);
// expected.Add(2);
// Assert.Equal(expected, value);
// }
//}
}
| 34.233333 | 81 | 0.576436 | [
"MIT"
] | dahlbyk-demo/data-structures-and-algorithms-401 | DataStructures.Tests/HashTests/IntersectionTests.cs | 1,029 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("30510511-98B5-11CF-BB82-00AA00BDCE0B")]
[NativeTypeName("struct ISVGAnimatedPathData : IDispatch")]
[NativeInheritance("IDispatch")]
public unsafe partial struct ISVGAnimatedPathData
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, Guid*, void**, int>)(lpVtbl[0]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, uint>)(lpVtbl[1]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, uint>)(lpVtbl[2]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
[return: NativeTypeName("HRESULT")]
public int GetTypeInfoCount([NativeTypeName("UINT *")] uint* pctinfo)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, uint*, int>)(lpVtbl[3]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), pctinfo);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
[return: NativeTypeName("HRESULT")]
public int GetTypeInfo([NativeTypeName("UINT")] uint iTInfo, [NativeTypeName("LCID")] uint lcid, ITypeInfo** ppTInfo)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, uint, uint, ITypeInfo**, int>)(lpVtbl[4]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), iTInfo, lcid, ppTInfo);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
[return: NativeTypeName("HRESULT")]
public int GetIDsOfNames([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LPOLESTR *")] ushort** rgszNames, [NativeTypeName("UINT")] uint cNames, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("DISPID *")] int* rgDispId)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, Guid*, ushort**, uint, uint, int*, int>)(lpVtbl[5]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), riid, rgszNames, cNames, lcid, rgDispId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
[return: NativeTypeName("HRESULT")]
public int Invoke([NativeTypeName("DISPID")] int dispIdMember, [NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LCID")] uint lcid, [NativeTypeName("WORD")] ushort wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult, EXCEPINFO* pExcepInfo, [NativeTypeName("UINT *")] uint* puArgErr)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, int, Guid*, uint, ushort, DISPPARAMS*, VARIANT*, EXCEPINFO*, uint*, int>)(lpVtbl[6]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(7)]
[return: NativeTypeName("HRESULT")]
public int putref_pathSegList(ISVGPathSegList* v)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, ISVGPathSegList*, int>)(lpVtbl[7]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(8)]
[return: NativeTypeName("HRESULT")]
public int get_pathSegList(ISVGPathSegList** p)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, ISVGPathSegList**, int>)(lpVtbl[8]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), p);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(9)]
[return: NativeTypeName("HRESULT")]
public int putref_normalizedPathSegList(ISVGPathSegList* v)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, ISVGPathSegList*, int>)(lpVtbl[9]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(10)]
[return: NativeTypeName("HRESULT")]
public int get_normalizedPathSegList(ISVGPathSegList** p)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, ISVGPathSegList**, int>)(lpVtbl[10]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), p);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(11)]
[return: NativeTypeName("HRESULT")]
public int putref_animatedPathSegList(ISVGPathSegList* v)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, ISVGPathSegList*, int>)(lpVtbl[11]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(12)]
[return: NativeTypeName("HRESULT")]
public int get_animatedPathSegList(ISVGPathSegList** p)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, ISVGPathSegList**, int>)(lpVtbl[12]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), p);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(13)]
[return: NativeTypeName("HRESULT")]
public int putref_animatedNormalizedPathSegList(ISVGPathSegList* v)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, ISVGPathSegList*, int>)(lpVtbl[13]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(14)]
[return: NativeTypeName("HRESULT")]
public int get_animatedNormalizedPathSegList(ISVGPathSegList** p)
{
return ((delegate* unmanaged<ISVGAnimatedPathData*, ISVGPathSegList**, int>)(lpVtbl[14]))((ISVGAnimatedPathData*)Unsafe.AsPointer(ref this), p);
}
}
}
| 48.621429 | 302 | 0.669458 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/MsHTML/ISVGAnimatedPathData.cs | 6,809 | C# |
using System;
using NetOffice;
namespace NetOffice.VisioApi.Enums
{
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum VisSpatialRelationFlags
{
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visSpatialIncludeGuides = 2,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>4</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visSpatialFrontToBack = 4,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>8</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visSpatialBackToFront = 8,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>16</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visSpatialIncludeHidden = 16,
/// <summary>
/// SupportByVersion Visio 11, 12, 14, 15, 16
/// </summary>
/// <remarks>32</remarks>
[SupportByVersionAttribute("Visio", 11,12,14,15,16)]
visSpatialIgnoreVisible = 32,
/// <summary>
/// SupportByVersion Visio 12, 14, 15, 16
/// </summary>
/// <remarks>64</remarks>
[SupportByVersionAttribute("Visio", 12,14,15,16)]
visSpatialIncludeDataGraphics = 64,
/// <summary>
/// SupportByVersion Visio 14, 15, 16
/// </summary>
/// <remarks>128</remarks>
[SupportByVersionAttribute("Visio", 14,15,16)]
visSpatialIncludeContainerShapes = 128
}
} | 27.786885 | 55 | 0.640708 | [
"MIT"
] | brunobola/NetOffice | Source/Visio/Enums/VisSpatialRelationFlags.cs | 1,697 | C# |
//--------------------------------------------
// Implementation provided by StackOverflow
// http://stackoverflow.com/questions/4140860/castle-windsor-dependency-resolver-for-mvc-3-rc
//--------------------------------------------
namespace SharpArch.Web.Castle
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using global::Castle.Windsor;
public class WindsorDependencyResolver : IDependencyResolver
{
private readonly IWindsorContainer container;
public WindsorDependencyResolver(IWindsorContainer container)
{
this.container = container;
}
public object GetService(Type serviceType)
{
return container.Kernel.HasComponent(serviceType) ? container.Resolve(serviceType) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return container.Kernel.HasComponent(serviceType) ? container.ResolveAll(serviceType).Cast<object>() : new object[] { };
}
}
} | 31.294118 | 132 | 0.625 | [
"Apache-2.0"
] | maxim5/code-inspector | data/c-sharp/2734dccd21ffe5db80056a4e83e0f18d_WindsorDependencyResolver.cs | 1,064 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AlipayMarketingCampaignDrawcampCreateModel Data Structure.
/// </summary>
public class AlipayMarketingCampaignDrawcampCreateModel : AlipayObject
{
/// <summary>
/// 单用户以支付宝账号维度可参与当前营销活动的总次数,由开发者自定义此数值
/// </summary>
[JsonPropertyName("account_count")]
public string AccountCount { get; set; }
/// <summary>
/// 以移动设备维度可参与当前营销活动的总次数,由开发者自定义此数值
/// </summary>
[JsonPropertyName("appid_count")]
public string AppidCount { get; set; }
/// <summary>
/// 单个用户当前活动允许中奖的最大次数,最大值999999
/// </summary>
[JsonPropertyName("award_count")]
public string AwardCount { get; set; }
/// <summary>
/// 活动奖品总中奖几率,开发者需传入整数值,如:传入99支付宝默认为99%
/// </summary>
[JsonPropertyName("award_rate")]
public string AwardRate { get; set; }
/// <summary>
/// 活动唯一标识,不能包含除中文、英文、数字以外的字符,创建后不能修改,需要保证在商户端不重复。
/// </summary>
[JsonPropertyName("camp_code")]
public string CampCode { get; set; }
/// <summary>
/// 活动结束时间,yyyy-MM-dd HH:00:00格式(到小时),需要大于活动开始时间
/// </summary>
[JsonPropertyName("camp_end_time")]
public string CampEndTime { get; set; }
/// <summary>
/// 活动名称,开发者自定义
/// </summary>
[JsonPropertyName("camp_name")]
public string CampName { get; set; }
/// <summary>
/// 活动开始时间,yyyy-MM-dd HH:00:00格式(到小时),时间不能早于当前日期的0点
/// </summary>
[JsonPropertyName("camp_start_time")]
public string CampStartTime { get; set; }
/// <summary>
/// 凭证验证规则id,通过alipay.marketing.campaign.cert.create 接口创建的凭证id
/// </summary>
[JsonPropertyName("cert_rule_id")]
public string CertRuleId { get; set; }
/// <summary>
/// 单用户以账户证件号(如身份证号、护照、军官证等)维度可参与当前营销活动的总次数,由开发者自定义此数值
/// </summary>
[JsonPropertyName("certification_count")]
public string CertificationCount { get; set; }
/// <summary>
/// 圈人规则id,通过alipay.marketing.campaign.rule.crowd.create 接口创建的规则id
/// </summary>
[JsonPropertyName("crowd_rule_id")]
public string CrowdRuleId { get; set; }
/// <summary>
/// 以认证手机号(与支付宝账号绑定的手机号)维度的可参与当前营销活动的总次数,由开发者自定义此数值
/// </summary>
[JsonPropertyName("mobile_count")]
public string MobileCount { get; set; }
/// <summary>
/// 开发者用于区分商户的唯一标识,由开发者自定义,用于区分是开发者名下哪一个商户的请求,为空则为默认标识
/// </summary>
[JsonPropertyName("mpid")]
public string Mpid { get; set; }
/// <summary>
/// 奖品模型,至少需要配置一个奖品
/// </summary>
[JsonPropertyName("prize_list")]
public List<MpPrizeInfoModel> PrizeList { get; set; }
/// <summary>
/// 营销验证规则id,由支付宝配置
/// </summary>
[JsonPropertyName("promo_rule_id")]
public string PromoRuleId { get; set; }
/// <summary>
/// 活动触发类型,目前支持 CAMP_USER_TRIGGER:用户触发(开发者调用alipay.marketing.campaign.drawcamp.trigger 接口触发); CAMP_SYS_TRIGGER:系统触发,必须配置实时人群验证规则(如:配置了监听用户支付事件,支付宝会根据活动规则自动发奖,无需用户手动触发)。
/// </summary>
[JsonPropertyName("trigger_type")]
public string TriggerType { get; set; }
/// <summary>
/// 实时人群验证规则id,由支付宝配置
/// </summary>
[JsonPropertyName("trigger_user_rule_id")]
public string TriggerUserRuleId { get; set; }
/// <summary>
/// 人群验证规则id,由支付宝配置
/// </summary>
[JsonPropertyName("user_rule_id")]
public string UserRuleId { get; set; }
}
}
| 31.708333 | 178 | 0.583443 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayMarketingCampaignDrawcampCreateModel.cs | 4,891 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ESocketServerLauncher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ESocketServerLauncher")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("d944c782-b93c-4f2f-ae27-11f341d278cd")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 27 | 57 | 0.694695 | [
"MIT"
] | Mr-sB/EasySocket | ESocketServerLauncher/Properties/AssemblyInfo.cs | 1,340 | C# |
namespace ChromeDevTools.Host.Runtime.Browser
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
/// <summary>
/// PermissionType
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum PermissionType
{
[EnumMember(Value = "accessibilityEvents")]
AccessibilityEvents,
[EnumMember(Value = "audioCapture")]
AudioCapture,
[EnumMember(Value = "backgroundSync")]
BackgroundSync,
[EnumMember(Value = "clipboardRead")]
ClipboardRead,
[EnumMember(Value = "clipboardWrite")]
ClipboardWrite,
[EnumMember(Value = "durableStorage")]
DurableStorage,
[EnumMember(Value = "flash")]
Flash,
[EnumMember(Value = "geolocation")]
Geolocation,
[EnumMember(Value = "midi")]
Midi,
[EnumMember(Value = "midiSysex")]
MidiSysex,
[EnumMember(Value = "notifications")]
Notifications,
[EnumMember(Value = "paymentHandler")]
PaymentHandler,
[EnumMember(Value = "protectedMediaIdentifier")]
ProtectedMediaIdentifier,
[EnumMember(Value = "sensors")]
Sensors,
[EnumMember(Value = "videoCapture")]
VideoCapture,
}
} | 30.045455 | 56 | 0.608926 | [
"MIT"
] | fforjan/ChromeDevTools.Host | ChromeDevTools.Host/Runtime/Browser/PermissionType.cs | 1,322 | C# |
namespace BuildService.Services.Messaging.SendGrid
{
using Newtonsoft.Json;
public class SendGridContent
{
public SendGridContent()
{
}
public SendGridContent(string type, string content)
{
this.Type = type;
this.Value = content;
}
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
}
| 19.791667 | 59 | 0.551579 | [
"MIT"
] | adena/BuildService | Services/BuildService.Services.Messaging/SendGrid/SendGridContent.cs | 477 | C# |
using System;
using Microsoft.Extensions.Logging;
using R5T.T0064;
namespace R5T.D0095
{
[ServiceDefinitionMarker]
public interface IFileLoggerProvider : ILoggerProvider, IServiceDefinition
{
}
} | 15.357143 | 78 | 0.753488 | [
"MIT"
] | SafetyCone/R5T.D0095 | source/R5T.D0095.Base/Code/Services/Definitions/IFileLoggerProvider.cs | 215 | C# |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays.Settings
{
public class SettingsSlider<T> : SettingsSlider<T, OsuSliderBar<T>>
where T : struct, IEquatable<T>
{
}
public class SettingsSlider<T, U> : SettingsItem<T>
where T : struct, IEquatable<T>
where U : SliderBar<T>, new()
{
protected override Drawable CreateControl() => new U
{
Margin = new MarginPadding { Top = 5, Bottom = 5 },
RelativeSizeAxes = Axes.X
};
public float KeyboardStep;
[BackgroundDependencyLoader]
private void load()
{
var slider = Control as U;
if (slider != null)
slider.KeyboardStep = KeyboardStep;
}
}
}
| 28.684211 | 93 | 0.60367 | [
"MIT"
] | GDhero58/Undertale- | osu.Game/Overlays/Settings/SettingsSlider.cs | 1,092 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace JARVIS
{
public partial class spl : Form
{
public spl()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value < 100)
{
progressBar1.Value = progressBar1.Value + 2;
}
else
{
timer1.Enabled = false;
Form1 frl = new Form1();
frl.Show();
this.Visible = false;
}
}
}
}
| 21.277778 | 60 | 0.530026 | [
"MIT"
] | MartinDala/Sistema-de-Senha--Para-Balc-os-CSharp | spl.cs | 768 | C# |
using FluentValidation;
namespace Application.Groups.Command.CreateMessage
{
public class CreateMessageCommandValidator : AbstractValidator<CreateMessageCommand>
{
public CreateMessageCommandValidator()
{
// content
RuleFor(x => x.Content)
.NotEmpty();
}
}
} | 23.928571 | 88 | 0.626866 | [
"MIT"
] | IndyNaessens/WebApi-Ucll-Mobile | src/Application/Groups/Command/CreateMessage/CreateMessageCommandValidator.cs | 335 | C# |
using ObjectTK.Shaders.Sources;
using ObjectTK.Shaders.Variables;
using OpenTK;
namespace Sphere.Shaders
{
[FragmentShaderSource("Shading.Fragment.Light.Point")]
public class PointLightProgram
: LightProgram
{
public Uniform<Vector3> LightPosition { get; protected set; }
public Uniform<Vector3> Attenuation { get; protected set; }
}
} | 27.857143 | 70 | 0.687179 | [
"MIT"
] | JcBernack/simplex-sphere | Sphere/Shaders/PointLightProgram.cs | 392 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Web.LibraryManager.Cache;
using Microsoft.Web.LibraryManager.Contracts;
using Microsoft.Web.LibraryManager.Resources;
namespace Microsoft.Web.LibraryManager.Providers.Cdnjs
{
/// <summary>Internal use only</summary>
internal sealed class CdnjsProvider : BaseProvider
{
private const string DownloadUrlFormat = "https://cdnjs.cloudflare.com/ajax/libs/{0}/{1}/{2}"; // https://aka.ms/ezcd7o/{0}/{1}/{2}
public const string IdText = "cdnjs";
private CdnjsCatalog _catalog;
/// <summary>
/// Initializes a new instance of the <see cref="CdnjsProvider"/> class.
/// </summary>
/// <param name="hostInteraction">The host interaction.</param>
/// <param name="cacheService">The instance of a <see cref="CacheService"/> to use.</param>
public CdnjsProvider(IHostInteraction hostInteraction, CacheService cacheService)
:base(hostInteraction, cacheService)
{
}
/// <inheritdoc />
public override string Id => IdText;
/// <inheritdoc />
public override string LibraryIdHintText => Text.CdnjsLibraryIdHintText;
/// <inheritdoc />
public override ILibraryCatalog GetCatalog()
{
return _catalog ?? (_catalog = new CdnjsCatalog(this, _cacheService, LibraryNamingScheme));
}
/// <summary>
/// Returns the CdnjsLibrary's Name
/// </summary>
/// <param name="library"></param>
/// <returns></returns>
public override string GetSuggestedDestination(ILibrary library)
{
if (library != null && library is CdnjsLibrary cdnjsLibrary)
{
return cdnjsLibrary.Name;
}
return string.Empty;
}
protected override string GetDownloadUrl(ILibraryInstallationState state, string sourceFile)
{
return string.Format(DownloadUrlFormat, state.Name, state.Version, sourceFile);
}
}
}
| 35.983607 | 139 | 0.634624 | [
"Apache-2.0"
] | RobJohnston/LibraryManager | src/LibraryManager/Providers/Cdnjs/CdnjsProvider.cs | 2,197 | 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("DiceRollerLogicLayer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DiceRollerLogicLayer")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("9f9c3afb-0db7-4d19-89db-cdc51383ffb8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.189189 | 84 | 0.748054 | [
"MIT"
] | Dibasic/dice-roller | DiceRollerLogicLayer/Properties/AssemblyInfo.cs | 1,416 | C# |
using System;
namespace LC
{
class Program
{
static void Main(string[] args)
{
_ = new MyClass();
}
}
}
| 11.071429 | 39 | 0.445161 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | UniversityOfPlymouthComputing/MobileDev-XamarinForms | code/Chapter2/Lectures/Part1/LooseCoupling/LC/Program.cs | 157 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boss_Controller : MonoBehaviour
{
public Transform target;
public GameObject badBullet;
public Transform badBulletSpawn;
public Transform lookPos;
private void Start()
{
badBulletSpawn.transform.position = -new Vector3(0,0,1f);
badBullet.transform.position = badBulletSpawn.transform.position;
while (this.gameObject != null)
{
StartCoroutine(BeginSpawning());
break;
}
}
IEnumerator BeginSpawning()
{
yield return new WaitForSeconds(2.0f);
SpawnBullet();
yield return new WaitForSeconds(2.0f);
}
private void Update()
{
transform.LookAt(target);
Vector3 pos = lookPos.eulerAngles;
if(this.gameObject == null)
{
StopCoroutine(BeginSpawning());
}
}
void SpawnBullet()
{
Instantiate(badBullet, badBulletSpawn.transform.position, Quaternion.identity);
}
} | 23.173913 | 87 | 0.62758 | [
"MIT"
] | RacerZStudios/CubeAttack | CubeAttack_Prototype/Boss_Controller.cs | 1,068 | C# |
using System.ComponentModel.DataAnnotations;
using Abp.Authorization.Roles;
using HotelBookingApp.Authorization.Users;
namespace HotelBookingApp.Authorization.Roles
{
public class Role : AbpRole<User>
{
public const int MaxDescriptionLength = 5000;
public Role()
{
}
public Role(int? tenantId, string displayName)
: base(tenantId, displayName)
{
}
public Role(int? tenantId, string name, string displayName)
: base(tenantId, name, displayName)
{
}
[StringLength(MaxDescriptionLength)]
public string Description {get; set;}
}
}
| 22.931034 | 67 | 0.627068 | [
"MIT"
] | Shaikh-Qasim/HotelBookingApp | aspnet-core/src/HotelBookingApp.Core/Authorization/Roles/Role.cs | 667 | C# |
using CG.Options;
using System;
using System.ComponentModel.DataAnnotations;
namespace CG.Olive.Web.Options
{
/// <summary>
/// This class contains configuration settings for authenticating the
/// website through OIDC.
/// </summary>
public class OidcAuthOptions : OptionsBase
{
// *******************************************************************
// Properties.
// *******************************************************************
#region Properties
/// <summary>
/// This property contains a client identifier for the website.
/// </summary>
[Required]
public string ClientId { get; set; }
/// <summary>
/// This property contains a client secret for the website.
/// </summary>
[Required]
public string ClientSecret { get; set; }
#endregion
}
}
| 26.676471 | 78 | 0.495039 | [
"MIT"
] | CodeGator/CG.Olive | src/Web/CG.Olive.Web/Options/OidcAuthOptions.cs | 909 | C# |
using System;
using SimpleAtomPubSub.Publisher.Persistance;
using SimpleAtomPubSub.Serialization;
using SimpleAtomPubSub.Subscriber.DeadLetter;
using SimpleAtomPubSub.Subscriber.Handlers;
namespace SimpleAtomPubSub.Subscriber.Subscription
{
public class ProcessingChannel
{
public event EventHandler<MessageFailedEventArgs> MessageFailed;
public event EventHandler<Message> MessageProcessed;
private readonly IMessageDeserializer _deserializer;
private readonly IHandler<object> _handlers;
public ProcessingChannel(IMessageDeserializer deserializer, IHandler<object> handlers)
{
_deserializer = deserializer;
_handlers = handlers;
}
public void ProcessEvent(object sender, Message message)
{
try
{
var mbody = _deserializer.Deserialize(message.Body);
_handlers.Handle(mbody);
MessageProcessed?.Invoke(this, message);
}
catch (Exception ex)
{
MessageFailed?.Invoke(this, new MessageFailedEventArgs { Message = message, Exception = ex });
}
}
}
} | 32.864865 | 110 | 0.646382 | [
"MIT"
] | peterbeams/SimpleAtomPubSub | src/SimpleAtomPubSub/Subscriber/Subscription/ProcessingChannel.cs | 1,216 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class QuestDisableInteraction : ActionBool
{
public QuestDisableInteraction(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 21.533333 | 110 | 0.733746 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/QuestDisableInteraction.cs | 309 | C# |
using Windows.UI.Xaml.Controls;
using Astrolabe.Pages;
namespace AstrolabeExample.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class FirstView : AstrolabePage
{
public FirstView()
{
this.InitializeComponent();
}
}
} | 23.0625 | 81 | 0.623306 | [
"MIT"
] | ismiller/astrolabe | AstrolabeExample/Views/FirstView.xaml.cs | 371 | C# |
// Copyright (c) Binshop and Contributors. All rights reserved.
// Licensed under the MIT License
using Binshop.PaymentGateway.Constants;
using System.Net.Http;
using System.Threading.Tasks;
namespace Binshop.PaymentGateway.Services
{
public class DefaultQueryService : IQueryService
{
private readonly GatewayAuthenticationBuilder _authBuilder;
private readonly IUriComposer _uriComposer;
private readonly IHttpClientFactory _httpClientFactory;
public DefaultQueryService(GatewayAuthenticationBuilder authBuilder,
IUriComposer uriComposer,
IHttpClientFactory httpClientFactory)
{
_authBuilder = authBuilder;
_uriComposer = uriComposer;
_httpClientFactory = httpClientFactory;
}
public async Task<string> GetByTransactionId(string id)
{
var httpClient = _httpClientFactory.CreateClient();
httpClient.DefaultRequestHeaders.Authorization = _authBuilder.Build();
var requestUri = _uriComposer.Build(ResourceTemplates.TEMPLATE_TRANSACTION_BY_ID, (ResourceTemplates.PARAM_NAME_TRANSACTION_ID, id));
var response = await httpClient.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}
| 38.054054 | 145 | 0.6875 | [
"MIT"
] | Binshop/apple-pay-demo | src/PaymentGateway/Services/DefaultQueryService.cs | 1,408 | C# |
// LEGAL INFORMATION:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using NUnit.Framework;
namespace TestCentric.Gui
{
public class XmlRtfConverterTests
{
[Test]
public void SimpleXmlTest()
{
var xml = @"
<A a='1' b='2'>
<B/>
<!-- this is a comment -->
<C>C content</C>
<D>
<![CDATA[
Within this Character Data block I can use < >
]]>
</D>
</A>";
//We use an empty color table - all colors will be black.
var converter = new Xml2RtfConverter(2, new Dictionary<Xml2RtfConverter.ColorKinds, Color>());
var doc = new XmlDocument();
doc.LoadXml(xml);
var rtf = converter.Convert(doc.FirstChild);
//Check the header
int headerLength = 259 + 3 * Environment.NewLine.Length;
Assert.That(rtf.Substring(0, headerLength), Is.EqualTo("{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Courier New;}}" + Environment.NewLine +
@"{{\colortbl ;\red0\green0\blue0;\red0\green0\blue0;\red0\green0\blue0;\red0\green0\blue0;\red0\green0\blue0;\red0\green0\blue0;\red0\green0\blue0;}}" + Environment.NewLine +
@"\viewkind4\uc1\pard\f0\fs20" + Environment.NewLine));
//CHeck the content
Assert.That(rtf.Substring(headerLength), Is.EqualTo(
@"\cf5<\cf1A \cf3a=\cf4'1' \cf3b=\cf4'2'\cf5>\par" +
@" \cf5<\cf1B \cf5/>\par" +
@" \cf6<!-- this is a comment -->\par" +
@" \cf5<\cf1C\cf5>\cf2C content\cf5</\cf1C\cf5>\par" +
@" \cf5<\cf1D\cf5>\par" +
@"\cf7<![CDATA[\par " +
@"Within this Character Data block I can use < >\par" + //note indentation in the CDATA is purely from based on the original CDATA content
@"]]>\par" +
@" \cf5</\cf1D\cf5>\par" +
@"\cf5</\cf1A\cf5>\par"));
}
}
}
| 37.981481 | 191 | 0.560215 | [
"MIT"
] | Acidburn0zzz/testcentric-experimental-gui | src/TestCentric/tests/XmlRtfConverterTests.cs | 2,051 | C# |
#pragma checksum "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "ff7f0d6279f2e38f10999a975ea0269f5a66ede6"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Students_Delete), @"mvc.1.0.view", @"/Views/Students/Delete.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\GIT\MvcFirst\MvcFirst\Views\_ViewImports.cshtml"
using MvcFirst;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\GIT\MvcFirst\MvcFirst\Views\_ViewImports.cshtml"
using MvcFirst.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"ff7f0d6279f2e38f10999a975ea0269f5a66ede6", @"/Views/Students/Delete.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"634614b0035bfe59c8b0d9dc55c84b8639347198", @"/Views/_ViewImports.cshtml")]
public class Views_Students_Delete : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<MvcFirst.Models.Student>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "hidden", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Delete", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\r\n");
#nullable restore
#line 3 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
ViewData["Title"] = "Delete";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1>Delete</h1>\r\n\r\n<h3>Are you sure you want to delete this?</h3>\r\n<div>\r\n <h4>Student</h4>\r\n <hr />\r\n <dl class=\"row\">\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 15 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
Write(Html.DisplayNameFor(model => model.FirstName));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 18 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
Write(Html.DisplayFor(model => model.FirstName));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 21 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
Write(Html.DisplayNameFor(model => model.LastName));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 24 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
Write(Html.DisplayFor(model => model.LastName));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 27 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
Write(Html.DisplayNameFor(model => model.AverageScore));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 30 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
Write(Html.DisplayFor(model => model.AverageScore));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 33 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
Write(Html.DisplayNameFor(model => model.Group));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 36 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
Write(Html.DisplayFor(model => model.Group.Id));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd class>\r\n </dl>\r\n \r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ff7f0d6279f2e38f10999a975ea0269f5a66ede67075", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ff7f0d6279f2e38f10999a975ea0269f5a66ede67341", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
#nullable restore
#line 41 "C:\GIT\MvcFirst\MvcFirst\Views\Students\Delete.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Id);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n <input type=\"submit\" value=\"Delete\" class=\"btn btn-danger\" /> |\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ff7f0d6279f2e38f10999a975ea0269f5a66ede69101", async() => {
WriteLiteral("Back to List");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n</div>\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<MvcFirst.Models.Student> Html { get; private set; }
}
}
#pragma warning restore 1591
| 58.679426 | 299 | 0.716895 | [
"MIT"
] | stone1234765/MvcFirst | MvcFirst/obj/Debug/netcoreapp3.1/Razor/Views/Students/Delete.cshtml.g.cs | 12,264 | C# |
using System;
using NuGetPe;
namespace PackageExplorerViewModel
{
public sealed class SymbolValidatorResultViewModel
{
private readonly SymbolValidatorResult? _result;
public SymbolValidatorResultViewModel(SymbolValidatorResult? symbolValidatorResult)
{
_result = symbolValidatorResult;
}
public SymbolValidationResult SourceLinkResult => _result?.SourceLinkResult ?? SymbolValidationResult.NothingToValidate;
public string? SourceLinkErrorMessage => _result?.SourceLinkErrorMessage;
public DeterministicResult DeterministicResult => _result?.DeterministicResult ?? DeterministicResult.NothingToValidate;
public string? DeterministicErrorMessage => _result?.DeterministicErrorMessage;
public HasCompilerFlagsResult CompilerFlagsResult => _result?.CompilerFlagsResult ?? HasCompilerFlagsResult.NothingToValidate;
public string? CompilerFlagsMessage => _result?.CompilerFlagsMessage;
public Exception? Exception => _result?.Exception;
}
}
| 37.75 | 134 | 0.763482 | [
"MIT"
] | MarcelWolf1983/NuGetPackageExplorer | PackageViewModel/SymbolValidatorResultViewModel.cs | 1,059 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.