content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
// Copyright 2018 Google LLC
//
// 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 Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201806;
using System;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201806 {
/// <summary>
/// This code example illustrates how to graduate a trial. See the Campaign
/// Drafts and Experiments guide for more information:
/// https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
/// </summary>
public class GraduateTrial : ExampleBase {
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args) {
GraduateTrial codeExample = new GraduateTrial();
Console.WriteLine(codeExample.Description);
try {
long trialId = long.Parse("INSERT_TRIAL_ID_HERE");
codeExample.Run(new AdWordsUser(), trialId);
} catch (Exception e) {
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description {
get {
return "This code example illustrates how to graduate a trial. See the Campaign " +
"Drafts and Experiments guide for more information: " +
"https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="trialId">Id of the trial to be graduated.</param>
public void Run(AdWordsUser user, long trialId) {
using (TrialService trialService = (TrialService) user.GetService(
AdWordsService.v201806.TrialService)) {
// To graduate a trial, you must specify a different budget from the
// base campaign. The base campaign (in order to have had a trial based
// on it) must have a non-shared budget, so it cannot be shared with
// the new independent campaign created by graduation.
Budget budget = CreateBudget(user);
Trial trial = new Trial() {
id = trialId,
budgetId = budget.budgetId,
status = TrialStatus.GRADUATED
};
TrialOperation trialOperation = new TrialOperation() {
@operator = Operator.SET,
operand = trial
};
try {
// Update the trial.
trial = trialService.mutate(new TrialOperation[] { trialOperation }).value[0];
// Graduation is a synchronous operation, so the campaign is already
// ready. If you promote instead, make sure to see the polling scheme
// demonstrated in AddTrial.cs to wait for the asynchronous operation
// to finish.
Console.WriteLine("Trial ID {0} graduated. Campaign ID {1} was given a new budget " +
"ID {2} and is no longer dependent on this trial.", trial.id, trial.trialCampaignId,
budget.budgetId);
} catch (Exception e) {
throw new System.ApplicationException("Failed to graduate trial.", e);
}
}
}
/// <summary>
/// Creates the budget.
/// </summary>
/// <param name="user">The user.</param>
/// <returns>The new budget.</returns>
public Budget CreateBudget(AdWordsUser user) {
using (BudgetService budgetService = (BudgetService) user.GetService(
AdWordsService.v201806.BudgetService)) {
Budget budget = new Budget() {
name = "Budget #" + ExampleUtilities.GetRandomString(),
amount = new Money() {
microAmount = 50000000L
},
deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD
};
BudgetOperation budgetOperation = new BudgetOperation() {
@operator = Operator.ADD,
operand = budget
};
return budgetService.mutate(new BudgetOperation[] { budgetOperation }).value[0];
}
}
}
}
| 38.130081 | 98 | 0.644136 | [
"Apache-2.0"
] | MajaGrubbe/googleads-dotnet-lib | examples/AdWords/CSharp/v201806/CampaignManagement/GraduateTrial.cs | 4,690 | C# |
// <copyright file="ReverseMode.cs" company="Geo.NET">
// Copyright (c) Geo.NET.
// Licensed under the MIT license. See the LICENSE file in the solution root for full license information.
// </copyright>
namespace Geo.MapBox.Enums
{
/// <summary>
/// The possible modes for results from a reverse geocoding request.
/// </summary>
public enum ReverseMode
{
/// <summary>
/// The closest feature to always be returned first.
/// </summary>
Distance,
/// <summary>
/// High-prominence features to be sorted higher than nearer, lower-prominence features.
/// </summary>
Score,
}
}
| 27.875 | 106 | 0.617339 | [
"MIT"
] | JustinCanton/Geo.NET | src/Geo.MapBox/Enums/ReverseMode.cs | 671 | C# |
using System;
using System.Collections.Generic;
namespace PhoneBook
{
public class Directory
{
public static List<Person> phoneBookList { get; set;}
static Directory()
{
phoneBookList = new List<Person>();
phoneBookList.Add(new Person("AHMET", "VURAL",123456789));
phoneBookList.Add(new Person("VELİ", "YILMAZ",812547832));
phoneBookList.Add(new Person("AYÇA", "KAR",846387412));
phoneBookList.Add(new Person("SERTAP", "YAVUZ",251987452));
phoneBookList.Add(new Person("MEHMET", "YAR",698534157));
}
public void AddPersonToDirectory(string name, string surname, long no)
{
phoneBookList.Add(new Person(name,surname,no));
}
public void ListDirectory()
{
Console.WriteLine("Telefon Rehberi");
Console.WriteLine("**********************************************");
foreach (var item in phoneBookList)
{
Console.WriteLine("isim: {0}",item.Name1);
Console.WriteLine("Soyisim: {0}",item.Surname1);
Console.WriteLine("Telefon Numarası: {0}",item.Number1);
Console.WriteLine("-");
}
Program.Options();
}
}
} | 32.3 | 80 | 0.55031 | [
"MIT"
] | MuhammetFatihYilmaz/PhoneBook | Directory.cs | 1,295 | C# |
using Newtonsoft.Json.Linq;
using Tridion.ContentManager.Extensibility;
using Tridion.ContentManager.Extensibility.Events;
using Tridion.ContentManager.Notifications;
using Tridion.ContentManager.Publishing;
namespace PublishTransactionNotification.EventHandler
{
[TcmExtension("Sends a notification to the user when a Publish Transaction finishes")]
public class SendNotificationHandler : TcmExtension
{
public SendNotificationHandler()
{
// subscribe to the save event for publish transactions
EventSystem.Subscribe<PublishTransaction, SaveEventArgs>(SendNotification, EventPhases.TransactionCommitted);
}
private static void SendNotification(PublishTransaction subject, SaveEventArgs e, EventPhases phases)
{
// only send a message when the publishing is finished. The publish transaction gets saved at least when created and on a status update
if (!subject.IsCompleted)
{
return;
}
// create an object that contains some data that we want to send to the client as the details of the message
JObject details = JObject.FromObject(new
{
creatorId = subject.Creator.Id.ToString(),
state = subject.State.ToString(),
title = subject.Title
});
NotificationMessage message = new NotificationMessage
{
// we need an identifier that we can use in the UI extension to distinguish our messages from others
Action = "example:publishtransactionfinished",
SubjectIds = new[] { subject.Id.ToString() },
Details = details.ToString()
};
subject.Session.NotificationsManager.BroadcastNotification(message);
}
}
}
| 40.543478 | 148 | 0.654155 | [
"Apache-2.0"
] | sdl/publish-transaction-notification | EventHandler/SendNotificationHandler.cs | 1,867 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.Admin.Entities;
using IdentityServer4.Admin.Infrastructure;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ApiResource = IdentityServer4.Models.ApiResource;
using Client = IdentityServer4.Models.Client;
using GrantTypes = IdentityServer4.Models.GrantTypes;
using IdentityResource = IdentityServer4.Models.IdentityResource;
namespace IdentityServer4.Admin
{
internal static class SeedData
{
public static async Task EnsureTestData(IServiceProvider serviceProvider)
{
Console.WriteLine("Seeding database...");
// Add client
await AddClients(serviceProvider);
// Add apiResource
await AddApiResources(serviceProvider);
await CommitAsync(serviceProvider);
var dbContext = (AdminDbContext) serviceProvider.GetRequiredService<IDbContext>();
if (await dbContext.Users.CountAsync() <= 1)
{
await AddPermissions(serviceProvider);
await AddRoles(serviceProvider);
await AddUsers(serviceProvider);
}
await CommitAsync(serviceProvider);
Console.WriteLine("Done seeding database.");
Console.WriteLine();
}
private static async Task AddPermissions(IServiceProvider serviceProvider)
{
var context = (AdminDbContext) serviceProvider.GetRequiredService<IDbContext>();
var permission = new Permission
{Name = AdminConsts.AdminName, Description = "Super admin permission"};
await context.Permissions.AddAsync(permission);
await CommitAsync(serviceProvider);
}
private static async Task CommitAsync(IServiceProvider serviceProvider)
{
await serviceProvider.GetRequiredService<IDbContext>().SaveChangesAsync();
}
private static async Task AddApiResources(IServiceProvider serviceProvider)
{
var context = (AdminDbContext) serviceProvider.GetRequiredService<IDbContext>();
if (!await context.ApiResources.AnyAsync())
{
Console.WriteLine("ApiResources being populated");
foreach (var resource in GetApiResources().ToList())
{
await context.ApiResources.AddAsync(resource.ToEntity());
}
}
else
{
Console.WriteLine("ApiResources already populated");
}
}
public static async Task AddIdentityResources(IServiceProvider serviceProvider)
{
var context = (AdminDbContext) serviceProvider.GetRequiredService<IDbContext>();
if (!await context.IdentityResources.AnyAsync())
{
Console.WriteLine("IdentityResources being populated");
foreach (var resource in GetIdentityResources().ToList())
{
await context.IdentityResources.AddAsync(resource.ToEntity());
}
}
else
{
Console.WriteLine("IdentityResources already populated");
}
await CommitAsync(serviceProvider);
}
private static async Task AddClients(IServiceProvider serviceProvider)
{
var context = (AdminDbContext) serviceProvider.GetRequiredService<IDbContext>();
if (!await context.Clients.AnyAsync())
{
Console.WriteLine("Clients being populated");
foreach (var client in GetClients().ToList())
{
await context.Clients.AddAsync(client.ToEntity());
}
}
else
{
Console.WriteLine("Clients already populated");
}
}
private static async Task AddUsers(IServiceProvider serviceProvider)
{
var ids = new[]
{
"d237e995-572f-409c-8ca9-852e1d522ef0",
"ee1d1d60-3a47-443e-8ef4-5412634aaca7",
"994e9d44-821e-4b58-b207-185297cc7eab",
"928844b3-4dbe-4d0a-9fee-7eac2d0369a6",
"2bfd5be9-0caf-4f2d-9a80-e5d426749ce7",
"8325387e-2ab4-42dd-9e3c-d98a0563a15f",
"ae7a8445-4d8f-469c-823c-0c94ce4d0839",
"d47b19e9-0cfb-4b95-bfde-97c48b91982e",
"583cef3e-564c-4dbd-8fad-78d762fbad6a",
"69a86e9f-2091-4fd6-84ac-90b9592cae80",
"6b94a518-011d-414a-8330-1d3ce99a7ae7",
"11ba7ad4-6230-44c0-a517-add90e0836a2",
"11550f5f-fc5c-494e-b018-f03d1ad0ddfa",
"98a4beb5-6ec0-4962-bb8d-e1a291ddb651",
"a8e76fa1-89da-4c13-bf43-d6219c8e6d40",
"d961ab17-8ad3-4a2b-a808-63529d67af7f",
"6dc2c7e0-c51f-4d4b-b035-691cb5d7711f",
"af70d04a-d79e-473f-b6d2-2193d594981e",
"b150af67-59e5-4f77-861f-cd3f866cafbd",
"7f8e17f7-03a0-4c09-997e-7ac5c9e3ba96",
"5aca084c-7b3d-49c7-a694-62ff3784dd7e",
"f47655b7-b77e-4522-ba3a-ed14b0cd3773",
"02ccd0dd-1de8-4364-b74f-fe1e4b32fd7c",
"137f199a-f5b5-4ec1-b05a-baaf4e92fa23",
"b101c693-b5e1-4a6c-a5c1-1f8936f1ee58",
"17c8bce3-a52c-41ad-883b-c2338de8d668",
"0f571c50-3c74-4bce-add2-92d5e99aa79b",
"02c4a35f-d0dd-48be-9f41-b7e3e379458b",
"09b68a01-ccf3-4d80-b92d-ee193a2e3773",
"b4d8a044-5c99-410f-a559-6e326f004d2b",
"d1931d32-85b0-472e-a84b-c94068ee55bf",
"cf693e0e-5ed6-4395-b341-ccb38085ff81",
"5accc292-f42f-4bcf-a66c-eb6c14d8a313",
"7dfb6851-6ae5-40e0-8061-ac94a090a0af",
"40a08c9c-8d35-4588-8266-b8a7d707d3a3",
"0161e23f-a3ca-4cd6-917d-322cb0964a80",
"ca8497eb-fda7-45d5-99b4-e484d51df91f",
"e5f0595c-2914-446c-b1c2-55101d6d10f6",
"598a529c-2aab-4dda-9c63-a1b179dcc15d",
"a1a361a7-7a14-4ad4-b6ca-04a5e3ea5929",
"232cbaac-44cd-49fa-aacb-e4a2acd0647f",
"0c472cb4-b25b-4b97-a82d-d6d410825455",
"feafce75-ea20-4460-8a4b-73707024ed92",
"119abebd-9380-4a2c-b20d-6326958c677f",
"75fd1d9e-c311-4205-8091-2bb314d68479",
"557783ef-d5f4-4249-86aa-ae45d789402d",
"84a9f75c-1529-496e-bcd2-bd0975b7a1d5",
"2963924a-3a2b-419b-8b46-b33e4a8f6221",
"ec607691-dbba-4cfd-b0b6-d0b52fdaedc7",
"e1ce6a2c-79e7-4c6c-98fe-b9da1c9bd3bd",
"e42db022-9d39-48dd-8784-9834cf39b035",
"217dc07f-a1ea-44e1-903b-28f59ad05c5c",
"d6c7e572-7500-41d6-8e99-da56f3a48bb0",
"77753d74-f412-46b9-8428-7d83794c4681",
"73fdbc51-ef00-4593-befd-82567766ee8e",
"d9e44d7a-153e-4903-9ef7-d8116ff776b8",
"ad229877-778b-4fb4-986f-f0e00591fbf3",
"bc55b7e2-a71d-49cc-86a7-d489e5e6b321",
"3100da87-8905-421a-90d5-3e7a93d8df46",
"c5aaf8b1-571f-454c-994a-2e07ce75fc2b",
"aa3579cb-7b32-4886-9931-7ee69e67d07d",
"3c8339c7-def5-4c19-bcd9-22d60506fc64",
"5b12ebe8-d898-44aa-b276-4898f985aa40",
"ea6dc37b-64da-4723-bdb8-c9205475151c",
"4b0b4d04-4360-4109-9fcc-e280ed7fe1a8",
"ce3e828f-c1a3-45e5-a87b-8daf4c75bf94",
"9ff836de-9806-4889-b63d-c6e72829a696",
"e8734e6d-56dc-4d82-9839-fca815eb2329",
"54dec57a-e990-4b38-bbef-be63f5bd3c54",
"18f69c8f-6c22-486b-85ab-ee999cc17312"
};
for (int i = 0; i < 30; ++i)
{
await AddUser(serviceProvider,
ids[i],
"User" + i,
"FirstName " + i,
"LastName " + i,
"1qazZAQ!",
"email" + i + "@163.com",
"13899981" + i,
"专家团队", "A2", "咨询师", "021-7896651" + i,
"expert");
}
for (int i = 30; i < 60; ++i)
{
await AddUser(serviceProvider,
ids[i],
"User" + i,
"FirstName " + i,
"LastName " + i,
"1qazZAQ!",
"email" + i + "@163.com",
"13899981" + i,
"销售团队", "A2", "机构销售", "021-7896651" + i,
"sale");
}
}
private static async Task AddUser(IServiceProvider serviceProvider, string id, string name, string firstName,
string lastName, string password, string email,
string phone, string group, string level, string title, string officePhone,
params string[] roles)
{
var userMgr = serviceProvider.GetRequiredService<UserManager<User>>();
var user = new User
{
Id = Guid.Parse(id),
UserName = name,
FirstName = firstName,
LastName = lastName,
Email = email,
Group = group,
EmailConfirmed = true,
PhoneNumber = phone,
PhoneNumberConfirmed = true,
Level = level,
Title = title,
OfficePhone = officePhone,
TwoFactorEnabled = false,
Sex = 0,
LockoutEnabled = true,
CreationTime = DateTime.Now,
IsDeleted = false,
AccessFailedCount = 0
};
await userMgr.CreateAsync(user, password);
foreach (var role in roles)
{
await userMgr.AddToRoleAsync(user, role);
}
}
private static async Task<Role> AddRole(IServiceProvider serviceProvider, string name, string description)
{
var roleMgr = serviceProvider.GetRequiredService<RoleManager<Role>>();
var role = await roleMgr.FindByNameAsync(name);
if (role == null)
{
role = new Role
{
Name = name,
Description = description
};
var result = await roleMgr.CreateAsync(role);
return result.Succeeded ? role : null;
}
return null;
}
private static async Task AddRoles(IServiceProvider serviceProvider)
{
await AddRole(serviceProvider, "expert-admin", "专家团队管理员");
await AddRole(serviceProvider, "expert", "专家团队成员");
await AddRole(serviceProvider, "expert-qc", "专家团队 QC");
await AddRole(serviceProvider, "expert-op", "The operator of expert group");
await AddRole(serviceProvider, "sale", "销售");
await CommitAsync(serviceProvider);
}
private static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("expert-api", "专家系统"),
new ApiResource("email-proxy-api", "邮件系统")
};
}
// scopes define the resources in your system
private static IEnumerable<IdentityResource> GetIdentityResources()
{
var openId = new IdentityResources.OpenId();
openId.DisplayName = "用户标识";
var profile = new IdentityResources.Profile
{
DisplayName = "基本信息: 如姓名、角色等", Description = ""
};
profile.UserClaims.Add(JwtClaimTypes.Role);
var fullProfile = new IdentityResources.Profile
{
Name = "full_profile", DisplayName = "完整信息: 如姓名、角色、电话、邮件、公司信息等", Description = ""
};
fullProfile.UserClaims.Add(JwtClaimTypes.Role);
fullProfile.UserClaims.Add(JwtClaimTypes.PhoneNumber);
fullProfile.UserClaims.Add(JwtClaimTypes.Email);
fullProfile.UserClaims.Add("title");
fullProfile.UserClaims.Add("group");
fullProfile.UserClaims.Add("level");
fullProfile.UserClaims.Add("office_phone");
fullProfile.UserClaims.Add("full_name");
return new List<IdentityResource>
{
openId,
profile,
fullProfile
};
}
// clients want to access resources (aka scopes)
private static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
new Client
{
ClientId = "vue-expert",
ClientName = "专家系统",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
AllowedCorsOrigins = {"http://localhost:6568"},
RedirectUris = {"http://localhost:6568/signin-oidc"},
PostLogoutRedirectUris = {"http://localhost:6568/signout-callback-oidc"},
RequireConsent = true,
AllowOfflineAccess = false,
AccessTokenLifetime = 3600 * 24 * 7,
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
"full_profile",
"expert-api",
"email-proxy-api"
}
},
new Client
{
ClientId = "email-proxy",
ClientName = "邮件系统",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
AllowedCorsOrigins = {"http://localhost:6570"},
RedirectUris = {"http://localhost:6570/signin-oidc.html"},
PostLogoutRedirectUris = {"http://localhost:6570"},
RequireConsent = true,
AllowOfflineAccess = false,
AccessTokenLifetime = 3600 * 24 * 7,
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
"full_profile",
"email-proxy-api"
}
}
};
}
public static async Task EnsureData(IServiceProvider serviceProvider)
{
var dbContext = (AdminDbContext) serviceProvider.GetRequiredService<IDbContext>();
if (await dbContext.Users.CountAsync() == 0)
{
var permission = new Permission
{Name = AdminConsts.AdminName, Description = "Super admin permission"};
await dbContext.Permissions.AddAsync(permission);
var role = new Role
{
Id = Guid.NewGuid(),
Name = AdminConsts.AdminName,
Description = "Super admin"
};
await serviceProvider.GetRequiredService<RoleManager<Role>>().CreateAsync(role);
await dbContext.RolePermissions.AddAsync(new RolePermission
{RoleId = role.Id, PermissionId = permission.Id});
var userMgr = serviceProvider.GetRequiredService<UserManager<User>>();
var user = new User
{
Id = Guid.NewGuid(),
UserName = "admin",
Email = "admin@ids4admin.com",
EmailConfirmed = true,
CreationTime = DateTime.Now,
IsDeleted = false,
};
var password = serviceProvider.GetRequiredService<IConfiguration>()["ADMIN_PASSWORD"];
if (string.IsNullOrWhiteSpace(password))
{
password = "1qazZAQ!";
}
await userMgr.CreateAsync(user, password);
await userMgr.AddToRoleAsync(user, AdminConsts.AdminName);
await dbContext.SaveChangesAsync();
}
}
}
} | 40.251781 | 117 | 0.535053 | [
"MIT"
] | blinds52/IdentityServer4.Admin | src/IdentityServer4.Admin/SeedData.cs | 17,120 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 14.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.NuGet
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\d\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\NuGet\PackagesConfig.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "14.0.0.0")]
public partial class PackagesConfig : PackagesConfigBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
this.Write(@"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
<package id=""Microsoft.Bcl"" version=""1.1.10"" targetFramework=""portable-net45+win+wpa81+wp80+MonoAndroid10+xamarinios10+MonoTouch10"" />
<package id=""Microsoft.Bcl.Build"" version=""1.0.14"" targetFramework=""portable-net45+win+wpa81+wp80+MonoAndroid10+xamarinios10+MonoTouch10"" />
<package id=""Microsoft.Net.Http"" version=""2.2.29"" targetFramework=""portable-net45+win+wpa81+wp80+MonoAndroid10+xamarinios10+MonoTouch10"" />
<package id=""PCLCrypto"" version=""1.0.2.15130"" targetFramework=""portable-net40+sl50+win+wpa81+wp80+MonoAndroid10+xamarinios10+MonoTouch10"" />
<package id=""PCLStorage"" version=""1.0.2"" targetFramework=""portable-net45+win+wp80+MonoAndroid10+xamarinios10+MonoTouch10"" />
<package id=""Validation"" version=""2.0.6.15003"" targetFramework=""portable-net45+win+wp80+MonoAndroid10+xamarinios10+MonoTouch10"" />
");
#line 14 "C:\d\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\NuGet\PackagesConfig.tt"
if(((string)this.Session["AssemblyName"]).Equals("AWSSDK.MobileAnalytics",StringComparison.CurrentCultureIgnoreCase)
|| ((string)this.Session["AssemblyName"]).Equals("AWSSDK.CognitoSync",StringComparison.CurrentCultureIgnoreCase))
{
#line default
#line hidden
this.Write(@" <package id=""SQLitePCLRaw.bundle_green"" version=""1.0.1"" targetFramework=""portable45-net45+win8+wp8+wpa81"" />
<package id=""SQLitePCLRaw.core"" version=""1.0.1"" targetFramework=""portable45-net45+win8+wp8+wpa81"" />
<package id=""System.Data.SQLite"" version=""1.0.97.0"" targetFramework=""net35"" />
<package id=""System.Data.SQLite.Core"" version=""1.0.97.0"" targetFramework=""net35"" />
<package id=""System.Data.SQLite.Linq"" version=""1.0.97.0"" targetFramework=""net35"" />
<package id=""System.Data.SQLite.EF6"" version=""1.0.97.0"" targetFramework=""net35"" />
");
#line 25 "C:\d\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\NuGet\PackagesConfig.tt"
}
#line default
#line hidden
this.Write("</packages>");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "14.0.0.0")]
public class PackagesConfigBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
protected System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 40.063768 | 148 | 0.561351 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | generator/ServiceClientGeneratorLib/Generators/NuGet/PackagesConfig.cs | 13,824 | C# |
// SPDX-FileCopyrightText: 2009 smdn <smdn@smdn.jp>
// SPDX-License-Identifier: MIT
using System;
using System.IO;
using System.Net;
using System.Xml;
namespace Smdn.Xml;
public class XmlCachedUrlResolver : XmlUrlResolver {
public XmlCachedUrlResolver(string cacheDirectory)
: this(cacheDirectory, TimeSpan.FromDays(10.0))
{
}
public XmlCachedUrlResolver(string cacheDirectory, TimeSpan cacheExpirationInterval)
{
if (cacheDirectory == null)
throw new ArgumentNullException(nameof(cacheDirectory));
if (cacheExpirationInterval < TimeSpan.Zero)
throw ExceptionUtils.CreateArgumentMustBeZeroOrPositive(nameof(cacheExpirationInterval), cacheExpirationInterval);
this.cacheDirectory = cacheDirectory;
this.cacheExpirationInterval = cacheExpirationInterval;
}
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
{
if (absoluteUri == null)
throw new ArgumentNullException(nameof(absoluteUri));
if (!absoluteUri.IsAbsoluteUri)
throw new UriFormatException("absoluteUri is not absolute URI");
if (ofObjectToReturn != null && !typeof(Stream).IsAssignableFrom(ofObjectToReturn))
throw new XmlException("argument ofObjectToReturn is invalid");
if (string.Equals(absoluteUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
return File.OpenRead(absoluteUri.LocalPath);
var rootDirectory = Path.Combine(cacheDirectory, absoluteUri.Host);
var relativePath = absoluteUri.LocalPath.Substring(1).Replace('/', Path.DirectorySeparatorChar);
return Smdn.IO.CachedWebFile.OpenRead(absoluteUri,
Path.Combine(rootDirectory, relativePath),
cacheExpirationInterval);
}
private string cacheDirectory;
private TimeSpan cacheExpirationInterval;
}
| 37.34 | 120 | 0.740761 | [
"MIT"
] | smdn/Smdn.Fundamentals | src/Smdn.Core.Miscellaneous/Smdn.Xml/XmlCachedUrlResolver.cs | 1,867 | C# |
namespace Mapbox.Examples
{
using Mapbox.Unity.Map;
using Mapbox.Unity.Utilities;
using Mapbox.Utils;
using UnityEngine;
using UnityEngine.EventSystems;
using System;
public class QuadTreeCameraMovement : MonoBehaviour
{
[SerializeField]
[Range(1, 20)]
public float _panSpeed = 1.0f;
[SerializeField]
float _zoomSpeed = 0.25f;
[SerializeField]
public Camera _referenceCamera;
[SerializeField]
AbstractMap _mapManager;
[SerializeField]
bool _useDegreeMethod;
private Vector3 _origin;
private Vector3 _mousePosition;
private Vector3 _mousePositionPrevious;
private bool _shouldDrag;
private bool _isInitialized = false;
private Plane _groundPlane = new Plane(Vector3.up, 0);
private bool _dragStartedOnUI = false;
void Awake()
{
if (null == _referenceCamera)
{
_referenceCamera = GetComponent<Camera>();
if (null == _referenceCamera) { Debug.LogErrorFormat("{0}: reference camera not set", this.GetType().Name); }
}
_mapManager.OnInitialized += () =>
{
_isInitialized = true;
};
}
public void Update()
{
if (Input.GetMouseButtonDown(0) && EventSystem.current.IsPointerOverGameObject())
{
_dragStartedOnUI = true;
}
if (Input.GetMouseButtonUp(0))
{
_dragStartedOnUI = false;
}
}
private void LateUpdate()
{
if (!_isInitialized) { return; }
if (!_dragStartedOnUI)
{
if (Input.touchSupported && Input.touchCount > 0)
{
HandleTouch();
}
else
{
HandleMouseAndKeyBoard();
}
}
}
void HandleMouseAndKeyBoard()
{
// zoom
float scrollDelta = 0.0f;
scrollDelta = Input.GetAxis("Mouse ScrollWheel");
ZoomMapUsingTouchOrMouse(scrollDelta);
//pan keyboard
float xMove = Input.GetAxis("Horizontal");
float zMove = Input.GetAxis("Vertical");
PanMapUsingKeyBoard(xMove, zMove);
//pan mouse
PanMapUsingTouchOrMouse();
}
void HandleTouch()
{
float zoomFactor = 0.0f;
//pinch to zoom.
switch (Input.touchCount)
{
case 1:
{
PanMapUsingTouchOrMouse();
}
break;
case 2:
{
// Store both touches.
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
// Find the position in the previous frame of each touch.
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// Find the magnitude of the vector (the distance) between the touches in each frame.
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
// Find the difference in the distances between each frame.
zoomFactor = 0.01f * (touchDeltaMag - prevTouchDeltaMag);
}
ZoomMapUsingTouchOrMouse(zoomFactor);
break;
default:
break;
}
}
void ZoomMapUsingTouchOrMouse(float zoomFactor)
{
var zoom = Mathf.Max(0.0f, Mathf.Min(_mapManager.Zoom + zoomFactor * _zoomSpeed, 21.0f));
if (Math.Abs(zoom - _mapManager.Zoom) > 0.0f)
{
_mapManager.UpdateMap(_mapManager.CenterLatitudeLongitude, zoom);
}
}
void PanMapUsingKeyBoard(float xMove, float zMove)
{
if (Math.Abs(xMove) > 0.0f || Math.Abs(zMove) > 0.0f)
{
// Get the number of degrees in a tile at the current zoom level.
// Divide it by the tile width in pixels ( 256 in our case)
// to get degrees represented by each pixel.
// Keyboard offset is in pixels, therefore multiply the factor with the offset to move the center.
float factor = _panSpeed * (Conversions.GetTileScaleInDegrees((float)_mapManager.CenterLatitudeLongitude.x, _mapManager.AbsoluteZoom));
var latitudeLongitude = new Vector2d(_mapManager.CenterLatitudeLongitude.x + zMove * factor * 2.0f, _mapManager.CenterLatitudeLongitude.y + xMove * factor * 4.0f);
_mapManager.UpdateMap(latitudeLongitude, _mapManager.Zoom);
}
}
void PanMapUsingTouchOrMouse()
{
if (_useDegreeMethod)
{
UseDegreeConversion();
}
else
{
UseMeterConversion();
}
}
void UseMeterConversion()
{
if (Input.GetMouseButtonUp(1))
{
var mousePosScreen = Input.mousePosition;
//assign distance of camera to ground plane to z, otherwise ScreenToWorldPoint() will always return the position of the camera
//http://answers.unity3d.com/answers/599100/view.html
mousePosScreen.z = _referenceCamera.transform.localPosition.y;
var pos = _referenceCamera.ScreenToWorldPoint(mousePosScreen);
var latlongDelta = _mapManager.WorldToGeoPosition(pos);
Debug.Log("Latitude: " + latlongDelta.x + " Longitude: " + latlongDelta.y);
}
if (Input.GetMouseButton(0) && !EventSystem.current.IsPointerOverGameObject())
{
var mousePosScreen = Input.mousePosition;
//assign distance of camera to ground plane to z, otherwise ScreenToWorldPoint() will always return the position of the camera
//http://answers.unity3d.com/answers/599100/view.html
mousePosScreen.z = _referenceCamera.transform.localPosition.y;
_mousePosition = _referenceCamera.ScreenToWorldPoint(mousePosScreen);
if (_shouldDrag == false)
{
_shouldDrag = true;
_origin = _referenceCamera.ScreenToWorldPoint(mousePosScreen);
}
}
else
{
_shouldDrag = false;
}
if (_shouldDrag == true)
{
var changeFromPreviousPosition = _mousePositionPrevious - _mousePosition;
if (Mathf.Abs(changeFromPreviousPosition.x) > 0.0f || Mathf.Abs(changeFromPreviousPosition.y) > 0.0f)
{
_mousePositionPrevious = _mousePosition;
var offset = _origin - _mousePosition;
if (Mathf.Abs(offset.x) > 0.0f || Mathf.Abs(offset.z) > 0.0f)
{
if (null != _mapManager)
{
float factor = _panSpeed * Conversions.GetTileScaleInMeters((float)0, _mapManager.AbsoluteZoom) / _mapManager.UnityTileSize;
var latlongDelta = Conversions.MetersToLatLon(new Vector2d(offset.x * factor, offset.z * factor));
var newLatLong = _mapManager.CenterLatitudeLongitude + latlongDelta;
_mapManager.UpdateMap(newLatLong, _mapManager.Zoom);
}
}
_origin = _mousePosition;
}
else
{
if (EventSystem.current.IsPointerOverGameObject())
{
return;
}
_mousePositionPrevious = _mousePosition;
_origin = _mousePosition;
}
}
}
void UseDegreeConversion()
{
if (Input.GetMouseButton(0) && !EventSystem.current.IsPointerOverGameObject())
{
var mousePosScreen = Input.mousePosition;
//assign distance of camera to ground plane to z, otherwise ScreenToWorldPoint() will always return the position of the camera
//http://answers.unity3d.com/answers/599100/view.html
mousePosScreen.z = _referenceCamera.transform.localPosition.y;
_mousePosition = _referenceCamera.ScreenToWorldPoint(mousePosScreen);
if (_shouldDrag == false)
{
_shouldDrag = true;
_origin = _referenceCamera.ScreenToWorldPoint(mousePosScreen);
}
}
else
{
_shouldDrag = false;
}
if (_shouldDrag == true)
{
var changeFromPreviousPosition = _mousePositionPrevious - _mousePosition;
if (Mathf.Abs(changeFromPreviousPosition.x) > 0.0f || Mathf.Abs(changeFromPreviousPosition.y) > 0.0f)
{
_mousePositionPrevious = _mousePosition;
var offset = _origin - _mousePosition;
if (Mathf.Abs(offset.x) > 0.0f || Mathf.Abs(offset.z) > 0.0f)
{
if (null != _mapManager)
{
// Get the number of degrees in a tile at the current zoom level.
// Divide it by the tile width in pixels ( 256 in our case)
// to get degrees represented by each pixel.
// Mouse offset is in pixels, therefore multiply the factor with the offset to move the center.
float factor = _panSpeed * Conversions.GetTileScaleInDegrees((float)_mapManager.CenterLatitudeLongitude.x, _mapManager.AbsoluteZoom) / _mapManager.UnityTileSize;
var latitudeLongitude = new Vector2d(_mapManager.CenterLatitudeLongitude.x + offset.z * factor, _mapManager.CenterLatitudeLongitude.y + offset.x * factor);
_mapManager.UpdateMap(latitudeLongitude, _mapManager.Zoom);
}
}
_origin = _mousePosition;
}
else
{
if (EventSystem.current.IsPointerOverGameObject())
{
return;
}
_mousePositionPrevious = _mousePosition;
_origin = _mousePosition;
}
}
}
private Vector3 getGroundPlaneHitPoint(Ray ray)
{
float distance;
if (!_groundPlane.Raycast(ray, out distance)) { return Vector3.zero; }
return ray.GetPoint(distance);
}
}
} | 28.79402 | 168 | 0.69032 | [
"Apache-2.0"
] | 483759/Next-Place | unity/NextPlace/Assets/Mapbox/Examples/Scripts/QuadTreeCameraMovement.cs | 8,669 | C# |
using System;
using System.Collections.Generic;
using ModestTree;
namespace Zenject
{
public static class SignalExtensions
{
public static SignalBinderWithId DeclareSignal<T>(this DiContainer container)
where T : ISignalBase
{
var info = new BindInfo(typeof(T));
var signalSettings = new SignalSettings();
container.Bind<T>(info).AsCached().WithArguments(signalSettings, info);
return new SignalBinderWithId(info, signalSettings);
}
public static SignalHandlerBinderWithId BindSignal<TSignal>(this DiContainer container)
where TSignal : ISignal
{
var binder = container.StartBinding();
return new SignalHandlerBinderWithId(
container, typeof(TSignal), binder);
}
public static SignalHandlerBinderWithId<TParam1> BindSignal<TParam1, TSignal>(this DiContainer container)
where TSignal : ISignal<TParam1>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
#endif
{
var binder = container.StartBinding();
return new SignalHandlerBinderWithId<TParam1>(
container, typeof(TSignal), binder);
}
public static SignalHandlerBinderWithId<TParam1, TParam2> BindSignal<TParam1, TParam2, TSignal>(this DiContainer container)
where TSignal : ISignal<TParam1, TParam2>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
where TParam2 : class
#endif
{
var binder = container.StartBinding();
return new SignalHandlerBinderWithId<TParam1, TParam2>(
container, typeof(TSignal), binder);
}
public static SignalHandlerBinderWithId<TParam1, TParam2, TParam3> BindSignal<TParam1, TParam2, TParam3, TSignal>(this DiContainer container)
where TSignal : ISignal<TParam1, TParam2, TParam3>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
where TParam2 : class
where TParam3 : class
#endif
{
var binder = container.StartBinding();
return new SignalHandlerBinderWithId<TParam1, TParam2, TParam3>(
container, typeof(TSignal), binder);
}
public static SignalHandlerBinderWithId<TParam1, TParam2, TParam3, TParam4> BindSignal<TParam1, TParam2, TParam3, TParam4, TSignal>(this DiContainer container)
where TSignal : ISignal<TParam1, TParam2, TParam3, TParam4>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
where TParam2 : class
where TParam3 : class
where TParam4 : class
#endif
{
var binder = container.StartBinding();
return new SignalHandlerBinderWithId<TParam1, TParam2, TParam3, TParam4>(
container, typeof(TSignal), binder);
}
}
}
| 41.691358 | 167 | 0.649393 | [
"MIT"
] | antoniovalentini/greenfield-unity | projects/Helpers/Assets/Plugins/Zenject/Source/Signals/SignalExtensions.cs | 3,377 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Baseline;
using Marten.Util;
using Xunit;
namespace Marten.Testing.Linq.Compatibility.Support
{
public abstract class LinqTestContext<TFixture, TSelf> : IClassFixture<TFixture> where TFixture : TargetSchemaFixture
{
protected static IList<LinqTestCase> testCases = new List<LinqTestCase>();
public TFixture Fixture { get; }
static LinqTestContext()
{
_descriptions = readDescriptions();
}
protected LinqTestContext(TFixture fixture)
{
Fixture = fixture;
}
protected static void @where(Expression<Func<Target, bool>> expression)
{
var comparison = new TargetComparison(q => q.Where(expression)) {Ordered = false};
testCases.Add(comparison);
}
protected static void ordered(Func<IQueryable<Target>, IQueryable<Target>> func)
{
var comparison = new TargetComparison(func) {Ordered = true};
testCases.Add(comparison);
}
protected static void unordered(Func<IQueryable<Target>, IQueryable<Target>> func)
{
var comparison = new TargetComparison(func) {Ordered = false};
testCases.Add(comparison);
}
protected static void selectInOrder<T>(Func<IQueryable<Target>, IQueryable<T>> selector)
{
var comparison = new OrderedSelectComparison<T>(selector);
testCases.Add(comparison);
}
private static string[] _methodNames = new string[] {"@where", nameof(ordered), nameof(unordered), nameof(selectInOrder)};
private static string[] _descriptions;
protected static string[] readDescriptions()
{
var path = AppContext.BaseDirectory;
while (!path.EndsWith("Marten.Testing"))
{
path = path.ParentDirectory();
}
var filename = typeof(TSelf).Name + ".cs";
var codefile = path.AppendPath("Linq", "Compatibility", filename);
var list = new List<string>();
new FileSystem().ReadTextFile(codefile, line =>
{
line = line.Trim();
if (_methodNames.Any(x => line.StartsWith(x)))
{
var start = line.IndexOf('(') + 1;
var description = line.Substring(start, line.Length - start - 2);
list.Add(description);
}
});
return list.ToArray();
}
public static IEnumerable<object[]> GetDescriptions()
{
return _descriptions.Select(x => new object[] {x});
}
protected async Task assertTestCase(string description, IDocumentStore store)
{
var index = _descriptions.IndexOf(description);
var testCase = testCases[index];
using (var session = store.QuerySession())
{
await testCase.Compare(session, Fixture.Documents);
}
}
}
} | 29.008929 | 130 | 0.568483 | [
"MIT"
] | thrane/marten | src/Marten.Testing/Linq/Compatibility/Support/LinqTestContext.cs | 3,249 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Box.V2.Managers;
using System.Threading.Tasks;
using Box.V2.Models;
using Moq;
using Box.V2.Models.Request;
namespace Box.V2.Test
{
[TestClass]
public class BoxGroupsManagerTest : BoxResourceManagerTest
{
private readonly BoxGroupsManager _groupsManager;
public BoxGroupsManagerTest()
{
_groupsManager = new BoxGroupsManager(Config.Object, Service, Converter, AuthRepository);
}
[TestMethod]
public async Task GetGroupItems_ValidResponse_ValidGroups()
{
Handler.Setup(h => h.ExecuteAsync<BoxCollection<BoxGroup>>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxCollection<BoxGroup>>>(new BoxResponse<BoxCollection<BoxGroup>>()
{
Status = ResponseStatus.Success,
ContentString = @"{""total_count"": 14,
""entries"": [ {""type"": ""group"", ""id"": ""26477"", ""name"": ""adfasdf"", ""created_at"": ""2011-02-15T14:07:22-08:00"", ""modified_at"": ""2011-10-05T19:04:40-07:00""},
{""type"": ""group"", ""id"": ""1263"", ""name"": ""Enterprise Migration"", ""created_at"": ""2009-04-20T19:36:17-07:00"", ""modified_at"": ""2011-10-05T19:05:10-07:00""}],
""limit"": 2, ""offset"": 0}"
}));
BoxCollection<BoxGroup> items = await _groupsManager.GetAllGroupsAsync();
Assert.AreEqual(items.TotalCount, 14, "Wrong total count");
Assert.AreEqual(items.Entries.Count, 2, "Wrong count of entries");
Assert.AreEqual(items.Entries[0].Type, "group", "Wrong type");
Assert.AreEqual(items.Entries[0].Id, "26477", "Wrong id");
Assert.AreEqual(items.Entries[0].Name, "adfasdf", "Wrong name");
Assert.AreEqual(items.Entries[0].CreatedAt, DateTime.Parse("2011-02-15T14:07:22-08:00"), "Wrong created at");
Assert.AreEqual(items.Entries[0].ModifiedAt, DateTime.Parse("2011-10-05T19:04:40-07:00"), "Wrong modified at");
Assert.AreEqual(items.Offset, 0, "Wrong offset");
Assert.AreEqual(items.Limit, 2, "Wrong limit");
}
[TestMethod]
public async Task GetGroup_ValidResponse_ValidGroup()
{
Handler.Setup(h => h.ExecuteAsync<BoxGroup>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxGroup>>(new BoxResponse<BoxGroup>()
{
Status = ResponseStatus.Success,
ContentString = @"{""type"": ""group"", ""id"": ""26477"", ""name"": ""adfasdf"", ""created_at"": ""2011-02-15T14:07:22-08:00"", ""modified_at"": ""2011-10-05T19:04:40-07:00""}"
}));
BoxGroup group = await _groupsManager.GetGroupAsync("222");
Assert.AreEqual("26477", group.Id, "Wrong Id");
Assert.AreEqual("group", group.Type, "Wrong type");
Assert.AreEqual("adfasdf", group.Name, "Wrong name");
Assert.AreEqual(DateTime.Parse("2011-02-15T14:07:22-08:00"), group.CreatedAt, "Wrong created at");
Assert.AreEqual(DateTime.Parse("2011-10-05T19:04:40-07:00"), group.ModifiedAt, "Wrong modified at");
}
[TestMethod]
public async Task GetGroupItems_ValidResponse_NoGroups()
{
Handler.Setup(h => h.ExecuteAsync<BoxCollection<BoxGroup>>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxCollection<BoxGroup>>>(new BoxResponse<BoxCollection<BoxGroup>>()
{
Status = ResponseStatus.Success,
ContentString = @"{""total_count"": 0,
""limit"": 2, ""offset"": 0}"
}));
BoxCollection<BoxGroup> items = await _groupsManager.GetAllGroupsAsync();
Assert.AreEqual(0, items.TotalCount, "Wrong count");
Assert.AreEqual(0, items.Offset, "Wrong offset");
Assert.AreEqual(2, items.Limit, "Wrong limit");
}
[TestMethod]
public async Task CreateGroup_ValidResponse_NewGroup()
{
Handler.Setup(h => h.ExecuteAsync<BoxGroup>(It.IsAny<BoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxGroup>>(new BoxResponse<BoxGroup>()
{
Status = ResponseStatus.Success,
ContentString = @"{ ""type"": ""group"", ""id"": ""159322"", ""name"": ""TestGroup2"", ""created_at"": ""2013-11-12T15:19:47-08:00"", ""modified_at"": ""2013-11-12T15:19:47-08:00"" }"
}));
BoxGroupRequest request = new BoxGroupRequest(){ Name = "NewGroup" };
BoxGroup group = await _groupsManager.CreateAsync(request);
Assert.AreEqual<string>("TestGroup2", group.Name, "Wrong group name");
Assert.AreEqual<string>("159322", group.Id, "Wrong id");
Assert.AreEqual(DateTime.Parse("2013-11-12T15:19:47-08:00"), group.ModifiedAt, "Wrong modified at");
Assert.AreEqual(DateTime.Parse("2013-11-12T15:19:47-08:00"), group.CreatedAt, "Wrong created at");
}
[TestMethod]
public async Task DeleteGroup_ValidResponse_ValidGroup()
{
Handler.Setup(h=>h.ExecuteAsync<BoxGroup>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxGroup>>(new BoxResponse<BoxGroup>()
{
Status = ResponseStatus.Success,
ContentString = ""
}));
var result = await _groupsManager.DeleteAsync("1234");
Assert.IsTrue(result, "Unsuccessful delete");
}
[TestMethod]
public async Task UpdateGroup_ValidResponse_ValidGroup()
{
Handler.Setup(h => h.ExecuteAsync<BoxGroup>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxGroup>>(new BoxResponse<BoxGroup>()
{
Status = ResponseStatus.Success,
ContentString = @"{ ""type"": ""group"", ""id"": ""159322"", ""name"": ""TestGroup2"", ""created_at"": ""2013-11-12T15:19:47-08:00"", ""modified_at"": ""2013-11-12T15:19:47-08:00"" }"
}));
BoxGroupRequest request = new BoxGroupRequest() { Name = "groupName" };
BoxGroup group = await _groupsManager.UpdateAsync("123", request);
Assert.AreEqual<string>("TestGroup2", group.Name, "Wrong Group name");
Assert.AreEqual<string>("159322", group.Id, "Wrong group id");
Assert.AreEqual(DateTime.Parse("2013-11-12T15:19:47-08:00"), group.ModifiedAt, "Wrong modified at");
Assert.AreEqual(DateTime.Parse("2013-11-12T15:19:47-08:00"), group.CreatedAt, "Wrong created at");
}
[TestMethod]
public async Task AddGroupMembership_ValidResponse()
{
Handler.Setup(h => h.ExecuteAsync<BoxGroupMembership>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxGroupMembership>>(new BoxResponse<BoxGroupMembership>()
{
Status = ResponseStatus.Success,
ContentString = @"{ ""type"": ""group_membership"", ""id"": ""2381570"",
""user"": { ""type"": ""user"", ""id"": ""4940223"", ""name"": ""<script>alert(12);</script>"", ""login"": ""testmaster@box.net""},
""group"": { ""type"": ""group"", ""id"": ""159622"", ""name"": ""test204bbee0-f3b0-43b4-b213-214fcd2cb9a7"" },
""role"": ""member"",
""created_at"": ""2013-11-13T13:19:44-08:00"",
""modified_at"": ""2013-11-13T13:19:44-08:00""}"
}));
BoxGroupMembershipRequest request = new BoxGroupMembershipRequest()
{
User = new BoxRequestEntity() { Id = "123" },
Group = new BoxGroupRequest() { Id = "456" }
};
BoxGroupMembership response = await _groupsManager.AddMemberToGroupAsync(request);
Assert.AreEqual("2381570", response.Id, "Wrong Membership id");
Assert.AreEqual("group_membership", response.Type, "wrong type");
Assert.AreEqual("159622", response.Group.Id, "Wrong group id");
Assert.AreEqual("4940223", response.User.Id, "Wrong user id");
Assert.AreEqual("member", response.Role, "Wrong role");
Assert.AreEqual(DateTime.Parse("2013-11-13T13:19:44-08:00"), response.CreatedAt, "Wrong created at");
Assert.AreEqual(DateTime.Parse("2013-11-13T13:19:44-08:00"), response.ModifiedAt, "Wrong modified at");
}
[TestMethod]
public async Task DeleteMembership_ValidResponse_ValidGroup()
{
Handler.Setup(h => h.ExecuteAsync<BoxGroup>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxGroup>>(new BoxResponse<BoxGroup>()
{
Status = ResponseStatus.Success,
ContentString = ""
}));
var result = await _groupsManager.DeleteGroupMembershipAsync("1234");
Assert.IsTrue(result, "Unsuccessful group membership delete");
}
[TestMethod]
public async Task GetAllMemberships_ValidResponse_ValidGroup()
{
Handler.Setup(h => h.ExecuteAsync<BoxCollection<BoxGroupMembership>>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxCollection<BoxGroupMembership>>>(new BoxResponse<BoxCollection<BoxGroupMembership>>()
{
Status = ResponseStatus.Success,
ContentString = @"{ ""total_count"": 2, ""entries"": [{
""type"": ""group_membership"", ""id"": ""136639"",
""user"": {""type"": ""user"",""id"": ""6102564"", ""name"": ""<script>alert('atk');</script>"", ""login"": ""testanyregister@box.net""},
""group"": {""type"": ""group"",""id"": ""26477"",""name"": ""adfasdf""},""role"": ""member""},
{""type"": ""group_membership"",""id"": ""273529"",
""user"": {""type"": ""user"",""id"": ""13928063"",""name"": ""spootie"",""login"": ""tevanspratt++39478@box.net""},
""group"": {""type"": ""group"", ""id"": ""26477"", ""name"": ""adfasdf""}, ""role"": ""member""}], ""offset"": 0,""limit"": 100}"
}));
BoxCollection<BoxGroupMembership> response = await _groupsManager.GetAllGroupMembershipsForGroupAsync("123");
Assert.AreEqual(2, response.TotalCount, "Wrong total count");
Assert.AreEqual(2, response.Entries.Count, "Wrong number of entries");
Assert.AreEqual("group_membership", response.Entries[0].Type, "Wrong type");
Assert.AreEqual("6102564", response.Entries[0].User.Id, "Wrong user id");
Assert.AreEqual("26477", response.Entries[0].Group.Id, "Wrong group id");
}
[TestMethod]
public async Task GetAllMemberships_ValidResponse_ValidUser()
{
Handler.Setup(h => h.ExecuteAsync<BoxCollection<BoxGroupMembership>>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxCollection<BoxGroupMembership>>>(new BoxResponse<BoxCollection<BoxGroupMembership>>()
{
Status = ResponseStatus.Success,
ContentString = @"{ ""total_count"": 2, ""entries"": [{
""type"": ""group_membership"", ""id"": ""136639"",
""user"": {""type"": ""user"",""id"": ""6102564"", ""name"": ""<script>alert('atk');</script>"", ""login"": ""testanyregister@box.net""},
""group"": {""type"": ""group"",""id"": ""26477"",""name"": ""adfasdf""},""role"": ""member""},
{""type"": ""group_membership"",""id"": ""273529"",
""user"": {""type"": ""user"",""id"": ""13928063"",""name"": ""spootie"",""login"": ""tevanspratt++39478@box.net""},
""group"": {""type"": ""group"", ""id"": ""26477"", ""name"": ""adfasdf""}, ""role"": ""member""}], ""offset"": 0,""limit"": 100}"
}));
BoxCollection<BoxGroupMembership> response = await _groupsManager.GetAllGroupMembershipsForUserAsync("123");
Assert.AreEqual(2, response.TotalCount, "Wrong total count");
Assert.AreEqual(2, response.Entries.Count, "Wrong number of entries");
Assert.AreEqual("group_membership", response.Entries[0].Type, "Wrong type");
Assert.AreEqual("6102564", response.Entries[0].User.Id, "Wrong user id");
Assert.AreEqual("26477", response.Entries[0].Group.Id, "Wrong group id");
}
[TestMethod]
public async Task GetGroupMembership_ValidResponse()
{
Handler.Setup(h => h.ExecuteAsync<BoxGroupMembership>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxGroupMembership>>(new BoxResponse<BoxGroupMembership>()
{
Status = ResponseStatus.Success,
ContentString = @"{ ""type"": ""group_membership"", ""id"": ""2381570"",
""user"": { ""type"": ""user"", ""id"": ""4940223"", ""name"": ""<script>alert(12);</script>"", ""login"": ""testmaster@box.net""},
""group"": { ""type"": ""group"", ""id"": ""159622"", ""name"": ""test204bbee0-f3b0-43b4-b213-214fcd2cb9a7"" },
""role"": ""member"",
""created_at"": ""2013-11-13T13:19:44-08:00"",
""modified_at"": ""2013-11-13T13:19:44-08:00""}"
}));
BoxGroupMembership response = await _groupsManager.GetGroupMembershipAsync("123");
Assert.AreEqual("2381570", response.Id, "Wrong Membership id");
Assert.AreEqual("group_membership", response.Type, "wrong type");
Assert.AreEqual("159622", response.Group.Id, "Wrong group id");
Assert.AreEqual("4940223", response.User.Id, "Wrong user id");
Assert.AreEqual("member", response.Role, "Wrong role");
Assert.AreEqual(DateTime.Parse("2013-11-13T13:19:44-08:00"), response.CreatedAt, "Wrong created at");
Assert.AreEqual(DateTime.Parse("2013-11-13T13:19:44-08:00"), response.ModifiedAt, "Wrong modified at");
}
[TestMethod]
public async Task UpdateGroupMembership_ValidResponse()
{
Handler.Setup(h => h.ExecuteAsync<BoxGroupMembership>(It.IsAny<IBoxRequest>()))
.Returns(() => Task.FromResult<IBoxResponse<BoxGroupMembership>>(new BoxResponse<BoxGroupMembership>()
{
Status = ResponseStatus.Success,
ContentString = @"{ ""type"": ""group_membership"", ""id"": ""2381570"",
""user"": { ""type"": ""user"", ""id"": ""4940223"", ""name"": ""<script>alert(12);</script>"", ""login"": ""testmaster@box.net""},
""group"": { ""type"": ""group"", ""id"": ""159622"", ""name"": ""test204bbee0-f3b0-43b4-b213-214fcd2cb9a7"" },
""role"": ""admin"",
""created_at"": ""2013-11-13T13:19:44-08:00"",
""modified_at"": ""2013-11-13T13:19:44-08:00""}"
}));
BoxGroupMembershipRequest request = new BoxGroupMembershipRequest() { Role = "anything"};
BoxGroupMembership response = await _groupsManager.UpdateGroupMembershipAsync("123", request);
Assert.AreEqual("2381570", response.Id, "Wrong Membership id");
Assert.AreEqual("group_membership", response.Type, "wrong type");
Assert.AreEqual("159622", response.Group.Id, "Wrong group id");
Assert.AreEqual("4940223", response.User.Id, "Wrong user id");
Assert.AreEqual("admin", response.Role, "Wrong role");
Assert.AreEqual(DateTime.Parse("2013-11-13T13:19:44-08:00"), response.CreatedAt, "Wrong created at");
Assert.AreEqual(DateTime.Parse("2013-11-13T13:19:44-08:00"), response.ModifiedAt, "Wrong modified at");
}
}
}
| 59.041522 | 224 | 0.543515 | [
"Apache-2.0"
] | ajweber/box-windows-sdk-v2 | Box.V2.Test/BoxGroupsManagerTest.cs | 17,065 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Migrate.Latest.Inputs
{
public sealed class CollectorAgentPropertiesArgs : Pulumi.ResourceArgs
{
[Input("spnDetails")]
public Input<Inputs.CollectorBodyAgentSpnPropertiesArgs>? SpnDetails { get; set; }
public CollectorAgentPropertiesArgs()
{
}
}
}
| 27.434783 | 90 | 0.714739 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Migrate/Latest/Inputs/CollectorAgentPropertiesArgs.cs | 631 | C# |
using UnityEngine;
using System.Collections;
public class Pusher : MonoBehaviour {
public KeyCode forwardKey = KeyCode.N;
public KeyCode leftKey = KeyCode.B;
public KeyCode rightKey = KeyCode.M;
public float damping = 0.1f;
public float thrust = 100.0f; // Newtons
public float mass = 1.0f;
public Vector3 velocity;
public Vector3 force;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey(forwardKey))
{
force += transform.forward * thrust;
}
if (Input.GetKey(leftKey))
{
force -= transform.right * thrust;
}
if (Input.GetKey(rightKey))
{
force += transform.right * thrust;
}
Vector3 acceleration = force / mass;
velocity += acceleration * Time.deltaTime;
transform.Translate(velocity * Time.deltaTime, Space.World);
if (velocity.sqrMagnitude > float.Epsilon)
{
transform.forward = velocity;
}
float dampingThisFrame = 1.0f - (damping * Time.deltaTime);
velocity *= dampingThisFrame;
force = Vector3.zero;
}
}
| 26.166667 | 69 | 0.577229 | [
"MIT"
] | praised/gameengines2015 | unity/Vectors1/Assets/Pusher.cs | 1,258 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using HarmonyLib;
using Microsoft.Xna.Framework;
using Pathoschild.Stardew.Common.Patching;
using Pathoschild.Stardew.SmallBeachFarm.Framework;
using Pathoschild.Stardew.SmallBeachFarm.Framework.Config;
using StardewModdingAPI;
using StardewValley;
using SObject = StardewValley.Object;
namespace Pathoschild.Stardew.SmallBeachFarm.Patches
{
/// <summary>Encapsulates Harmony patches for the <see cref="Farm"/> instance.</summary>
internal class FarmPatcher : BasePatcher
{
/*********
** Fields
*********/
/// <summary>Encapsulates logging for the Harmony patch.</summary>
private static IMonitor Monitor;
/// <summary>The mod configuration.</summary>
private static ModConfig Config;
/// <summary>Get whether the given location is the Small Beach Farm.</summary>
private static Func<GameLocation, bool> IsSmallBeachFarm;
/// <summary>Get the fish that should be available from the given tile.</summary>
private static Func<Farm, int, int, FishType> GetFishType;
/// <summary>Whether the mod is currently applying patch changes (to avoid infinite recursion),</summary>
private static bool IsInPatch;
/*********
** Public methods
*********/
/// <summary>Initialize the patcher.</summary>
/// <param name="monitor">Encapsulates logging for the Harmony patch.</param>
/// <param name="config">The mod configuration.</param>
/// <param name="isSmallBeachFarm">Get whether the given location is the Small Beach Farm.</param>
/// <param name="getFishType">Get the fish that should be available from the given tile.</param>
public FarmPatcher(IMonitor monitor, ModConfig config, Func<GameLocation, bool> isSmallBeachFarm, Func<Farm, int, int, FishType> getFishType)
{
FarmPatcher.Monitor = monitor;
FarmPatcher.Config = config;
FarmPatcher.IsSmallBeachFarm = isSmallBeachFarm;
FarmPatcher.GetFishType = getFishType;
}
/// <inheritdoc />
public override void Apply(Harmony harmony, IMonitor monitor)
{
harmony.Patch(
original: this.RequireMethod<Farm>(nameof(Farm.getFish)),
prefix: this.GetHarmonyMethod(nameof(FarmPatcher.Before_GetFish))
);
harmony.Patch(
original: this.RequireMethod<Farm>("resetLocalState"),
prefix: this.GetHarmonyMethod(nameof(FarmPatcher.After_ResetLocalState))
);
harmony.Patch(
original: this.RequireMethod<Farm>("resetSharedState"),
prefix: this.GetHarmonyMethod(nameof(FarmPatcher.After_ResetSharedState))
);
harmony.Patch(
original: this.RequireMethod<GameLocation>(nameof(GameLocation.cleanupBeforePlayerExit)),
prefix: this.GetHarmonyMethod(nameof(FarmPatcher.After_CleanupBeforePlayerExit))
);
harmony.Patch(
original: this.RequireMethod<GameLocation>(nameof(GameLocation.getRandomTile)),
prefix: this.GetHarmonyMethod(nameof(FarmPatcher.After_GetRandomTile))
);
}
/*********
** Private methods
*********/
/// <summary>A method called via Harmony before <see cref="Farm.getFish"/>, which gets ocean fish from the beach properties if fishing the ocean water.</summary>
/// <param name="__instance">The farm instance.</param>
/// <param name="millisecondsAfterNibble">An argument passed through to the underlying method.</param>
/// <param name="bait">An argument passed through to the underlying method.</param>
/// <param name="waterDepth">An argument passed through to the underlying method.</param>
/// <param name="who">An argument passed through to the underlying method.</param>
/// <param name="baitPotency">An argument passed through to the underlying method.</param>
/// <param name="bobberTile">The tile containing the bobber.</param>
/// <param name="__result">The return value to use for the method.</param>
/// <returns>Returns <c>true</c> if the original logic should run, or <c>false</c> to use <paramref name="__result"/> as the return value.</returns>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "The naming convention is defined by Harmony.")]
private static bool Before_GetFish(Farm __instance, float millisecondsAfterNibble, int bait, int waterDepth, Farmer who, double baitPotency, Vector2 bobberTile, ref SObject __result)
{
if (FarmPatcher.IsInPatch || !FarmPatcher.IsSmallBeachFarm(who?.currentLocation))
return true;
try
{
FarmPatcher.IsInPatch = true;
FishType type = FarmPatcher.GetFishType(__instance, (int)bobberTile.X, (int)bobberTile.Y);
FarmPatcher.Monitor.VerboseLog($"Fishing {type.ToString().ToLower()} tile at ({bobberTile.X / Game1.tileSize}, {bobberTile.Y / Game1.tileSize}).");
switch (type)
{
case FishType.Ocean:
__result = __instance.getFish(millisecondsAfterNibble, bait, waterDepth, who, baitPotency, bobberTile, "Beach");
return false;
case FishType.River:
// match riverland farm behavior
__result = Game1.random.NextDouble() < 0.3
? __instance.getFish(millisecondsAfterNibble, bait, waterDepth, who, baitPotency, bobberTile, "Forest")
: __instance.getFish(millisecondsAfterNibble, bait, waterDepth, who, baitPotency, bobberTile, "Town");
return false;
default:
return true; // run original method
}
}
finally
{
FarmPatcher.IsInPatch = false;
}
}
/// <summary>A method called via Harmony after <see cref="Farm.resetLocalState"/>.</summary>
/// <param name="__instance">The farm instance.</param>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "The naming convention is defined by Harmony.")]
private static void After_ResetLocalState(GameLocation __instance)
{
if (!FarmPatcher.IsSmallBeachFarm(__instance))
return;
// change background track
if (FarmPatcher.ShouldUseBeachMusic())
Game1.changeMusicTrack("ocean", music_context: Game1.MusicContext.SubLocation);
}
/// <summary>A method called via Harmony after <see cref="Farm.resetSharedState"/>.</summary>
/// <param name="__instance">The farm instance.</param>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "The naming convention is defined by Harmony.")]
private static void After_ResetSharedState(GameLocation __instance)
{
if (!FarmPatcher.IsSmallBeachFarm(__instance))
return;
// toggle campfire (derived from StardewValley.Locations.Mountain:resetSharedState
Vector2 campfireTile = new Vector2(64, 22);
if (FarmPatcher.Config.AddCampfire)
{
if (!__instance.objects.ContainsKey(campfireTile))
{
__instance.objects.Add(campfireTile, new Torch(campfireTile, 146, true)
{
IsOn = false,
Fragility = SObject.fragility_Indestructable
});
}
}
else if (__instance.objects.TryGetValue(campfireTile, out SObject obj) && obj is Torch torch && torch.ParentSheetIndex == 146)
__instance.objects.Remove(campfireTile);
}
/// <summary>A method called via Harmony after <see cref="Farm.cleanupBeforePlayerExit"/>.</summary>
/// <param name="__instance">The farm instance.</param>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "The naming convention is defined by Harmony.")]
private static void After_CleanupBeforePlayerExit(GameLocation __instance)
{
if (!FarmPatcher.IsSmallBeachFarm(__instance))
return;
// change background track
if (FarmPatcher.ShouldUseBeachMusic())
Game1.changeMusicTrack("none", music_context: Game1.MusicContext.SubLocation);
}
/// <summary>A method called via Harmony after <see cref="GameLocation.getRandomTile"/>.</summary>
/// <param name="__instance">The farm instance.</param>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "The naming convention is defined by Harmony.")]
private static void After_GetRandomTile(GameLocation __instance, ref Vector2 __result)
{
if (!FarmPatcher.IsSmallBeachFarm(__instance))
return;
// reduce chance of ocean tiles in random tile selection, which makes things like beach crates much less likely than vanilla
Farm farm = (Farm)__instance;
int maxTileY = FarmPatcher.Config.EnableIslands ? farm.Map.Layers[0].LayerHeight : 31;
for (int i = 0; FarmPatcher.GetFishType(farm, (int)__result.X, (int)__result.Y) == FishType.Ocean && i < 250; i++)
__result = new Vector2(Game1.random.Next(farm.Map.Layers[0].LayerWidth), Game1.random.Next(maxTileY));
}
/// <summary>Get whether the Small Beach Farm's music should be overridden with the beach sounds.</summary>
private static bool ShouldUseBeachMusic()
{
return FarmPatcher.Config.UseBeachMusic && !Game1.isRaining;
}
}
}
| 50.442211 | 190 | 0.626718 | [
"MIT"
] | TehPers/StardewMods | SmallBeachFarm/Patches/FarmPatcher.cs | 10,038 | C# |
// Copyright (c) 2018 Aurigma Inc. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using Aurigma.PhotoKiosk.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Threading;
namespace Aurigma.PhotoKiosk
{
public partial class BluetoothLoadScreen : Page
{
private FindingPhotosStage _findingPhotosStage;
private bool _isDisposed;
private DispatcherTimer _timer;
private List<string> _bluetoothPaths;
private int _uploadedFilesCount;
public BluetoothLoadScreen()
{
if (ExecutionEngine.Instance != null)
Resources.MergedDictionaries.Add(ExecutionEngine.Instance.Resource);
InitializeComponent();
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(Constants.InactionTimerInterval);
_timer.Tick += TimerTickHandler;
_uploadedFilesCount = 0;
string instructionsText = (string)FindResource(Constants.HowToLoadPhotosUsingBluetoothTextKey);
if (instructionsText.Contains(Constants.BluetoothHostNamePlaceHolder))
{
_bluetoothDescription.Inlines.Add(new Run(instructionsText.Substring(0, instructionsText.IndexOf(Constants.SpecialKeyFramer))));
_bluetoothDescription.Inlines.Add(new Bold(new Underline(new Run(ExecutionEngine.Config.BluetoothHost.Value))));
_bluetoothDescription.Inlines.Add(new Run(instructionsText.Substring(instructionsText.IndexOf(Constants.SpecialKeyFramer) + Constants.BluetoothHostNamePlaceHolder.Length)));
}
else
_bluetoothDescription.Text = instructionsText;
_bluetoothPaths = new List<string>();
}
public BluetoothLoadScreen(FindingPhotosStage stage)
: this()
{
_findingPhotosStage = stage;
}
~BluetoothLoadScreen()
{
Dispose(false);
}
public void Dispose()
{
try
{
Dispose(true);
}
finally
{
GC.SuppressFinalize(this);
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
_isDisposed = true;
}
private void CheckDisposedState()
{
if (_isDisposed)
throw new ObjectDisposedException("SelectDeviceScreen");
}
private void LoadedEventHandler(object sender, RoutedEventArgs e)
{
_timer.Start();
_filesCountTextBlock.Text = (string)FindResource(Constants.ReadyToReceivePhotosTextKey);
_nextButton.IsEnabled = false;
_bluetoothPaths.Clear();
}
private void UnloadedEventHandler(object sender, RoutedEventArgs e)
{
_timer.Stop();
}
private void ButtonPrevStageClickHandler(object sender, RoutedEventArgs e)
{
CheckDisposedState();
_findingPhotosStage.SwitchToSelectDeviceScreen();
}
private void ButtonNextClickHandler(object sender, RoutedEventArgs e)
{
CheckDisposedState();
_findingPhotosStage.SelectedFolders = _bluetoothPaths;
_findingPhotosStage.SwitchToProcessScreen();
}
private void TimerTickHandler(object sender, EventArgs args)
{
int filesCount = GetFilesCount();
if (filesCount == 0)
{
_filesCountTextBlock.Text = (string)FindResource(Constants.ReadyToReceivePhotosTextKey);
_nextButton.IsEnabled = false;
}
else if (filesCount != _uploadedFilesCount)
{
_uploadedFilesCount = filesCount;
_filesCountTextBlock.Text = (string)FindResource(Constants.ReceivedPhotosCountTextKey) + _uploadedFilesCount.ToString();
_nextButton.IsEnabled = true;
ExecutionEngine.Instance.RegisterUserAction();
}
}
private int GetFilesCount()
{
int filesCount = 0;
var paths = new List<string>();
paths.Add(ExecutionEngine.Config.BluetoothFolder.Value);
while (paths.Count > 0)
{
if (System.IO.Directory.Exists(paths[0]))
{
_bluetoothPaths.Add(paths[0]);
var dirInfo = new DirectoryInfo(paths[0]);
paths.RemoveAt(0);
try
{
filesCount += dirInfo.GetFiles().Length;
foreach (DirectoryInfo subdirInfo in dirInfo.GetDirectories())
{
paths.Add(subdirInfo.FullName);
}
}
catch (Exception e)
{
ExecutionEngine.EventLogger.WriteExceptionInfo(e);
}
}
}
return filesCount;
}
}
} | 33.53125 | 189 | 0.578751 | [
"MIT"
] | aurigma/PhotoKiosk | PhotoKiosk/Stages/FindingPhotosStage/BluetoothLoadScreen.xaml.cs | 5,367 | C# |
using FD.SampleData.Data.Generators;
using FD.SampleData.Models.HumanResources;
using FD.SampleData.Models.Individual;
using FD.SampleData.Models.Production;
using FD.SampleData.Models.Purchasing;
using FD.SampleData.Models.Sales;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace FD.SampleData.Contexts
{
public class SalesDbContext : BaseDbContext
{
public virtual DbSet<Department> Departments { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<EmployeeDepartmentHistory> EmployeeDepartmentHistories { get; set; }
public virtual DbSet<EmployeePayHistory> EmployeePayHistories { get; set; }
public virtual DbSet<JobCandidate> JobCandidates { get; set; }
public virtual DbSet<Shift> Shifts { get; set; }
public virtual DbSet<Address> Addresses { get; set; }
public virtual DbSet<AddressType> AddressTypes { get; set; }
public virtual DbSet<BusinessEntity> BusinessEntities { get; set; }
public virtual DbSet<BusinessEntityAddress> BusinessEntityAddresses { get; set; }
public virtual DbSet<BusinessEntityContact> BusinessEntityContacts { get; set; }
public virtual DbSet<ContactType> ContactTypes { get; set; }
public virtual DbSet<CountryRegion> CountryRegions { get; set; }
public virtual DbSet<EmailAddress> EmailAddresses { get; set; }
public virtual DbSet<Password> Passwords { get; set; }
public virtual DbSet<Person> People { get; set; }
public virtual DbSet<PersonPhone> PersonPhones { get; set; }
public virtual DbSet<PhoneNumberType> PhoneNumberTypes { get; set; }
public virtual DbSet<StateProvince> StateProvinces { get; set; }
public virtual DbSet<BillOfMaterial> BillOfMaterials { get; set; }
public virtual DbSet<Culture> Cultures { get; set; }
public virtual DbSet<Illustration> Illustrations { get; set; }
public virtual DbSet<Location> Locations { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<ProductCategory> ProductCategories { get; set; }
public virtual DbSet<ProductCostHistory> ProductCostHistories { get; set; }
public virtual DbSet<ProductDescription> ProductDescriptions { get; set; }
public virtual DbSet<ProductInventory> ProductInventories { get; set; }
public virtual DbSet<ProductListPriceHistory> ProductListPriceHistories { get; set; }
public virtual DbSet<ProductModel> ProductModels { get; set; }
public virtual DbSet<ProductModelIllustration> ProductModelIllustrations { get; set; }
public virtual DbSet<ProductModelProductDescriptionCulture> ProductModelProductDescriptionCultures { get; set; }
public virtual DbSet<ProductPhoto> ProductPhotoes { get; set; }
public virtual DbSet<ProductProductPhoto> ProductProductPhotoes { get; set; }
public virtual DbSet<ProductReview> ProductReviews { get; set; }
public virtual DbSet<ProductSubcategory> ProductSubcategories { get; set; }
public virtual DbSet<ScrapReason> ScrapReasons { get; set; }
public virtual DbSet<TransactionHistory> TransactionHistories { get; set; }
public virtual DbSet<TransactionHistoryArchive> TransactionHistoryArchives { get; set; }
public virtual DbSet<UnitMeasure> UnitMeasures { get; set; }
public virtual DbSet<WorkOrder> WorkOrders { get; set; }
public virtual DbSet<WorkOrderRouting> WorkOrderRoutings { get; set; }
public virtual DbSet<ProductVendor> ProductVendors { get; set; }
public virtual DbSet<PurchaseOrderDetail> PurchaseOrderDetails { get; set; }
public virtual DbSet<PurchaseOrderHeader> PurchaseOrderHeaders { get; set; }
public virtual DbSet<ShipMethod> ShipMethods { get; set; }
public virtual DbSet<Vendor> Vendors { get; set; }
public virtual DbSet<CountryRegionCurrency> CountryRegionCurrencies { get; set; }
public virtual DbSet<CreditCard> CreditCards { get; set; }
public virtual DbSet<Currency> Currencies { get; set; }
public virtual DbSet<CurrencyRate> CurrencyRates { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<PersonCreditCard> PersonCreditCards { get; set; }
public virtual DbSet<SalesOrderDetail> SalesOrderDetails { get; set; }
public virtual DbSet<SalesOrderHeader> SalesOrderHeaders { get; set; }
public virtual DbSet<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReasons { get; set; }
public virtual DbSet<SalesPerson> SalesPersons { get; set; }
public virtual DbSet<SalesPersonQuotaHistory> SalesPersonQuotaHistories { get; set; }
public virtual DbSet<SalesReason> SalesReasons { get; set; }
public virtual DbSet<SalesTaxRate> SalesTaxRates { get; set; }
public virtual DbSet<SalesTerritory> SalesTerritories { get; set; }
public virtual DbSet<SalesTerritoryHistory> SalesTerritoryHistories { get; set; }
public virtual DbSet<ShoppingCartItem> ShoppingCartItems { get; set; }
public virtual DbSet<SpecialOffer> SpecialOffers { get; set; }
public virtual DbSet<SpecialOfferProduct> SpecialOfferProducts { get; set; }
public virtual DbSet<Store> Stores { get; set; }
public virtual DbSet<ProductDocument> ProductDocuments { get; set; }
public SalesDbContext()
{
}
public SalesDbContext(DbContextOptions<SalesDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Person>()
.HasMany<EmailAddress>()
.WithOne(e => e.Person);
modelBuilder.Entity<Person>()
.HasMany<PersonPhone>()
.WithOne(p => p.Person);
modelBuilder.Entity<Password>()
.HasOne<Person>()
.WithOne(p => p.Password)
.HasForeignKey<Password>(p => p.BusinessEntityID);
}
public override async Task Seed(int? seedSize)
{
// seed addresses and people
List<Address> addresses = await IndividualGenerator.GenerateAddresses();
await AddRangeAsync(addresses);
await SaveChangesAsync();
List<Person> people = await IndividualGenerator.GenerateIndividuals();
await AddRangeAsync(people);
await SaveChangesAsync();
}
}
}
| 55.495868 | 120 | 0.68965 | [
"MIT"
] | araujofrancisco/FD.DataProvider | FD.SampleData/Contexts/SalesDbContext.cs | 6,717 | C# |
using FS.Query.Scripts.SelectionScripts.Filters.Comparables;
using FS.Query.Scripts.SelectionScripts.Parameters;
using FS.Query.Scripts.SelectionScripts.Selects;
using FS.Query.Settings;
using System;
using System.Data;
using System.Text;
namespace FS.Query.Scripts.SelectionScripts
{
public class BuildedScript
{
private readonly string buildedScript;
public BuildedScript(
string buildedScript,
Select[] selectColumns,
ScriptParameters scriptParameters)
{
this.buildedScript = buildedScript;
SelectColumns = selectColumns;
this.ScriptParameters = scriptParameters;
}
public Select[] SelectColumns { get; }
public ScriptParameters ScriptParameters { get; }
public IDbCommand PrepareCommand(
DbSettings dbSettings,
ScriptParameters scriptParameters,
IDbConnection dbConnection)
{
var command = dbConnection.CreateCommand();
command.CommandText = AddParameters(dbSettings, scriptParameters, command);
command.CommandTimeout = 30;
command.CommandType = CommandType.Text;
return command;
}
private string AddParameters(DbSettings dbSettings, ScriptParameters scriptParameters, IDbCommand command)
{
var scriptBuilder = new StringBuilder(buildedScript);
foreach (var parameter in ScriptParameters.Parameters)
{
var parameterToInject = scriptParameters.Get(parameter.Key);
if (parameterToInject is null || parameter.Value != parameterToInject)
throw new Exception("The script parameters differ.");
if (parameterToInject is ComparableValue comparableValue)
{
var commandParameter = command.CreateParameter();
comparableValue.AddParameter(parameter.Key, commandParameter, dbSettings);
command.Parameters.Add(commandParameter);
continue;
}
else if (parameterToInject is ComparableEnumerable comparableEnumerable)
{
var values = comparableEnumerable.BuildAsString(dbSettings).ToString();
scriptBuilder.Replace(parameter.Key, values);
continue;
}
}
return scriptBuilder.ToString();
}
}
}
| 35.394366 | 114 | 0.619976 | [
"MIT"
] | bh-schmidt/FS.Query | src/FS.Query/Scripts/SelectionScripts/BuildedScript.cs | 2,515 | C# |
/*
Copyright (c) 2016 Roman Atachiants
Copyright (c) 2011-2013 Mike Jones, Matt Weimer
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Source code is modified from Mike Jones's JSON Serialization and Deserialization library (https://www.ghielectronics.com/community/codeshare/entry/357)
using System;
using System.Collections;
using System.Globalization;
using System.Text;
#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
using Microsoft.SPOT;
#endif
namespace Emitter
{
/// <summary>
/// Parses JSON strings into a Hashtable. The Hashtable contains one or more key/value pairs
/// (DictionaryEntry objects). Each key is the name of a property that (hopefully) exists
/// in the class object that it represents. Each value is one of the following:
/// Hastable - Another list of one or more DictionaryEntry objects, essentially representing
/// a property that is another class.
/// ArrayList - An array of one or more objects, which themselves can be one of the items
/// enumerated in this list.
/// Value Type - an actual value, such as a string, int, bool, Guid, DateTime, etc
/// </summary>
internal class JsonParser
{
protected enum Token
{
None = 0,
ObjectBegin, // {
ObjectEnd, // }
ArrayBegin, // [
ArrayEnd, // ]
PropertySeparator, // :
ItemsSeparator, // ,
StringType, // " <-- string of characters
NumberType, // 0-9 <-- number, fixed or floating point
BooleanTrue, // true
BooleanFalse, // false
NullType // null
}
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a Hashtable, a double, long, a string, null, true, or false</returns>
public static object JsonDecode(string json)
{
bool success = true;
return JsonDecode(json, ref success);
}
/// <summary>
/// Parses the string json into a value; and fills 'success' with the successfullness of the parse.
/// </summary>
/// <param name="json">A JSON string.</param>
/// <param name="success">Successful parse?</param>
/// <returns>An ArrayList, a Hashtable, a double, a long, a string, null, true, or false</returns>
public static object JsonDecode(string json, ref bool success)
{
success = true;
if (json != null)
{
char[] charArray = json.ToCharArray();
int index = 0;
object value = ParseValue(charArray, ref index, ref success);
return value;
}
else
{
return null;
}
}
protected static Hashtable ParseObject(char[] json, ref int index, ref bool success)
{
Hashtable table = new Hashtable();
Token token;
// {
NextToken(json, ref index);
bool done = false;
while (!done)
{
token = LookAhead(json, index);
if (token == Token.None)
{
success = false;
return null;
}
else if (token == Token.ItemsSeparator)
{
NextToken(json, ref index);
}
else if (token == Token.ObjectEnd)
{
NextToken(json, ref index);
return table;
}
else
{
// name
string name = ParseString(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != Token.PropertySeparator)
{
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
table[name] = value;
}
}
return table;
}
protected static ArrayList ParseArray(char[] json, ref int index, ref bool success)
{
ArrayList array = new ArrayList();
// [
NextToken(json, ref index);
bool done = false;
while (!done)
{
Token token = LookAhead(json, index);
if (token == Token.None)
{
success = false;
return null;
}
else if (token == Token.ItemsSeparator)
{
NextToken(json, ref index);
}
else if (token == Token.ArrayEnd)
{
NextToken(json, ref index);
break;
}
else
{
object value = ParseValue(json, ref index, ref success);
if (!success)
{
return null;
}
array.Add(value);
}
}
return array;
}
protected static object ParseValue(char[] json, ref int index, ref bool success)
{
switch (LookAhead(json, index))
{
case Token.StringType:
return ParseString(json, ref index, ref success);
case Token.NumberType:
return ParseNumber(json, ref index, ref success);
case Token.ObjectBegin:
return ParseObject(json, ref index, ref success);
case Token.ArrayBegin:
return ParseArray(json, ref index, ref success);
case Token.BooleanTrue:
NextToken(json, ref index);
return true;
case Token.BooleanFalse:
NextToken(json, ref index);
return false;
case Token.NullType:
NextToken(json, ref index);
return null;
case Token.None:
break;
}
success = false;
return null;
}
protected static string ParseString(char[] json, ref int index, ref bool success)
{
StringBuilder s = new StringBuilder();
EatWhitespace(json, ref index);
// "
char c = json[index++];
bool complete = false;
while (!complete)
{
if (index == json.Length)
{
break;
}
c = json[index++];
if (c == '"')
{
complete = true;
break;
}
else if (c == '\\')
{
if (index == json.Length)
{
break;
}
c = json[index++];
if (c == '"')
{
s.Append('"');
}
else if (c == '\\')
{
s.Append('\\');
}
else if (c == '/')
{
s.Append('/');
}
else if (c == 'b')
{
s.Append('\b');
}
else if (c == 'f')
{
s.Append('\f');
}
else if (c == 'n')
{
s.Append('\n');
}
else if (c == 'r')
{
s.Append('\r');
}
else if (c == 't')
{
s.Append('\t');
}
else if (c == 'u')
{
int remainingLength = json.Length - index;
if (remainingLength >= 4)
{
// parse the 32 bit hex into an integer codepoint
uint codePoint;
if (!(success = Utils.TryParseUInt32(new string(json, index, 4), NumberEncoding.Hexadecimal, out codePoint)))
{
return "";
}
// convert the integer codepoint to a unicode char and add to string
s.Append(Utils.ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
}
else
{
break;
}
}
}
else
{
s.Append(c);
}
}
if (!complete)
{
success = false;
return null;
}
return s.ToString();
}
/// <summary>
/// Determines the type of number (int, double, etc) and returns an object
/// containing that value.
/// </summary>
/// <param name="json"></param>
/// <param name="index"></param>
/// <param name="success"></param>
/// <returns></returns>
protected static object ParseNumber(char[] json, ref int index, ref bool success)
{
EatWhitespace(json, ref index);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
// We now have the number as a string. Parse it to determine the type of number.
string value = new string(json, index, charLength);
// Since the Json doesn't contain the Type of the property, and since multiple number
// values can fit in the various Types (e.g. 33 decimal fits in an Int16, UInt16,
// Int32, UInt32, Int64, and UInt64), we need to be a bit smarter in how we deal with
// the size of the number, and also the case (negative or positive).
object result = null;
string dot = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
string comma = CultureInfo.CurrentUICulture.NumberFormat.NumberGroupSeparator;
string minus = CultureInfo.CurrentUICulture.NumberFormat.NegativeSign;
string plus = CultureInfo.CurrentUICulture.NumberFormat.PositiveSign;
if (value.Contains(dot) || value.Contains(comma) || value.Contains("e") || value.Contains("E"))
{
// We have either a double or a float. Force it to be a double
// and let the deserializer unbox it into the proper size.
result = Double.Parse(new string(json, index, charLength));
}
else
{
NumberEncoding style = NumberEncoding.Decimal;
if(value.StartsWith("0x") || (value.IndexOfAny(new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F' }) >= 0))
{
style = NumberEncoding.Hexadecimal;
}
result = Utils.ParseInt64(value, style);
}
index = lastIndex + 1;
return result;
}
protected static int GetLastIndexOfNumber(char[] json, int index)
{
int lastIndex;
for (lastIndex = index; lastIndex < json.Length; lastIndex++) {
if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) {
break;
}
}
return lastIndex - 1;
}
protected static void EatWhitespace(char[] json, ref int index)
{
for (; index < json.Length; index++) {
if (" \t\n\r".IndexOf(json[index]) == -1) {
break;
}
}
}
protected static Token LookAhead(char[] json, int index)
{
int saveIndex = index;
return NextToken(json, ref saveIndex);
}
protected static Token NextToken(char[] json, ref int index)
{
EatWhitespace(json, ref index);
if (index == json.Length) {
return Token.None;
}
char c = json[index];
index++;
switch (c) {
case '{':
return Token.ObjectBegin;
case '}':
return Token.ObjectEnd;
case '[':
return Token.ArrayBegin;
case ']':
return Token.ArrayEnd;
case ',':
return Token.ItemsSeparator;
case '"':
return Token.StringType;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '-':
return Token.NumberType;
case ':':
return Token.PropertySeparator;
}
index--;
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5) {
if (json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
json[index + 4] == 'e') {
index += 5;
return Token.BooleanFalse;
}
}
// true
if (remainingLength >= 4) {
if (json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e') {
index += 4;
return Token.BooleanTrue;
}
}
// null
if (remainingLength >= 4) {
if (json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l') {
index += 4;
return Token.NullType;
}
}
return Token.None;
}
}
}
| 24.975052 | 154 | 0.596354 | [
"EPL-1.0"
] | ContinuumLR/csharp | Emitter/Json/JsonParser.cs | 12,013 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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("AWSSDK.Organizations")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Organizations. AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Organizations. AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS Organizations. AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS Organizations. AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- AWS Organizations. AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- AWS Organizations. AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.3.103.13")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 56.661017 | 280 | 0.784325 | [
"Apache-2.0"
] | costleya/aws-sdk-net | sdk/src/Services/Organizations/Properties/AssemblyInfo.cs | 3,343 | C# |
/* Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using IBApi;
using System.Collections;
namespace TWSLib
{
[ComVisible(true), Guid("D85B33C9-7347-4C2A-AA85-DA9E34F27D10")]
public interface IPriceIncrementList
{
[DispId(-4)]
object _NewEnum { [return: MarshalAs(UnmanagedType.IUnknown)] get; }
[DispId(0)]
object this[int index] { [return: MarshalAs(UnmanagedType.IDispatch)] get; }
[DispId(1)]
int Count { get; }
[DispId(2)]
[return: MarshalAs(UnmanagedType.IDispatch)]
object AddEmpty();
[DispId(3)]
[return: MarshalAs(UnmanagedType.IDispatch)]
object Add(ComPriceIncrement cpi);
}
[ComVisible(true), ClassInterface(ClassInterfaceType.None)]
public class ComPriceIncrementList : IPriceIncrementList
{
private ComList<ComPriceIncrement, IBApi.PriceIncrement> PriceIncrementList;
public ComPriceIncrementList() : this(null) { }
public ComPriceIncrementList(PriceIncrement[] priceIncrements)
{
this.PriceIncrementList = (priceIncrements.Length > 0) ? new ComList<ComPriceIncrement, IBApi.PriceIncrement>(new List<IBApi.PriceIncrement>(priceIncrements)) : null;
}
public object _NewEnum
{
get { return PriceIncrementList.GetEnumerator(); }
}
public object this[int index]
{
get { return PriceIncrementList[index]; }
}
public int Count
{
get { return PriceIncrementList.Count; }
}
public object AddEmpty()
{
var rval = new ComPriceIncrement();
PriceIncrementList.Add(rval);
return rval;
}
public object Add(ComPriceIncrement comPriceIncrement)
{
var rval = comPriceIncrement;
PriceIncrementList.Add(rval);
return rval;
}
}
}
| 28.701299 | 178 | 0.633937 | [
"MIT"
] | SolomatovS/Tws2UniFeeder | csharpclient/activex/ControlImpl/IPriceIncrementList.cs | 2,212 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using static Root;
public readonly struct NativeFunction : INativeFunction
{
public MemoryAddress Address {get;}
public NativeModule Source {get;}
public string Name {get;}
[MethodImpl(Inline)]
public NativeFunction(NativeModule src, MemoryAddress @base, string name)
{
Source = src;
Address = @base;
Name = name;
}
public string Format()
=> Address.Format();
}
} | 25.645161 | 81 | 0.460377 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/core/src/native/NativeFunction.cs | 795 | C# |
using System.IO;
using UnSave.Types;
namespace UnSave.Serialization
{
public interface IUnrealStructSerializer
{
IUnrealProperty DeserializeStruct(BinaryReader reader);
void SerializeStruct(IUnrealProperty structProp, BinaryWriter writer);
bool SupportsType(string type);
}
} | 26.083333 | 78 | 0.744409 | [
"MIT"
] | agc93/unsave | src/UnSave/Serialization/IUnrealStructSerializer.cs | 315 | C# |
using System;
namespace System.Data.SQLiteCipher
{
internal static class SqliteConnectionExtensions
{
public static int ExecuteNonQuery(
this SqliteConnection connection,
string commandText,
params SqliteParameter[] parameters)
{
using var command = connection.CreateCommand();
command.CommandText = commandText;
command.Parameters.AddRange(parameters);
return command.ExecuteNonQuery();
}
public static T ExecuteScalar<T>(
this SqliteConnection connection,
string commandText,
params SqliteParameter[] parameters)
=> (T)connection.ExecuteScalar(commandText, parameters);
private static object ExecuteScalar(
this SqliteConnection connection,
string commandText,
params SqliteParameter[] parameters)
{
using var command = connection.CreateCommand();
command.CommandText = commandText;
command.Parameters.AddRange(parameters);
return command.ExecuteScalar();
}
}
}
| 30.342105 | 68 | 0.618387 | [
"MIT"
] | erikzhouxin/NSqliteCipher | src/SQLiteCipher/SqliteConnectionExtensions.cs | 1,153 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using DeviceTesting.Pages.FilledCheckbox;
using DeviceTesting.Pages.FloatingMultiButton;
using Xamarin.Forms;
namespace DeviceTesting
{
public class FunctionalityNavigationService : IFunctionalityNavigationService
{
private readonly INavigation m_navigation;
public FunctionalityNavigationService(INavigation navigation)
{
m_navigation = navigation;
}
private static Page GetFunctionality(string functionality)
{
switch (functionality)
{
case "FilledCheckBox":
return new FilledCheckBoxPage();
case "FloatingMultiButton":
return new FloatingMultiButtonPage();
default:
return new MainPage();
}
}
public async Task PushFunctionality(string functionality)
{
await m_navigation.PushAsync(GetFunctionality(functionality));
}
}
public interface IFunctionalityNavigationService
{
Task PushFunctionality(string functionality);
}
}
| 29.093023 | 82 | 0.618705 | [
"MIT"
] | haavamoa/FirstUIFramework.Forms | src/DeviceTesting/DeviceTesting/FunctionalityNavigationService.cs | 1,253 | C# |
// ============================================================================
// FileName: PasswordHash.cs
//
// Description:
// This class deals with storing and verifying password hashes.
//
// Author(s):
// Aaron Clauson (aaron@sipsorcery.com)
//
// History:
// 13 Jan 2012 Aaron Clauson Created. Borrowed some code snippets from
// http://code.google.com/p/stackid/source/browse/OpenIdProvider/Current.cs#1135.
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
// =============================================================================
using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace SIPSorcery.Sys
{
public class PasswordHash
{
private const int
RFC289_MINIMUM_ITERATIONS =
5000; // The minimum number of iterations to use when deriving the password hash. This slows the algorithm down to help mitigate against brute force and rainbow attacks.
private const int SALT_SIZE = 16;
private static RNGCryptoServiceProvider _randomProvider = new RNGCryptoServiceProvider();
/// <summary>
/// Generates a salt that can be used to generate a password hash. The salt is a combination of a block of bytes to represent the
/// salt entropy and an integer that represents the iteration count to feed into the RFC289 algorithm used to derive the password hash.
/// The iterations count is used to slow down the hash generating algorithm to mitigate brute force and rainbow table attacks.
/// </summary>
/// <param name="explicitIterations">The number of iterations used to derive the password bytes. Must be greater than the constant specifying the minimum iterations.</param>
/// <returns>A string it the format iterations.salt.</returns>
public static string GenerateSalt(int? explicitIterations = null)
{
if (explicitIterations.HasValue && explicitIterations.Value < RFC289_MINIMUM_ITERATIONS)
{
throw new ArgumentException("Cannot be less than " + RFC289_MINIMUM_ITERATIONS, "explicitIterations");
}
byte[] salt = new byte[SALT_SIZE];
_randomProvider.GetBytes(salt);
var iterations = (explicitIterations ?? RFC289_MINIMUM_ITERATIONS).ToString("X");
return iterations + "." + Convert.ToBase64String(salt);
}
/// <summary>
/// Generates the password hash from the password and salt. THe salt must be in the format iterations.salt.
/// </summary>
/// <param name="value">The value to generate a hash for.</param>
/// <param name="salt">The salt (and iteration count) to generate the hash with.</param>
/// <returns>The hash.</returns>
public static string Hash(string value, string salt)
{
var i = salt.IndexOf('.');
var iters = int.Parse(salt.Substring(0, i), NumberStyles.HexNumber);
salt = salt.Substring(i + 1);
using (var pbkdf2 =
new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(value), Convert.FromBase64String(salt), iters))
{
var key = pbkdf2.GetBytes(24);
return Convert.ToBase64String(key);
}
}
}
} | 44.076923 | 187 | 0.610239 | [
"MIT"
] | 13927729580/AKStream | SipSorcery/sys/Crypto/PasswordHash.cs | 3,440 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SwiftFramework.Utils
{
[RequireComponent(typeof(Animator))]
public class ManualAnimator : MonoBehaviour
{
private Animator anim;
private Animator Animator => anim = anim ?? GetComponent<Animator>();
[SerializeField] private string[] stateNames = new string[0];
[SerializeField] [HideInInspector] private int[] stateHashes = new int[0];
private void OnValidate()
{
#if UNITY_EDITOR
UnityEditor.Animations.AnimatorController ac = GetComponent<Animator>().runtimeAnimatorController as UnityEditor.Animations.AnimatorController;
var states = ac.layers[0].stateMachine.states;
stateHashes = new int[states.Length];
stateNames = new string[states.Length];
for (int i = 0; i < states.Length; i++)
{
stateHashes[i] = states[i].state.nameHash;
stateNames[i] = states[i].state.name;
}
#endif
}
public bool IsAnimating
{
get => Animator.enabled;
set => Animator.enabled = value;
}
private float Normalize(float time)
{
if (time < 0)
{
return 0;
}
if (Mathf.Approximately(time, 1))
{
return .999f;
}
return time;
}
public void Evaluate(float timeNormalized, string stateName)
{
Animator.Play(stateName, 0, Normalize(timeNormalized));
}
public void Evaluate(float timeNormalized, int stateIndex = 0)
{
if(Mathf.Approximately(timeNormalized, 1))
{
timeNormalized = .99f;
}
Animator.Play(stateHashes[stateIndex], 0, Normalize(timeNormalized));
}
}
}
| 29.30303 | 155 | 0.563082 | [
"MIT"
] | dimaswift/swift-framework | Runtime/Utils/ManualAnimator.cs | 1,936 | C# |
//
// System.Net.NetworkInformation.PingException
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2006 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System;
using System.Collections;
using System.Runtime.Serialization;
namespace System.Net.NetworkInformation {
[Serializable]
public class PingException : InvalidOperationException {
public PingException (string message)
: base (message)
{
}
public PingException (string message, Exception innerException)
: base (message, innerException)
{
}
protected PingException (SerializationInfo serializationInfo, StreamingContext streamingContext)
: base (serializationInfo, streamingContext)
{
}
}
}
#endif
| 33.909091 | 99 | 0.735121 | [
"MIT"
] | GrapeCity/pagefx | mono/mcs/class/System/System.Net.NetworkInformation/PingException.cs | 1,865 | C# |
using System;
class Wave_6
{
public static void Main(string[] args)
{
int waveHeight = 4; //change value to increase or decrease the height of wave
int wL = 4; //wave length->change value to increase or decrease the length of wave
int wH = waveHeight - 1; //for loop cond.
int x = wH; //if cond for printing
int cp; //print char
for (int i = 0; i <= wH; i++)
{
cp = 'Z'; // set print char.
for (int j = 0; j <= wH * wL * 2; j++)
{
if (j % (wH * 2) == x || j % (wH * 2) == wH + i)
{
Console.Write((char)cp);
}
else
{
Console.Write(" ");
}
cp--; // decrement print char
/reset print char to 'Z'/
if (cp < 'A')
{
cp = cp + 26;
}
}
x--;
Console.WriteLine();
}
Console.ReadKey(true);
}
}
| 16.08 | 84 | 0.511194 | [
"MIT"
] | Ankur-586/Printing-Pattern-Programs | CSharpPatternPrograms/WavePatterns/Program6.cs | 806 | C# |
using NatCruise.Design.Data;
using NatCruise.Design.Models;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Input;
using NatCruise.Util;
namespace NatCruise.Design.ViewModels
{
public class StratumTemplateFieldsViewModel : ViewModelBase
{
private StratumTemplate _stratumTemplate;
private ObservableCollection<StratumTemplateTreeFieldSetup> _fieldSetups;
private IEnumerable<TreeField> _treeFields;
private StratumTemplateTreeFieldSetup _selectedTreeFieldSetup;
private ICommand _moveUpCommand;
private ICommand _moveDownCommand;
private ICommand _addCommand;
private ICommand _removeCommand;
public StratumTemplateFieldsViewModel(ITemplateDataservice templateDataservice)
{
TemplateDataservice = templateDataservice ?? throw new ArgumentNullException(nameof(templateDataservice));
TreeFields = TemplateDataservice.GetTreeFields();
}
public ICommand AddCommand => _addCommand ??= new DelegateCommand<TreeField>(AddTreeFieldSetup);
public ICommand RemoveCommand => _removeCommand ??= new DelegateCommand<StratumTemplateTreeFieldSetup>(RemoveTreeFieldSetup);
public ICommand MoveUpCommand => _moveUpCommand ??= new DelegateCommand<StratumTemplateTreeFieldSetup>(MoveUp);
public ICommand MoveDownCommand => _moveDownCommand ??= new DelegateCommand<StratumTemplateTreeFieldSetup>(MoveDown);
public IEnumerable<TreeField> TreeFields
{
get => _treeFields;
set
{
SetProperty(ref _treeFields, value);
RaisePropertyChanged(nameof(AvalibleTreeFields));
}
}
public IEnumerable<TreeField> AvalibleTreeFields
{
get
{
if(TreeFields == null) { return null; }
if (TreeFieldSetups == null || TreeFieldSetups.Count == 0)
{ return TreeFields; }
else
{
var takenTreeFields = TreeFieldSetups.Select(x => x.Field).ToArray();
return TreeFields.Where(x => takenTreeFields.Contains(x.Field) == false)
.ToArray();
}
}
}
public ObservableCollection<StratumTemplateTreeFieldSetup> TreeFieldSetups
{
get => _fieldSetups;
set => SetProperty(ref _fieldSetups, value);
}
public ITemplateDataservice TemplateDataservice { get; }
public StratumTemplateTreeFieldSetup SelectedTreeFieldSetup
{
get => _selectedTreeFieldSetup;
set
{
if (_selectedTreeFieldSetup != null)
{ _selectedTreeFieldSetup.PropertyChanged += SelectedTreeFieldSetup_PropertyChanged; }
SetProperty(ref _selectedTreeFieldSetup, value);
if (value != null)
{
value.PropertyChanged -= SelectedTreeFieldSetup_PropertyChanged;
var dbType = TreeFields.Where(x => x.Field == value.Field).SingleOrDefault()?.DbType;
IsDefaultReal = string.Compare(dbType, "REAL", true) == 0;
IsDefaultInt = string.Compare(dbType, "INTEGER", true) == 0;
IsDefaultBoolean = string.Compare(dbType, "BOOLEAN", true) == 0;
IsDefaultText = string.Compare(dbType, "TEXT", true) == 0;
}
else
{
IsDefaultReal = false;
IsDefaultInt = false;
IsDefaultBoolean = false;
IsDefaultText = false;
}
RaisePropertyChanged(nameof(IsDefaultBoolean));
RaisePropertyChanged(nameof(IsDefaultInt));
RaisePropertyChanged(nameof(IsDefaultReal));
RaisePropertyChanged(nameof(IsDefaultText));
}
}
public bool IsDefaultReal { get; set; }
public bool IsDefaultInt { get; set; }
public bool IsDefaultBoolean { get; set; }
public bool IsDefaultText { get; set; }
public StratumTemplate StratumTemplate
{
get => _stratumTemplate;
set
{
SetProperty(ref _stratumTemplate, value);
LoadFieldSetups();
}
}
protected void LoadFieldSetups()
{
var stratumTemplateName = StratumTemplate?.StratumTemplateName;
if (stratumTemplateName != null)
{
var fieldSetups = TemplateDataservice.GetStratumTemplateTreeFieldSetups(stratumTemplateName);
TreeFieldSetups = new ObservableCollection<StratumTemplateTreeFieldSetup>(fieldSetups);
}
else
{
TreeFieldSetups = new ObservableCollection<StratumTemplateTreeFieldSetup>();
}
RaisePropertyChanged(nameof(AvalibleTreeFields));
}
private void SelectedTreeFieldSetup_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var sttfs = (StratumTemplateTreeFieldSetup)sender;
if(sttfs is null) { return; }
TemplateDataservice.UpsertStratumTemplateTreeFieldSetup(sttfs);
}
public void AddTreeFieldSetup(TreeField treeField)
{
if (treeField == null) { return; }
var stratumTemplateName = StratumTemplate?.StratumTemplateName;
var newtfsd = new StratumTemplateTreeFieldSetup()
{
Field = treeField.Field,
FieldOrder = TreeFieldSetups.Count,
StratumTemplateName = stratumTemplateName,
};
TemplateDataservice.UpsertStratumTemplateTreeFieldSetup(newtfsd);
TreeFieldSetups.Add(newtfsd);
RaisePropertyChanged(nameof(AvalibleTreeFields));
}
public void RemoveTreeFieldSetup(StratumTemplateTreeFieldSetup tfsd)
{
if (tfsd is null) { throw new ArgumentNullException(nameof(tfsd)); }
TemplateDataservice.DeleteStratumTemplateTreeFieldSetup(tfsd);
TreeFieldSetups.Remove(tfsd);
}
public void MoveUp(StratumTemplateTreeFieldSetup tfsd)
{
if (tfsd == null) { return; }
var selectedIndex = TreeFieldSetups.IndexOf(tfsd);
if (selectedIndex == TreeFieldSetups.Count - 1) { return; }
var newIndex = selectedIndex + 1;
var otherTfsd = TreeFieldSetups[newIndex];
tfsd.FieldOrder = newIndex;
otherTfsd.FieldOrder = selectedIndex;
TemplateDataservice.UpsertStratumTemplateTreeFieldSetup(tfsd);
TemplateDataservice.UpsertStratumTemplateTreeFieldSetup(otherTfsd);
TreeFieldSetups.Move(selectedIndex, newIndex);
}
public void MoveDown(StratumTemplateTreeFieldSetup tfsd)
{
if (tfsd == null) { return; }
var selectedIndex = TreeFieldSetups.IndexOf(tfsd);
if (selectedIndex < 1) { return; }
var newIndex = selectedIndex - 1;
var otherTfsd = TreeFieldSetups[newIndex];
tfsd.FieldOrder = newIndex;
otherTfsd.FieldOrder = selectedIndex;
TemplateDataservice.UpsertStratumTemplateTreeFieldSetup(tfsd);
TemplateDataservice.UpsertStratumTemplateTreeFieldSetup(otherTfsd);
TreeFieldSetups.Move(selectedIndex, newIndex);
}
}
} | 38.914573 | 133 | 0.615057 | [
"CC0-1.0"
] | FMSC-Measurements/NatCruise | src/NatCruise.Design/ViewModels/StratumTemplateFieldsViewModel.cs | 7,746 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
namespace RLib.DB.Mig
{
public class DataMig
{
public bool isrunning { get; set; }
List<DbStructure.KVModel> tables = new List<DbStructure.KVModel>();
List<TableMig> tablemigs = new List<TableMig>();
Config.ImportActionModel actmodel = null;
Stopwatch sw = new Stopwatch();
public void GetSpeed(out long avgspeed, out long lastspeed)
{
avgspeed = 0;
lastspeed = 0;
long allcount = tablemigs.Sum(x => x.currentprocesscount);
double scound = sw.Elapsed.TotalSeconds;
scound = scound <= 0 ? 1 : scound;
avgspeed = (int)(allcount / scound);
double se = scound - lastseconds;
if (se != 0)
{
lastspeed = (int)((allcount - lastitemcount) / se);
}
else
{
lastspeed = allcount - lastitemcount;
}
lastitemcount = allcount;
lastseconds = scound;
}
Thread mainthread = null;
public bool finishedinit = false;
public double processmins { get { return sw.Elapsed.TotalMinutes; } }
public DataMig(Config.ImportActionModel actmodel)
{
this.actmodel = actmodel;
using (var dbconn1 = DbConn.CreateConn(DbType.SQLSERVER, actmodel.database1.source, actmodel.database1.port, actmodel.database1.database, actmodel.database1.userid, actmodel.database1.password))
{
dbconn1.Open();
DbStructure.IDbStructure dbstru = new DbStructure.DbStructureSqlServer();
tables = dbstru.GetTables(dbconn1);
}
if (actmodel.excepttables != null)
{
foreach (var a in actmodel.excepttables)
{
tables.RemoveAll(x => x.name == a);
}
}
foreach (var a in tables)
{
TableMig tm = new TableMig(actmodel, a.name);
tablemigs.Add(tm);
}
}
long lastitemcount = 0;
double lastseconds = 0;
public void Start()
{
sw.Restart();
mainthread = new Thread(() =>
{
//==
try
{
finishedinit = false;
Config.Log.Write("正在初始化...");
foreach (var tm in tablemigs)
{
tm.Step1_Syn();
}
Config.Log.Write("初始化完成!");
finishedinit = true;
Config.Log.Write("正在按表开始数据迁移...");
while (true)
{
int rcount = tablemigs.Count(x => x.runstatus == 1);
if (rcount < actmodel.importthreadcount)
{
var torun = tablemigs.Where(x => x.runstatus == 0).Take(actmodel.importthreadcount - rcount);
foreach (var a in torun)
{
a.Start();
}
}
int ncount = tablemigs.Count(x => x.runstatus == 0);
if (ncount == 0)
break;
else
Thread.Sleep(TimeSpan.FromSeconds(1));
}
Config.Log.Write("所有表数据迁移已开启完成!");
}
catch (Exception ex)
{
Config.Log.Error("启动出错!{0}", ex.Message);
}
});
mainthread.IsBackground = true;
mainthread.Start();
isrunning = true;
}
public void Stop()
{
if (mainthread != null)
{
try { mainthread.Abort(); mainthread = null; }
catch { }
}
foreach (var a in tablemigs)
{
try { a.Stop(); }
catch { }
}
sw.Stop();
isrunning = false;
}
public List<Config.MigDataProcessModel> GetProcessTableBar()
{
//DataTable tb = new DataTable();
//tb.Columns.Add(new DataColumn() { ColumnName = "tablename", Caption = "表名", DataType = typeof(string) });
//tb.Columns.Add(new DataColumn() { ColumnName = "totalitemcount", Caption = "总记录数", DataType = typeof(string) });
//tb.Columns.Add(new DataColumn() { ColumnName = "successcount", Caption = "已处理记录数", DataType = typeof(string) });
//tb.Columns.Add(new DataColumn() { ColumnName = "processpercent", Caption = "处理百分比", DataType = typeof(string) });
//tb.Columns.Add(new DataColumn() { ColumnName = "remaintime", Caption = "剩余时间", DataType = typeof(string) });
//tb.Columns.Add(new DataColumn() { ColumnName = "status", Caption = "状态", DataType = typeof(string) });
List<Config.MigDataProcessModel> tb = new List<Config.MigDataProcessModel>();
foreach (var a in tablemigs)
{
Config.MigDataProcessModel dr = new Config.MigDataProcessModel();
long succ_count = a.successcount;
long curr_pro_count = a.currentprocesscount;
long all_count = a.allitemcount;
dr.tablename = a.tablename;
dr.totalitemcount = a.allitemcount;
dr.waitcount = a.waitcount;
dr.successcount = succ_count + curr_pro_count;
dr.rowbuffercount = a.rowbuffercount;
dr.execbuffercount = a.execbuffercount;
if (all_count > 0)
{
dr.processpercent = (succ_count + curr_pro_count) * 100 / all_count;
}
else
{
dr.processpercent = finishedinit ? 100 : 0;
}
long reamin_count = all_count - curr_pro_count - succ_count;
double remain_percent = 0;
if (curr_pro_count > 0)
{
remain_percent = ((double)reamin_count) / curr_pro_count;
dr.remainmins = a.currentprocesstime.Elapsed.TotalMinutes * remain_percent;
}
else
{
if (a.allitemcount == succ_count + curr_pro_count)
{
dr.remainmins = 0;
}
else
{
dr.remainmins = -1;
}
}
dr.statuscode = a.runstatus;
switch (a.runstatus)
{
case -1:
dr.statusmsg = "异常";
break;
case 0:
dr.statusmsg = "未开始";
break;
case 1:
dr.statusmsg = "运行中";
break;
case 2:
dr.statusmsg = "已完成(停止,用时" + a.currentprocesstime.Elapsed.TotalMinutes.ToString("0.00") + "mins)";
break;
default:
dr.statusmsg = "未知状态" + a.runstatus.ToString();
break;
}
tb.Add(dr);
}
return tb;
}
}
public class TableMig
{
public int runstatus { get; private set; }
//public int processpercent { get; set; }
public long currentprocesscount { get; set; }
public long successcount { get; set; }
public long allitemcount { get; set; }
public long waitcount { get { return listdata.Count + listinsert.Sum(x => x.count); } }
public long rowbuffercount { get { return listdata.Count; } }
public long execbuffercount { get { return listinsert.Count; } }
public Stopwatch currentprocesstime = new Stopwatch();
DbStructure.STable tablestru;
// DbConn dbconn1 = null;
// DbConn dbconn2 = null;
Config.ImportActionModel actmodel = null;
bool getdata_complet = false;
bool preparedata_complet = false;
const int Buffer_Page_Count = 3;
const int Buffer_Exec_Count = 5;
// int setdata_pagesize = 1000;
int beginindex = 0;
public string tablename = "";
List<DataRow> listdata = new List<DataRow>();
List<Config.ExecModel> listinsert = new List<Config.ExecModel>();
object lock_rows = new object();
object lock_listinsert = new object();
public TableMig(Config.ImportActionModel actmodel, string tablename)
{
this.actmodel = actmodel;
this.tablename = tablename;
}
Thread mainthread = null;
Thread getdatathread = null;
Thread setdatathread = null;
Thread preparethread = null;
int zero_count = 0;
DbConn getdataconn = null;
private void GetDataAction()
{
if (getdata_complet)
return;
int getdata_pagesize = 20000;
lock (actmodel.lockobjofcus)
{
if (actmodel.cutomsactions != null && actmodel.cutomsactions.Exists(x => x.tablename == tablename))
{
getdata_pagesize = actmodel.cutomsactions.FirstOrDefault(x => x.tablename == tablename).getpagesize;
}
else if (actmodel.getpagesize > 0)
{
getdata_pagesize = actmodel.getpagesize;
}
}
if (listdata.Count > getdata_pagesize * Buffer_Page_Count)
{
//Config.Log.Write("GetDataAction 空转");
return;
}
if (listdata.Count == 0)
{
zero_count++;
}
else
{
zero_count = 0;
}
if (zero_count >= 2)
{
zero_count = 0;
getdata_pagesize = 2 * getdata_pagesize;
}
if (getdataconn == null)
{
getdataconn = DbConn.CreateConn(DbType.SQLSERVER, actmodel.database1.source, actmodel.database1.port, actmodel.database1.database, actmodel.database1.userid, actmodel.database1.password);
getdataconn.Open();
}
List<ProcedureParameter> paras = new List<ProcedureParameter>();
string sql = "select * from (SELECT ROW_NUMBER() over (order by {0}) as rownumber,* FROM {1} {2}) A where A.rownumber between @beginindex and @endindex";
string order_con = "";
if (tablestru.primarykey != null)
{
foreach (var a in tablestru.primarykey.columns)
{
order_con += a.name + " asc,";
}
}
else
{
order_con += " getdate()";
}
//else if (tablestru.identityattribute != null && tablestru.identityattribute.Count == 1)
//{
// order_con += tablestru.identityattribute[0].column.name + " asc,";
//}
//else
//{
// order_con += tablestru.columns.First().name + " asc,";
//}
order_con = order_con.TrimEnd(',');
string where_con = "";
sql = string.Format(sql, order_con, tablename, where_con);
paras.Add(new ProcedureParameter("@beginindex", beginindex + 1));
paras.Add(new ProcedureParameter("@endindex", beginindex + getdata_pagesize));
DataTable tb = getdataconn.SqlToDataTable(sql, paras);
tb.Columns.Remove("rownumber");
beginindex = beginindex + tb.Rows.Count;
lock (lock_rows)
{
foreach (DataRow r in tb.Rows)
{
listdata.Add(r);
}
}
if (tb.Rows.Count != getdata_pagesize)
getdata_complet = true;
}
int setdataerrorcount = 0;
DbConnMySql setdatamysqlconn = null;
private int SetDataAction()
{
if (listinsert.Count == 0)
{
//Config.Log.Write("SetDataAction 空转");//test
return 0;
}
Config.ExecModel insert_model = null;
lock (lock_listinsert)
{
if (listinsert.Count > 0)
{
insert_model = listinsert[0];
listinsert.Remove(insert_model);
}
}
if (insert_model == null)
return 0;
if (setdatamysqlconn == null)
{
var dbconn2 = DbConn.CreateConn(DbType.MYSQL, actmodel.database2.source, actmodel.database2.port, actmodel.database2.database, actmodel.database2.userid, actmodel.database2.password);
dbconn2.Open();
setdatamysqlconn = dbconn2 as DbConnMySql;
}
// Stopwatch swofexce = new Stopwatch();
// swofexce.Start();
//Config.Log.Write("---SetDataAction Sql执行开始");
setdatamysqlconn.BeginTransaction();
try
{
setdatamysqlconn.ExecuteSqlLocal(insert_model.sql, insert_model.paras, -1);
setdatamysqlconn.Commit();
// swofexce.Stop();
// Config.Log.Write("---SetDataAction Sql执行用时:{0}", swofexce.Elapsed.TotalMilliseconds.ToString("0.00"));
setdataerrorcount = 0;
}
catch (Exception ex)
{
setdataerrorcount++;
setdatamysqlconn.Rollback();
lock (lock_listinsert)
{
listinsert.Insert(0, insert_model);
}
Config.Log.Error("插入数据出错:" + ex.Message);
if (setdataerrorcount >= 3)
{
setdataerrorcount = 0;
throw ex;
}
else
{
return -1;
}
}
currentprocesscount += insert_model.count;
return insert_model.count;
}
private int PrepareData()
{
if (listdata.Count == 0)
{
// Config.Log.Write("PrepareData 空转");//test
return 0;
}
if (listinsert.Count >= Buffer_Exec_Count)
{
return 0;
}
int insertpagesize = 1000;
lock (actmodel.lockobjofcus)
{
if (actmodel.cutomsactions != null && actmodel.cutomsactions.Exists(x => x.tablename == tablename))
{
insertpagesize = actmodel.cutomsactions.FirstOrDefault(x => x.tablename == tablename).insertpagesize;
}
else if (actmodel.insertpagesize > 0)
{
insertpagesize = actmodel.insertpagesize;
}
}
List<MySql.Data.MySqlClient.MySqlParameter> paras = new List<MySql.Data.MySqlClient.MySqlParameter>();
List<DataRow> toinsertrows = new List<DataRow>();
lock (lock_rows)
{
toinsertrows = listdata.Take(insertpagesize).ToList();
listdata.RemoveRange(0, toinsertrows.Count);
}
if (toinsertrows.Count == 0)
{
// Config.Log.Write("SetDataAction toinsertrows=0 空转");//test
return 0;
}
StringBuilder sb = new StringBuilder();
List<string> allcolumns = new List<string>();
foreach (DataColumn dc in toinsertrows[0].Table.Columns)
{
allcolumns.Add(dc.ColumnName);
}
sb.AppendFormat("insert into {0}({1})\r\nvalues\r\n", tablename, string.Join(",", allcolumns));
for (int i = 0; i < toinsertrows.Count; i++)
{
allcolumns.Clear();
foreach (DataColumn dc in toinsertrows[i].Table.Columns)
{
string parname = "@" + dc.ColumnName + "_" + i.ToString();
allcolumns.Add(parname);
object objvalue = toinsertrows[i][dc.ColumnName];
if (objvalue == null)
{
objvalue = System.DBNull.Value;
}
if (objvalue.GetType() == typeof(string))
{
string strvalue = objvalue.ToString();
string rvalue = Comm.StringToSafeString(strvalue);
if (strvalue != rvalue)
{
objvalue = rvalue;
Config.Log.Alert("四字节字符过滤:[{2}]转化为[{3}] =表:{0} 列:{1} ", tablename, dc.ColumnName, strvalue, rvalue);
}
}
paras.Add(new MySql.Data.MySqlClient.MySqlParameter(parname, objvalue));
}
sb.AppendFormat("({0})\r\n,", string.Join(",", allcolumns));
}
lock (lock_listinsert)
{
listinsert.Add(new Config.ExecModel() { sql = sb.ToString().TrimEnd(',') + ";", paras = paras, count = toinsertrows.Count });
}
return toinsertrows.Count;
}
public void Start()
{
runstatus = 1;
if (mainthread == null || mainthread.ThreadState != System.Threading.ThreadState.Running)
{
mainthread = new Thread(Step2_Asyn);
mainthread.IsBackground = true;
mainthread.Start();
}
}
public void Step1_Syn()
{
using (var dbconn1 = DbConn.CreateConn(DbType.SQLSERVER, actmodel.database1.source, actmodel.database1.port, actmodel.database1.database, actmodel.database1.userid, actmodel.database1.password))
using (var dbconn2 = DbConn.CreateConn(DbType.MYSQL, actmodel.database2.source, actmodel.database2.port, actmodel.database2.database, actmodel.database2.userid, actmodel.database2.password))
{
dbconn1.Open();
dbconn2.Open();
DbStructure.DbStructureSqlServer mssqlstr = new DbStructure.DbStructureSqlServer();
tablestru = mssqlstr.GetTableStructure(dbconn1, tablename);
string sql = "select count(1) as cc from " + tablename + " ";
allitemcount = (int)dbconn1.ExecuteScalar(sql, null);
successcount = (int)((long)dbconn2.ExecuteScalar(sql, null));
// (tablestru.identityattribute != null && tablestru.identityattribute.Count == 1)
if (tablestru.primarykey != null)
{
List<string> pkcol = new List<string>();
List<string> pkorder = new List<string>();
if (tablestru.primarykey != null)
{
foreach (var a in tablestru.primarykey.columns)
{
pkcol.Add(a.name);
pkorder.Add(a.name + " desc ");
}
}
//else// if (tablestru.identityattribute != null && tablestru.identityattribute.Count == 1)
//{
// pkcol.Add(tablestru.identityattribute[0].column.name);
// pkorder.Add(tablestru.identityattribute[0].column.name + " desc ");
//}
//else
//{
// pkcol.Add(tablestru.columns.First().name);
// pkorder.Add(tablestru.columns.First().name + " desc ");
//}
string sqltop = "select {0} from {1} order by {2} limit 0,1;";
sqltop = string.Format(sqltop, string.Join(",", pkcol), tablename, string.Join(",", pkorder));
DataTable tboftop = dbconn2.SqlToDataTable(sqltop, null);
if (tboftop.Rows.Count == 1)
{
List<ProcedureParameter> parasofgetrownum = new List<ProcedureParameter>();
string sqlofpno = "select top 1 A.rownumber from ( SELECT ROW_NUMBER() over (order by {0}) as rownumber,{1} from {2} ) A where {3}";
List<string> getrownum_order = new List<string>();
List<string> getrownum_where = new List<string>();
foreach (string s in pkcol)
{
object value = tboftop.Rows[0][s];
if (value != null)
{
if (value.GetType() == typeof(MySql.Data.Types.MySqlDateTime))
{
MySql.Data.Types.MySqlDateTime nvalue = (MySql.Data.Types.MySqlDateTime)value;
string sofmydatetime = value.ToString();
if (string.IsNullOrEmpty(sofmydatetime))
{
value = System.DBNull.Value;
}
else
{
value = Convert.ToDateTime(sofmydatetime);
}
}
}
getrownum_order.Add(s + " asc");
getrownum_where.Add(s + "=@" + s);
parasofgetrownum.Add(new ProcedureParameter("@" + s, value));
}
sqlofpno = string.Format(sqlofpno, string.Join(",", getrownum_order), string.Join(",", pkcol), tablename, string.Join(" and ", getrownum_where));
object prerownum = dbconn1.ExecuteScalar(sqlofpno, parasofgetrownum, 2);
if (prerownum != null && prerownum.GetType() != typeof(System.DBNull))
{
beginindex = Convert.ToInt32(prerownum);
}
}
}
else
{
beginindex =(int)successcount;
}
}
}
private void Step2_Asyn()
{
Config.Log.Write("表[{0}]开始数据迁移...", tablename);
runstatus = 1;
currentprocesscount = 0;
currentprocesstime.Restart();
getdatathread = new Thread(() =>
{
try
{
while (true)
{
if (allitemcount == successcount + currentprocesscount)
{
getdata_complet = true;
}
if (getdata_complet)
{
break;
}
// Stopwatch swofallfun = new Stopwatch();
GetDataAction();
//swofallfun.Stop();
//Config.Log.Write("GetDataAction 调用用时:{0}", swofallfun.Elapsed.TotalMilliseconds.ToString("0.00"));
Thread.Sleep(10);
}
Config.Log.Write("表[{0}]生产者线程[取数据]正常关闭", tablename);
}
catch (Exception ex)
{
runstatus = -1;
Config.Log.Error("表[{0}]生产者线程[取数据]终止:{1}", tablename, ex.Message);
}
finally
{
getdata_complet = true;
if (getdataconn != null)
getdataconn.Dispose();
}
});
getdatathread.IsBackground = true;
getdatathread.Start();
preparethread = new Thread(() =>
{
try
{
while (true)
{
if (getdata_complet && rowbuffercount == 0)
{
preparedata_complet = true;
break;
}
PrepareData();
Thread.Sleep(10);
}
Config.Log.Write("表[{0}]生产者线程[预处理数据]正常关闭", tablename);
}
catch (Exception ex)
{
preparedata_complet = true;
runstatus = -1;
Config.Log.Error("表[{0}]生产者线程[预处理数据]终止:{1}", tablename, ex.Message);
}
});
preparethread.IsBackground = true;
preparethread.Start();
setdatathread = new Thread(() =>
{
try
{
while (true)
{
//Stopwatch swofallfun = new Stopwatch();
// swofallfun.Start();
//Config.Log.Write("");
//Config.Log.Write("--SetDataAction 调用开始");
int insert_count = SetDataAction();
// swofallfun.Stop();
// Config.Log.Write("--SetDataAction 调用用时:{0}", swofallfun.Elapsed.TotalMilliseconds.ToString("0.00"));
if (preparedata_complet && waitcount == 0)
{
if (runstatus != -1)
runstatus = 2;
currentprocesstime.Stop();
break;
}
else
{
if (insert_count <= 0)
Thread.Sleep(50);
}
}
Config.Log.Write("表[{0}]消费者线程正常关闭", tablename);
}
catch (Exception ex)
{
runstatus = -1;
Config.Log.Error("表[{0}]消费者线程终止:{1}", tablename, ex.Message);
}
finally
{
if (setdatamysqlconn != null)
setdatamysqlconn.Dispose();
}
});
setdatathread.IsBackground = true;
setdatathread.Start();
}
public void Stop()
{
Config.Log.Write("正在关闭[{0}]的数据迁移...", tablename);
currentprocesstime.Stop();
try
{
if (mainthread != null && mainthread.ThreadState != System.Threading.ThreadState.Stopped)
{
mainthread.Abort();
mainthread = null;
}
}
catch { }
try
{
if (preparethread != null && preparethread.ThreadState != System.Threading.ThreadState.Stopped)
{
preparethread.Abort();
preparethread = null;
}
}
catch { }
try
{
if (setdatathread != null && setdatathread.ThreadState != System.Threading.ThreadState.Stopped)
{
setdatathread.Abort();
setdatathread = null;
}
}
catch { }
try
{
if (getdatathread != null && getdatathread.ThreadState != System.Threading.ThreadState.Stopped)
{
getdatathread.Abort();
getdatathread = null;
}
}
catch { }
runstatus = 0;
Config.Log.Write("表[{0}]的数据迁移关闭!", tablename);
}
}
}
| 38.949932 | 206 | 0.448756 | [
"Apache-2.0"
] | buweixiaomi/ruanal | src/RLib/DB/Mig/DataMig.cs | 29,234 | C# |
namespace Sitecore.FakeDb.Tests.Data.Engines
{
using System;
using System.IO;
using FluentAssertions;
using Ploeh.AutoFixture.Xunit2;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.FakeDb.Data.Engines;
using Sitecore.Globalization;
using Xunit;
public class DataStorageTest
{
private readonly DataStorage dataStorage;
private const string ItemIdsRootId = "{11111111-1111-1111-1111-111111111111}";
private const string ItemIdsContentRoot = "{0DE95AE4-41AB-4D01-9EB0-67441B7C2450}";
private const string ItemIdsTemplateRoot = "{3C1715FE-6A13-4FCF-845F-DE308BA9741D}";
private const string ItemIdsBranchesRoot = "{BAD98E0E-C1B5-4598-AC13-21B06218B30C}";
private const string ItemIdsSystemRoot = "{13D6D6C6-C50B-4BBD-B331-2B04F1A58F21}";
private const string ItemIdsMediaLibraryRoot = "{3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1}";
private const string TemplateIdsTemplate = "{AB86861A-6030-46C5-B394-E8F99E8B87DB}";
private const string ItemIdsTemplateSection = "{E269FBB5-3750-427A-9149-7AA950B49301}";
private const string ItemIdsTemplateField = "{455A3E98-A627-4B40-8035-E683A0331AC7}";
private const string TemplateIdsBranch = "{35E75C72-4985-4E09-88C3-0EAC6CD1E64F}";
private const string RootParentId = "{00000000-0000-0000-0000-000000000000}";
private const string TemplateIdSitecore = "{C6576836-910C-4A3D-BA03-C277DBD3B827}";
public const string TemplateIdMainSection = "{E3E2D58C-DF95-4230-ADC9-279924CECE84}";
public const string TemplateIdBranchFolder = "{85ADBF5B-E836-4932-A333-FE0F9FA1ED1E}";
public DataStorageTest()
{
this.dataStorage = new DataStorage(Database.GetDatabase("master"));
}
[Theory]
[InlineData(ItemIdsRootId, "sitecore", TemplateIdSitecore, RootParentId, "/sitecore")]
[InlineData(ItemIdsContentRoot, "content", TemplateIdMainSection, ItemIdsRootId, "/sitecore/content")]
[InlineData(ItemIdsTemplateRoot, "templates", TemplateIdMainSection, ItemIdsRootId, "/sitecore/templates")]
[InlineData(ItemIdsBranchesRoot, "Branches", TemplateIdBranchFolder, ItemIdsTemplateRoot, "/sitecore/templates/Branches")]
[InlineData(ItemIdsSystemRoot, "system", TemplateIdMainSection, ItemIdsRootId, "/sitecore/system")]
[InlineData(ItemIdsMediaLibraryRoot, "media library", TemplateIdMainSection, ItemIdsRootId, "/sitecore/media library")]
[InlineData(TemplateIdsTemplate, "Template", TemplateIdsTemplate, ItemIdsTemplateRoot, "/sitecore/templates/template")]
[InlineData(ItemIdsTemplateSection, "Template section", ItemIdsTemplateSection, ItemIdsTemplateRoot, "/sitecore/templates/template section")]
[InlineData(ItemIdsTemplateField, "Template field", ItemIdsTemplateField, ItemIdsTemplateRoot, "/sitecore/templates/template field")]
[InlineData(TemplateIdsBranch, "Branch", TemplateIdsTemplate, ItemIdsTemplateRoot, "/sitecore/templates/branch")]
public void ShouldInitializeDefaultFakeItems(string itemId, string itemName, string templateId, string parentId, string fullPath)
{
// assert
this.dataStorage.GetFakeItem(ID.Parse(itemId)).ID.ToString().Should().Be(itemId);
this.dataStorage.GetFakeItem(ID.Parse(itemId)).Name.Should().Be(itemName);
this.dataStorage.GetFakeItem(ID.Parse(itemId)).TemplateID.ToString().Should().Be(templateId);
this.dataStorage.GetFakeItem(ID.Parse(itemId)).ParentID.ToString().Should().Be(parentId);
this.dataStorage.GetFakeItem(ID.Parse(itemId)).FullPath.Should().Be(fullPath);
}
[Fact]
public void ShouldCreateDefaultFakeTemplate()
{
this.dataStorage.GetFakeItem(new TemplateID(new ID(TemplateIdSitecore))).Should().BeEquivalentTo(new DbTemplate("Main Section", new TemplateID(new ID(TemplateIdSitecore))));
this.dataStorage.GetFakeItem(new TemplateID(new ID(TemplateIdMainSection))).Should().BeEquivalentTo(new DbTemplate("Main Section", new TemplateID(new ID(TemplateIdMainSection))));
this.dataStorage.GetFakeItem(TemplateIDs.Template).Should().BeEquivalentTo(new DbTemplate("Template", TemplateIDs.Template));
this.dataStorage.GetFakeItem(TemplateIDs.Folder).Should().BeEquivalentTo(new DbTemplate("Folder", TemplateIDs.Folder));
}
[Fact]
public void ShouldGetExistingItem()
{
// act & assert
this.dataStorage.GetFakeItem(ItemIDs.ContentRoot).Should().NotBeNull();
this.dataStorage.GetFakeItem(ItemIDs.ContentRoot).Should().BeOfType<DbItem>();
this.dataStorage.GetSitecoreItem(ItemIDs.ContentRoot, Language.Current).Should().NotBeNull();
this.dataStorage.GetSitecoreItem(ItemIDs.ContentRoot, Language.Current).Should().BeAssignableTo<Item>();
}
[Fact]
public void ShouldGetNullIdIfNoItemPresent()
{
// act & assert
this.dataStorage.GetFakeItem(ID.NewID).Should().BeNull();
this.dataStorage.GetSitecoreItem(ID.NewID, Language.Current).Should().BeNull();
}
[Fact]
public void ShouldGetSitecoreItemFieldIdsFromTemplateAndValuesFromItems()
{
// arrange
var itemId = ID.NewID;
var templateId = ID.NewID;
var fieldId = ID.NewID;
this.dataStorage.AddFakeItem(new DbTemplate("Sample", templateId) { Fields = { new DbField("Title", fieldId) } });
this.dataStorage.AddFakeItem(new DbItem("Sample", itemId, templateId) { Fields = { new DbField("Title", fieldId) { Value = "Welcome!" } } });
// act
var item = this.dataStorage.GetSitecoreItem(itemId, Language.Current);
// assert
item[fieldId].Should().Be("Welcome!");
}
[Fact]
public void ShouldGetSitecoreItemWithEmptyFieldIfNoItemFieldFound()
{
// arrange
var itemId = ID.NewID;
var templateId = ID.NewID;
var fieldId = ID.NewID;
this.dataStorage.AddFakeItem(new DbTemplate("Sample", templateId) { Fields = { new DbField("Title", fieldId) } });
this.dataStorage.AddFakeItem(new DbItem("Sample", itemId, templateId));
// act
var item = this.dataStorage.GetSitecoreItem(itemId, Language.Current);
// assert
item.InnerData.Fields[fieldId].Should().BeNull();
// We have changed the way we create ItemData to give more control to Sitecore
// and in order for the default string.Empty to come back from Field.Value
// Sitecore needs to be able to make a trip up the templates path
// and it in turn requires the Db context
// item[fieldId].Should().BeEmpty();
}
[Fact]
public void ShouldSetSecurityFieldForRootItem()
{
// assert
this.dataStorage.GetFakeItem(ItemIDs.RootID).Fields[FieldIDs.Security].Value.Should().Be("ar|Everyone|p*|+*|");
}
[Theory]
[InlineData("core", true)]
[InlineData("master", false)]
[InlineData("web", false)]
public void ShouldCreateFieldTypesRootInCoreDatabase(string database, bool exists)
{
// arrange
using (var db = new Db(database))
{
// act
var result = db.GetItem("/sitecore/system/Field Types") != null;
// assert
result.Should().Be(exists);
}
}
[Theory, AutoData]
public void GetBlobStreamReturnsNullIfNoStreamFound(Guid someBlobId)
{
this.dataStorage.GetBlobStream(someBlobId).Should().BeNull();
}
[Theory, AutoData]
public void SetBlobStreamOverridesExistingStream(Guid blobId, [NoAutoProperties] MemoryStream existing, [NoAutoProperties]MemoryStream @new)
{
this.dataStorage.SetBlobStream(blobId, existing);
this.dataStorage.SetBlobStream(blobId, @new);
this.dataStorage.GetBlobStream(blobId).Should().BeSameAs(@new);
}
[Theory, AutoData]
public void SetBlobStreamThrowsIfStreamIsNull(Guid blobId)
{
Assert.Throws<ArgumentNullException>(() => this.dataStorage.SetBlobStream(blobId, null));
}
}
} | 41.803191 | 185 | 0.720957 | [
"MIT"
] | pveller/Sitecore.FakeDb | test/Sitecore.FakeDb.Tests/Data/Engines/DataStorageTest.cs | 7,861 | C# |
/* =======================================================================
Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Linq;
namespace BoSSS.Foundation.IO {
/// <summary>
/// The first part of a full <see cref="Guid"/>. Useful for the selection
/// of objects without having to specify the full-length
/// <see cref="Guid"/>.
/// </summary>
public struct PartialGuid : IComparable, IComparable<PartialGuid>, IEquatable<PartialGuid> {
/// <summary>
/// The length of a guid <b>by definition</b>
/// </summary>
private const int GUID_LENGTH = 32;
/// <summary>
/// Use a full guid as internal storage so that validation routines are
/// automatically reused
/// </summary>
private Guid guid;
/// <summary>
/// The number of digits of <see cref="guid"/> that are significant for
/// this guid (i.e., the length of this partial guid)
/// </summary>
private int significantLength;
/// <summary>
/// Initializes a new instance of the <see cref="PartialGuid"/> struct.
/// </summary>
/// <param name="partialGuid">
/// A portion of a guid, i.e. a substring of a string in a format that
/// defines a valid <see cref="Guid"/>.
/// </param>
public PartialGuid(string partialGuid) {
partialGuid = partialGuid.Replace("-", "");
if (partialGuid.Length > GUID_LENGTH) {
throw new ArgumentException(String.Format(
"A guid must not be longer than {0} characters",
GUID_LENGTH));
}
significantLength = partialGuid.Length;
guid = Guid.Parse(partialGuid.PadRight(GUID_LENGTH, '0'));
}
#region IComparable Members
/// <summary>
/// See <see cref="CompareTo(PartialGuid)"/>
/// </summary>
/// <param name="obj">
/// See <see cref="CompareTo(PartialGuid)"/>
/// </param>
/// <returns>
/// See <see cref="CompareTo(PartialGuid)"/>
/// </returns>
public int CompareTo(object obj) {
if (obj is PartialGuid) {
return CompareTo((PartialGuid)obj);
} else if (obj is Guid) {
return CompareTo((Guid)obj);
} else {
throw new ArgumentException(
"Cannot compare to non-Guids");
}
}
#endregion
#region IComparable<PartialGuid> Members
/// <summary>
/// Compares this guid to the given <paramref name="other"/> by
/// comparing the respective string representations.
/// </summary>
/// <param name="other">
/// The partial guid to be compared to.
/// </param>
/// <returns>
/// See <see cref="IComparable{T}.CompareTo"/>.
/// </returns>
public int CompareTo(PartialGuid other) {
return this.ToString().CompareTo(other.ToString());
}
#endregion
#region IEquatable<PartialGuid> Members
/// <summary>
/// Checks of this guid is equal to the given
/// <paramref name="guid"/> by comparing only the respective string
/// representation <b>up to the length of the shorter guid</b>. As a
/// result, this is a diffuse equality comparison.
/// </summary>
/// <param name="guid">
/// The guid to be compared to.
/// </param>
/// <returns>
/// True, if both strings are <b>approximately</b> equal.
/// </returns>
public bool Equals(PartialGuid guid) {
if (significantLength <= guid.significantLength) {
return this.ToString().Equals(
guid.ToString().Substring(0, this.significantLength));
} else {
return guid.ToString().Equals(
ToString().Substring(0, guid.significantLength));
}
}
#endregion
/// <summary>
/// Returns a <see cref="System.String" /> that represents this
/// instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString() {
return guid.ToString("N", null).Substring(0, significantLength);
}
/// <summary>
/// See <see cref="Equals(PartialGuid)"/>
/// </summary>
/// <param name="obj">
/// See <see cref="Equals(PartialGuid)"/>
/// </param>
/// <returns>
/// See <see cref="Equals(PartialGuid)"/>
/// </returns>
public override bool Equals(object obj) {
if (obj is PartialGuid) {
return Equals((PartialGuid)obj);
} else if (obj is Guid) {
return Equals((Guid)obj);
} else {
return false;
}
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing
/// algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode() {
return guid.ToByteArray().Take(significantLength).GetHashCode();
}
/// <summary>
/// See <see cref="Equals(PartialGuid)"/>
/// </summary>
/// <param name="a">
/// See <see cref="Equals(PartialGuid)"/>
/// </param>
/// <param name="b">
/// See <see cref="Equals(PartialGuid)"/>
/// </param>
/// <returns>
/// See <see cref="Equals(PartialGuid)"/>
/// </returns>
public static bool operator ==(PartialGuid a, PartialGuid b) {
return a.Equals(b);
}
/// <summary>
/// Negation of <see cref="Equals(PartialGuid)"/>
/// </summary>
/// <param name="a">
/// See <see cref="Equals(PartialGuid)"/>
/// </param>
/// <param name="b">
/// See <see cref="Equals(PartialGuid)"/>
/// </param>
/// <returns>
/// Negation of <see cref="Equals(PartialGuid)"/>
/// </returns>
public static bool operator !=(PartialGuid a, PartialGuid b) {
return !a.Equals(b);
}
/// <summary>
/// Implicit conversion from a string to a partial guid
/// </summary>
/// <param name="partialGuid">
/// A string representing a portion of a <see cref="Guid"/>.
/// </param>
/// <returns>
/// A partial guid.
/// </returns>
/// <remarks>
/// In some sense, this operator violates the contract for an implicit
/// conversion since it may fail if <paramref name="partialGuid"/> is
/// not in a suitable format. However, the additional benefit when
/// using a console interface outweigh this disadvantage.
/// </remarks>
public static implicit operator PartialGuid(string partialGuid) {
return new PartialGuid(partialGuid);
}
/// <summary>
/// Implicit conversion from a <see cref="Guid"/> to a partial guid.
/// </summary>
/// <param name="guid">
/// A string representing a portion of a <see cref="Guid"/>.
/// </param>
/// <returns>
/// A partial guid.
/// </returns>
public static implicit operator PartialGuid(Guid guid) {
return new PartialGuid(guid.ToString("N", null));
}
}
}
| 35.937238 | 110 | 0.522529 | [
"Apache-2.0"
] | FDYdarmstadt/BoSSS | src/L2-foundation/BoSSS.Foundation/PartialGuid.cs | 8,353 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Common;
using NuGet.ProjectModel;
namespace NuGet.Commands
{
/// <summary>
/// Shared code to run the "restore" command for dotnet restore, nuget.exe, and VS.
/// </summary>
public static class RestoreRunner
{
/// <summary>
/// Create requests, execute requests, and commit restore results.
/// </summary>
public static async Task<IReadOnlyList<RestoreSummary>> RunAsync(RestoreArgs restoreContext, CancellationToken token)
{
// Create requests
var requests = await GetRequests(restoreContext);
// Run requests
return await RunAsync(requests, restoreContext, token);
}
/// <summary>
/// Create requests, execute requests, and commit restore results.
/// </summary>
public static async Task<IReadOnlyList<RestoreSummary>> RunAsync(RestoreArgs restoreContext)
{
// Run requests
return await RunAsync(restoreContext, CancellationToken.None);
}
/// <summary>
/// Execute and commit restore requests.
/// </summary>
private static async Task<IReadOnlyList<RestoreSummary>> RunAsync(
IEnumerable<RestoreSummaryRequest> restoreRequests,
RestoreArgs restoreContext,
CancellationToken token)
{
var maxTasks = GetMaxTaskCount(restoreContext);
var log = restoreContext.Log;
if (maxTasks > 1)
{
log.LogVerbose(string.Format(
CultureInfo.CurrentCulture,
Strings.Log_RunningParallelRestore,
maxTasks));
}
else
{
log.LogVerbose(Strings.Log_RunningNonParallelRestore);
}
// Get requests
var requests = new Queue<RestoreSummaryRequest>(restoreRequests);
var restoreTasks = new List<Task<RestoreSummary>>(maxTasks);
var restoreSummaries = new List<RestoreSummary>(requests.Count);
// Run requests
while (requests.Count > 0)
{
// Throttle and wait for a task to finish if we have hit the limit
if (restoreTasks.Count == maxTasks)
{
var restoreSummary = await CompleteTaskAsync(restoreTasks);
restoreSummaries.Add(restoreSummary);
}
var request = requests.Dequeue();
var task = Task.Run(() => ExecuteAndCommitAsync(request, token), token);
restoreTasks.Add(task);
}
// Wait for all restores to finish
while (restoreTasks.Count > 0)
{
var restoreSummary = await CompleteTaskAsync(restoreTasks);
restoreSummaries.Add(restoreSummary);
}
// Summary
return restoreSummaries;
}
/// <summary>
/// Execute and commit restore requests.
/// </summary>
public static async Task<IReadOnlyList<RestoreResultPair>> RunWithoutCommit(
IEnumerable<RestoreSummaryRequest> restoreRequests,
RestoreArgs restoreContext)
{
var maxTasks = GetMaxTaskCount(restoreContext);
var log = restoreContext.Log;
if (maxTasks > 1)
{
log.LogVerbose(string.Format(
CultureInfo.CurrentCulture,
Strings.Log_RunningParallelRestore,
maxTasks));
}
else
{
log.LogVerbose(Strings.Log_RunningNonParallelRestore);
}
// Get requests
var requests = new Queue<RestoreSummaryRequest>(restoreRequests);
var restoreTasks = new List<Task<RestoreResultPair>>(maxTasks);
var restoreResults = new List<RestoreResultPair>(maxTasks);
// Run requests
while (requests.Count > 0)
{
// Throttle and wait for a task to finish if we have hit the limit
if (restoreTasks.Count == maxTasks)
{
var restoreSummary = await CompleteTaskAsync(restoreTasks);
restoreResults.Add(restoreSummary);
}
var request = requests.Dequeue();
var task = Task.Run(() => ExecuteAsync(request, CancellationToken.None));
restoreTasks.Add(task);
}
// Wait for all restores to finish
while (restoreTasks.Count > 0)
{
var restoreSummary = await CompleteTaskAsync(restoreTasks);
restoreResults.Add(restoreSummary);
}
// Summary
return restoreResults;
}
/// <summary>
/// Create restore requests but do not execute them.
/// </summary>
public static async Task<IReadOnlyList<RestoreSummaryRequest>> GetRequests(RestoreArgs restoreContext)
{
// Get requests
var requests = new List<RestoreSummaryRequest>();
var inputs = new List<string>(restoreContext.Inputs);
// If there are no inputs, use the current directory
if (restoreContext.PreLoadedRequestProviders.Count < 1 && !inputs.Any())
{
inputs.Add(Path.GetFullPath("."));
}
// Ignore casing on windows and mac
var comparer = (RuntimeEnvironmentHelper.IsWindows || RuntimeEnvironmentHelper.IsMacOSX) ?
StringComparer.OrdinalIgnoreCase
: StringComparer.Ordinal;
var uniqueRequest = new HashSet<string>(comparer);
// Create requests
// Pre-loaded requests
foreach (var request in await CreatePreLoadedRequests(restoreContext))
{
// De-dupe requests
if (request.Request.LockFilePath == null
|| uniqueRequest.Add(request.Request.LockFilePath))
{
requests.Add(request);
}
}
// Input based requests
foreach (var input in inputs)
{
var inputRequests = await CreateRequests(input, restoreContext);
if (inputRequests.Count == 0)
{
// No need to throw here - the situation is harmless, and we want to report all possible
// inputs that don't resolve to a project.
var message = string.Format(
CultureInfo.CurrentCulture,
Strings.Error_UnableToLocateRestoreTarget,
Path.GetFullPath(input));
await restoreContext.Log.LogAsync(RestoreLogMessage.CreateWarning(NuGetLogCode.NU1501, message));
}
foreach (var request in inputRequests)
{
// De-dupe requests
if (uniqueRequest.Add(request.Request.LockFilePath))
{
requests.Add(request);
}
}
}
return requests;
}
private static int GetMaxTaskCount(RestoreArgs restoreContext)
{
var maxTasks = 1;
if (!restoreContext.DisableParallel && !RuntimeEnvironmentHelper.IsMono)
{
maxTasks = Environment.ProcessorCount;
}
if (maxTasks < 1)
{
maxTasks = 1;
}
return maxTasks;
}
private static async Task<RestoreSummary> ExecuteAndCommitAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
{
var result = await ExecuteAsync(summaryRequest, token);
return await CommitAsync(result, token);
}
private static async Task<RestoreResultPair> ExecuteAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
{
var log = summaryRequest.Request.Log;
log.LogVerbose(string.Format(
CultureInfo.CurrentCulture,
Strings.Log_ReadingProject,
summaryRequest.InputPath));
// Run the restore
var request = summaryRequest.Request;
// Read the existing lock file, this is needed to support IsLocked=true
// This is done on the thread and not as part of creating the request due to
// how long it takes to load the lock file.
if (request.ExistingLockFile == null)
{
request.ExistingLockFile = LockFileUtilities.GetLockFile(request.LockFilePath, log);
}
var command = new RestoreCommand(request);
var result = await command.ExecuteAsync(token);
return new RestoreResultPair(summaryRequest, result);
}
public static async Task<RestoreSummary> CommitAsync(RestoreResultPair restoreResult, CancellationToken token)
{
var summaryRequest = restoreResult.SummaryRequest;
var result = restoreResult.Result;
var log = summaryRequest.Request.Log;
// Commit the result
log.LogInformation(Strings.Log_Committing);
await result.CommitAsync(log, token);
if (result.Success)
{
log.LogMinimal(string.Format(
CultureInfo.CurrentCulture,
Strings.Log_RestoreComplete,
DatetimeUtility.ToReadableTimeFormat(result.ElapsedTime),
summaryRequest.InputPath));
}
else
{
log.LogMinimal(string.Format(
CultureInfo.CurrentCulture,
Strings.Log_RestoreFailed,
DatetimeUtility.ToReadableTimeFormat(result.ElapsedTime),
summaryRequest.InputPath));
}
// Remote the summary messages from the assets file. This will be removed later.
var messages = restoreResult.Result.LockFile.LogMessages.Select(e => new RestoreLogMessage(e.Level, e.Code, e.Message));
// Build the summary
return new RestoreSummary(
result,
summaryRequest.InputPath,
summaryRequest.ConfigFiles,
summaryRequest.Sources,
messages);
}
private static async Task<RestoreSummary> CompleteTaskAsync(List<Task<RestoreSummary>> restoreTasks)
{
var doneTask = await Task.WhenAny(restoreTasks);
restoreTasks.Remove(doneTask);
return await doneTask;
}
private static async Task<RestoreResultPair>
CompleteTaskAsync(List<Task<RestoreResultPair>> restoreTasks)
{
var doneTask = await Task.WhenAny(restoreTasks);
restoreTasks.Remove(doneTask);
return await doneTask;
}
private static async Task<IReadOnlyList<RestoreSummaryRequest>> CreatePreLoadedRequests(
RestoreArgs restoreContext)
{
var results = new List<RestoreSummaryRequest>();
foreach (var provider in restoreContext.PreLoadedRequestProviders)
{
var requests = await provider.CreateRequests(restoreContext);
results.AddRange(requests);
}
return results;
}
private static async Task<IReadOnlyList<RestoreSummaryRequest>> CreateRequests(
string input,
RestoreArgs restoreContext)
{
foreach (var provider in restoreContext.RequestProviders)
{
if (await provider.Supports(input))
{
return await provider.CreateRequests(
input,
restoreContext);
}
}
if (File.Exists(input) || Directory.Exists(input))
{
// Not a file or directory we know about. Try to be helpful without response.
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, GetInvalidInputErrorMessage(input), input));
}
throw new FileNotFoundException(input);
}
public static string GetInvalidInputErrorMessage(string input)
{
Debug.Assert(File.Exists(input) || Directory.Exists(input));
if (File.Exists(input))
{
var fileExtension = Path.GetExtension(input);
if (".json".Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
{
return Strings.Error_InvalidCommandLineInputJson;
}
if (".config".Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
{
return Strings.Error_InvalidCommandLineInputConfig;
}
}
return Strings.Error_InvalidCommandLineInput;
}
}
}
| 36.023684 | 138 | 0.562495 | [
"Apache-2.0"
] | RussKie/NuGet.Client | src/NuGet.Core/NuGet.Commands/RestoreCommand/RestoreRunner.cs | 13,689 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(NET35 || NET20 || NETFX_CORE)
using JWT.Net.Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
#if NET20
using JWT.Net.Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Reflection;
using JWT.Net.Newtonsoft.Json.Serialization;
using System.Globalization;
using JWT.Net.Newtonsoft.Json.Utilities;
namespace JWT.Net.Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a F# discriminated union type to and from JSON.
/// </summary>
public class DiscriminatedUnionConverter : JsonConverter
{
private const string CasePropertyName = "Case";
private const string FieldsPropertyName = "Fields";
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
Type t = value.GetType();
object result = FSharpUtils.GetUnionFields(null, value, t, null);
object info = FSharpUtils.GetUnionCaseInfo(result);
object fields = FSharpUtils.GetUnionCaseFields(result);
object caseName = FSharpUtils.GetUnionCaseInfoName(info);
object[] fieldsAsArray = fields as object[];
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(CasePropertyName) : CasePropertyName);
writer.WriteValue((string)caseName);
if (fieldsAsArray != null && fieldsAsArray.Length > 0)
{
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName);
serializer.Serialize(writer, fields);
}
writer.WriteEndObject();
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
object matchingCaseInfo = null;
string caseName = null;
JArray fields = null;
// start object
ReadAndAssert(reader);
while (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = reader.Value.ToString();
if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase))
{
ReadAndAssert(reader);
IEnumerable cases = (IEnumerable)FSharpUtils.GetUnionCases(null, objectType, null);
caseName = reader.Value.ToString();
foreach (object c in cases)
{
if ((string)FSharpUtils.GetUnionCaseInfoName(c) == caseName)
{
matchingCaseInfo = c;
break;
}
}
if (matchingCaseInfo == null)
throw JsonSerializationException.Create(reader, "No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
}
else if (string.Equals(propertyName, FieldsPropertyName, StringComparison.OrdinalIgnoreCase))
{
ReadAndAssert(reader);
if (reader.TokenType != JsonToken.StartArray)
throw JsonSerializationException.Create(reader, "Union fields must been an array.");
fields = (JArray)JToken.ReadFrom(reader);
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected property '{0}' found when reading union.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
ReadAndAssert(reader);
}
if (matchingCaseInfo == null)
throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName));
PropertyInfo[] fieldProperties = (PropertyInfo[])FSharpUtils.GetUnionCaseInfoFields(matchingCaseInfo);
object[] typedFieldValues = new object[fieldProperties.Length];
if (fieldProperties.Length > 0 && fields == null)
throw JsonSerializationException.Create(reader, "No '{0}' property with union fields found.".FormatWith(CultureInfo.InvariantCulture, FieldsPropertyName));
if (fields != null)
{
if (fieldProperties.Length != fields.Count)
throw JsonSerializationException.Create(reader, "The number of field values does not match the number of properties definied by union '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
for (int i = 0; i < fields.Count; i++)
{
JToken t = fields[i];
PropertyInfo fieldProperty = fieldProperties[i];
typedFieldValues[i] = t.ToObject(fieldProperty.PropertyType, serializer);
}
}
return FSharpUtils.MakeUnion(null, matchingCaseInfo, typedFieldValues, null);
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
if (typeof(IEnumerable).IsAssignableFrom(objectType))
return false;
// all fsharp objects have CompilationMappingAttribute
// get the fsharp assembly from the attribute and initialize latebound methods
object[] attributes;
#if !(NETFX_CORE || PORTABLE)
attributes = objectType.GetCustomAttributes(true);
#else
attributes = objectType.GetTypeInfo().GetCustomAttributes(true).ToArray();
#endif
bool isFSharpType = false;
foreach (object attribute in attributes)
{
Type attributeType = attribute.GetType();
if (attributeType.FullName == "Microsoft.FSharp.Core.CompilationMappingAttribute")
{
FSharpUtils.EnsureInitialized(attributeType.Assembly());
isFSharpType = true;
break;
}
}
if (!isFSharpType)
return false;
return (bool)FSharpUtils.IsUnion(null, objectType, null);
}
private static void ReadAndAssert(JsonReader reader)
{
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end when reading union.");
}
}
}
#endif | 42.313084 | 214 | 0.617118 | [
"MIT"
] | cnwenli/JWT.Net | JWT.Net/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs | 9,057 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.AppPlatform.Latest
{
public static class GetDeployment
{
public static Task<GetDeploymentResult> InvokeAsync(GetDeploymentArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetDeploymentResult>("azure-nextgen:appplatform/latest:getDeployment", args ?? new GetDeploymentArgs(), options.WithVersion());
}
public sealed class GetDeploymentArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the App resource.
/// </summary>
[Input("appName", required: true)]
public string AppName { get; set; } = null!;
/// <summary>
/// The name of the Deployment resource.
/// </summary>
[Input("deploymentName", required: true)]
public string DeploymentName { get; set; } = null!;
/// <summary>
/// The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the Service resource.
/// </summary>
[Input("serviceName", required: true)]
public string ServiceName { get; set; } = null!;
public GetDeploymentArgs()
{
}
}
[OutputType]
public sealed class GetDeploymentResult
{
/// <summary>
/// The name of the resource.
/// </summary>
public readonly string Name;
/// <summary>
/// Properties of the Deployment resource
/// </summary>
public readonly Outputs.DeploymentResourcePropertiesResponse Properties;
/// <summary>
/// Sku of the Deployment resource
/// </summary>
public readonly Outputs.SkuResponse? Sku;
/// <summary>
/// The type of the resource.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetDeploymentResult(
string name,
Outputs.DeploymentResourcePropertiesResponse properties,
Outputs.SkuResponse? sku,
string type)
{
Name = name;
Properties = properties;
Sku = sku;
Type = type;
}
}
}
| 30.795455 | 181 | 0.601845 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/AppPlatform/Latest/GetDeployment.cs | 2,710 | C# |
namespace Poker
{
using System;
using System.Collections.Generic;
using System.Text;
public class Hand : IHand
{
private IList<ICard> cards;
public Hand(IList<ICard> cards)
{
this.Cards = cards;
}
public IList<ICard> Cards
{
get
{
return this.cards;
}
private set
{
if (value == null)
{
throw new ArgumentException("Value for 'Cards' can not be null");
}
this.cards = value;
}
}
public override string ToString()
{
StringBuilder result = new StringBuilder();
foreach (var card in this.Cards)
{
result.Append(card);
}
return result.ToString();
}
}
} | 20.021739 | 85 | 0.432139 | [
"MIT"
] | kaizer04/Telerik-Academy-2013-2014 | KPK/Test-Driven-Development-Demo-Homework/Hand.cs | 923 | C# |
[assembly: CLSCompliant(false)]
// ReSharper disable InvertIf
namespace Atc.CodingRules.Updater.CLI;
[ExcludeFromCodeCoverage]
public static class Program
{
public static Task<int> Main(string[] args)
{
ArgumentNullException.ThrowIfNull(args);
args = SetProjectPathFromDotArgumentIfNeeded(args);
args = SetHelpArgumentIfNeeded(args);
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.Build();
var consoleLoggerConfiguration = new ConsoleLoggerConfiguration();
configuration.GetRequiredSection("ConsoleLogger").Bind(consoleLoggerConfiguration);
ProgramCsHelper.SetMinimumLogLevelIfNeeded(args, consoleLoggerConfiguration);
var serviceCollection = ServiceCollectionFactory.Create(consoleLoggerConfiguration);
var app = CommandAppFactory.CreateWithRootCommand<RootCommand>(serviceCollection);
app.ConfigureCommands();
return app.RunAsync(args);
}
private static string[] SetProjectPathFromDotArgumentIfNeeded(string[] args)
{
if (!args.Contains(".", StringComparer.Ordinal))
{
return args;
}
var newArgs = new List<string>();
foreach (var s in args)
{
if (".".Equals(s, StringComparison.Ordinal))
{
if (!(args.Contains(ArgumentCommandConstants.ShortProjectPath, StringComparer.OrdinalIgnoreCase) ||
args.Contains(ArgumentCommandConstants.LongProjectPath, StringComparer.OrdinalIgnoreCase)))
{
newArgs.Add(ArgumentCommandConstants.ShortProjectPath);
}
newArgs.Add(Environment.CurrentDirectory);
}
else
{
newArgs.Add(s);
}
}
if (!newArgs.Contains(NameCommandConstants.Run, StringComparer.OrdinalIgnoreCase) &&
!newArgs.Contains(NameCommandConstants.SanityCheck, StringComparer.OrdinalIgnoreCase) &&
!newArgs.Contains(CommandConstants.NameOptionsFile, StringComparer.OrdinalIgnoreCase) &&
!newArgs.Contains(NameCommandConstants.AnalyzerProviders, StringComparer.OrdinalIgnoreCase) &&
(newArgs.Contains(ArgumentCommandConstants.ShortProjectPath, StringComparer.OrdinalIgnoreCase) ||
newArgs.Contains(ArgumentCommandConstants.LongProjectPath, StringComparer.OrdinalIgnoreCase)))
{
newArgs.Insert(0, NameCommandConstants.Run);
}
if (!newArgs.Contains(CommandConstants.ArgumentShortVerbose, StringComparer.OrdinalIgnoreCase) ||
!newArgs.Contains(CommandConstants.ArgumentLongVerbose, StringComparer.OrdinalIgnoreCase))
{
newArgs.Add(CommandConstants.ArgumentShortVerbose);
}
return newArgs.ToArray();
}
private static string[] SetHelpArgumentIfNeeded(string[] args)
{
if (args.Length == 0)
{
return new[] { CommandConstants.ArgumentShortHelp };
}
if (args.Contains(NameCommandConstants.AnalyzerProviders, StringComparer.OrdinalIgnoreCase) &&
args.Contains(NameCommandConstants.AnalyzerProvidersCleanupCache, StringComparer.OrdinalIgnoreCase))
{
return args;
}
if (!(args.Contains(ArgumentCommandConstants.ShortProjectPath, StringComparer.OrdinalIgnoreCase) ||
args.Contains(ArgumentCommandConstants.LongProjectPath, StringComparer.OrdinalIgnoreCase)))
{
if (args.Contains(NameCommandConstants.SanityCheck, StringComparer.OrdinalIgnoreCase))
{
return new[] { NameCommandConstants.SanityCheck, CommandConstants.ArgumentShortHelp };
}
if (args.Contains(CommandConstants.NameOptionsFile, StringComparer.OrdinalIgnoreCase) &&
(args.Contains(CommandConstants.NameOptionsFileCreate, StringComparer.OrdinalIgnoreCase) ||
args.Contains(CommandConstants.NameOptionsFileValidate, StringComparer.OrdinalIgnoreCase)))
{
return new[] { CommandConstants.NameOptionsFile, CommandConstants.ArgumentShortHelp };
}
if (args.Contains(NameCommandConstants.AnalyzerProviders, StringComparer.OrdinalIgnoreCase) &&
args.Contains(NameCommandConstants.AnalyzerProvidersCollect, StringComparer.OrdinalIgnoreCase))
{
return new[] { NameCommandConstants.AnalyzerProviders, CommandConstants.ArgumentShortHelp };
}
if (args.Contains(NameCommandConstants.Run, StringComparer.OrdinalIgnoreCase))
{
return new[] { NameCommandConstants.Run, CommandConstants.ArgumentShortHelp };
}
}
return args;
}
} | 40.8 | 115 | 0.668913 | [
"MIT"
] | JKrag/atc-coding-rules-updater | src/Atc.CodingRules.Updater.CLI/Program.cs | 4,896 | C# |
using BusinessRules;
using BusinessRules.Products;
using Entities.Enums;
using Entities.Products;
using Entities.System;
using Entities.Views;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using UserInterface.Modules;
using UserInterface.Querries;
namespace UserInterface.Products
{
public partial class FrmPizzaSizeCRUD : Form
{
private bool newregister;
int returnControl = 0;
public FrmPizzaSizeCRUD()
{
InitializeComponent();
MonetaryMask.AplyEvents(txtSizePriceAdditional);
IdFieldMasks.AplyEvents(txtSizeId);
}
private void FrmPizzaSizeCRUD_Load(object sender, EventArgs e)
{
ClearForm();
}
#region --== Button Methods ==--
private void BtnSizeSearch_Click(object sender, EventArgs e)
{
List<EntityViewProducts> pizzaSizes = new PizzaSizeBus().GetEntityViewProducts(Status.Todos);
if (pizzaSizes.Count < 1)
{
//verify if list is empty
MessageBox.Show("Sem dados para exibir!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
//send list to Generic search form
FrmGenericQueriesProducts FrmPizzaSizeQueryProduct = new FrmGenericQueriesProducts("Pesquisa de Adicionais", Status.Todos);
FrmPizzaSizeQueryProduct.queryList = pizzaSizes;
FrmPizzaSizeQueryProduct.ShowDialog();
returnControl = FrmPizzaSizeQueryProduct.returnControl;
//Break if returno control is invalid
if (returnControl < 1) { return; }
txtSizeId.Text = returnControl.ToString();
TxtSizeId_Validating(txtSizeId, new CancelEventArgs());
btnSizeSearch.Focus();
}
private void BtnSave_Click(object sender, EventArgs e)
{
if (!FieldsVerification()) { return; }
//Fields to save to DB on Aditional Table
PizzaSizeBus _szeBus = new PizzaSizeBus();
PizzaSize pizzaSizeToCreate = new PizzaSize();
pizzaSizeToCreate.Description = txtSizeDescription.Text.Trim();
pizzaSizeToCreate.FlvorsQty = Convert.ToInt32(txtQtyFlavors.Text.Trim());
pizzaSizeToCreate.SizeRemark = txtSizeRemark.Text.Trim();
MonetaryMask.UnMakeMask(txtSizePriceAdditional, new EventArgs());
pizzaSizeToCreate.AdditionalPrice = Convert.ToDouble(txtSizePriceAdditional.Text);
pizzaSizeToCreate.SizeStatus = szeStatus.CurrentStatus;
pizzaSizeToCreate.LastChangeDate = DateTime.Now;
pizzaSizeToCreate.LastChangeUserId = Session.User.Id;
if (newregister)//Record new register to DB
{
if (_szeBus.CreatePizzaSize(pizzaSizeToCreate))
{
MessageBox.Show("Sabor cadastrado com sucesso!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Information);
if (Functions.OptimizeAll())
{
lblSaveOptimize.Text = "DBOTMZ";
ClearForm();
}
else
{
lblSaveOptimize.Text = "DB!OTMZ";
ClearForm();
this.Close();
}
}
else
{
MessageBox.Show("Não foi possível concluir o registro!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
else //Alters existent register on Db
{
pizzaSizeToCreate.Id = Convert.ToInt32(txtSizeId.Text.Trim());
if (_szeBus.UpdatePizzaSize(pizzaSizeToCreate))
{
MessageBox.Show("Sabor Atualizado com sucesso!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Information);
ClearForm();
}
else
{
MessageBox.Show("Não foi possível concluir o atualização!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void BtnDelete_Click(object sender, EventArgs e)
{
IdFieldMasks.UnMakeMask(txtSizeId, new EventArgs());
int pizzaSizeToDelete = Convert.ToInt32(txtSizeId.Text.Trim());
PizzaSizeBus _szeBus = new PizzaSizeBus();
if (_szeBus.DeletePizzaSize(pizzaSizeToDelete))
{
MessageBox.Show("Sabor excluído com sucesso!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Information);
ClearForm();
}
else
{
MessageBox.Show("Não foi possível excluir o registro!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void BtnCancel_Click(object sender, EventArgs e)
{
ClearForm();
this.Close();
}
#endregion
#region --== Action Methods ==--
private void TxtSizeId_Validating(object sender, CancelEventArgs e)
{
if (txtSizeId.Text.Trim() == string.Empty) { return; }
PizzaSize pizzaSizeToDisplay = new PizzaSizeBus()
.FindById(Convert.ToInt32(txtSizeId.Text.Trim()));
if (pizzaSizeToDisplay.Description == null || pizzaSizeToDisplay.Id == 0)
{
btnDelete.Enabled = false;
ClearForm();
return;
}
newregister = false;
txtSizeDescription.Text = pizzaSizeToDisplay.Description;
txtQtyFlavors.Text = pizzaSizeToDisplay.FlvorsQty.ToString();
txtSizeRemark.Text = pizzaSizeToDisplay.SizeRemark;
txtSizePriceAdditional.Text = pizzaSizeToDisplay.AdditionalPrice.ToString("C2");
szeStatus.StartStatus(pizzaSizeToDisplay.SizeStatus);
btnDelete.Enabled = true;
IdFieldMasks.MakeMask(txtSizeId, new EventArgs());
}
#endregion
#region --== Auxiliary Methods ==--
public void ClearForm()
{
txtSizeId.Text = string.Empty;
txtSizeId.Text = new PizzaSizeBus().FindNextCode().ToString();
txtSizeDescription.Text = string.Empty;
txtQtyFlavors.Text = string.Empty;
txtSizeRemark.Text = string.Empty;
txtSizePriceAdditional.Text = string.Empty;
btnDelete.Enabled = false;
szeStatus.StartStatus(Status.Ativo);
newregister = true;
IdFieldMasks.MakeMask(txtSizeId, new EventArgs());
MonetaryMask.MakeMask(txtSizePriceAdditional, new EventArgs());
Functions.SetSelectedFocus(txtSizeDescription);
}
private bool FieldsVerification()
{
if (txtSizeDescription.Text.Trim() == string.Empty)
{
MessageBox.Show("Você deve informar uma descrição para o tamanho!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
if ((txtQtyFlavors.Text.Trim() == string.Empty) || Convert.ToInt32(txtQtyFlavors.Text.Trim()) <= 0)
{
MessageBox.Show("Você deve informar pelo menos \n uma unidade de quantidade de sabores!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
MonetaryMask.UnMakeMask(txtSizePriceAdditional, new EventArgs());
if (Convert.ToDouble(txtSizePriceAdditional.Text.Trim()) <= 0.00)
{
MessageBox.Show("Valor não condizente com a quantidade de sabores,\n favor corrigir!",
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
return true;
}
#endregion
}
}
| 36.718487 | 135 | 0.539764 | [
"Apache-2.0"
] | almoretto/LaFamiglia_Pizzaria_Delivery | LaFamigliaPizzeriaDelivery/UserInterface/Products/FrmPizzaSizeCRUD.cs | 8,755 | C# |
using BepInEx;
using BepInEx.Configuration;
using EnforcerPlugin.Modules;
using EntityStates;
using EntityStates.Enforcer;
using EntityStates.Enforcer.NeutralSpecial;
using IL.RoR2.ContentManagement;
using KinematicCharacterController;
using R2API;
using R2API.Utils;
using RoR2;
using RoR2.CharacterAI;
using RoR2.Projectile;
using RoR2.Skills;
using RoR2.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
namespace EnforcerPlugin
{
[BepInDependency("com.bepis.r2api", BepInDependency.DependencyFlags.HardDependency)]
[BepInDependency("com.DestroyedClone.AncientScepter", BepInDependency.DependencyFlags.SoftDependency)]
[BepInDependency("com.KomradeSpectre.Aetherium", BepInDependency.DependencyFlags.SoftDependency)]
[BepInDependency("com.Sivelos.SivsItems", BepInDependency.DependencyFlags.SoftDependency)]
[BepInDependency("com.K1454.SupplyDrop", BepInDependency.DependencyFlags.SoftDependency)]
[BepInDependency("com.TeamMoonstorm.Starstorm2", BepInDependency.DependencyFlags.SoftDependency)]
[BepInDependency("com.cwmlolzlz.skills", BepInDependency.DependencyFlags.SoftDependency)]
[BepInDependency("com.KingEnderBrine.ItemDisplayPlacementHelper", BepInDependency.DependencyFlags.SoftDependency)]
[NetworkCompatibility(CompatibilityLevel.EveryoneMustHaveMod, VersionStrictness.EveryoneNeedSameModVersion)]
[BepInPlugin(MODUID, "Enforcer", "3.2.5")]
[R2APISubmoduleDependency(new string[]
{
"PrefabAPI",
"LanguageAPI",
"SoundAPI",
"UnlockableAPI"
})]
public class EnforcerModPlugin : BaseUnityPlugin
{
public const string MODUID = "com.EnforcerGang.Enforcer";
public const string characterName = "Enforcer";
public const string characterSubtitle = "Unwavering Bastion";
public const string characterOutro = "..and so he left, unsure of his title as protector.";
public const string characterOutroFailure = "..and so he vanished, the planet's minorities finally at peace.";
public const string characterLore = "\n<style=cMono>\"You don't have to do this.\"</style>\r\n\r\nThe words echoed in his head, yet he pushed forward. The pod was only a few steps away — he had a chance to leave — but something in his core kept him moving. He didn't know what it was, but he didn't question it. It was a natural force: the same force that always drove him to follow orders.\n\nThis time, however, it didn't seem so natural. There were no orders. The heavy trigger and its rhythmic thunder were his — and his alone.";
public static EnforcerModPlugin instance;
public static bool holdonasec = true;
internal static List<GameObject> bodyPrefabs = new List<GameObject>();
internal static List<GameObject> masterPrefabs = new List<GameObject>();
internal static List<GameObject> projectilePrefabs = new List<GameObject>();
internal static List<SurvivorDef> survivorDefs = new List<SurvivorDef>();
//i didn't want this to be static considering we're using an instance now but it throws 23 errors if i remove the static modifier
//i'm not dealing with that
public static GameObject characterPrefab;
public static GameObject characterDisplay;
public static GameObject needlerCrosshair;
public static GameObject nemesisSpawnEffect;
public static GameObject bulletTracer;
public static GameObject bulletTracerSSG;
public static GameObject laserTracer;
public static GameObject bungusTracer = Resources.Load<GameObject>("Prefabs/Effects/Tracers/TracerEngiTurret");
public static GameObject minigunTracer;
public static Material bungusMat;
public static GameObject tearGasProjectilePrefab;
public GameObject tearGasPrefab;
public static GameObject damageGasProjectile;
public GameObject damageGasEffect;
public static GameObject stunGrenade;
public static GameObject shockGrenade;
public static GameObject blockEffectPrefab;
public static GameObject heavyBlockEffectPrefab;
public static GameObject hammerSlamEffect;
public GameObject doppelganger;
public static readonly Color characterColor = new Color(0.26f, 0.27f, 0.46f);
public static SkillDef shieldDownDef;//skilldef used while shield is down
public static SkillDef shieldUpDef;//skilldef used while shield is up
public static SkillDef shieldOffDef;//skilldef used while shield is off
public static SkillDef shieldOnDef;//skilldef used while shield is on
public static SkillDef boardDownDef;
public static SkillDef boardUpDef;
public static SkillDef tearGasScepterDef;
public static SkillDef shockGrenadeDef;
public static bool cum; //don't ask
public static bool aetheriumInstalled = false;
public static bool sivsItemsInstalled = false;
public static bool supplyDropInstalled = false;
public static bool starstormInstalled = false;
public static bool skillsPlusInstalled = false;
public static bool IDPHelperInstalled = false;
//public static uint doomGuyIndex = 2;
//public static uint engiIndex = 3;
//public static uint stormtrooperIndex = 4;
//public static uint frogIndex = 7;
// a blacklist for teleporter particles- the fix for it is retarded so we just disable them on certain characters.
private static List<string> _tpParticleBlacklist = new List<string>
{
"PALADIN_NAME",
"LUNAR_KNIGHT_BODY_NAME",
"NEMMANDO_NAME",
"EXECUTIONER_NAME",
"MINER_NAME"
};
private SkillLocator _skillLocator;
private CharacterSelectSurvivorPreviewDisplayController _previewController;
//更新许可证 DO WHAT THE FUCK YOU WANT TO
//public EnforcerPlugin()
//{
// //don't touch this
// // what does all this even do anyway?
// //its our plugin constructor
//
//i'm touching this. fuck you
//
// //awake += EnforcerPlugin_Load;
// //start += EnforcerPlugin_LoadStart;
//}
private void Awake() {
//touch this all you want tho
Modules.Config.ConfigShit(this);
Modules.States.FixStates();
Assets.PopulateAssets();
SetupModCompat();
MemeSetup();
CreatePrefab();
CreateDisplayPrefab();
EnforcerUnlockables.RegisterUnlockables();
RegisterCharacter();
ItemDisplays.PopulateDisplays();
Skins.RegisterSkins();
Modules.Buffs.RegisterBuffs();
RegisterProjectile();
CreateDoppelganger();
CreateCrosshair();
new NemforcerPlugin().Init();
Hook();
//new Modules.ContentPacks().CreateContentPack();
RoR2.ContentManagement.ContentManager.collectContentPackProviders += ContentManager_collectContentPackProviders;
RoR2.ContentManagement.ContentManager.onContentPacksAssigned += ContentManager_onContentPacksAssigned;
gameObject.AddComponent<TestValueManager>();
}
private void SetupModCompat() {
//aetherium item displays- dll won't compile without a reference to aetherium
if (BepInEx.Bootstrap.Chainloader.PluginInfos.ContainsKey("com.KomradeSpectre.Aetherium")) {
aetheriumInstalled = true;
}
//sivs item displays- dll won't compile without a reference
if (BepInEx.Bootstrap.Chainloader.PluginInfos.ContainsKey("com.Sivelos.SivsItems")) {
sivsItemsInstalled = true;
}
//supply drop item displays- dll won't compile without a reference
if (BepInEx.Bootstrap.Chainloader.PluginInfos.ContainsKey("com.K1454.SupplyDrop")) {
supplyDropInstalled = true;
}
//scepter stuff
if (BepInEx.Bootstrap.Chainloader.PluginInfos.ContainsKey("com.DestroyedClone.AncientScepter")) {
ScepterSkillSetup();
ScepterSetup();
}
//shartstorm 2 xDDDD
if (BepInEx.Bootstrap.Chainloader.PluginInfos.ContainsKey("com.TeamMoonstorm.Starstorm2")) {
starstormInstalled = true;
}
//skillsplus
if (BepInEx.Bootstrap.Chainloader.PluginInfos.ContainsKey("com.cwmlolzlz.skills")) {
skillsPlusInstalled = true;
SkillsPlusCompat.init();
}
//weapon idrs
if (BepInEx.Bootstrap.Chainloader.PluginInfos.ContainsKey("com.KingEnderBrine.ItemDisplayPlacementHelper")) {
IDPHelperInstalled = true;
}
}
private void ContentManager_onContentPacksAssigned(HG.ReadOnlyArray<RoR2.ContentManagement.ReadOnlyContentPack> obj)
{
EnforcerItemDisplays.RegisterDisplays();
NemItemDisplays.RegisterDisplays();
}
private void ContentManager_collectContentPackProviders(RoR2.ContentManagement.ContentManager.AddContentPackProviderDelegate addContentPackProvider) {
addContentPackProvider(new Modules.ContentPacks());
}
private void Start()
{
/*foreach(SurvivorDef i in SurvivorCatalog.survivorDefs)
{
Debug.Log(Language.GetString((i.displayNameToken), "EN_US") + " sort position: " + i.desiredSortPosition);
}*/
}
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private void ScepterSetup()
{
AncientScepter.AncientScepterItem.instance.RegisterScepterSkill(tearGasScepterDef, "EnforcerBody", SkillSlot.Utility, 0);
AncientScepter.AncientScepterItem.instance.RegisterScepterSkill(shockGrenadeDef, "EnforcerBody", SkillSlot.Utility, 1);
}
private void Hook()
{
//add hooks here
On.RoR2.HealthComponent.TakeDamage += HealthComponent_TakeDamage;
On.EntityStates.GolemMonster.FireLaser.OnEnter += FireLaser_OnEnter;
On.EntityStates.BaseState.OnEnter += BaseState_OnEnter;
//On.RoR2.GlobalEventManager.OnHitEnemy += GlobalEventManager_OnEnemyHit;
On.RoR2.CharacterBody.RecalculateStats += CharacterBody_RecalculateStats;
On.RoR2.CharacterBody.Update += CharacterBody_Update;
On.RoR2.CharacterBody.OnLevelUp += CharacterBody_OnLevelChanged;
On.RoR2.CharacterMaster.OnInventoryChanged += CharacterMaster_OnInventoryChanged;
On.RoR2.BodyCatalog.SetBodyPrefabs += BodyCatalog_SetBodyPrefabs;
On.RoR2.SceneDirector.Start += SceneDirector_Start;
On.RoR2.ArenaMissionController.BeginRound += ArenaMissionController_BeginRound;
On.RoR2.ArenaMissionController.EndRound += ArenaMissionController_EndRound;
On.RoR2.EscapeSequenceController.BeginEscapeSequence += EscapeSequenceController_BeginEscapeSequence;
On.RoR2.UI.MainMenu.BaseMainMenuScreen.OnEnter += BaseMainMenuScreen_OnEnter;
On.RoR2.CharacterSelectBarController.Start += CharacterSelectBarController_Start;
On.RoR2.MapZone.TryZoneStart += MapZone_TryZoneStart;
On.RoR2.HealthComponent.Suicide += HealthComponent_Suicide;
//On.RoR2.TeleportOutController.OnStartClient += TeleportOutController_OnStartClient;
On.EntityStates.GlobalSkills.LunarNeedle.FireLunarNeedle.OnEnter += FireLunarNeedle_OnEnter;
On.RoR2.EntityStateMachine.SetState += EntityStateMachine_SetState;
}
#region Hooks
private bool isMonsoon()
{
bool flag = true;
if (Run.instance.selectedDifficulty == DifficultyIndex.Easy || Run.instance.selectedDifficulty == DifficultyIndex.Normal) flag = false;
return flag;
}
private void TeleportOutController_OnStartClient(On.RoR2.TeleportOutController.orig_OnStartClient orig, TeleportOutController self)
{
// fuck you hopoo
// no. big particle funny
if (self.target)
{
CharacterBody targetBody = self.target.GetComponent<CharacterBody>();
if (targetBody)
{
if (EnforcerModPlugin._tpParticleBlacklist.Contains(targetBody.baseNameToken))
{
self.bodyGlowParticles.Play();
return;
}
}
}
orig(self);
}
private void MapZone_TryZoneStart(On.RoR2.MapZone.orig_TryZoneStart orig, MapZone self, Collider other)
{
if (other.gameObject)
{
CharacterBody body = other.GetComponent<CharacterBody>();
if (body)
{
if (body.baseNameToken == "NEMFORCER_NAME" || body.baseNameToken == "NEMFORCER_BOSS_NAME")
{
var teamComponent = body.teamComponent;
if (teamComponent)
{
if (teamComponent.teamIndex != TeamIndex.Player)
{
teamComponent.teamIndex = TeamIndex.Player;
orig(self, other);
teamComponent.teamIndex = TeamIndex.Monster;
return;
}
}
}
}
}
orig(self, other);
}
private void ArenaMissionController_BeginRound(On.RoR2.ArenaMissionController.orig_BeginRound orig, ArenaMissionController self)
{
if (self.currentRound == 0)
{
if (isMonsoon() && Run.instance.stageClearCount >= 5)
{
bool invasion = false;
for (int i = CharacterMaster.readOnlyInstancesList.Count - 1; i >= 0; i--)
{
CharacterMaster master = CharacterMaster.readOnlyInstancesList[i];
if (!Modules.Config.globalInvasion.Value)
{
if (master.teamIndex == TeamIndex.Player && master.bodyPrefab == BodyCatalog.FindBodyPrefab("EnforcerBody"))
{
invasion = true;
}
}
else
{
if (master.teamIndex == TeamIndex.Player)
{
invasion = true;
}
}
}
if (invasion && NetworkServer.active)
{
ChatMessage.SendColored("You feel an overwhelming presence..", new Color(0.149f, 0.0039f, 0.2117f));
}
}
}
orig(self);
if (self.currentRound == 9)
{
if (isMonsoon() && Run.instance.stageClearCount >= 5)
{
for (int i = CharacterMaster.readOnlyInstancesList.Count - 1; i >= 0; i--)
{
CharacterMaster master = CharacterMaster.readOnlyInstancesList[i];
if (!Modules.Config.globalInvasion.Value)
{
if (Modules.Config.multipleInvasions.Value)
{
if (master.teamIndex == TeamIndex.Player && master.bodyPrefab == BodyCatalog.FindBodyPrefab("EnforcerBody"))
{
NemesisInvasionManager.PerformInvasion(new Xoroshiro128Plus(Run.instance.seed));
master.gameObject.AddComponent<NemesisInvasion>().hasInvaded = true;
}
}
else
{
bool flag = false;
if (master.teamIndex == TeamIndex.Player && master.bodyPrefab == BodyCatalog.FindBodyPrefab("EnforcerBody"))
{
flag = true;
master.gameObject.AddComponent<NemesisInvasion>().hasInvaded = true;
}
if (flag) NemesisInvasionManager.PerformInvasion(new Xoroshiro128Plus(Run.instance.seed));
}
}
else
{
if (Modules.Config.multipleInvasions.Value)
{
if (master.teamIndex == TeamIndex.Player && master.playerCharacterMasterController)
{
NemesisInvasionManager.PerformInvasion(new Xoroshiro128Plus(Run.instance.seed));
master.gameObject.AddComponent<NemesisInvasion>().hasInvaded = true;
}
}
else
{
bool flag = false;
if (master.teamIndex == TeamIndex.Player && master.playerCharacterMasterController)
{
flag = true;
master.gameObject.AddComponent<NemesisInvasion>().hasInvaded = true;
}
if (flag) NemesisInvasionManager.PerformInvasion(new Xoroshiro128Plus(Run.instance.seed));
}
}
}
}
}
}
private void ArenaMissionController_EndRound(On.RoR2.ArenaMissionController.orig_EndRound orig, ArenaMissionController self)
{
orig(self);
if (self.currentRound == 9 || self.currentRound == 10)
{
if (isMonsoon() && Run.instance.stageClearCount < 5)
{
bool pendingInvasion = false;
if (!Modules.Config.globalInvasion.Value)
{
for (int i = CharacterMaster.readOnlyInstancesList.Count - 1; i >= 0; i--)
{
CharacterMaster master = CharacterMaster.readOnlyInstancesList[i];
if (master.teamIndex == TeamIndex.Player && master.bodyPrefab == BodyCatalog.FindBodyPrefab("EnforcerBody"))
{
master.gameObject.AddComponent<NemesisInvasion>().pendingInvasion = true;
pendingInvasion = true;
}
}
}
else
{
for (int i = CharacterMaster.readOnlyInstancesList.Count - 1; i >= 0; i--)
{
CharacterMaster master = CharacterMaster.readOnlyInstancesList[i];
if (master.teamIndex == TeamIndex.Player && master.playerCharacterMasterController)
{
master.gameObject.AddComponent<NemesisInvasion>().pendingInvasion = true;
pendingInvasion = true;
}
}
}
if (pendingInvasion && NetworkServer.active)
{
ChatMessage.SendColored("The void peers into you....", new Color(0.149f, 0.0039f, 0.2117f));
}
}
}
}
private void EscapeSequenceController_BeginEscapeSequence(On.RoR2.EscapeSequenceController.orig_BeginEscapeSequence orig, EscapeSequenceController self)
{
if (isMonsoon())
{
for (int i = CharacterMaster.readOnlyInstancesList.Count - 1; i >= 0; i--)
{
CharacterMaster master = CharacterMaster.readOnlyInstancesList[i];
bool hasInvaded = false;
if (!Modules.Config.globalInvasion.Value)
{
if (master.teamIndex == TeamIndex.Player && master.bodyPrefab == BodyCatalog.FindBodyPrefab("EnforcerBody") && master.GetBody())
{
var j = master.gameObject.GetComponent<NemesisInvasion>();
if (j)
{
if (j.pendingInvasion && !j.hasInvaded)
{
j.pendingInvasion = false;
j.hasInvaded = true;
if (Modules.Config.multipleInvasions.Value) NemesisInvasionManager.PerformInvasion(new Xoroshiro128Plus(Run.instance.seed));
else if (!hasInvaded) NemesisInvasionManager.PerformInvasion(new Xoroshiro128Plus(Run.instance.seed));
hasInvaded = true;
}
}
}
}
else
{
if (master.teamIndex == TeamIndex.Player && master.playerCharacterMasterController && master.GetBody())
{
var j = master.gameObject.GetComponent<NemesisInvasion>();
if (j)
{
if (j.pendingInvasion && !j.hasInvaded)
{
j.pendingInvasion = false;
j.hasInvaded = true;
if (Modules.Config.multipleInvasions.Value) NemesisInvasionManager.PerformInvasion(new Xoroshiro128Plus(Run.instance.seed));
else if (!hasInvaded) NemesisInvasionManager.PerformInvasion(new Xoroshiro128Plus(Run.instance.seed));
hasInvaded = true;
}
}
}
}
}
}
orig(self);
}
private void BodyCatalog_SetBodyPrefabs(On.RoR2.BodyCatalog.orig_SetBodyPrefabs orig, GameObject[] newBodyPrefabs)
{
//nicely done brother
for (int i = 0; i < newBodyPrefabs.Length; i++)
{
if (newBodyPrefabs[i].name == "EnforcerBody" && newBodyPrefabs[i] != characterPrefab)
{
newBodyPrefabs[i].name = "OldEnforcerBody";
}
}
orig(newBodyPrefabs);
}
private void CharacterBody_RecalculateStats(On.RoR2.CharacterBody.orig_RecalculateStats orig, CharacterBody self)
{
orig(self);
if (self)
{
if (self.HasBuff(Modules.Buffs.protectAndServeBuff))
{
self.armor += 10f;
self.moveSpeed *= 0.35f;
self.maxJumpCount = 0;
}
if (self.HasBuff(Modules.Buffs.minigunBuff))
{
self.armor += 60f;
self.moveSpeed *= 0.8f;
}
if (self.HasBuff(Modules.Buffs.energyShieldBuff))
{
self.maxJumpCount = 0;
self.armor += 40f;
self.moveSpeed *= 0.65f;
}
if (self.HasBuff(Modules.Buffs.skateboardBuff)) {
self.characterMotor.airControl = 0.1f;
}
if (self.HasBuff(Modules.Buffs.impairedBuff))
{
self.maxJumpCount = 0;
self.armor -= 20f;
self.moveSpeed *= 0.25f;
self.attackSpeed *= 0.75f;
}
if (self.HasBuff(Modules.Buffs.nemImpairedBuff))
{
self.maxJumpCount = 0;
self.moveSpeed *= 0.25f;
}
if (self.HasBuff(Modules.Buffs.smallSlowBuff))
{
self.armor += 10f;
self.moveSpeed *= 0.7f;
}
if (self.HasBuff(Modules.Buffs.bigSlowBuff))
{
self.moveSpeed *= 0.2f;
}
//regen passive
if (self.baseNameToken == "NEMFORCER_NAME" || self.baseNameToken == "NEMFORCER_BOSS_NAME")
{
HealthComponent hp = self.healthComponent;
float regenValue = hp.fullCombinedHealth * NemforcerPlugin.passiveRegenBonus;
float regen = Mathf.SmoothStep(regenValue, 0, hp.combinedHealth / hp.fullCombinedHealth);
// reduce it while taking damage, scale it back up over time- only apply this to the normal boss and let ultra keep the bullshit regen
if (self.teamComponent.teamIndex == TeamIndex.Monster && self.baseNameToken == "NEMFORCER_NAME")
{
float maxRegenValue = regen;
float i = Mathf.Clamp(self.outOfDangerStopwatch, 0f, 5f);
regen = Util.Remap(i, 0f, 5f, 0f, maxRegenValue);
}
self.regen += regen;
if (self.teamComponent.teamIndex == TeamIndex.Monster)
{
self.regen *= 0.8f;
if (self.HasBuff(RoR2Content.Buffs.SuperBleed) || self.HasBuff(RoR2Content.Buffs.Bleeding)) self.regen = 0f;
}
}
}
}
private void CharacterMaster_OnInventoryChanged(On.RoR2.CharacterMaster.orig_OnInventoryChanged orig, CharacterMaster self)
{
orig(self);
if (self.hasBody)
{
if (self.GetBody().baseNameToken == "ENFORCER_NAME")
{
var weaponComponent = self.GetBody().GetComponent<EnforcerWeaponComponent>();
if (weaponComponent)
{
weaponComponent.DelayedResetWeaponsAndShields();
weaponComponent.ModelCheck();
}
}
else
{
if (self.GetBody().baseNameToken == "NEMFORCER_NAME")
{
var nemComponent = self.GetBody().GetComponent<NemforcerController>();
if (nemComponent)
{
nemComponent.DelayedResetWeapon();
nemComponent.ModelCheck();
}
}
else if (self.inventory && Modules.Config.useNeedlerCrosshair.Value)
{
if (self.inventory.GetItemCount(RoR2Content.Items.LunarPrimaryReplacement) > 0)
{
self.GetBody().crosshairPrefab = needlerCrosshair;
}
}
}
}
}
private void CharacterBody_OnLevelChanged(On.RoR2.CharacterBody.orig_OnLevelUp orig, CharacterBody self)
{
orig(self);
if (self.baseNameToken == "ENFORCER_NAME")
{
var lightController = self.GetComponent<EnforcerLightControllerAlt>();
if (lightController)
{
lightController.FlashLights(4);
}
}
}
private void HealthComponent_TakeDamage(On.RoR2.HealthComponent.orig_TakeDamage orig, HealthComponent self, DamageInfo info)
{
bool blocked = false;
if ((info.damageType & DamageType.BarrierBlocked) != DamageType.Generic && self.body.baseNameToken == "ENFORCER_NAME")
{
blocked = true;
}
if (self.body.baseNameToken == "ENFORCER_NAME" && info.attacker)
{
//uncomment this if barrier blocking isnt enough and you need to check facing direction like old days
CharacterBody body = info.attacker.GetComponent<CharacterBody>();
if (body) {
//this is probably why this isn't networked
EnforcerComponent enforcerComponent = self.body.GetComponent<EnforcerComponent>();
//ugly hack cause golems kept hitting past shield
//actually they're just not anymore? probably cause shield isn't parented anymroe
//code stays for deflecting tho
if (body.baseNameToken == "GOLEM_BODY_NAME" && GetShieldBlock(self, info, enforcerComponent)) {
blocked = self.body.HasBuff(Modules.Buffs.protectAndServeBuff);
if (enforcerComponent != null) {
if (enforcerComponent.isDeflecting) {
blocked = true;
}
//Debug.LogWarning("firin mah layzor " + NetworkServer.active);
//enforcerComponent.invokeOnLaserHitEvent();
}
}
if (enforcerComponent) {
enforcerComponent.AttackBlocked(blocked);
}
}
}
if (blocked)
{
GameObject blockEffect = EnforcerModPlugin.blockEffectPrefab;
if (info.procCoefficient >= 1) blockEffect = EnforcerModPlugin.heavyBlockEffectPrefab;
EffectData effectData = new EffectData
{
origin = info.position,
rotation = Util.QuaternionSafeLookRotation((info.force != Vector3.zero) ? info.force : UnityEngine.Random.onUnitSphere)
};
EffectManager.SpawnEffect(blockEffect, effectData, true);
info.rejected = true;
}
if (self.body.name == "EnergyShield")
{
info.damage = info.procCoefficient;
}
orig(self, info);
}
private void EntityStateMachine_SetState(On.RoR2.EntityStateMachine.orig_SetState orig, EntityStateMachine self, EntityState newState)
{
if(self.commonComponents.characterBody?.bodyIndex == BodyCatalog.FindBodyIndex("EnforcerBody"))
{
if (newState is EntityStates.GlobalSkills.LunarNeedle.FireLunarNeedle)
newState = new FireNeedler();
}
orig(self, newState);
}
private void BaseState_OnEnter(On.EntityStates.BaseState.orig_OnEnter orig, BaseState self) {
orig(self);
if (self.outer.customName == "EnforcerParry") {
self.damageStat *= 5f;
}
List<string> absolutelydisgustinghackynamecheck = new List<string> {
"NebbysWrath.VariantEntityStates.LesserWisp.FireStoneLaser",
"NebbysWrath.VariantEntityStates.GreaterWisp.FireDoubleStoneLaser",
};
if (absolutelydisgustinghackynamecheck.Contains(self.GetType().ToString())) {
CheckEnforcerParry(self.GetAimRay());
}
}
private void FireLaser_OnEnter(On.EntityStates.GolemMonster.FireLaser.orig_OnEnter orig, EntityStates.GolemMonster.FireLaser self)
{
orig(self);
Ray ray = self.modifiedAimRay;
CheckEnforcerParry(ray);
}
private static void CheckEnforcerParry(Ray ray) {
RaycastHit raycastHit;
if (Physics.Raycast(ray, out raycastHit, 1000f, LayerIndex.world.mask | LayerIndex.defaultLayer.mask | LayerIndex.entityPrecise.mask)) {
//do I have this power?
GameObject gob = raycastHit.transform.GetComponent<HurtBox>()?.healthComponent.gameObject;
if (!gob) {
gob = raycastHit.transform.GetComponent<HealthComponent>()?.gameObject;
}
//I believe I do. it makes the decompiled version look mad ugly tho
EnforcerComponent enforcer = gob?.GetComponent<EnforcerComponent>();
//Debug.LogWarning($"tran {raycastHit.transform}, " +
// $"hurt {raycastHit.transform.GetComponent<HurtBox>()}, " +
// $"health {raycastHit.transform.GetComponent<HurtBox>()?.healthComponent.gameObject}, " +
// $"{gob?.GetComponent<EnforcerComponent>()}");
if (enforcer) {
enforcer.invokeOnLaserHitEvent();
}
}
}
private void FireLunarNeedle_OnEnter(On.EntityStates.GlobalSkills.LunarNeedle.FireLunarNeedle.orig_OnEnter orig, EntityStates.GlobalSkills.LunarNeedle.FireLunarNeedle self)
{
// this actually didn't work, hopefully someone else can figure it out bc needler shotgun sounds badass
// don't forget to register the state if you do :^)
if (false)//self.outer.commonComponents.characterBody)
{
if (self.outer.commonComponents.characterBody.bodyIndex == BodyCatalog.FindBodyIndex("EnforcerBody"))
{
self.outer.SetNextState(new FireNeedler());
Debug.Log("uh");
return;
}
}
orig(self);
}
private void SceneDirector_Start(On.RoR2.SceneDirector.orig_Start orig, SceneDirector self)
{
if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "moon")
{
//null checks to hell and back
if (GameObject.Find("EscapeSequenceController")) {
if (GameObject.Find("EscapeSequenceController").transform.Find("EscapeSequenceObjects")) {
if (GameObject.Find("EscapeSequenceController").transform.Find("EscapeSequenceObjects").transform.Find("SmoothFrog")) {
GameObject.Find("EscapeSequenceController").transform.Find("EscapeSequenceObjects").transform.Find("SmoothFrog").gameObject.AddComponent<FrogComponent>();
}
}
}
}
if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "bazaar")
{
if (DifficultyIndex.Hard <= Run.instance.selectedDifficulty && Run.instance.stageClearCount >= 5)
{
bool conditionsMet = false;
for (int i = CharacterMaster.readOnlyInstancesList.Count - 1; i >= 0; i--)
{
CharacterMaster master = CharacterMaster.readOnlyInstancesList[i];
if (master.teamIndex == TeamIndex.Player && master.bodyPrefab == BodyCatalog.FindBodyPrefab("EnforcerBody"))
{
var j = master.GetComponent<NemesisInvasion>();
if (!j) conditionsMet = true;
else if (!j.hasInvaded && !j.pendingInvasion) conditionsMet = true;
}
}
if (conditionsMet && NetworkServer.active)
{
ChatMessage.SendColored("An unusual energy emanates from below..", new Color(0.149f, 0.0039f, 0.2117f));
}
}
}
orig(self);
}
private void BaseMainMenuScreen_OnEnter(On.RoR2.UI.MainMenu.BaseMainMenuScreen.orig_OnEnter orig, RoR2.UI.MainMenu.BaseMainMenuScreen self, RoR2.UI.MainMenu.MainMenuController menuController)
{
orig(self, menuController);
if (UnityEngine.Random.value <= 0.1f)
{
GameObject hammer = Instantiate(Assets.nemesisHammer);
hammer.transform.position = new Vector3(35, 4.5f, 21);
hammer.transform.rotation = Quaternion.Euler(new Vector3(45, 270, 0));
hammer.transform.localScale = new Vector3(12, 12, 340);
}
}
private void CharacterSelectBarController_Start(On.RoR2.CharacterSelectBarController.orig_Start orig, CharacterSelectBarController self) {
string bodyName = NemforcerPlugin.characterPrefab.GetComponent<CharacterBody>().baseNameToken;
bool unlocked = LocalUserManager.readOnlyLocalUsersList.Any((LocalUser localUser) => localUser.userProfile.HasUnlockable(EnforcerUnlockables.nemesisUnlockableDef));
SurvivorCatalog.FindSurvivorDefFromBody(NemforcerPlugin.characterPrefab).hidden = !unlocked;
orig(self);
}
private void HealthComponent_Suicide(On.RoR2.HealthComponent.orig_Suicide orig, HealthComponent self, GameObject killerOverride, GameObject inflictorOverride, DamageType damageType) {
if (damageType == DamageType.VoidDeath) {
//Debug.LogWarning("voidDeath");
if (self.body.baseNameToken == "NEMFORCER_NAME" || self.body.baseNameToken == "NEMFORCER_BOSS_NAME") {
//Debug.LogWarning("nemmememme");
if (self.body.teamComponent.teamIndex != TeamIndex.Player) {
//Debug.LogWarning("spookyscary");
return;
}
}
}
orig(self, killerOverride, inflictorOverride, damageType);
}
private bool GetShieldBlock(HealthComponent self, DamageInfo info, EnforcerComponent shieldComponent)
{
CharacterBody charB = self.GetComponent<CharacterBody>();
Ray aimRay = shieldComponent.aimRay;
Vector3 relativePosition = info.attacker.transform.position - aimRay.origin;
float angle = Vector3.Angle(shieldComponent.shieldDirection, relativePosition);
return angle < 55;
}
/*private void GlobalEventManager_OnEnemyHit(On.RoR2.GlobalEventManager.orig_OnHitEnemy orig, GlobalEventManager self, DamageInfo info, GameObject victim)
{
ShieldComponent shieldComponent = self.GetComponent<ShieldComponent>();
if (shieldComponent && info.attacker && victim.GetComponent<CharacterBody>().HasBuff(jackBoots))
{
bool canBlock = GetShieldDebuffBlock(victim, info, shieldComponent);
if (canBlock)
{
//this is gross and i don't even know if it works but i'm too tired to test it rn
// yeah ok it literally doesn't work, ig ive up, we'll call it a feature if no one else can fix it
if (info.damageType.HasFlag(DamageType.IgniteOnHit) || info.damageType.HasFlag(DamageType.PercentIgniteOnHit) || info.damageType.HasFlag(DamageType.BleedOnHit) || info.damageType.HasFlag(DamageType.ClayGoo) || info.damageType.HasFlag(DamageType.Nullify) || info.damageType.HasFlag(DamageType.SlowOnHit)) info.damageType = DamageType.Generic;
return;
}
}
orig(self, info, victim);
}*/
/*private bool GetShieldDebuffBlock(GameObject self, DamageInfo info, ShieldComponent shieldComponent)
{
CharacterBody charB = self.GetComponent<CharacterBody>();
Ray aimRay = shieldComponent.aimRay;
Vector3 relativePosition = info.attacker.transform.position - aimRay.origin;
float angle = Vector3.Angle(shieldComponent.shieldDirection, relativePosition);
return angle < ShieldBlockAngle;
}*/
private void CharacterBody_Update(On.RoR2.CharacterBody.orig_Update orig, CharacterBody self)
{
if (self.name == "EnergyShield")
{
return;
}
orig(self);
}
#endregion
private static GameObject CreateBodyModel(GameObject main)
{
Destroy(main.transform.Find("ModelBase").gameObject);
Destroy(main.transform.Find("CameraPivot").gameObject);
Destroy(main.transform.Find("AimOrigin").gameObject);
return Assets.MainAssetBundle.LoadAsset<GameObject>("mdlEnforcer");
}
private static GameObject CreateDisplayModel()
{
return Assets.MainAssetBundle.LoadAsset<GameObject>("EnforcerDisplay");
}
private static void CreateDisplayPrefab()
{
GameObject model = CreateDisplayModel();
ChildLocator childLocator = model.GetComponent<ChildLocator>();
CharacterModel characterModel = model.AddComponent<CharacterModel>();
characterModel.body = null;
//let's set up rendereinfos in editor man
//for (int i = 0; i < characterModel.baseRendererInfos.Length; i++)
//{
// CharacterModel.RendererInfo rendererInfo = characterModel.baseRendererInfos[i];
// rendererInfo.defaultMaterial = Assets.CloneMaterial(rendererInfo.defaultMaterial);
//}
characterModel.baseRendererInfos = new CharacterModel.RendererInfo[]
{
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcerShield", 0f, Color.black, 1f),
renderer = childLocator.FindChild("ShieldModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
//not hotpoo shader for transparency
defaultMaterial = childLocator.FindChild("ShieldGlassModel").gameObject.GetComponent<SkinnedMeshRenderer>().material, //Assets.CreateMaterial("matSexforcerShieldGlass", 0f, Color.black, 1f),
renderer = childLocator.FindChild("ShieldGlassModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = true
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcerBoard", 0f, Color.black, 1f),
renderer = childLocator.FindChild("SkamteBordModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcerGun", 1f, Color.white, 0f),
renderer = childLocator.FindChild("GunModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matClassicGunSuper", 0f, Color.black, 0f),
renderer = childLocator.FindChild("SuperGunModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matClassicGunHMG", 0f, Color.black, 0f),
renderer = childLocator.FindChild("HMGModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcerHammer", 0f, Color.black, 0f),
renderer = childLocator.FindChild("HammerModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcer", 1f, Color.white, 0f),
renderer = childLocator.FindChild("PauldronModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcer", 1f, Color.white, 0f),
renderer = childLocator.FindChild("Model").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
}
};
characterModel.autoPopulateLightInfos = true;
characterModel.invisibilityCount = 0;
characterModel.temporaryOverlays = new List<TemporaryOverlay>();
characterModel.mainSkinnedMeshRenderer = characterModel.baseRendererInfos[8].renderer.gameObject.GetComponent<SkinnedMeshRenderer>();
characterDisplay = PrefabAPI.InstantiateClone(model, "EnforcerDisplay", true);
characterDisplay.AddComponent<MenuSoundComponent>();
characterDisplay.AddComponent<EnforcerLightController>();
characterDisplay.AddComponent<EnforcerLightControllerAlt>();
//i really wish this was set up in code rather than in the editor so we wouldn't have to build a new assetbundle and redo the components/events every time something on the prefab changes
//it's seriously tedious as fuck.
// just make it not tedious 4head
// turns out addlistener doesn't even fuckin work so I actually can't set it up in code even if when I wanted to try the inferior way
//pain.
//but yea i tried it too and gave up so understandable
CharacterSelectSurvivorPreviewDisplayController displayController = characterDisplay.GetComponent<CharacterSelectSurvivorPreviewDisplayController>();
if (displayController) displayController.bodyPrefab = characterPrefab;
}
private static void CreatePrefab()
{
//...what?
// https://youtu.be/zRXl8Ow2bUs
#region add all the things
characterPrefab = PrefabAPI.InstantiateClone(Resources.Load<GameObject>("Prefabs/CharacterBodies/CommandoBody"), "EnforcerBody");
characterPrefab.GetComponent<NetworkIdentity>().localPlayerAuthority = true;
GameObject model = CreateBodyModel(characterPrefab);
GameObject modelBase = new GameObject("ModelBase");
modelBase.transform.parent = characterPrefab.transform;
modelBase.transform.localPosition = new Vector3(0f, -0.91f, 0f);
modelBase.transform.localRotation = Quaternion.identity;
modelBase.transform.localScale = Vector3.one;
GameObject cameraPivot = new GameObject("CameraPivot");
cameraPivot.transform.parent = modelBase.transform;
cameraPivot.transform.localPosition = new Vector3(0f, 0f, 0f); //1.6
cameraPivot.transform.localRotation = Quaternion.identity;
cameraPivot.transform.localScale = Vector3.one;
GameObject aimOirign = new GameObject("AimOrigin");
aimOirign.transform.parent = modelBase.transform;
aimOirign.transform.localPosition = new Vector3(0f, 3f, 0f); //1.8
aimOirign.transform.localRotation = Quaternion.identity;
aimOirign.transform.localScale = Vector3.one;
CharacterDirection characterDirection = characterPrefab.GetComponent<CharacterDirection>();
characterDirection.moveVector = Vector3.zero;
characterDirection.targetTransform = modelBase.transform;
characterDirection.overrideAnimatorForwardTransform = null;
characterDirection.rootMotionAccumulator = null;
characterDirection.modelAnimator = model.GetComponentInChildren<Animator>();
characterDirection.driveFromRootRotation = false;
characterDirection.turnSpeed = 720f;
CharacterBody bodyComponent = characterPrefab.GetComponent<CharacterBody>();
bodyComponent.name = "EnforcerBody";
bodyComponent.baseNameToken = "ENFORCER_NAME";
bodyComponent.subtitleNameToken = "ENFORCER_SUBTITLE";
bodyComponent.bodyFlags = CharacterBody.BodyFlags.ImmuneToExecutes;
bodyComponent.rootMotionInMainState = false;
bodyComponent.mainRootSpeed = 0;
bodyComponent.baseMaxHealth = Modules.Config.baseHealth.Value;
bodyComponent.levelMaxHealth = Modules.Config.healthGrowth.Value;
bodyComponent.baseRegen = Modules.Config.baseRegen.Value;
bodyComponent.levelRegen = Modules.Config.regenGrowth.Value;
bodyComponent.baseMaxShield = 0;
bodyComponent.levelMaxShield = 0;
bodyComponent.baseMoveSpeed = Modules.Config.baseMovementSpeed.Value;
bodyComponent.levelMoveSpeed = 0;
bodyComponent.baseAcceleration = 80;
bodyComponent.baseJumpPower = 15;
bodyComponent.levelJumpPower = 0;
bodyComponent.baseDamage = Modules.Config.baseDamage.Value;
bodyComponent.levelDamage = Modules.Config.damageGrowth.Value;
bodyComponent.baseAttackSpeed = 1;
bodyComponent.levelAttackSpeed = 0;
bodyComponent.baseCrit = Modules.Config.baseCrit.Value;
bodyComponent.levelCrit = 0;
bodyComponent.baseArmor = Modules.Config.baseArmor.Value;
bodyComponent.levelArmor = Modules.Config.armorGrowth.Value;
bodyComponent.baseJumpCount = 1;
bodyComponent.sprintingSpeedMultiplier = 1.45f;
bodyComponent.wasLucky = false;
bodyComponent.hideCrosshair = false;
bodyComponent.crosshairPrefab = Resources.Load<GameObject>("Prefabs/Crosshair/SMGCrosshair");
bodyComponent.aimOriginTransform = aimOirign.transform;
bodyComponent.hullClassification = HullClassification.Human;
bodyComponent.portraitIcon = Assets.charPortrait;
bodyComponent.isChampion = false;
bodyComponent.currentVehicle = null;
bodyComponent.skinIndex = 0U;
bodyComponent.bodyColor = characterColor;
bodyComponent.spreadBloomDecayTime = 0.7f;
Modules.States.AddSkill(typeof(EnforcerMain));
Modules.States.AddSkill(typeof(FireNeedler));
EntityStateMachine stateMachine = bodyComponent.GetComponent<EntityStateMachine>();
stateMachine.mainStateType = new SerializableEntityStateType(typeof(EnforcerMain));
//why
//in the god damn fuck
//does AddComponent default to an extension coming from the fucking starstorm dll
EntityStateMachine octagonapus = bodyComponent.gameObject.AddComponent<EntityStateMachine>();
octagonapus.customName = "EnforcerParry";
NetworkStateMachine networkStateMachine = bodyComponent.GetComponent<NetworkStateMachine>();
networkStateMachine.stateMachines = networkStateMachine.stateMachines.Append(octagonapus).ToArray();
SerializableEntityStateType idleState = new SerializableEntityStateType(typeof(Idle));
octagonapus.initialStateType = idleState;
octagonapus.mainStateType = idleState;
CharacterMotor characterMotor = characterPrefab.GetComponent<CharacterMotor>();
characterMotor.walkSpeedPenaltyCoefficient = 1f;
characterMotor.characterDirection = characterDirection;
characterMotor.muteWalkMotion = false;
characterMotor.mass = 200f;
characterMotor.airControl = 0.25f;
characterMotor.disableAirControlUntilCollision = false;
characterMotor.generateParametersOnAwake = true;
CameraTargetParams cameraTargetParams = characterPrefab.GetComponent<CameraTargetParams>();
cameraTargetParams.cameraParams = ScriptableObject.CreateInstance<CharacterCameraParams>();
cameraTargetParams.cameraParams.maxPitch = 70;
cameraTargetParams.cameraParams.minPitch = -70;
cameraTargetParams.cameraParams.wallCushion = 0.1f;
cameraTargetParams.cameraParams.pivotVerticalOffset = 1.37f;
cameraTargetParams.cameraParams.standardLocalCameraPos = EnforcerMain.standardCameraPosition;
cameraTargetParams.cameraPivotTransform = null;
cameraTargetParams.aimMode = CameraTargetParams.AimType.Standard;
cameraTargetParams.recoil = Vector2.zero;
cameraTargetParams.idealLocalCameraPos = Vector3.zero;
cameraTargetParams.dontRaycastToPivot = false;
model.transform.parent = modelBase.transform;
model.transform.localPosition = Vector3.zero;
model.transform.localRotation = Quaternion.identity;
ModelLocator modelLocator = characterPrefab.GetComponent<ModelLocator>();
modelLocator.modelTransform = model.transform;
modelLocator.modelBaseTransform = modelBase.transform;
ChildLocator childLocator = model.GetComponent<ChildLocator>();
//bubble shield stuff
/*GameObject engiShieldObj = Resources.Load<GameObject>("Prefabs/Projectiles/EngiBubbleShield");
Material shieldFillMat = UnityEngine.Object.Instantiate<Material>(engiShieldObj.transform.Find("Collision").Find("ActiveVisual").GetComponent<MeshRenderer>().material);
childLocator.FindChild("BungusShieldFill").GetComponent<MeshRenderer>().material = shieldFillMat;
Material shieldOuterMat = UnityEngine.Object.Instantiate<Material>(engiShieldObj.transform.Find("Collision").Find("ActiveVisual").Find("Edge").GetComponent<MeshRenderer>().material);
childLocator.FindChild("BungusShieldOutline").GetComponent<MeshRenderer>().material = shieldOuterMat;*/
/*Material marauderShieldFillMat = UnityEngine.Object.Instantiate<Material>(shieldFillMat);
marauderShieldFillMat.SetTexture("_MainTex", Assets.MainAssetBundle.LoadAsset<Material>("matMarauderShield").GetTexture("_MainTex"));
marauderShieldFillMat.SetTexture("_EmTex", Assets.MainAssetBundle.LoadAsset<Material>("matMarauderShield").GetTexture("_EmissionMap"));
childLocator.FindChild("MarauderShieldFill").GetComponent<MeshRenderer>().material = marauderShieldFillMat;
Material marauderShieldOuterMat = UnityEngine.Object.Instantiate<Material>(shieldOuterMat);
marauderShieldOuterMat.SetTexture("_MainTex", Assets.MainAssetBundle.LoadAsset<Material>("matMarauderShield").GetTexture("_MainTex"));
marauderShieldOuterMat.SetTexture("_EmTex", Assets.MainAssetBundle.LoadAsset<Material>("matMarauderShield").GetTexture("_EmissionMap"));
childLocator.FindChild("MarauderShieldOutline").GetComponent<MeshRenderer>().material = marauderShieldOuterMat;*/
/*var stuff1 = childLocator.FindChild("BungusShieldFill").gameObject.AddComponent<AnimateShaderAlpha>();
var stuff2 = engiShieldObj.transform.Find("Collision").Find("ActiveVisual").GetComponent<AnimateShaderAlpha>();
stuff1.alphaCurve = stuff2.alphaCurve;
stuff1.decal = stuff2.decal;
stuff1.destroyOnEnd = false;
stuff1.disableOnEnd = false;
stuff1.time = 0;
stuff1.timeMax = 0.6f;*/
//childLocator.FindChild("BungusShieldFill").gameObject.AddComponent<ObjectScaleCurve>().timeMax = 0.3f;
CharacterModel characterModel = model.AddComponent<CharacterModel>();
characterModel.body = bodyComponent;
characterModel.baseRendererInfos = new CharacterModel.RendererInfo[]
{
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcerShield", 0f, Color.black, 1f),
renderer = childLocator.FindChild("ShieldModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
//not hotpoo shader for transparency
defaultMaterial = childLocator.FindChild("ShieldGlassModel").gameObject.GetComponent<SkinnedMeshRenderer>().material, //Assets.CreateMaterial("matSexforcerShieldGlass", 0f, Color.black, 1f),
renderer = childLocator.FindChild("ShieldGlassModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = true
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcerBoard", 0f, Color.black, 1f),
renderer = childLocator.FindChild("SkamteBordModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcerGun", 1f, Color.white, 0f),
renderer = childLocator.FindChild("GunModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matClassicGunSuper", 0f, Color.black, 0f),
renderer = childLocator.FindChild("SuperGunModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matClassicGunHMG", 0f, Color.black, 0f),
renderer = childLocator.FindChild("HMGModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcerHammer", 0f, Color.black, 0f),
renderer = childLocator.FindChild("HammerModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcer", 1f, Color.white, 0f),
renderer = childLocator.FindChild("PauldronModel").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
},
new CharacterModel.RendererInfo
{
defaultMaterial = Assets.CreateMaterial("matEnforcer", 1f, Color.white, 0f),
renderer = childLocator.FindChild("Model").gameObject.GetComponent<SkinnedMeshRenderer>(),
defaultShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On,
ignoreOverlays = false
}
};
characterModel.autoPopulateLightInfos = true;
characterModel.invisibilityCount = 0;
characterModel.temporaryOverlays = new List<TemporaryOverlay>();
characterModel.mainSkinnedMeshRenderer = childLocator.FindChild("Model").gameObject.GetComponent<SkinnedMeshRenderer>();
if (IDPHelperInstalled) {
characterModel.gameObject.AddComponent<EnforcerItemDisplayEditorComponent>();
}
childLocator.FindChild("Chair").GetComponent<MeshRenderer>().material = Assets.CreateMaterial("matChair", 0f, Color.black, 0f);
//fuck man
childLocator.FindChild("Head").transform.localScale = Vector3.one * Modules.Config.headSize.Value;
HealthComponent healthComponent = characterPrefab.GetComponent<HealthComponent>();
healthComponent.health = 160f;
healthComponent.shield = 0f;
healthComponent.barrier = 0f;
healthComponent.magnetiCharge = 0f;
healthComponent.body = null;
healthComponent.dontShowHealthbar = false;
healthComponent.globalDeathEventChanceCoefficient = 1f;
CharacterDeathBehavior characterDeathBehavior = characterPrefab.GetComponent<CharacterDeathBehavior>();
characterDeathBehavior.deathStateMachine = characterPrefab.GetComponent<EntityStateMachine>();
//characterDeathBehavior.deathState = new SerializableEntityStateType(typeof(GenericCharacterDeath));
SfxLocator sfxLocator = characterPrefab.GetComponent<SfxLocator>();
sfxLocator.deathSound = Sounds.DeathSound;
sfxLocator.barkSound = "";
sfxLocator.openSound = "";
sfxLocator.landingSound = "Play_char_land";
sfxLocator.fallDamageSound = "Play_char_land_fall_damage";
sfxLocator.aliveLoopStart = "";
sfxLocator.aliveLoopStop = "";
Rigidbody rigidbody = characterPrefab.GetComponent<Rigidbody>();
rigidbody.mass = 200f;
rigidbody.drag = 0f;
rigidbody.angularDrag = 0f;
rigidbody.useGravity = false;
rigidbody.isKinematic = true;
rigidbody.interpolation = RigidbodyInterpolation.None;
rigidbody.collisionDetectionMode = CollisionDetectionMode.Discrete;
rigidbody.constraints = RigidbodyConstraints.None;
CapsuleCollider capsuleCollider = characterPrefab.GetComponent<CapsuleCollider>();
capsuleCollider.isTrigger = false;
capsuleCollider.material = null;
capsuleCollider.center = new Vector3(0f, 0f, 0f);
capsuleCollider.radius = 0.5f;
capsuleCollider.height = 1.82f;
capsuleCollider.direction = 1;
KinematicCharacterMotor kinematicCharacterMotor = characterPrefab.GetComponent<KinematicCharacterMotor>();
kinematicCharacterMotor.CharacterController = characterMotor;
kinematicCharacterMotor.Capsule = capsuleCollider;
kinematicCharacterMotor.Rigidbody = rigidbody;
kinematicCharacterMotor.DetectDiscreteCollisions = false;
kinematicCharacterMotor.GroundDetectionExtraDistance = 0f;
kinematicCharacterMotor.MaxStepHeight = 0.2f;
kinematicCharacterMotor.MinRequiredStepDepth = 0.1f;
kinematicCharacterMotor.MaxStableSlopeAngle = 55f;
kinematicCharacterMotor.MaxStableDistanceFromLedge = 0.5f;
kinematicCharacterMotor.PreventSnappingOnLedges = false;
kinematicCharacterMotor.MaxStableDenivelationAngle = 55f;
kinematicCharacterMotor.RigidbodyInteractionType = RigidbodyInteractionType.None;
kinematicCharacterMotor.PreserveAttachedRigidbodyMomentum = true;
kinematicCharacterMotor.HasPlanarConstraint = false;
kinematicCharacterMotor.PlanarConstraintAxis = Vector3.up;
kinematicCharacterMotor.StepHandling = StepHandlingMethod.None;
kinematicCharacterMotor.LedgeHandling = true;
kinematicCharacterMotor.InteractiveRigidbodyHandling = true;
kinematicCharacterMotor.SafeMovement = false;
HurtBoxGroup hurtBoxGroup = model.AddComponent<HurtBoxGroup>();
HurtBox mainHurtbox = model.transform.Find("MainHurtbox").gameObject.AddComponent<HurtBox>();
mainHurtbox.gameObject.layer = LayerIndex.entityPrecise.intVal;
mainHurtbox.healthComponent = healthComponent;
mainHurtbox.isBullseye = true;
mainHurtbox.damageModifier = HurtBox.DamageModifier.Normal;
mainHurtbox.hurtBoxGroup = hurtBoxGroup;
mainHurtbox.indexInGroup = 0;
//make a hurtbox for the shield since this works apparently !
HurtBox shieldHurtbox = childLocator.FindChild("ShieldHurtbox").gameObject.AddComponent<HurtBox>();
shieldHurtbox.gameObject.layer = LayerIndex.entityPrecise.intVal;
shieldHurtbox.healthComponent = healthComponent;
shieldHurtbox.isBullseye = false;
shieldHurtbox.damageModifier = HurtBox.DamageModifier.Barrier;
shieldHurtbox.hurtBoxGroup = hurtBoxGroup;
shieldHurtbox.indexInGroup = 1;
HurtBox shieldHurtbox2 = childLocator.FindChild("ShieldHurtbox2").gameObject.AddComponent<HurtBox>();
shieldHurtbox2.gameObject.layer = LayerIndex.entityPrecise.intVal;
shieldHurtbox2.healthComponent = healthComponent;
shieldHurtbox2.isBullseye = false;
shieldHurtbox2.damageModifier = HurtBox.DamageModifier.Barrier;
shieldHurtbox2.hurtBoxGroup = hurtBoxGroup;
shieldHurtbox2.indexInGroup = 1;
childLocator.FindChild("ShieldHurtboxParent").gameObject.SetActive(false);
hurtBoxGroup.hurtBoxes = new HurtBox[]
{
mainHurtbox,
shieldHurtbox,
shieldHurtbox2
};
hurtBoxGroup.mainHurtBox = mainHurtbox;
hurtBoxGroup.bullseyeCount = 1;
//make a hitbox for shoulder bash
HitBoxGroup hitBoxGroup = model.AddComponent<HitBoxGroup>();
GameObject chargeHitbox = childLocator.FindChild("ChargeHitbox").gameObject;
HitBox hitBox = chargeHitbox.AddComponent<HitBox>();
chargeHitbox.layer = LayerIndex.projectile.intVal;
hitBoxGroup.hitBoxes = new HitBox[]
{
hitBox
};
hitBoxGroup.groupName = "Charge";
//hammer hitbox
HitBoxGroup hammerHitBoxGroup = model.AddComponent<HitBoxGroup>();
GameObject hammerHitbox = childLocator.FindChild("ActualHammerHitbox").gameObject;
HitBox hammerHitBox = hammerHitbox.AddComponent<HitBox>();
hammerHitbox.layer = LayerIndex.projectile.intVal;
hammerHitBoxGroup.hitBoxes = new HitBox[]
{
hammerHitBox
};
hammerHitBoxGroup.groupName = "Hammer";
//hammer hitbox2
HitBoxGroup hammerHitBoxGroup2 = model.AddComponent<HitBoxGroup>();
GameObject hammerHitbox2 = childLocator.FindChild("HammerHitboxBig").gameObject;
HitBox hammerHitBox2 = hammerHitbox2.AddComponent<HitBox>();
hammerHitbox2.layer = LayerIndex.projectile.intVal;
hammerHitBoxGroup2.hitBoxes = new HitBox[]
{
hammerHitBox2
};
hammerHitBoxGroup2.groupName = "HammerBig";
FootstepHandler footstepHandler = model.AddComponent<FootstepHandler>();
footstepHandler.baseFootstepString = "Play_player_footstep";
footstepHandler.sprintFootstepOverrideString = "";
footstepHandler.enableFootstepDust = true;
footstepHandler.footstepDustPrefab = Resources.Load<GameObject>("Prefabs/GenericFootstepDust");
RagdollController ragdollController = model.GetComponent<RagdollController>();
PhysicMaterial physicMat = Resources.Load<GameObject>("Prefabs/CharacterBodies/CommandoBody").GetComponentInChildren<RagdollController>().bones[1].GetComponent<Collider>().material;
foreach (Transform i in ragdollController.bones)
{
if (i)
{
i.gameObject.layer = LayerIndex.ragdoll.intVal;
Collider j = i.GetComponent<Collider>();
if (j)
{
j.material = physicMat;
j.sharedMaterial = physicMat;
}
}
}
AimAnimator aimAnimator = model.AddComponent<AimAnimator>();
aimAnimator.directionComponent = characterDirection;
aimAnimator.pitchRangeMax = 60f;
aimAnimator.pitchRangeMin = -60f;
aimAnimator.yawRangeMin = -90f;
aimAnimator.yawRangeMax = 90f;
aimAnimator.pitchGiveupRange = 30f;
aimAnimator.yawGiveupRange = 10f;
aimAnimator.giveupDuration = 3f;
aimAnimator.inputBank = characterPrefab.GetComponent<InputBankTest>();
characterPrefab.AddComponent<EnforcerComponent>();
characterPrefab.AddComponent<EnforcerWeaponComponent>();
characterPrefab.AddComponent<EnforcerNetworkComponent>();
characterPrefab.AddComponent<EnforcerLightController>();
characterPrefab.AddComponent<EnforcerLightControllerAlt>();
#endregion
}
private void RegisterCharacter()
{
string desc = "The Enforcer is a defensive juggernaut who can take and give a beating.<color=#CCD3E0>" + Environment.NewLine + Environment.NewLine;
desc = desc + "< ! > Riot Shotgun can pierce through many enemies at once." + Environment.NewLine + Environment.NewLine;
desc = desc + "< ! > Batting away enemies with Shield Bash guarantees you will keep enemies at a safe range." + Environment.NewLine + Environment.NewLine;
desc = desc + "< ! > Use Tear Gas to weaken large crowds of enemies, then get in close and crush them." + Environment.NewLine + Environment.NewLine;
desc = desc + "< ! > When you can, use Protect and Serve against walls to prevent enemies from flanking you." + Environment.NewLine + Environment.NewLine;
string outro = characterOutro;
if (Modules.Config.forceUnlock.Value) outro = "..and so he left, having cheated not only the game, but himself. He didn't grow. He didn't improve. He took a shortcut and gained nothing. He experienced a hollow victory. Nothing was risked and nothing was rained.";
LanguageAPI.Add("ENFORCER_NAME", characterName);
LanguageAPI.Add("ENFORCER_DESCRIPTION", desc);
LanguageAPI.Add("ENFORCER_SUBTITLE", characterSubtitle);
//LanguageAPI.Add("ENFORCER_LORE", "I'M FUCKING INVINCIBLE");
LanguageAPI.Add("ENFORCER_LORE", characterLore);
LanguageAPI.Add("ENFORCER_OUTRO_FLAVOR", outro);
LanguageAPI.Add("ENFORCER_OUTRO_FAILURE", characterOutroFailure);
characterDisplay.AddComponent<NetworkIdentity>();
Modules.Survivors.RegisterNewSurvivor(characterPrefab,
characterDisplay,
"ENFORCER",
Modules.Config.forceUnlock.Value? null : EnforcerUnlockables.enforcerUnlockableDef,
5.1f);
SkillSetup();
bodyPrefabs.Add(characterPrefab);
}
private void RegisterProjectile()
{
//i'm the treasure, baby, i'm the prize, i'm yours forever
stunGrenade = Resources.Load<GameObject>("Prefabs/Projectiles/CommandoGrenadeProjectile").InstantiateClone("EnforcerStunGrenade", true);
ProjectileController stunGrenadeController = stunGrenade.GetComponent<ProjectileController>();
ProjectileImpactExplosion stunGrenadeImpact = stunGrenade.GetComponent<ProjectileImpactExplosion>();
GameObject stunGrenadeModel = Assets.stunGrenadeModel.InstantiateClone("StunGrenadeGhost", true);
stunGrenadeModel.AddComponent<NetworkIdentity>();
stunGrenadeModel.AddComponent<ProjectileGhostController>();
stunGrenadeController.ghostPrefab = stunGrenadeModel;
stunGrenadeImpact.lifetimeExpiredSoundString = "";
stunGrenadeImpact.explosionSoundString = Sounds.StunExplosion;
stunGrenadeImpact.offsetForLifetimeExpiredSound = 1;
stunGrenadeImpact.destroyOnEnemy = false;
stunGrenadeImpact.destroyOnWorld = false;
stunGrenadeImpact.timerAfterImpact = true;
stunGrenadeImpact.falloffModel = BlastAttack.FalloffModel.None;
stunGrenadeImpact.lifetimeAfterImpact = 0f;
stunGrenadeImpact.lifetimeRandomOffset = 0;
stunGrenadeImpact.blastRadius = 8;
stunGrenadeImpact.blastDamageCoefficient = 1;
stunGrenadeImpact.blastProcCoefficient = 1f;
stunGrenadeImpact.fireChildren = false;
stunGrenadeImpact.childrenCount = 0;
stunGrenadeImpact.bonusBlastForce = -2000f * Vector3.up;
stunGrenadeController.procCoefficient = 1;
shockGrenade = Resources.Load<GameObject>("Prefabs/Projectiles/CommandoGrenadeProjectile").InstantiateClone("EnforcerShockGrenade", true);
ProjectileController shockGrenadeController = shockGrenade.GetComponent<ProjectileController>();
ProjectileImpactExplosion shockGrenadeImpact = shockGrenade.GetComponent<ProjectileImpactExplosion>();
GameObject shockGrenadeModel = Assets.stunGrenadeModelAlt.InstantiateClone("ShockGrenadeGhost", true);
shockGrenadeModel.AddComponent<NetworkIdentity>();
shockGrenadeModel.AddComponent<ProjectileGhostController>();
shockGrenadeController.ghostPrefab = shockGrenadeModel;
shockGrenadeImpact.lifetimeExpiredSoundString = "";
shockGrenadeImpact.explosionSoundString = "Play_mage_m2_impact";
shockGrenadeImpact.offsetForLifetimeExpiredSound = 1;
shockGrenadeImpact.destroyOnEnemy = false;
shockGrenadeImpact.destroyOnWorld = false;
shockGrenadeImpact.timerAfterImpact = true;
shockGrenadeImpact.falloffModel = BlastAttack.FalloffModel.None;
shockGrenadeImpact.lifetimeAfterImpact = 0f;
shockGrenadeImpact.lifetimeRandomOffset = 0;
shockGrenadeImpact.blastRadius = 14f;
shockGrenadeImpact.blastDamageCoefficient = 1;
shockGrenadeImpact.blastProcCoefficient = 1f;
shockGrenadeImpact.fireChildren = false;
shockGrenadeImpact.childrenCount = 0;
shockGrenadeImpact.bonusBlastForce = -2000f * Vector3.up;
shockGrenadeImpact.impactEffect = CreateShockGrenadeEffect();
shockGrenadeController.procCoefficient = 1;
tearGasProjectilePrefab = Resources.Load<GameObject>("Prefabs/Projectiles/CommandoGrenadeProjectile").InstantiateClone("EnforcerTearGasGrenade", true);
tearGasPrefab = Resources.Load<GameObject>("Prefabs/Projectiles/SporeGrenadeProjectileDotZone").InstantiateClone("TearGasDotZone", true);
ProjectileController grenadeController = tearGasProjectilePrefab.GetComponent<ProjectileController>();
ProjectileController tearGasController = tearGasPrefab.GetComponent<ProjectileController>();
ProjectileDamage grenadeDamage = tearGasProjectilePrefab.GetComponent<ProjectileDamage>();
ProjectileDamage tearGasDamage = tearGasPrefab.GetComponent<ProjectileDamage>();
ProjectileSimple simple = tearGasProjectilePrefab.GetComponent<ProjectileSimple>();
TeamFilter filter = tearGasPrefab.GetComponent<TeamFilter>();
ProjectileImpactExplosion grenadeImpact = tearGasProjectilePrefab.GetComponent<ProjectileImpactExplosion>();
Destroy(tearGasPrefab.GetComponent<ProjectileDotZone>());
BuffWard buffWard = tearGasPrefab.AddComponent<BuffWard>();
filter.teamIndex = TeamIndex.Player;
GameObject grenadeModel = Assets.tearGasGrenadeModel.InstantiateClone("TearGasGhost", true);
grenadeModel.AddComponent<NetworkIdentity>();
grenadeModel.AddComponent<ProjectileGhostController>();
grenadeController.ghostPrefab = grenadeModel;
//tearGasController.ghostPrefab = Assets.tearGasEffectPrefab;
grenadeImpact.lifetimeExpiredSoundString = "";
grenadeImpact.explosionSoundString = Sounds.GasExplosion;
grenadeImpact.offsetForLifetimeExpiredSound = 1;
grenadeImpact.destroyOnEnemy = false;
grenadeImpact.destroyOnWorld = false;
grenadeImpact.timerAfterImpact = true;
grenadeImpact.falloffModel = BlastAttack.FalloffModel.SweetSpot;
grenadeImpact.lifetime = 18;
grenadeImpact.lifetimeAfterImpact = 0.5f;
grenadeImpact.lifetimeRandomOffset = 0;
grenadeImpact.blastRadius = 6;
grenadeImpact.blastDamageCoefficient = 1;
grenadeImpact.blastProcCoefficient = 1;
grenadeImpact.fireChildren = true;
grenadeImpact.childrenCount = 1;
grenadeImpact.childrenProjectilePrefab = tearGasPrefab;
grenadeImpact.childrenDamageCoefficient = 0;
grenadeImpact.impactEffect = null;
grenadeController.startSound = "";
grenadeController.procCoefficient = 1;
tearGasController.procCoefficient = 0;
grenadeDamage.crit = false;
grenadeDamage.damage = 0f;
grenadeDamage.damageColorIndex = DamageColorIndex.Default;
grenadeDamage.damageType = DamageType.Stun1s;
grenadeDamage.force = 0;
tearGasDamage.crit = false;
tearGasDamage.damage = 0;
tearGasDamage.damageColorIndex = DamageColorIndex.WeakPoint;
tearGasDamage.damageType = DamageType.Stun1s;
tearGasDamage.force = -1000;
buffWard.radius = 18;
buffWard.interval = 1;
buffWard.rangeIndicator = null;
buffWard.buffDef = Modules.Buffs.impairedBuff;
buffWard.buffDuration = 1.5f;
buffWard.floorWard = false;
buffWard.expires = false;
buffWard.invertTeamFilter = true;
buffWard.expireDuration = 0;
buffWard.animateRadius = false;
//this is weird but it works
Destroy(tearGasPrefab.transform.GetChild(0).gameObject);
GameObject gasFX = Assets.tearGasEffectPrefab.InstantiateClone("FX", false);
gasFX.AddComponent<TearGasComponent>();
gasFX.AddComponent<DestroyOnTimer>().duration = 18f;
gasFX.transform.parent = tearGasPrefab.transform;
gasFX.transform.localPosition = Vector3.zero;
//i have this really big cut on my shin and it's bleeding but i'm gonna code instead of doing something about it
// that's the spirit, champ
tearGasPrefab.AddComponent<DestroyOnTimer>().duration = 18;
//scepter stuff.........
//damageGasProjectile = PrefabAPI.InstantiateClone(projectilePrefab, "DamageGasGrenade", true);
damageGasProjectile = Resources.Load<GameObject>("Prefabs/Projectiles/CommandoGrenadeProjectile").InstantiateClone("EnforcerTearGasScepterGrenade", true);
damageGasEffect = Resources.Load<GameObject>("Prefabs/Projectiles/SporeGrenadeProjectileDotZone").InstantiateClone("TearGasScepterDotZone", true);
ProjectileController scepterGrenadeController = damageGasProjectile.GetComponent<ProjectileController>();
ProjectileController scepterTearGasController = damageGasEffect.GetComponent<ProjectileController>();
ProjectileDamage scepterGrenadeDamage = damageGasProjectile.GetComponent<ProjectileDamage>();
ProjectileDamage scepterTearGasDamage = damageGasEffect.GetComponent<ProjectileDamage>();
ProjectileImpactExplosion scepterGrenadeImpact = damageGasProjectile.GetComponent<ProjectileImpactExplosion>();
ProjectileDotZone dotZone = damageGasEffect.GetComponent<ProjectileDotZone>();
dotZone.damageCoefficient = 2f;
dotZone.fireFrequency = 4f;
dotZone.forceVector = Vector3.zero;
dotZone.impactEffect = null;
dotZone.lifetime = 18f;
dotZone.overlapProcCoefficient = 0.05f;
dotZone.transform.localScale = Vector3.one * 28;
HitBoxGroup gasHitboxGroup = dotZone.GetComponent<HitBoxGroup>();
gasHitboxGroup.hitBoxes = new HitBox[] { gasHitboxGroup.gameObject.AddComponent<HitBox>() };
GameObject scepterGrenadeModel = Assets.tearGasGrenadeModelAlt.InstantiateClone("TearGasScepterGhost", true);
scepterGrenadeModel.AddComponent<NetworkIdentity>();
scepterGrenadeModel.AddComponent<ProjectileGhostController>();
scepterGrenadeController.ghostPrefab = scepterGrenadeModel;
//tearGasController.ghostPrefab = Assets.tearGasEffectPrefab;
scepterGrenadeImpact.lifetimeExpiredSoundString = "";
scepterGrenadeImpact.explosionSoundString = Sounds.GasExplosion;
scepterGrenadeImpact.offsetForLifetimeExpiredSound = 1;
scepterGrenadeImpact.destroyOnEnemy = false;
scepterGrenadeImpact.destroyOnWorld = false;
scepterGrenadeImpact.timerAfterImpact = true;
scepterGrenadeImpact.falloffModel = BlastAttack.FalloffModel.SweetSpot;
scepterGrenadeImpact.lifetime = 18;
scepterGrenadeImpact.lifetimeAfterImpact = 0.5f;
scepterGrenadeImpact.lifetimeRandomOffset = 0;
scepterGrenadeImpact.blastRadius = 6;
scepterGrenadeImpact.blastDamageCoefficient = 1;
scepterGrenadeImpact.blastProcCoefficient = 1;
scepterGrenadeImpact.fireChildren = true;
scepterGrenadeImpact.childrenCount = 1;
scepterGrenadeImpact.childrenProjectilePrefab = damageGasEffect;
scepterGrenadeImpact.childrenDamageCoefficient = 0.5f;
scepterGrenadeImpact.impactEffect = null;
scepterGrenadeController.startSound = "";
scepterGrenadeController.procCoefficient = 1;
scepterTearGasController.procCoefficient = 0;
scepterGrenadeDamage.crit = false;
scepterGrenadeDamage.damage = 0f;
scepterGrenadeDamage.damageColorIndex = DamageColorIndex.Default;
scepterGrenadeDamage.damageType = DamageType.Stun1s;
scepterGrenadeDamage.force = 0;
scepterTearGasDamage.crit = false;
scepterTearGasDamage.damage = 1f;
scepterTearGasDamage.damageColorIndex = DamageColorIndex.WeakPoint;
scepterTearGasDamage.damageType = DamageType.Generic;
scepterTearGasDamage.force = -10;
Destroy(damageGasEffect.transform.GetChild(0).gameObject);
GameObject scepterGasFX = Assets.tearGasEffectPrefabAlt.InstantiateClone("FX", false);
scepterGasFX.AddComponent<TearGasComponent>();
scepterGasFX.AddComponent<DestroyOnTimer>().duration = 18f;
scepterGasFX.transform.parent = damageGasEffect.transform;
scepterGasFX.transform.localPosition = Vector3.zero;
damageGasEffect.AddComponent<DestroyOnTimer>().duration = 18;
BuffWard buffWard2 = damageGasEffect.AddComponent<BuffWard>();
buffWard2.radius = 18;
buffWard2.interval = 1;
buffWard2.rangeIndicator = null;
buffWard2.buffDef = Modules.Buffs.impairedBuff;
buffWard2.buffDuration = 1.5f;
buffWard2.floorWard = false;
buffWard2.expires = false;
buffWard2.invertTeamFilter = true;
buffWard2.expireDuration = 0;
buffWard2.animateRadius = false;
//bullet tracers
bulletTracer = Resources.Load<GameObject>("Prefabs/Effects/Tracers/TracerCommandoShotgun").InstantiateClone("EnforcerBulletTracer", true);
if (!bulletTracer.GetComponent<EffectComponent>()) bulletTracer.AddComponent<EffectComponent>();
if (!bulletTracer.GetComponent<VFXAttributes>()) bulletTracer.AddComponent<VFXAttributes>();
if (!bulletTracer.GetComponent<NetworkIdentity>()) bulletTracer.AddComponent<NetworkIdentity>();
Material bulletMat = null;
foreach (LineRenderer i in bulletTracer.GetComponentsInChildren<LineRenderer>())
{
if (i)
{
bulletMat = UnityEngine.Object.Instantiate<Material>(i.material);
bulletMat.SetColor("_TintColor", new Color(0.68f, 0.58f, 0.05f));
i.material = bulletMat;
i.startColor = new Color(0.68f, 0.58f, 0.05f);
i.endColor = new Color(0.68f, 0.58f, 0.05f);
}
}
bulletTracerSSG = Resources.Load<GameObject>("Prefabs/Effects/Tracers/TracerCommandoShotgun").InstantiateClone("EnforcerBulletTracer", true);
if (!bulletTracerSSG.GetComponent<EffectComponent>()) bulletTracerSSG.AddComponent<EffectComponent>();
if (!bulletTracerSSG.GetComponent<VFXAttributes>()) bulletTracerSSG.AddComponent<VFXAttributes>();
if (!bulletTracerSSG.GetComponent<NetworkIdentity>()) bulletTracerSSG.AddComponent<NetworkIdentity>();
foreach (LineRenderer i in bulletTracerSSG.GetComponentsInChildren<LineRenderer>())
{
if (i)
{
Material material = UnityEngine.Object.Instantiate<Material>(i.material);
material.SetColor("_TintColor", Color.yellow);
i.material = material;
i.startColor = new Color(0.8f, 0.24f, 0f);
i.endColor = new Color(0.8f, 0.24f, 0f);
}
}
laserTracer = Resources.Load<GameObject>("Prefabs/Effects/Tracers/TracerCommandoShotgun").InstantiateClone("EnforcerLaserTracer", true);
if (!laserTracer.GetComponent<EffectComponent>()) laserTracer.AddComponent<EffectComponent>();
if (!laserTracer.GetComponent<VFXAttributes>()) laserTracer.AddComponent<VFXAttributes>();
if (!laserTracer.GetComponent<NetworkIdentity>()) laserTracer.AddComponent<NetworkIdentity>();
foreach (LineRenderer i in laserTracer.GetComponentsInChildren<LineRenderer>())
{
if (i)
{
Material material = UnityEngine.Object.Instantiate<Material>(i.material);
material.SetColor("_TintColor", Color.red);
i.material = material;
i.startColor = new Color(0.8f, 0.19f, 0.19f);
i.endColor = new Color(0.8f, 0.19f, 0.19f);
}
}
minigunTracer = Resources.Load<GameObject>("Prefabs/Effects/Tracers/TracerClayBruiserMinigun").InstantiateClone("NemforcerMinigunTracer", true);
var line = minigunTracer.GetComponent<LineRenderer>();
line.material = bulletMat;
line.startColor = new Color(0.68f, 0.58f, 0.05f);
line.endColor = new Color(0.68f, 0.58f, 0.05f);
line.startWidth = 0.2f;
line.endWidth = 0.2f;
if (!minigunTracer.GetComponent<EffectComponent>()) minigunTracer.AddComponent<EffectComponent>();
if (!minigunTracer.GetComponent<VFXAttributes>()) minigunTracer.AddComponent<VFXAttributes>();
if (!minigunTracer.GetComponent<NetworkIdentity>()) minigunTracer.AddComponent<NetworkIdentity>();
//block effect
blockEffectPrefab = Resources.Load<GameObject>("Prefabs/Effects/BearProc").InstantiateClone("EnforcerBlockEffect", true);
blockEffectPrefab.GetComponent<EffectComponent>().soundName = Sounds.ShieldBlockLight;
if (!blockEffectPrefab.GetComponent<NetworkIdentity>()) blockEffectPrefab.AddComponent<NetworkIdentity>();
//heavy block effect
heavyBlockEffectPrefab = Resources.Load<GameObject>("Prefabs/Effects/BearProc").InstantiateClone("EnforcerHeavyBlockEffect", true);
heavyBlockEffectPrefab.GetComponent<EffectComponent>().soundName = Sounds.ShieldBlockHeavy;
if (!heavyBlockEffectPrefab.GetComponent<NetworkIdentity>()) heavyBlockEffectPrefab.AddComponent<NetworkIdentity>();
//hammer slam effect for enforcer m1 and nemforcer m2
hammerSlamEffect = Resources.Load<GameObject>("Prefabs/Effects/ImpactEffects/ParentSlamEffect").InstantiateClone("EnforcerHammerSlamEffect");
hammerSlamEffect.GetComponent<EffectComponent>().applyScale = true;
Transform dust = hammerSlamEffect.transform.Find("Dust, Directional");
if(dust) dust.localScale = new Vector3(1, 0.7f, 1);
Transform nova = hammerSlamEffect.transform.Find("Nova Sphere");
if(nova) nova.localScale = new Vector3(8, 8, 8);
if (!hammerSlamEffect.GetComponent<NetworkIdentity>()) hammerSlamEffect.AddComponent<NetworkIdentity>();
projectilePrefabs.Add(tearGasProjectilePrefab);
projectilePrefabs.Add(damageGasProjectile);
projectilePrefabs.Add(tearGasPrefab);
projectilePrefabs.Add(damageGasEffect);
projectilePrefabs.Add(stunGrenade);
projectilePrefabs.Add(shockGrenade);
Modules.Effects.AddEffect(bulletTracer);
Modules.Effects.AddEffect(bulletTracerSSG);
Modules.Effects.AddEffect(laserTracer);
Modules.Effects.AddEffect(minigunTracer);
Modules.Effects.AddEffect(blockEffectPrefab, Sounds.ShieldBlockLight);
Modules.Effects.AddEffect(heavyBlockEffectPrefab, Sounds.ShieldBlockHeavy);
Modules.Effects.AddEffect(hammerSlamEffect);
}
private GameObject CreateShockGrenadeEffect()
{
GameObject effect = PrefabAPI.InstantiateClone(Resources.Load<GameObject>("prefabs/effects/lightningstakenova"), "EnforcerShockGrenadeExplosionEffect", false);
EffectComponent ec = effect.GetComponent<EffectComponent>();
ec.applyScale = true;
ec.soundName = "Play_item_use_lighningArm"; //This typo is in the game.
Modules.Effects.effectDefs.Add(new EffectDef(effect));
return effect;
}
private void CreateCrosshair()
{
needlerCrosshair = PrefabAPI.InstantiateClone(Resources.Load<GameObject>("Prefabs/Crosshair/LoaderCrosshair"), "NeedlerCrosshair", true);
needlerCrosshair.AddComponent<NetworkIdentity>();
Destroy(needlerCrosshair.GetComponent<LoaderHookCrosshairController>());
needlerCrosshair.GetComponent<RawImage>().enabled = false;
var control = needlerCrosshair.GetComponent<CrosshairController>();
control.maxSpreadAlpha = 0;
control.maxSpreadAngle = 3;
control.minSpreadAlpha = 0;
control.spriteSpreadPositions = new CrosshairController.SpritePosition[]
{
new CrosshairController.SpritePosition
{
target = needlerCrosshair.transform.GetChild(2).GetComponent<RectTransform>(),
zeroPosition = new Vector3(-20f, 0, 0),
onePosition = new Vector3(-48f, 0, 0)
},
new CrosshairController.SpritePosition
{
target = needlerCrosshair.transform.GetChild(3).GetComponent<RectTransform>(),
zeroPosition = new Vector3(20f, 0, 0),
onePosition = new Vector3(48f, 0, 0)
}
};
Destroy(needlerCrosshair.transform.GetChild(0).gameObject);
Destroy(needlerCrosshair.transform.GetChild(1).gameObject);
}
private void CreateDoppelganger()
{
doppelganger = PrefabAPI.InstantiateClone(Resources.Load<GameObject>("Prefabs/CharacterMasters/MercMonsterMaster"), "EnforcerMonsterMaster");
foreach (AISkillDriver ai in doppelganger.GetComponentsInChildren<AISkillDriver>())
{
BaseUnityPlugin.DestroyImmediate(ai);
}
BaseAI baseAI = doppelganger.GetComponent<BaseAI>();
baseAI.aimVectorMaxSpeed = 60;
baseAI.aimVectorDampTime = 0.15f;
AISkillDriver exitShieldDriver = doppelganger.AddComponent<AISkillDriver>();
exitShieldDriver.customName = "ExitShield";
exitShieldDriver.movementType = AISkillDriver.MovementType.Stop;
exitShieldDriver.moveTargetType = AISkillDriver.TargetType.CurrentEnemy;
exitShieldDriver.activationRequiresAimConfirmation = false;
exitShieldDriver.activationRequiresTargetLoS = false;
exitShieldDriver.selectionRequiresTargetLoS = false;
exitShieldDriver.maxDistance = 512f;
exitShieldDriver.minDistance = 45f;
exitShieldDriver.requireSkillReady = true;
exitShieldDriver.aimType = AISkillDriver.AimType.MoveDirection;
exitShieldDriver.ignoreNodeGraph = false;
exitShieldDriver.moveInputScale = 1f;
exitShieldDriver.driverUpdateTimerOverride = 0.5f;
exitShieldDriver.buttonPressType = AISkillDriver.ButtonPressType.Hold;
exitShieldDriver.minTargetHealthFraction = Mathf.NegativeInfinity;
exitShieldDriver.maxTargetHealthFraction = Mathf.Infinity;
exitShieldDriver.minUserHealthFraction = Mathf.NegativeInfinity;
exitShieldDriver.maxUserHealthFraction = Mathf.Infinity;
exitShieldDriver.skillSlot = SkillSlot.Special;
exitShieldDriver.requiredSkill = shieldUpDef;
/*AISkillDriver grenadeDriver = doppelganger.AddComponent<AISkillDriver>();
grenadeDriver.customName = "ThrowGrenade";
grenadeDriver.movementType = AISkillDriver.MovementType.ChaseMoveTarget;
grenadeDriver.moveTargetType = AISkillDriver.TargetType.CurrentEnemy;
grenadeDriver.activationRequiresAimConfirmation = true;
grenadeDriver.activationRequiresTargetLoS = false;
grenadeDriver.selectionRequiresTargetLoS = true;
grenadeDriver.requireSkillReady = true;
grenadeDriver.maxDistance = 64f;
grenadeDriver.minDistance = 0f;
grenadeDriver.aimType = AISkillDriver.AimType.AtCurrentEnemy;
grenadeDriver.ignoreNodeGraph = false;
grenadeDriver.moveInputScale = 1f;
grenadeDriver.driverUpdateTimerOverride = 0.5f;
grenadeDriver.buttonPressType = AISkillDriver.ButtonPressType.TapContinuous;
grenadeDriver.minTargetHealthFraction = Mathf.NegativeInfinity;
grenadeDriver.maxTargetHealthFraction = Mathf.Infinity;
grenadeDriver.minUserHealthFraction = Mathf.NegativeInfinity;
grenadeDriver.maxUserHealthFraction = Mathf.Infinity;
grenadeDriver.skillSlot = SkillSlot.Utility;*/
AISkillDriver shoulderBashDriver = doppelganger.AddComponent<AISkillDriver>();
shoulderBashDriver.customName = "ShoulderBash";
shoulderBashDriver.movementType = AISkillDriver.MovementType.ChaseMoveTarget;
shoulderBashDriver.moveTargetType = AISkillDriver.TargetType.CurrentEnemy;
shoulderBashDriver.activationRequiresAimConfirmation = true;
shoulderBashDriver.activationRequiresTargetLoS = false;
shoulderBashDriver.selectionRequiresTargetLoS = true;
shoulderBashDriver.maxDistance = 6f;
shoulderBashDriver.minDistance = 0f;
shoulderBashDriver.requireSkillReady = true;
shoulderBashDriver.aimType = AISkillDriver.AimType.AtCurrentEnemy;
shoulderBashDriver.ignoreNodeGraph = true;
shoulderBashDriver.moveInputScale = 1f;
shoulderBashDriver.driverUpdateTimerOverride = 2f;
shoulderBashDriver.buttonPressType = AISkillDriver.ButtonPressType.Hold;
shoulderBashDriver.minTargetHealthFraction = Mathf.NegativeInfinity;
shoulderBashDriver.maxTargetHealthFraction = Mathf.Infinity;
shoulderBashDriver.minUserHealthFraction = Mathf.NegativeInfinity;
shoulderBashDriver.maxUserHealthFraction = Mathf.Infinity;
shoulderBashDriver.skillSlot = SkillSlot.Secondary;
//shoulderBashDriver.requiredSkill = shieldDownDef;
shoulderBashDriver.shouldSprint = true;
/*AISkillDriver shoulderBashPrepDriver = doppelganger.AddComponent<AISkillDriver>();
shoulderBashPrepDriver.customName = "ShoulderBashPrep";
shoulderBashPrepDriver.movementType = AISkillDriver.MovementType.ChaseMoveTarget;
shoulderBashPrepDriver.moveTargetType = AISkillDriver.TargetType.CurrentEnemy;
shoulderBashPrepDriver.activationRequiresAimConfirmation = true;
shoulderBashPrepDriver.activationRequiresTargetLoS = false;
shoulderBashPrepDriver.selectionRequiresTargetLoS = false;
shoulderBashPrepDriver.maxDistance = 12f;
shoulderBashPrepDriver.minDistance = 0f;
shoulderBashPrepDriver.requireSkillReady = true;
shoulderBashPrepDriver.aimType = AISkillDriver.AimType.AtCurrentEnemy;
shoulderBashPrepDriver.ignoreNodeGraph = true;
shoulderBashPrepDriver.moveInputScale = 1f;
shoulderBashPrepDriver.driverUpdateTimerOverride = -1f;
shoulderBashPrepDriver.buttonPressType = AISkillDriver.ButtonPressType.Abstain;
shoulderBashPrepDriver.minTargetHealthFraction = Mathf.NegativeInfinity;
shoulderBashPrepDriver.maxTargetHealthFraction = Mathf.Infinity;
shoulderBashPrepDriver.minUserHealthFraction = Mathf.NegativeInfinity;
shoulderBashPrepDriver.maxUserHealthFraction = Mathf.Infinity;
shoulderBashPrepDriver.skillSlot = SkillSlot.Secondary;
//shoulderBashPrepDriver.requiredSkill = shieldDownDef;
shoulderBashPrepDriver.shouldSprint = true;*/
AISkillDriver swapToMinigunDriver = doppelganger.AddComponent<AISkillDriver>();
swapToMinigunDriver.customName = "EnterShield";
swapToMinigunDriver.movementType = AISkillDriver.MovementType.Stop;
swapToMinigunDriver.moveTargetType = AISkillDriver.TargetType.CurrentEnemy;
swapToMinigunDriver.activationRequiresAimConfirmation = false;
swapToMinigunDriver.activationRequiresTargetLoS = false;
swapToMinigunDriver.selectionRequiresTargetLoS = false;
swapToMinigunDriver.maxDistance = 30f;
swapToMinigunDriver.minDistance = 0f;
swapToMinigunDriver.requireSkillReady = true;
swapToMinigunDriver.aimType = AISkillDriver.AimType.MoveDirection;
swapToMinigunDriver.ignoreNodeGraph = true;
swapToMinigunDriver.moveInputScale = 1f;
swapToMinigunDriver.driverUpdateTimerOverride = -1f;
swapToMinigunDriver.buttonPressType = AISkillDriver.ButtonPressType.Hold;
swapToMinigunDriver.minTargetHealthFraction = Mathf.NegativeInfinity;
swapToMinigunDriver.maxTargetHealthFraction = Mathf.Infinity;
swapToMinigunDriver.minUserHealthFraction = Mathf.NegativeInfinity;
swapToMinigunDriver.maxUserHealthFraction = Mathf.Infinity;
swapToMinigunDriver.skillSlot = SkillSlot.Special;
swapToMinigunDriver.requiredSkill = shieldDownDef;
AISkillDriver shieldBashDriver = doppelganger.AddComponent<AISkillDriver>();
shieldBashDriver.customName = "ShieldBash";
shieldBashDriver.movementType = AISkillDriver.MovementType.ChaseMoveTarget;
shieldBashDriver.moveTargetType = AISkillDriver.TargetType.CurrentEnemy;
shieldBashDriver.activationRequiresAimConfirmation = false;
shieldBashDriver.activationRequiresTargetLoS = false;
shieldBashDriver.selectionRequiresTargetLoS = false;
shieldBashDriver.maxDistance = 6f;
shieldBashDriver.minDistance = 0f;
shieldBashDriver.requireSkillReady = true;
shieldBashDriver.aimType = AISkillDriver.AimType.AtCurrentEnemy;
shieldBashDriver.ignoreNodeGraph = true;
shieldBashDriver.moveInputScale = 1f;
shieldBashDriver.driverUpdateTimerOverride = -1f;
shieldBashDriver.buttonPressType = AISkillDriver.ButtonPressType.Hold;
shieldBashDriver.minTargetHealthFraction = Mathf.NegativeInfinity;
shieldBashDriver.maxTargetHealthFraction = Mathf.Infinity;
shieldBashDriver.minUserHealthFraction = Mathf.NegativeInfinity;
shieldBashDriver.maxUserHealthFraction = Mathf.Infinity;
shieldBashDriver.skillSlot = SkillSlot.Secondary;
//shieldBashDriver.requiredSkill = shieldUpDef;
AISkillDriver shieldFireDriver = doppelganger.AddComponent<AISkillDriver>();
shieldFireDriver.customName = "StandAndShoot";
shieldFireDriver.movementType = AISkillDriver.MovementType.Stop;
shieldFireDriver.moveTargetType = AISkillDriver.TargetType.CurrentEnemy;
shieldFireDriver.activationRequiresAimConfirmation = true;
shieldFireDriver.activationRequiresTargetLoS = false;
shieldFireDriver.selectionRequiresTargetLoS = false;
shieldFireDriver.maxDistance = 16f;
shieldFireDriver.minDistance = 0f;
shieldFireDriver.requireSkillReady = true;
shieldFireDriver.aimType = AISkillDriver.AimType.AtCurrentEnemy;
shieldFireDriver.ignoreNodeGraph = true;
shieldFireDriver.moveInputScale = 1f;
shieldFireDriver.driverUpdateTimerOverride = -1f;
shieldFireDriver.buttonPressType = AISkillDriver.ButtonPressType.Hold;
shieldFireDriver.minTargetHealthFraction = Mathf.NegativeInfinity;
shieldFireDriver.maxTargetHealthFraction = Mathf.Infinity;
shieldFireDriver.minUserHealthFraction = Mathf.NegativeInfinity;
shieldFireDriver.maxUserHealthFraction = Mathf.Infinity;
shieldFireDriver.skillSlot = SkillSlot.Primary;
//shieldFireDriver.requiredSkill = shieldUpDef;
AISkillDriver noShieldFireDriver = doppelganger.AddComponent<AISkillDriver>();
noShieldFireDriver.customName = "StrafeAndShoot";
noShieldFireDriver.movementType = AISkillDriver.MovementType.StrafeMovetarget;
noShieldFireDriver.moveTargetType = AISkillDriver.TargetType.CurrentEnemy;
noShieldFireDriver.activationRequiresAimConfirmation = true;
noShieldFireDriver.activationRequiresTargetLoS = false;
noShieldFireDriver.selectionRequiresTargetLoS = false;
noShieldFireDriver.maxDistance = 40f;
noShieldFireDriver.minDistance = 8f;
noShieldFireDriver.requireSkillReady = true;
noShieldFireDriver.aimType = AISkillDriver.AimType.AtCurrentEnemy;
noShieldFireDriver.ignoreNodeGraph = false;
noShieldFireDriver.moveInputScale = 1f;
noShieldFireDriver.driverUpdateTimerOverride = -1f;
noShieldFireDriver.buttonPressType = AISkillDriver.ButtonPressType.Hold;
noShieldFireDriver.minTargetHealthFraction = Mathf.NegativeInfinity;
noShieldFireDriver.maxTargetHealthFraction = Mathf.Infinity;
noShieldFireDriver.minUserHealthFraction = Mathf.NegativeInfinity;
noShieldFireDriver.maxUserHealthFraction = Mathf.Infinity;
noShieldFireDriver.skillSlot = SkillSlot.Primary;
//noShieldFireDriver.requiredSkill = shieldDownDef;
AISkillDriver followDriver = doppelganger.AddComponent<AISkillDriver>();
followDriver.customName = "Chase";
followDriver.movementType = AISkillDriver.MovementType.ChaseMoveTarget;
followDriver.moveTargetType = AISkillDriver.TargetType.CurrentEnemy;
followDriver.activationRequiresAimConfirmation = false;
followDriver.activationRequiresTargetLoS = false;
followDriver.maxDistance = Mathf.Infinity;
followDriver.minDistance = 0f;
followDriver.aimType = AISkillDriver.AimType.AtMoveTarget;
followDriver.ignoreNodeGraph = false;
followDriver.moveInputScale = 1f;
followDriver.driverUpdateTimerOverride = -1f;
followDriver.buttonPressType = AISkillDriver.ButtonPressType.Hold;
followDriver.minTargetHealthFraction = Mathf.NegativeInfinity;
followDriver.maxTargetHealthFraction = Mathf.Infinity;
followDriver.minUserHealthFraction = Mathf.NegativeInfinity;
followDriver.maxUserHealthFraction = Mathf.Infinity;
followDriver.skillSlot = SkillSlot.None;
masterPrefabs.Add(doppelganger);
CharacterMaster master = doppelganger.GetComponent<CharacterMaster>();
master.bodyPrefab = characterPrefab;
}
//add modifiers to your voids please
// no go fuck yourself :^)
// suck my dick
private void SkillSetup()
{
foreach (GenericSkill obj in characterPrefab.GetComponentsInChildren<GenericSkill>())
{
BaseUnityPlugin.DestroyImmediate(obj);
}
_skillLocator = characterPrefab.GetComponent<SkillLocator>();
_previewController = characterDisplay.GetComponent<CharacterSelectSurvivorPreviewDisplayController>();
PrimarySetup();
SecondarySetup();
UtilitySetup();
SpecialSetup();
CSSPreviewSetup();
}
#region skillSetups
private void PrimarySetup()
{
SkillDef primaryDef1 = PrimarySkillDef_RiotShotgun();
Modules.Skills.RegisterSkillDef(primaryDef1, typeof(RiotShotgun));
SkillDef primaryDef2 = PrimarySkillDef_SuperShotgun();
Modules.Skills.RegisterSkillDef(primaryDef2, typeof(SuperShotgun2));
SkillDef primaryDef3 = PrimarySkillDef_AssaultRifle();
Modules.Skills.RegisterSkillDef(primaryDef3, typeof(FireMachineGun));
SkillDef primaryDef4 = PrimarySkillDef_Hammer();
Modules.Skills.RegisterSkillDef(primaryDef4, typeof(HammerSwing));
SkillFamily.Variant primaryVariant1 = Modules.Skills.SetupSkillVariant(primaryDef1);
SkillFamily.Variant primaryVariant2 = Modules.Skills.SetupSkillVariant(primaryDef2, EnforcerUnlockables.enforcerDoomUnlockableDef);
SkillFamily.Variant primaryVariant3 = Modules.Skills.SetupSkillVariant(primaryDef3, EnforcerUnlockables.enforcerARUnlockableDef);
SkillFamily.Variant primaryVariant4 = Modules.Skills.SetupSkillVariant(primaryDef4);
_skillLocator.primary = Modules.Skills.RegisterSkillsToFamily(characterPrefab, "EnforcerPrimary", primaryVariant1, primaryVariant2, primaryVariant3);
_previewController.skillChangeResponses[0].triggerSkillFamily = _skillLocator.primary.skillFamily;
_previewController.skillChangeResponses[0].triggerSkill = primaryDef1;
_previewController.skillChangeResponses[1].triggerSkillFamily = _skillLocator.primary.skillFamily;
_previewController.skillChangeResponses[1].triggerSkill = primaryDef2;
_previewController.skillChangeResponses[2].triggerSkillFamily = _skillLocator.primary.skillFamily;
_previewController.skillChangeResponses[2].triggerSkill = primaryDef3;
//cursed
if (Modules.Config.cursed.Value)
{
Modules.Skills.RegisterAdditionalSkills(_skillLocator.primary, primaryVariant4);
_previewController.skillChangeResponses[3].triggerSkillFamily = _skillLocator.primary.skillFamily;
_previewController.skillChangeResponses[3].triggerSkill = primaryDef4;
}
}
private void SecondarySetup() {
SkillDef secondaryDef1 = SecondarySkillDef_Bash();
Modules.Skills.RegisterSkillDef(secondaryDef1, typeof(ShieldBash), typeof(ShoulderBash), typeof(ShoulderBashImpact));
SkillFamily.Variant secondaryVariant1 = Modules.Skills.SetupSkillVariant(secondaryDef1);
_skillLocator.secondary = Modules.Skills.RegisterSkillsToFamily(characterPrefab, "EnforcerSecondary", secondaryVariant1);
}
private void UtilitySetup()
{
SkillDef utilityDef1 = UtilitySkillDef_TearGas();
Modules.Skills.RegisterSkillDef(utilityDef1, typeof(AimTearGas), typeof(TearGas));
SkillDef utilityDef2 = UtilitySkillDef_StunGrenade();
Modules.Skills.RegisterSkillDef(utilityDef2, typeof(StunGrenade));
SkillFamily.Variant utilityVariant1 = Modules.Skills.SetupSkillVariant(utilityDef1);
SkillFamily.Variant utilityVariant2 = Modules.Skills.SetupSkillVariant(utilityDef2, EnforcerUnlockables.enforcerStunGrenadeUnlockableDef);
_skillLocator.utility = Modules.Skills.RegisterSkillsToFamily(characterPrefab, "EnforcerUtility", utilityVariant1, utilityVariant2);
}
private void SpecialSetup()
{
//shield
SkillDef specialDef1 = SpecialSkillDef_ProtectAndServe();
Modules.Skills.RegisterSkillDef(specialDef1, typeof(ProtectAndServe));
SkillDef specialDef1Down = SpecialSkillDef_ShieldDown();
Modules.Skills.RegisterSkillDef(specialDef1Down);
shieldDownDef = specialDef1;
shieldUpDef = specialDef1Down;
//cursed
//energy shield (lol)
SkillDef specialDef2 = SpecialSkillDef_EnergyShield();
Modules.Skills.RegisterSkillDef(specialDef2, typeof(EnergyShield));
SkillDef specialDef2Down = SpecialSkillDef_EnergyShieldDown();
Modules.Skills.RegisterSkillDef(specialDef2Down);
shieldOffDef = specialDef2;
shieldOnDef = specialDef2Down;
//skateboard
SkillDef specialDef3 = SpecialSkillDef_SkamteBord();
Modules.Skills.RegisterSkillDef(specialDef3, typeof(Skateboard));
SkillDef specialDef3Down = SpecialSkillDef_SkamteBordDown();
Modules.Skills.RegisterSkillDef(specialDef3Down);
boardDownDef = specialDef3;
boardUpDef = specialDef3Down;
//setup
SkillFamily.Variant specialVariant1 = Modules.Skills.SetupSkillVariant(specialDef1);
SkillFamily.Variant specialVariant2 = Modules.Skills.SetupSkillVariant(specialDef2);
SkillFamily.Variant specialVariant3 = Modules.Skills.SetupSkillVariant(specialDef3);
_skillLocator.special = Modules.Skills.RegisterSkillsToFamily(characterPrefab, "EnforcerSpecial", specialVariant1);
_previewController.skillChangeResponses[4].triggerSkillFamily = _skillLocator.special.skillFamily;
_previewController.skillChangeResponses[4].triggerSkill = specialDef1;
if (Modules.Config.cursed.Value)
{
Modules.Skills.RegisterAdditionalSkills(_skillLocator.special, specialVariant3);
_previewController.skillChangeResponses[5].triggerSkillFamily = _skillLocator.special.skillFamily;
_previewController.skillChangeResponses[5].triggerSkill = specialDef3;
////rip energy shield lol
////previewController.skillChangeResponses[6].triggerSkillFamily = skillLocator.special.skillFamily;
////previewController.skillChangeResponses[6].triggerSkill = specialDef2;
}
}
#region skilldefs
private SkillDef PrimarySkillDef_RiotShotgun()
{
string desc = "Fire a short-range blast that <style=cIsUtility>pierces</style> for <style=cIsDamage>" + Modules.Config.shotgunBulletCount.Value + "x" + 100f * Modules.Config.shotgunDamage.Value + "% damage.</style>";
LanguageAPI.Add("ENFORCER_PRIMARY_SHOTGUN_NAME", "Riot Shotgun");
LanguageAPI.Add("ENFORCER_PRIMARY_SHOTGUN_DESCRIPTION", desc);
SkillDef skillDefRiotShotgun = ScriptableObject.CreateInstance<SkillDef>();
skillDefRiotShotgun.activationState = new SerializableEntityStateType(typeof(RiotShotgun));
skillDefRiotShotgun.activationStateMachineName = "Weapon";
skillDefRiotShotgun.baseMaxStock = 1;
skillDefRiotShotgun.baseRechargeInterval = 0f;
skillDefRiotShotgun.beginSkillCooldownOnSkillEnd = false;
skillDefRiotShotgun.canceledFromSprinting = false;
skillDefRiotShotgun.fullRestockOnAssign = true;
skillDefRiotShotgun.interruptPriority = InterruptPriority.Any;
skillDefRiotShotgun.resetCooldownTimerOnUse = false;
skillDefRiotShotgun.isCombatSkill = true;
skillDefRiotShotgun.mustKeyPress = false;
skillDefRiotShotgun.cancelSprintingOnActivation = true;
skillDefRiotShotgun.rechargeStock = 1;
skillDefRiotShotgun.requiredStock = 1;
skillDefRiotShotgun.stockToConsume = 1;
skillDefRiotShotgun.icon = Assets.icon10Shotgun;
skillDefRiotShotgun.skillDescriptionToken = "ENFORCER_PRIMARY_SHOTGUN_DESCRIPTION";
skillDefRiotShotgun.skillName = "ENFORCER_PRIMARY_SHOTGUN_NAME";
skillDefRiotShotgun.skillNameToken = "ENFORCER_PRIMARY_SHOTGUN_NAME";
return skillDefRiotShotgun;
}
private SkillDef PrimarySkillDef_SuperShotgun()
{
string desc = "Fire up to 2 shotgun blasts for <style=cIsDamage>" + SuperShotgun2.bulletCount/2 + "x" + 100f * Modules.Config.superDamage.Value + "% damage</style>.\nWhile using <style=cIsUtility>Protect and Serve</style>, fire <style=cIsDamage>both barrels at once.</style>";
LanguageAPI.Add("ENFORCER_PRIMARY_SUPERSHOTGUN_NAME", "Super Shotgun");
LanguageAPI.Add("ENFORCER_PRIMARY_SUPERSHOTGUN_DESCRIPTION", desc);
SkillDef skillDefSuperShotgun = ScriptableObject.CreateInstance<SkillDef>();
skillDefSuperShotgun.activationState = new SerializableEntityStateType(typeof(SuperShotgun2));
skillDefSuperShotgun.activationStateMachineName = "Weapon";
skillDefSuperShotgun.baseMaxStock = 1;
skillDefSuperShotgun.baseRechargeInterval = 0f;
skillDefSuperShotgun.beginSkillCooldownOnSkillEnd = false;
skillDefSuperShotgun.canceledFromSprinting = false;
skillDefSuperShotgun.fullRestockOnAssign = true;
skillDefSuperShotgun.interruptPriority = InterruptPriority.Any;
skillDefSuperShotgun.resetCooldownTimerOnUse = false;
skillDefSuperShotgun.isCombatSkill = true;
skillDefSuperShotgun.mustKeyPress = false;
skillDefSuperShotgun.cancelSprintingOnActivation = true;
skillDefSuperShotgun.rechargeStock = 1;
skillDefSuperShotgun.requiredStock = 1;
skillDefSuperShotgun.stockToConsume = 1;
skillDefSuperShotgun.icon = Assets.icon11SuperShotgun;
skillDefSuperShotgun.skillDescriptionToken = "ENFORCER_PRIMARY_SUPERSHOTGUN_DESCRIPTION";
skillDefSuperShotgun.skillName = "ENFORCER_PRIMARY_SUPERSHOTGUN_NAME";
skillDefSuperShotgun.skillNameToken = "ENFORCER_PRIMARY_SUPERSHOTGUN_NAME";
return skillDefSuperShotgun;
}
private SkillDef PrimarySkillDef_AssaultRifle()
{
//string damage = $"<style=cIsDamage>{FireBurstRifle.projectileCount}x{100f * FireBurstRifle.damageCoefficient}% damage</style>";
//string desc = $"Fire a burst of bullets dealing {damage}. <style=cIsUtility>During Protect and Serve</style>, fires <style=cIsDamage>{2 * FireBurstRifle.projectileCount} bullets</style> instead.";
string damage = $"<style=cIsDamage>{100f * FireMachineGun.damageCoefficient}% damage</style>";
string desc = $"Unload a barrage of bullets for {damage}.\nWhile using <style=cIsUtility>Protect and Serve</style>, has <style=cIsDamage>increased accuracy</style>, but <style=cIsHealth>slower movement speed</style>.";
LanguageAPI.Add("ENFORCER_PRIMARY_RIFLE_NAME", "Heavy Machine Gun");
LanguageAPI.Add("ENFORCER_PRIMARY_RIFLE_DESCRIPTION", desc);
SkillDef skillDefAssaultRifle = ScriptableObject.CreateInstance<SkillDef>();
//skillDefAssaultRifle.activationState = new SerializableEntityStateType(typeof(FireBurstRifle));
skillDefAssaultRifle.activationState = new SerializableEntityStateType(typeof(FireMachineGun));
skillDefAssaultRifle.activationStateMachineName = "Weapon";
skillDefAssaultRifle.baseMaxStock = 1;
skillDefAssaultRifle.baseRechargeInterval = 0f;
skillDefAssaultRifle.beginSkillCooldownOnSkillEnd = false;
skillDefAssaultRifle.canceledFromSprinting = false;
skillDefAssaultRifle.fullRestockOnAssign = true;
skillDefAssaultRifle.interruptPriority = InterruptPriority.Any;
skillDefAssaultRifle.resetCooldownTimerOnUse = false;
skillDefAssaultRifle.isCombatSkill = true;
skillDefAssaultRifle.mustKeyPress = false;
skillDefAssaultRifle.cancelSprintingOnActivation = true;
skillDefAssaultRifle.rechargeStock = 1;
skillDefAssaultRifle.requiredStock = 1;
skillDefAssaultRifle.stockToConsume = 1;
skillDefAssaultRifle.icon = Assets.icon12AssaultRifle;
skillDefAssaultRifle.skillDescriptionToken = "ENFORCER_PRIMARY_RIFLE_DESCRIPTION";
skillDefAssaultRifle.skillName = "ENFORCER_PRIMARY_RIFLE_NAME";
skillDefAssaultRifle.skillNameToken = "ENFORCER_PRIMARY_RIFLE_NAME";
return skillDefAssaultRifle;
}
private SkillDef PrimarySkillDef_Hammer()
{
string damage = $"<style=cIsDamage>{ 100f * HammerSwing.damageCoefficient}% damage</style>";
string shieldDamage = $"<style=cIsDamage>{ 100f * HammerSwing.shieldDamageCoefficient}% damage</style>";
string desc = $"Swing your hammer for {damage}.\nWhile using Protect and Serve, swing in a <style=cIsUtility>larger area</style>, for {shieldDamage} instead.";
LanguageAPI.Add("ENFORCER_PRIMARY_HAMMER_NAME", "Breaching Hammer");
LanguageAPI.Add("ENFORCER_PRIMARY_HAMMER_DESCRIPTION", desc);
SkillDef skillDefHammer = ScriptableObject.CreateInstance<SkillDef>();
skillDefHammer.activationState = new SerializableEntityStateType(typeof(HammerSwing));
skillDefHammer.activationStateMachineName = "Weapon";
skillDefHammer.baseMaxStock = 1;
skillDefHammer.baseRechargeInterval = 0f;
skillDefHammer.beginSkillCooldownOnSkillEnd = false;
skillDefHammer.canceledFromSprinting = false;
skillDefHammer.fullRestockOnAssign = true;
skillDefHammer.interruptPriority = InterruptPriority.Any;
skillDefHammer.resetCooldownTimerOnUse = false;
skillDefHammer.isCombatSkill = true;
skillDefHammer.mustKeyPress = false;
skillDefHammer.cancelSprintingOnActivation = true;
skillDefHammer.rechargeStock = 1;
skillDefHammer.requiredStock = 1;
skillDefHammer.stockToConsume = 1;
skillDefHammer.icon = Assets.icon13Hammer;
skillDefHammer.skillDescriptionToken = "ENFORCER_PRIMARY_HAMMER_DESCRIPTION";
skillDefHammer.skillName = "ENFORCER_PRIMARY_HAMMER_NAME";
skillDefHammer.skillNameToken = "ENFORCER_PRIMARY_HAMMER_NAME";
return skillDefHammer;
}
private SkillDef SecondarySkillDef_Bash()
{
LanguageAPI.Add("KEYWORD_BASH", "<style=cKeywordName>Bash</style><style=cSub>Applies <style=cIsDamage>stun</style> and <style=cIsUtility>heavy knockback</style>.");
LanguageAPI.Add("KEYWORD_SPRINTBASH", $"<style=cKeywordName>Shoulder Bash</style><style=cSub><style=cIsDamage>Stunning.</style> A short charge that deals <style=cIsDamage>{100f * ShoulderBash.chargeDamageCoefficient}% damage</style>.\nHitting <style=cIsDamage>heavier enemies</style> deals <style=cIsDamage>{ShoulderBash.knockbackDamageCoefficient * 100f}% damage</style>.");
//string desc = $"<style=cIsDamage>Bash</style> nearby enemies for <style=cIsDamage>{100f * ShieldBash.damageCoefficient}% damage</style>. <style=cIsUtility>Deflects projectiles</style>. Use while <style=cIsUtility>sprinting</style> to perform a <style=cIsDamage>Shoulder Bash</style> for <style=cIsDamage>{100f * ShoulderBash.chargeDamageCoefficient}-{100f * ShoulderBash.knockbackDamageCoefficient}% damage</style> instead.";
string desc = $"<style=cIsDamage>Stunning</style>. Knock back enemies for <style=cIsDamage>{100f * ShieldBash.damageCoefficient}% damage</style> and <style=cIsUtility>deflect projectiles</style>.";
desc += $"\nWhile <style=cIsUtility>sprinting</style>, perform a <style=cIsDamage>Shoulder Bash</style> instead.";
//desc += $" Deals <style=cIsDamage>{100f * ShoulderBash.chargeDamageCoefficient}% damage</style> while sprinting.";
LanguageAPI.Add("ENFORCER_SECONDARY_BASH_NAME", "Shield Bash");
LanguageAPI.Add("ENFORCER_SECONDARY_BASH_DESCRIPTION", desc);
SkillDef mySkillDef = ScriptableObject.CreateInstance<SkillDef>( );
mySkillDef.activationState = new SerializableEntityStateType(typeof(ShieldBash));
mySkillDef.activationStateMachineName = "Weapon";
mySkillDef.baseMaxStock = 1;
mySkillDef.baseRechargeInterval = 6f;
mySkillDef.beginSkillCooldownOnSkillEnd = false;
mySkillDef.canceledFromSprinting = false;
mySkillDef.fullRestockOnAssign = true;
mySkillDef.interruptPriority = InterruptPriority.Skill;
mySkillDef.resetCooldownTimerOnUse = false;
mySkillDef.isCombatSkill = true;
mySkillDef.mustKeyPress = false;
mySkillDef.cancelSprintingOnActivation = false;
mySkillDef.rechargeStock = 1;
mySkillDef.requiredStock = 1;
mySkillDef.stockToConsume = 1;
mySkillDef.icon = Assets.icon20ShieldBash;
mySkillDef.skillName = "ENFORCER_SECONDARY_BASH_NAME";
mySkillDef.skillNameToken = "ENFORCER_SECONDARY_BASH_NAME";
mySkillDef.skillDescriptionToken = "ENFORCER_SECONDARY_BASH_DESCRIPTION";
mySkillDef.keywordTokens = new string[] {
"KEYWORD_STUNNING",
"KEYWORD_SPRINTBASH"
};
return mySkillDef;
}
private SkillDef UtilitySkillDef_TearGas()
{
LanguageAPI.Add("KEYWORD_BLINDED", "<style=cKeywordName>Impaired</style><style=cSub>Lowers <style=cIsDamage>movement speed</style> by <style=cIsDamage>75%</style>, <style=cIsDamage>attack speed</style> by <style=cIsDamage>25%</style> and <style=cIsHealth>armor</style> by <style=cIsDamage>20</style>.</style></style>");
LanguageAPI.Add("ENFORCER_UTILITY_TEARGAS_NAME", "Tear Gas");
LanguageAPI.Add("ENFORCER_UTILITY_TEARGAS_DESCRIPTION", "Toss a grenade that covers an area in <style=cIsDamage>Impairing</style> gas.");
SkillDef tearGasDef = ScriptableObject.CreateInstance<SkillDef>();
tearGasDef.activationState = new SerializableEntityStateType(typeof(AimTearGas));
tearGasDef.activationStateMachineName = "Weapon";
tearGasDef.baseMaxStock = 1;
tearGasDef.baseRechargeInterval = 24;
tearGasDef.beginSkillCooldownOnSkillEnd = true;
tearGasDef.canceledFromSprinting = false;
tearGasDef.fullRestockOnAssign = true;
tearGasDef.interruptPriority = InterruptPriority.Skill;
tearGasDef.resetCooldownTimerOnUse = false;
tearGasDef.isCombatSkill = true;
tearGasDef.mustKeyPress = true;
tearGasDef.cancelSprintingOnActivation = true;
tearGasDef.rechargeStock = 1;
tearGasDef.requiredStock = 1;
tearGasDef.stockToConsume = 1;
tearGasDef.icon = Assets.icon30TearGas;
tearGasDef.skillDescriptionToken = "ENFORCER_UTILITY_TEARGAS_DESCRIPTION";
tearGasDef.skillName = "ENFORCER_UTILITY_TEARGAS_NAME";
tearGasDef.skillNameToken = "ENFORCER_UTILITY_TEARGAS_NAME";
tearGasDef.keywordTokens = new string[] {
"KEYWORD_BLINDED"
};
return tearGasDef;
}
private SkillDef UtilitySkillDef_StunGrenade()
{
LanguageAPI.Add("ENFORCER_UTILITY_STUNGRENADE_NAME", "Stun Grenade");
LanguageAPI.Add("ENFORCER_UTILITY_STUNGRENADE_DESCRIPTION", "<style=cIsDamage>Stunning</style>. Launch a grenade that concusses enemies for <style=cIsDamage>" + 100f * StunGrenade.damageCoefficient + "% damage</style>. Hold up to 3.");
SkillDef stunGrenadeDef = ScriptableObject.CreateInstance<SkillDef>();
stunGrenadeDef.activationState = new SerializableEntityStateType(typeof(StunGrenade));
stunGrenadeDef.activationStateMachineName = "Weapon";
stunGrenadeDef.baseMaxStock = 3;
stunGrenadeDef.baseRechargeInterval = 7f;
stunGrenadeDef.beginSkillCooldownOnSkillEnd = false;
stunGrenadeDef.canceledFromSprinting = false;
stunGrenadeDef.fullRestockOnAssign = true;
stunGrenadeDef.interruptPriority = InterruptPriority.Skill;
stunGrenadeDef.resetCooldownTimerOnUse = false;
stunGrenadeDef.isCombatSkill = true;
stunGrenadeDef.mustKeyPress = false;
stunGrenadeDef.cancelSprintingOnActivation = true;
stunGrenadeDef.rechargeStock = 1;
stunGrenadeDef.requiredStock = 1;
stunGrenadeDef.stockToConsume = 1;
stunGrenadeDef.icon = Assets.icon31StunGrenade;
stunGrenadeDef.skillDescriptionToken = "ENFORCER_UTILITY_STUNGRENADE_DESCRIPTION";
stunGrenadeDef.skillName = "ENFORCER_UTILITY_STUNGRENADE_NAME";
stunGrenadeDef.skillNameToken = "ENFORCER_UTILITY_STUNGRENADE_NAME";
stunGrenadeDef.keywordTokens = new string[] {
"KEYWORD_STUNNING"
};
return stunGrenadeDef;
}
private SkillDef SpecialSkillDef_ProtectAndServe()
{
LanguageAPI.Add("ENFORCER_SPECIAL_SHIELDUP_NAME", "Protect and Serve");
LanguageAPI.Add("ENFORCER_SPECIAL_SHIELDUP_DESCRIPTION", "Take a defensive stance, <style=cIsUtility>blocking all damage from the front</style>. <style=cIsUtility>Enhances primary fire</style>, but <style=cIsHealth>prevents sprinting and jumping</style>.");
SkillDef mySkillDef = ScriptableObject.CreateInstance<SkillDef>();
mySkillDef.activationState = new SerializableEntityStateType(typeof(ProtectAndServe));
mySkillDef.activationStateMachineName = "Weapon";
mySkillDef.baseMaxStock = 1;
mySkillDef.baseRechargeInterval = 0f;
mySkillDef.beginSkillCooldownOnSkillEnd = false;
mySkillDef.canceledFromSprinting = false;
mySkillDef.fullRestockOnAssign = true;
mySkillDef.interruptPriority = InterruptPriority.PrioritySkill;
mySkillDef.resetCooldownTimerOnUse = false;
mySkillDef.isCombatSkill = true;
mySkillDef.mustKeyPress = true;
mySkillDef.cancelSprintingOnActivation = true;
mySkillDef.rechargeStock = 1;
mySkillDef.requiredStock = 1;
mySkillDef.stockToConsume = 1;
mySkillDef.icon = Assets.icon40Shield;
mySkillDef.skillDescriptionToken = "ENFORCER_SPECIAL_SHIELDUP_DESCRIPTION";
mySkillDef.skillName = "ENFORCER_SPECIAL_SHIELDUP_NAME";
mySkillDef.skillNameToken = "ENFORCER_SPECIAL_SHIELDUP_NAME";
return mySkillDef;
}
private SkillDef SpecialSkillDef_ShieldDown()
{
LanguageAPI.Add("ENFORCER_SPECIAL_SHIELDDOWN_NAME", "Protect and Serve");
LanguageAPI.Add("ENFORCER_SPECIAL_SHIELDDOWN_DESCRIPTION", "Take a defensive stance, <style=cIsUtility>blocking all damage from the front</style>. <style=cIsDamage>Increases attack speed</style>, but <style=cIsHealth>prevents sprinting and jumping</style>.");
SkillDef mySkillDef2 = ScriptableObject.CreateInstance<SkillDef>();
mySkillDef2.activationState = new SerializableEntityStateType(typeof(ProtectAndServe));
mySkillDef2.activationStateMachineName = "Weapon";
mySkillDef2.baseMaxStock = 1;
mySkillDef2.baseRechargeInterval = 0f;
mySkillDef2.beginSkillCooldownOnSkillEnd = false;
mySkillDef2.canceledFromSprinting = false;
mySkillDef2.fullRestockOnAssign = true;
mySkillDef2.interruptPriority = InterruptPriority.PrioritySkill;
mySkillDef2.resetCooldownTimerOnUse = false;
mySkillDef2.isCombatSkill = true;
mySkillDef2.mustKeyPress = true;
mySkillDef2.cancelSprintingOnActivation = false;
mySkillDef2.rechargeStock = 1;
mySkillDef2.requiredStock = 1;
mySkillDef2.stockToConsume = 1;
mySkillDef2.icon = Assets.icon40ShieldOff;
mySkillDef2.skillDescriptionToken = "ENFORCER_SPECIAL_SHIELDDOWN_DESCRIPTION";
mySkillDef2.skillName = "ENFORCER_SPECIAL_SHIELDDOWN_NAME";
mySkillDef2.skillNameToken = "ENFORCER_SPECIAL_SHIELDDOWN_NAME";
return mySkillDef2;
}
private SkillDef SpecialSkillDef_EnergyShield()
{
LanguageAPI.Add("ENFORCER_SPECIAL_SHIELDON_NAME", "Project and Swerve");
LanguageAPI.Add("ENFORCER_SPECIAL_SHIELDON_DESCRIPTION", "Take a defensive stance, <style=cIsUtility>projecting an Energy Shield in front of you</style>. <style=cIsDamage>Increases your rate of fire</style>, but <style=cIsUtility>prevents sprinting and jumping</style>.");
SkillDef mySkillDef = ScriptableObject.CreateInstance<SkillDef>();
mySkillDef.activationState = new SerializableEntityStateType(typeof(EnergyShield));
mySkillDef.activationStateMachineName = "Weapon";
mySkillDef.baseMaxStock = 1;
mySkillDef.baseRechargeInterval = 0f;
mySkillDef.beginSkillCooldownOnSkillEnd = false;
mySkillDef.canceledFromSprinting = false;
mySkillDef.fullRestockOnAssign = true;
mySkillDef.interruptPriority = InterruptPriority.PrioritySkill;
mySkillDef.resetCooldownTimerOnUse = false;
mySkillDef.isCombatSkill = true;
mySkillDef.mustKeyPress = true;
mySkillDef.cancelSprintingOnActivation = true;
mySkillDef.rechargeStock = 1;
mySkillDef.requiredStock = 1;
mySkillDef.stockToConsume = 1;
mySkillDef.icon = Assets.testIcon;
mySkillDef.skillDescriptionToken = "ENFORCER_SPECIAL_SHIELDON_DESCRIPTION";
mySkillDef.skillName = "ENFORCER_SPECIAL_SHIELDON_NAME";
mySkillDef.skillNameToken = "ENFORCER_SPECIAL_SHIELDON_NAME";
return mySkillDef;
}
private SkillDef SpecialSkillDef_EnergyShieldDown()
{
LanguageAPI.Add("ENFORCER_SPECIAL_SHIELDOFF_NAME", "Project and Swerve");
LanguageAPI.Add("ENFORCER_SPECIAL_SHIELDOFF_DESCRIPTION", "Take a defensive stance, <style=cIsUtility>projecting an Energy Shield in front of you</style>. <style=cIsDamage>Increases your rate of fire</style>, but <style=cIsUtility>prevents sprinting and jumping</style>.");
SkillDef mySkillDef2 = ScriptableObject.CreateInstance<SkillDef>();
mySkillDef2.activationState = new SerializableEntityStateType(typeof(EnergyShield));
mySkillDef2.activationStateMachineName = "Weapon";
mySkillDef2.baseMaxStock = 1;
mySkillDef2.baseRechargeInterval = 0f;
mySkillDef2.beginSkillCooldownOnSkillEnd = false;
mySkillDef2.canceledFromSprinting = false;
mySkillDef2.fullRestockOnAssign = true;
mySkillDef2.interruptPriority = InterruptPriority.PrioritySkill;
mySkillDef2.resetCooldownTimerOnUse = false;
mySkillDef2.isCombatSkill = true;
mySkillDef2.mustKeyPress = true;
mySkillDef2.cancelSprintingOnActivation = false;
mySkillDef2.rechargeStock = 1;
mySkillDef2.requiredStock = 1;
mySkillDef2.stockToConsume = 1;
mySkillDef2.icon = Assets.testIcon;
mySkillDef2.skillDescriptionToken = "ENFORCER_SPECIAL_SHIELDOFF_DESCRIPTION";
mySkillDef2.skillName = "ENFORCER_SPECIAL_SHIELDOFF_NAME";
mySkillDef2.skillNameToken = "ENFORCER_SPECIAL_SHIELDOFF_NAME";
return mySkillDef2;
}
private SkillDef SpecialSkillDef_SkamteBord()
{
LanguageAPI.Add("ENFORCER_SPECIAL_BOARDUP_NAME", "Skateboard");
LanguageAPI.Add("ENFORCER_SPECIAL_BOARDUP_DESCRIPTION", "Swag.");
SkillDef mySkillDef = ScriptableObject.CreateInstance<SkillDef>();
mySkillDef.activationState = new SerializableEntityStateType(typeof(Skateboard));
mySkillDef.activationStateMachineName = "Weapon";
mySkillDef.baseMaxStock = 1;
mySkillDef.baseRechargeInterval = 0f;
mySkillDef.beginSkillCooldownOnSkillEnd = false;
mySkillDef.canceledFromSprinting = false;
mySkillDef.fullRestockOnAssign = true;
mySkillDef.interruptPriority = InterruptPriority.PrioritySkill;
mySkillDef.resetCooldownTimerOnUse = false;
mySkillDef.isCombatSkill = true;
mySkillDef.mustKeyPress = true;
mySkillDef.cancelSprintingOnActivation = true;
mySkillDef.rechargeStock = 1;
mySkillDef.requiredStock = 1;
mySkillDef.stockToConsume = 1;
mySkillDef.icon = Assets.icon42SkateBoard;
mySkillDef.skillDescriptionToken = "ENFORCER_SPECIAL_BOARDUP_DESCRIPTION";
mySkillDef.skillName = "ENFORCER_SPECIAL_BOARDUP_NAME";
mySkillDef.skillNameToken = "ENFORCER_SPECIAL_BOARDUP_NAME";
return mySkillDef;
}
private SkillDef SpecialSkillDef_SkamteBordDown()
{
LanguageAPI.Add("ENFORCER_SPECIAL_BOARDDOWN_NAME", "Skateboard");
LanguageAPI.Add("ENFORCER_SPECIAL_BOARDDOWN_DESCRIPTION", "Unswag.");
SkillDef mySkillDef2 = ScriptableObject.CreateInstance<SkillDef>();
mySkillDef2.activationState = new SerializableEntityStateType(typeof(Skateboard));
mySkillDef2.activationStateMachineName = "Weapon";
mySkillDef2.baseMaxStock = 1;
mySkillDef2.baseRechargeInterval = 0f;
mySkillDef2.beginSkillCooldownOnSkillEnd = false;
mySkillDef2.canceledFromSprinting = false;
mySkillDef2.fullRestockOnAssign = true;
mySkillDef2.interruptPriority = InterruptPriority.PrioritySkill;
mySkillDef2.resetCooldownTimerOnUse = false;
mySkillDef2.isCombatSkill = true;
mySkillDef2.mustKeyPress = true;
mySkillDef2.cancelSprintingOnActivation = false;
mySkillDef2.rechargeStock = 1;
mySkillDef2.requiredStock = 1;
mySkillDef2.stockToConsume = 1;
mySkillDef2.icon = Assets.icon42SkateBoardOff;
mySkillDef2.skillDescriptionToken = "ENFORCER_SPECIAL_BOARDDOWN_DESCRIPTION";
mySkillDef2.skillName = "ENFORCER_SPECIAL_BOARDDOWN_NAME";
mySkillDef2.skillNameToken = "ENFORCER_SPECIAL_BOARDDOWN_NAME";
return mySkillDef2;
}
#endregion
private void ScepterSkillSetup()
{
LanguageAPI.Add("ENFORCER_UTILITY_TEARGASSCEPTER_NAME", "Mustard Gas");
LanguageAPI.Add("ENFORCER_UTILITY_TEARGASSCEPTER_DESCRIPTION", "Toss a grenade that covers an area in <style=cIsDamage>Impairing</style> gas, choking enemies for <style=cIsDamage>200% damage per second</style>.");
tearGasScepterDef = UtilitySkillDef_TearGas();
tearGasScepterDef.activationState = new SerializableEntityStateType(typeof(AimDamageGas));
tearGasScepterDef.icon = Assets.icon30TearGasScepter;
tearGasScepterDef.skillDescriptionToken = "ENFORCER_UTILITY_TEARGASSCEPTER_DESCRIPTION";
tearGasScepterDef.skillName = "ENFORCER_UTILITY_TEARGASSCEPTER_NAME";
tearGasScepterDef.skillNameToken = "ENFORCER_UTILITY_TEARGASSCEPTER_NAME";
tearGasScepterDef.keywordTokens = new string[] {
"KEYWORD_BLINDED"
};
Modules.Skills.RegisterSkillDef(tearGasScepterDef, typeof(AimDamageGas));
LanguageAPI.Add("ENFORCER_UTILITY_SHOCKGRENADE_NAME", "Shock Grenade");
LanguageAPI.Add("ENFORCER_UTILITY_SHOCKGRENADE_DESCRIPTION", "<style=cIsDamage>Shocking</style>. Launch a grenade that electrocutes enemies for <style=cIsDamage>" + 100f * ShockGrenade.damageCoefficient + "% damage</style>. Hold up to 3.");
shockGrenadeDef = UtilitySkillDef_StunGrenade();
shockGrenadeDef.activationState = new SerializableEntityStateType(typeof(ShockGrenade));
shockGrenadeDef.icon = Assets.icon31StunGrenadeScepter;
shockGrenadeDef.skillDescriptionToken = "ENFORCER_UTILITY_SHOCKGRENADE_DESCRIPTION";
shockGrenadeDef.skillName = "ENFORCER_UTILITY_SHOCKGRENADE_NAME";
shockGrenadeDef.skillNameToken = "ENFORCER_UTILITY_SHOCKGRENADE_NAME";
shockGrenadeDef.keywordTokens = new string[] {
"KEYWORD_SHOCKING"
};
Modules.Skills.RegisterSkillDef(shockGrenadeDef, typeof(ShockGrenade));
}
private void CSSPreviewSetup()
{
//something broke here i don't really understand it
// that's because holy shit i wrote this like a fucking ape. do not forgive me for this. I'm deleting it
//// NULLCHECK YOUR SHIT FOR FUCKS SAKE
//nullchecks are only for the unsure
//also this is a not-null check. do return; n00b
if (_previewController)
{
List<int> emptyIndices = new List<int>();
for (int i = 0; i < _previewController.skillChangeResponses.Length; i++)
{
if (_previewController.skillChangeResponses[i].triggerSkillFamily == null ||
_previewController.skillChangeResponses[i].triggerSkill == null)
{
emptyIndices.Add(i);
}
}
if (emptyIndices.Count == 0)
return;
List<CharacterSelectSurvivorPreviewDisplayController.SkillChangeResponse> responsesList = _previewController.skillChangeResponses.ToList();
for (int i = emptyIndices.Count - 1; i >= 0; i--)
{
responsesList.RemoveAt(emptyIndices[i]);
}
_previewController.skillChangeResponses = responsesList.ToArray();
}
}
private void MemeSetup()
{
Type[] memes = new Type[]
{
typeof(SirenToggle),
typeof(DefaultDance),
typeof(FLINTLOCKWOOD),
typeof(Rest),
typeof(Enforcer.Emotes.EnforcerSalute),
typeof(EntityStates.Nemforcer.Emotes.Salute),
};
for (int i = 0; i < memes.Length; i++)
{
Modules.States.AddSkill(memes[i]);
}
}
}
#endregion
} | 51.988091 | 541 | 0.638516 | [
"MIT"
] | Nebby1999/EnforcerMod | EnforcerMod_VS/EnforcerModPlugin.cs | 144,077 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeDevPnP.Core
{
/// <summary>
/// Specify restrictions to place on a document or item once it has been declared as a record. Changing this setting
/// will not affect items which have already been declared records.
/// </summary>
public enum EcmSiteRecordRestrictions
{
Unknown = 0,
/// <summary>
/// Records are no more restricted than non-records
/// </summary>
None = 1,
/// <summary>
/// Records can be edited but not deleted
/// </summary>
BlockDelete = 16,
/// <summary>
/// Records cannot be edited or deleted. Any change will require the record declaration to be revoked
/// </summary>
BlockEdit = 256
}
}
| 29.4 | 122 | 0.619048 | [
"Apache-2.0"
] | Chipzter/PnP | OfficeDevPnP.Core/OfficeDevPnP.Core/Enums/EcmSiteRecordRestrictions.cs | 884 | C# |
using Microsoft.Azure.ServiceBus;
using Smiosoft.PASS.ServiceBus.Queue;
using Smiosoft.PASS.UnitTests.TestHelpers.Messages;
namespace Smiosoft.PASS.ServiceBus.UnitTests.TestHelpers.Publishers
{
public class MessageOneQueuePublisher : QueuePublisher<DummyTestMessageOne>
{
public MessageOneQueuePublisher(IQueueClient client) : base(client)
{ }
public MessageOneQueuePublisher(string connectionString, string queueName) : base(connectionString, queueName)
{ }
}
}
| 29.75 | 112 | 0.817227 | [
"MIT"
] | smiosoft/pass | tests/Smiosoft.PASS.ServiceBus.UnitTests/TestHelpers/Publishers/MessageOneQueuePublisher.cs | 476 | C# |
using System.Web;
using System.Web.Mvc;
namespace aspnet45
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
//filters.Add(new RequireHttpsAttribute());
}
}
}
| 21.133333 | 80 | 0.643533 | [
"MIT"
] | jsturtevant/aspnet-security-demos | aspnet45/aspnet45/App_Start/FilterConfig.cs | 319 | C# |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// FireRiskByLocationRequest
/// </summary>
[DataContract]
public partial class FireRiskByLocationRequest : IEquatable<FireRiskByLocationRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="FireRiskByLocationRequest" /> class.
/// </summary>
[JsonConstructorAttribute]
protected FireRiskByLocationRequest() { }
/// <summary>
/// Initializes a new instance of the <see cref="FireRiskByLocationRequest" /> class.
/// </summary>
/// <param name="Locations">Locations (required).</param>
public FireRiskByLocationRequest(List<GeoRiskLocations> Locations = null)
{
// to ensure "Locations" is required (not null)
if (Locations == null)
{
throw new InvalidDataException("Locations is a required property for FireRiskByLocationRequest and cannot be null");
}
else
{
this.Locations = Locations;
}
}
/// <summary>
/// Gets or Sets Locations
/// </summary>
[DataMember(Name="locations", EmitDefaultValue=false)]
public List<GeoRiskLocations> Locations { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class FireRiskByLocationRequest {\n");
sb.Append(" Locations: ").Append(Locations).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as FireRiskByLocationRequest);
}
/// <summary>
/// Returns true if FireRiskByLocationRequest instances are equal
/// </summary>
/// <param name="other">Instance of FireRiskByLocationRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FireRiskByLocationRequest other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Locations == other.Locations ||
this.Locations != null &&
this.Locations.SequenceEqual(other.Locations)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Locations != null)
hash = hash * 59 + this.Locations.GetHashCode();
return hash;
}
}
}
}
| 34.342857 | 132 | 0.590682 | [
"Apache-2.0"
] | PitneyBowes/LocationIntelligenceSDK-CSharp | src/pb.locationIntelligence/Model/FireRiskByLocationRequest.cs | 4,808 | C# |
#pragma checksum "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4c8b712da9558eef2140b808fcac97f46905187c"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Administrador_Comentarios), @"mvc.1.0.view", @"/Views/Administrador/Comentarios.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Administrador/Comentarios.cshtml", typeof(AspNetCore.Views_Administrador_Comentarios))]
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;
#line 1 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\_ViewImports.cshtml"
using PontoDigitalMVC;
#line default
#line hidden
#line 2 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\_ViewImports.cshtml"
using PontoDigitalMVC.Models;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4c8b712da9558eef2140b808fcac97f46905187c", @"/Views/Administrador/Comentarios.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"02a18bbdda5bee1a9586dbbc95400b6b6e2de7f1", @"/Views/_ViewImports.cshtml")]
public class Views_Administrador_Comentarios : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<PontoDigitalMVC.ViewModel.ListasViewModel>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), 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("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/listas.css"), 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("type", new global::Microsoft.AspNetCore.Html.HtmlString("text/css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("bt_logout"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Login", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Logout", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
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.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper;
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()
{
#line 2 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
Layout = "_Layout";
#line default
#line hidden
BeginContext(82, 2, true);
WriteLiteral("\r\n");
EndContext();
BeginContext(84, 231, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "16eae0d788ea4a368272e7ce38adb0ae", async() => {
BeginContext(90, 112, true);
WriteLiteral("\r\n <meta charset=\"UTF-8\">\r\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\r\n ");
EndContext();
BeginContext(202, 63, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "3bacee15b32645b281b65f176365a61f", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(265, 43, true);
WriteLiteral("\r\n <title>Lista De Comentários</title>\r\n");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(315, 129, true);
WriteLiteral("\r\n\r\n<nav class=\"nav\">\r\n <div id=\"logo\">\r\n <img src=\"img/logo.png\" alt=\"logotipo\">\r\n </div>\r\n <ul>\r\n <li><a");
EndContext();
BeginWriteAttribute("href", " href=\'", 444, "\'", 491, 1);
#line 18 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
WriteAttributeValue("", 451, Url.Action("Usuarios", "Administrador"), 451, 40, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(492, 43, true);
WriteLiteral(">Lista de Usuários</a></li>\r\n <li><a");
EndContext();
BeginWriteAttribute("href", " href=\'", 535, "\'", 585, 1);
#line 19 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
WriteAttributeValue("", 542, Url.Action("Comentarios", "Administrador"), 542, 43, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(586, 46, true);
WriteLiteral(">Lista de Comentários</a></li>\r\n <li><a");
EndContext();
BeginWriteAttribute("href", " href=\'", 632, "\'", 676, 1);
#line 20 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
WriteAttributeValue("", 639, Url.Action("Index", "Administrador"), 639, 37, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(677, 30, true);
WriteLiteral(">Voltar</a></li>\r\n <li>");
EndContext();
BeginContext(707, 71, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ff9292e56fb1468b88b0ebb9b3ed3287", async() => {
BeginContext(768, 6, true);
WriteLiteral("Logout");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(778, 320, true);
WriteLiteral(@"</li>
</ul>
</nav>
<div class=""linha_amr""></div>
<div class=""container"">
<table class=""table"">
<thead class=""thead-dark"">
<tr>
<th>Id</th>
<th>Nome</th>
<th>Texto</th>
<th>Data da postagem</th>
</tr>
</thead>
<tbody>
");
EndContext();
#line 39 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
foreach(var c in Model.Comentarios)
{
#line default
#line hidden
BeginContext(1159, 20, true);
WriteLiteral(" <td>");
EndContext();
BeginContext(1180, 4, false);
#line 41 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
Write(c.Id);
#line default
#line hidden
EndContext();
BeginContext(1184, 27, true);
WriteLiteral("</td>\r\n <td>");
EndContext();
BeginContext(1212, 14, false);
#line 42 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
Write(c.Usuario.Nome);
#line default
#line hidden
EndContext();
BeginContext(1226, 27, true);
WriteLiteral("</td>\r\n <td>");
EndContext();
BeginContext(1254, 7, false);
#line 43 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
Write(c.Texto);
#line default
#line hidden
EndContext();
BeginContext(1261, 27, true);
WriteLiteral("</td>\r\n <td>");
EndContext();
BeginContext(1289, 13, false);
#line 44 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
Write(c.DataCriacao);
#line default
#line hidden
EndContext();
BeginContext(1302, 59, true);
WriteLiteral("</td>\r\n <td>\r\n <td><button><a");
EndContext();
BeginWriteAttribute("href", " href=\'", 1361, "\'", 1426, 3);
#line 46 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
WriteAttributeValue("", 1368, Url.Action("AprovarComentario", "Administrador"), 1368, 49, false);
#line default
#line hidden
WriteAttributeValue("", 1417, "?id=", 1417, 4, true);
#line 46 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
WriteAttributeValue("", 1421, c.Id, 1421, 5, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(1427, 62, true);
WriteLiteral(">Aprovar</a></button></td> \r\n <td><button><a");
EndContext();
BeginWriteAttribute("href", " href=\'", 1489, "\'", 1555, 3);
#line 47 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
WriteAttributeValue("", 1496, Url.Action("RejeitarComentario", "Administrador"), 1496, 50, false);
#line default
#line hidden
WriteAttributeValue("", 1546, "?id=", 1546, 4, true);
#line 47 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
WriteAttributeValue("", 1550, c.Id, 1550, 5, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(1556, 53, true);
WriteLiteral(">Rejeitar</a></button></td> \r\n </td>\r\n");
EndContext();
#line 49 "C:\Users\46309932829\Documents\Projetos\SENAI\PontoDigitalMVC\Views\Administrador\Comentarios.cshtml"
}
#line default
#line hidden
BeginContext(1624, 32, true);
WriteLiteral(" </tbody>\r\n</table>\r\n</div>\r\n");
EndContext();
}
#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<PontoDigitalMVC.ViewModel.ListasViewModel> Html { get; private set; }
}
}
#pragma warning restore 1591
| 57.667832 | 353 | 0.695204 | [
"MIT"
] | S0L4/PontoDigitalMVC | obj/Debug/netcoreapp2.1/Razor/Views/Administrador/Comentarios.g.cshtml.cs | 16,496 | C# |
namespace EasyNetQ.Host.Core
{
public interface IBusContainer : IBusProvider, IBusRegister
{
}
public interface IBusProvider
{
IBus this[string key] { get; }
IBus GetBus(string key);
}
public interface IBusRegister
{
void Register(string key, IBus bus);
}
}
| 16.947368 | 63 | 0.614907 | [
"MIT"
] | micdenny/EasyNetQ.Host | Source/EasyNetQ.Host.Core/IBusProvider.cs | 324 | C# |
using System;
namespace SharpEngine {
public class Circle : Shape {
public Circle(Material material) : base(CreateCircle(), material) {
}
static Vertex[] CreateCircle() {
const int numberOfSegments = 32;
const int verticesPerSegment = 3;
const float scale = .1f;
Vertex[] result = new Vertex[numberOfSegments*verticesPerSegment];
const float circleRadians = MathF.PI * 2;
var oldAngle = 0f;
for (int i = 0; i < numberOfSegments; i++) {
int currentVertex = i * verticesPerSegment;
var newAngle = circleRadians / numberOfSegments * (i + 1);
result[currentVertex++] = new Vertex(new Vector(), Color.Blue);
result[currentVertex++] = new Vertex(new Vector(MathF.Cos(oldAngle), MathF.Sin(oldAngle))*scale, Color.Green);
result[currentVertex] = new Vertex(new Vector(MathF.Cos(newAngle), MathF.Sin(newAngle))*scale, Color.Red);
oldAngle = newAngle;
}
return result;
}
}
} | 33.25 | 114 | 0.688507 | [
"MIT"
] | SaberSara/SharpEngine | Circle.cs | 931 | C# |
#nullable enable
using System;
using System.Collections.Generic;
using Content.Server.GameObjects.Components.NodeContainer.NodeGroups;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Power.ApcNetComponents
{
/// <summary>
/// Relays <see cref="PowerReceiverComponent"/>s in an area to a <see cref="IApcNet"/> so they can receive power.
/// </summary>
public interface IPowerProvider
{
void AddReceiver(PowerReceiverComponent receiver);
void RemoveReceiver(PowerReceiverComponent receiver);
void UpdateReceiverLoad(int oldLoad, int newLoad);
public IEntity? ProviderOwner { get; }
public bool HasApcPower { get; }
}
[RegisterComponent]
public class PowerProviderComponent : BaseApcNetComponent, IPowerProvider
{
public override string Name => "PowerProvider";
public IEntity ProviderOwner => Owner;
[ViewVariables]
public bool HasApcPower => Net.Powered;
/// <summary>
/// The max distance this can transmit power to <see cref="PowerReceiverComponent"/>s from.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public int PowerTransferRange { get => _powerTransferRange; set => SetPowerTransferRange(value); }
[DataField("powerTransferRange")]
private int _powerTransferRange = 3;
[ViewVariables]
public IReadOnlyList<PowerReceiverComponent> LinkedReceivers => _linkedReceivers;
private List<PowerReceiverComponent> _linkedReceivers = new();
/// <summary>
/// If <see cref="PowerReceiverComponent"/>s should consider connecting to this.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public bool Connectable { get; private set; } = true;
public static readonly IPowerProvider NullProvider = new NullPowerProvider();
public void AddReceiver(PowerReceiverComponent receiver)
{
var oldLoad = GetTotalLoad();
_linkedReceivers.Add(receiver);
var newLoad = oldLoad + receiver.Load;
Net.UpdatePowerProviderReceivers(this, oldLoad, newLoad);
}
public void RemoveReceiver(PowerReceiverComponent receiver)
{
var oldLoad = GetTotalLoad();
_linkedReceivers.Remove(receiver);
var newLoad = oldLoad - receiver.Load;
Net.UpdatePowerProviderReceivers(this, oldLoad, newLoad);
}
public void UpdateReceiverLoad(int oldLoad, int newLoad)
{
Net.UpdatePowerProviderReceivers(this, oldLoad, newLoad);
}
protected override void Startup()
{
base.Startup();
foreach (var receiver in FindAvailableReceivers())
{
receiver.Provider = this;
}
}
public override void OnRemove()
{
Connectable = false;
var receivers = _linkedReceivers.ToArray();
foreach (var receiver in receivers)
{
receiver.ClearProvider();
}
foreach (var receiver in receivers)
{
receiver.TryFindAndSetProvider();
}
base.OnRemove();
}
private List<PowerReceiverComponent> FindAvailableReceivers()
{
var nearbyEntities = IoCManager.Resolve<IEntityLookup>()
.GetEntitiesInRange(Owner, PowerTransferRange);
var receivers = new List<PowerReceiverComponent>();
foreach (var entity in nearbyEntities)
{
if (entity.TryGetComponent<PowerReceiverComponent>(out var receiver) &&
receiver.Connectable &&
receiver.NeedsProvider &&
receiver.Owner.Transform.Coordinates.TryDistance(Owner.EntityManager, Owner.Transform.Coordinates, out var distance) &&
distance < Math.Min(PowerTransferRange, receiver.PowerReceptionRange))
{
receivers.Add(receiver);
}
}
return receivers;
}
protected override void AddSelfToNet(IApcNet apcNet)
{
apcNet.AddPowerProvider(this);
}
protected override void RemoveSelfFromNet(IApcNet apcNet)
{
apcNet.RemovePowerProvider(this);
}
private void SetPowerTransferRange(int newPowerTransferRange)
{
var receivers = _linkedReceivers.ToArray();
foreach (var receiver in receivers)
{
receiver.ClearProvider();
}
_powerTransferRange = newPowerTransferRange;
foreach (var receiver in receivers)
{
receiver.TryFindAndSetProvider();
}
}
private int GetTotalLoad()
{
var load = 0;
foreach (var receiver in _linkedReceivers)
{
load += receiver.Load;
}
return load;
}
private class NullPowerProvider : IPowerProvider
{
/// <summary>
/// It is important that this returns false, so <see cref="PowerReceiverComponent"/>s with a <see cref="NullPowerProvider"/> have no power.
/// </summary>
public bool HasApcPower => false;
public void AddReceiver(PowerReceiverComponent receiver) { }
public void RemoveReceiver(PowerReceiverComponent receiver) { }
public void UpdateReceiverLoad(int oldLoad, int newLoad) { }
public IEntity? ProviderOwner => default;
}
}
}
| 33.712644 | 155 | 0.602455 | [
"MIT"
] | BingoJohnson/space-station-14 | Content.Server/GameObjects/Components/Power/ApcNetComponents/PowerProviderComponent.cs | 5,866 | C# |
namespace TraktNet.Exceptions
{
/// <summary>Exception, that will be thrown, if an access token is required, but was not provided.</summary>
public class TraktAuthorizationException : TraktException
{
/// <summary>
/// Initializes a new instance of the <see cref="TraktAuthorizationException" /> class with a default exception message.
/// </summary>
public TraktAuthorizationException() : this("Unauthorized - OAuth must be provided") { }
/// <summary>
/// Initializes a new instance of the <see cref="TraktAuthorizationException" /> class with a custom message.
/// </summary>
/// <param name="message">A custom exception message.</param>
public TraktAuthorizationException(string message) : base(message)
{
StatusCode = System.Net.HttpStatusCode.Unauthorized;
}
}
}
| 42.238095 | 128 | 0.656144 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Lib/Trakt.NET/Exceptions/TraktAuthorizationException.cs | 889 | C# |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !__IOS__
namespace NLog.LayoutRenderers
{
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// ASP Session variable.
/// </summary>
[LayoutRenderer("asp-session")]
public class AspSessionValueLayoutRenderer : LayoutRenderer
{
/// <summary>
/// Gets or sets the session variable name.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[RequiredParameter]
[DefaultParameter]
public string Variable { get; set; }
/// <summary>
/// Renders the specified ASP Session variable and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var session = AspHelper.GetSessionObject();
if (session != null)
{
if (this.Variable != null)
{
object variableValue = session.GetValue(this.Variable);
builder.Append(Convert.ToString(variableValue, CultureInfo.InvariantCulture));
}
Marshal.ReleaseComObject(session);
}
}
}
}
#endif
| 38.560976 | 116 | 0.672992 | [
"BSD-3-Clause"
] | YuLad/NLog | src/NLog/LayoutRenderers/AspSessionValueLayoutRenderer.cs | 3,162 | C# |
//-----------------------------------------------------------------------
// <copyright file="ListBoxExtensions.cs" company="Sphere 10 Software">
//
// Copyright (c) Sphere 10 Software. All rights reserved. (http://www.sphere10.com)
//
// Distributed under the MIT software license, see the accompanying file
// LICENSE or visit http://www.opensource.org/licenses/mit-license.php.
//
// <author>Herman Schoenfeld</author>
// <date>2018</date>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Sphere10.Framework {
public static class ListBoxExtensions {
/// <summary>
/// Removes the selected items from a listbox.
/// </summary>
/// <param name="listBox">The listbox to clear selected items from.</param>
public static void RemoveSelectedItems(this ListBox listBox) {
object[] selectedItems = listBox.SelectedItems.Cast<object>().ToArray();
foreach (object obj in selectedItems) {
listBox.Items.Remove(obj);
}
}
}
}
| 30.081081 | 83 | 0.626235 | [
"MIT"
] | Sphere10/Framework | src/Sphere10.Framework.Windows.Forms/Extensions/ListBoxExtensions.cs | 1,113 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\dxvahd.h(731,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[Guid("95f4edf4-6e03-4cd7-be1b-3075d665aa52"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IDXVAHD_VideoProcessor
{
[PreserveSig]
HRESULT SetVideoProcessBltState(/* [annotation][in] _In_ */ _DXVAHD_BLT_STATE State, /* [annotation][in] _In_ */ uint DataSize, /* [annotation][in] _In_reads_bytes_(DataSize) */ IntPtr pData);
[PreserveSig]
HRESULT GetVideoProcessBltState(/* [annotation][in] _In_ */ _DXVAHD_BLT_STATE State, /* [annotation][in] _In_ */ uint DataSize, /* [annotation][out] _Inout_updates_bytes_(DataSize) */ out IntPtr pData);
[PreserveSig]
HRESULT SetVideoProcessStreamState(/* [annotation][in] _In_ */ uint StreamNumber, /* [annotation][in] _In_ */ _DXVAHD_STREAM_STATE State, /* [annotation][in] _In_ */ uint DataSize, /* [annotation][in] _In_reads_bytes_(DataSize) */ IntPtr pData);
[PreserveSig]
HRESULT GetVideoProcessStreamState(/* [annotation][in] _In_ */ uint StreamNumber, /* [annotation][in] _In_ */ _DXVAHD_STREAM_STATE State, /* [annotation][in] _In_ */ uint DataSize, /* [annotation][out] _Inout_updates_bytes_(DataSize) */ out IntPtr pData);
[PreserveSig]
HRESULT VideoProcessBltHD(/* [annotation][in] _In_ */ ref int pOutputSurface, /* [annotation][in] _In_ */ uint OutputFrame, /* [annotation][in] _In_ */ int StreamCount, /* [annotation][size_is][in] _In_reads_(StreamCount) */ [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] _DXVAHD_STREAM_DATA[] pStreams);
}
}
| 66.269231 | 320 | 0.695879 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/IDXVAHD_VideoProcessor.cs | 1,725 | C# |
/* Midi2Cat
Description: A subsystem that facilitates mapping Windows MIDI devices to CAT commands.
Copyright (C) 2016 Andrew Mansfield, M0YGG
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; either version 2
of the License, or (at your option) any later version.
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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
The author can be reached by email at: midi2cat@cametrix.com
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Midi2Cat.IO
{
public partial class PickDialog : Form
{
public PickDialog()
{
InitializeComponent();
}
public string Prompt
{
set
{
promptLabel.Text = value;
}
}
public string[] Mappings
{
get
{
List<string> results = new List<string>();
foreach (var item in mappingsLB.CheckedItems)
{
results.Add((string)item);
}
return results.ToArray();
}
}
public string[] ExistingMappings
{
set
{
mappingsLB.Items.Clear();
foreach (string mapping in value)
{
mappingsLB.Items.Add(mapping);
}
}
}
private void mappingsLB_ItemCheck(object sender, ItemCheckEventArgs e)
{
int count=mappingsLB.CheckedItems.Count;
if (e.NewValue == CheckState.Checked)
count++;
else
count--;
doneButton.Enabled = count > 0;
}
}
}
| 26.670455 | 87 | 0.588837 | [
"MIT"
] | DH1KLM/PowerSDR-Thetis-G7KLJ | Project Files/Source/Midi2Cat/Midi2Cat.IO/PickDialog.cs | 2,349 | C# |
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Take.Elephant.Elasticsearch;
using Take.Elephant.Elasticsearch.Mapping;
using Xunit;
namespace Take.Elephant.Tests.Elasticsearch
{
[Trait("Category", nameof(Elasticsearch))]
public class ElasticsearchItemSetFacts : ItemSetFacts
{
public override ISet<Item> Create()
{
var mapping = MappingBuilder
.WithIndex(Guid.NewGuid().ToString())
.WithKeyField("GuidProperty")
.Build();
var settings =
new ConnectionSettings(new Uri("http://127.0.0.1:9200"))
.DefaultIndex("tests");
return new DelayedSetDecorator<Item>(
new ElasticsearchSet<Item>(
new ElasticClient(settings), mapping), 1000);
}
[Fact(Skip = "Elasticsearch doesn't implement a lazy IEnumerable, so the AsEnumerableAsync method will return a snapshot of the index.")]
public override Task EnumerateAfterRemovingItemsSucceeds()
{
return base.EnumerateAfterRemovingItemsSucceeds();
}
}
}
| 31.384615 | 145 | 0.63317 | [
"Apache-2.0"
] | DanielCouto/elephant | src/Take.Elephant.Tests/ElasticSearch/ElasticSearchItemSetFacts.cs | 1,226 | C# |
// Copyright (c) 2014-2017 Wolfgang Borgsmüller
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the License.txt file for details.
using System;
using System.Diagnostics;
using Chromium.Remote;
namespace Chromium.WebBrowser {
/// <summary>
/// The type of a javascript property.
/// </summary>
public enum JSPropertyType {
Dynamic,
Function,
Object
}
/// <summary>
/// Modes for the JSProperty.InvokeMode property.
/// </summary>
public enum JSInvokeMode {
/// <summary>
/// Inherit from parent object. This is the default mode
/// for javascript properties.
/// </summary>
Inherit,
/// <summary>
/// Callbacks from the render process are executed on the
/// thread that owns the browser's underlying window handle
/// within the context of the calling remote thread.
/// This is the default mode for the webbrowser object.
/// </summary>
Invoke,
/// <summary>
/// Callback from the render process are executed on the
/// worker thread which marshals the callback.
/// </summary>
DontInvoke
}
/// <summary>
/// Represents a javascript property in the render process to be added to
/// a browser frame's global object or to a child object.
/// </summary>
public abstract class JSProperty {
/// <summary>
/// The type of this property.
/// </summary>
public JSPropertyType PropertyType { get; private set; }
/// <summary>
/// The invoke mode for this property. See also JSInvokeMode.
/// Changes to the invoke mode will be effective after the next
/// time the browser creates a V8 context for the target frame.
/// </summary>
public JSInvokeMode InvokeMode { get; set; }
/// <summary>
/// Indicates whether render process callbacks on this javascript
/// property will be executed on the thread that owns the
/// browser's underlying window handle.
/// Depends on the invoke mode and, if invoke mode is inherit,
/// also on the parent object's and/or browser's invoke mode.
/// </summary>
public bool WillInvoke {
get {
switch(InvokeMode) {
case JSInvokeMode.Invoke:
return true;
case JSInvokeMode.DontInvoke:
return false;
default:
if(m_parent != null)
return m_parent.WillInvoke;
if(m_browser != null)
return m_browser.RemoteCallbacksWillInvoke;
return true;
}
}
}
/// <summary>
/// The name of this property.
/// May be null if this property is still unbound.
/// </summary>
public string Name { get; private set; }
private ChromiumWebBrowser m_browser;
private JSObject m_parent;
internal CfrV8Context v8Context { get; private set; }
private CfrV8Value v8Value;
internal JSProperty(JSPropertyType type, JSInvokeMode invokeMode) {
PropertyType = type;
InvokeMode = invokeMode;
}
/// <summary>
/// The browser this javascript property or the parent javascript object belongs to.
/// May be null if this property or it's parent is still unbound.
/// </summary>
public ChromiumWebBrowser Browser {
get {
if(m_browser != null)
return m_browser;
if(m_parent != null)
return m_parent.Browser;
return null;
}
}
/// <summary>
/// The parent javascript object of this property.
/// May be null if this property is still unbound.
/// </summary>
public JSObject Parent {
get {
return m_parent;
}
}
/* protected AND internal */
internal abstract CfrV8Value CreateV8Value();
internal CfrV8Value GetV8Value(CfrV8Context context) {
if(v8Value == null || !Object.ReferenceEquals(v8Context, context)) {
v8Context = context;
v8Value = CreateV8Value();
}
return v8Value;
}
internal void SetParent(string propertyName, JSObject parent) {
if(Object.ReferenceEquals(parent, this)) {
throw new ChromiumWebBrowserException("Can't add a javascript object to itself.");
}
CheckUnboundState();
Name = propertyName;
m_parent = parent;
}
internal void SetBrowser(string propertyName, ChromiumWebBrowser browser) {
CheckUnboundState();
Name = propertyName;
m_browser = browser;
}
internal void ClearParent() {
Name = null;
m_parent = null;
m_browser = null;
}
private void CheckUnboundState() {
if(m_parent != null) {
throw new ChromiumWebBrowserException("This property already belongs to an JSObject.");
}
if(m_browser != null) {
throw new ChromiumWebBrowserException("This property already belongs to a browser frame's global object.");
}
}
}
}
| 32.408046 | 123 | 0.553467 | [
"BSD-3-Clause"
] | git-thinh/chromiumfx-chromiumfx-3589bba7642c | ChromiumWebBrowser/JSProperty.cs | 5,640 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using MIGAZ.Generator;
using MIGAZ.Forms;
using Amazon.EC2.Model;
using Amazon.EC2;
using System.Net.NetworkInformation;
using MIGAZ.Models;
using System.Xml;
using System.Collections;
namespace MIGAZ
{
public partial class Window : Form
{
private ILogProvider _logProvider;
//private EC2Operation ec2 = null;
static IAmazonEC2 service;
DescribeInstancesResponse instResponse;
DescribeVpcsResponse vpcResponse;
DescribeVolumesResponse ebsVolumesResponse;
string accessKeyID;
string secretKeyID;
string selectedregion;
List<Amazon.RegionEndpoint> Regions;
//private string subscriptionid;
//private Dictionary<string, string> subscriptionsAndTenants;
private TemplateGenerator _templateGenerator;
private ISaveSelectionProvider _saveSelectionProvider;
private IStatusProvider _statusProvider;
private AwsObjectRetriever _awsObjectRetriever;
private dynamic telemetryProvider;
public Window()
{
InitializeComponent();
_logProvider = new FileLogProvider();
_statusProvider = new UIStatusProvider(lblStatus);
telemetryProvider = new CloudTelemetryProvider();
_saveSelectionProvider = new UISaveSelectionProvider();
Regions = new List<Amazon.RegionEndpoint>();
foreach (var region in Amazon.RegionEndpoint.EnumerableAllRegions)
{
Regions.Add(region);
}
//var tokenProvider = new InteractiveTokenProvider();
//
}
private void Window_Load(object sender, EventArgs e)
{
writeLog("Window_Load", "Program start");
instResponse = new DescribeInstancesResponse();
this.Text = "migAz AWS (" + Assembly.GetEntryAssembly().GetName().Version.ToString() + ")";
cmbRegion.DataSource = Regions;
// cmbRegion.Enabled = true;
NewVersionAvailable(); // check if there a new version of the app
}
//TODO CHECK
private void Window_FormClosing(object sender, FormClosingEventArgs e)
{
// If save selection option is enabled
if (app.Default.SaveSelection)
{
_saveSelectionProvider.Save(cmbRegion.Text, lvwVirtualNetworks, lvwVirtualMachines);
}
}
private void btnGetToken_Click(object sender, EventArgs e)
{
writeLog("GetToken_Click", "Start");
try
{
//Authenticate
authenticate();
cmbRegion.Enabled = true;
//Load Items
Load_Items();
lblSignInText.Text = $"Signed in as {accessKeyID}";
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void createEC2Client()
{
_awsObjectRetriever = new AwsObjectRetriever(accessKeyID, secretKeyID, (Amazon.RegionEndpoint)cmbRegion.SelectedValue, _logProvider, _statusProvider);
_templateGenerator = new TemplateGenerator(_logProvider, _statusProvider, _awsObjectRetriever, telemetryProvider);
}
private DescribeVolumesResponse getEbsVolumes()
{
return _awsObjectRetriever.Volumes;
}
public string GetRegion()
{
return selectedregion;
}
private DescribeVpcsResponse getVPCs()
{
return _awsObjectRetriever.Vpcs;
}
private DescribeInstancesResponse getEC2Instances()
{
return _awsObjectRetriever.Instances;
}
private void authenticate()
{
AuthenticationForm authForm = new AuthenticationForm();
if (authForm.ShowDialog(this) != DialogResult.OK)
{
this.Close();
}
accessKeyID = authForm.GetAWSAccessKeyID();
secretKeyID = authForm.GetAWSSecretKeyID();
}
private void lvwVirtualNetworks_ItemChecked(object sender, ItemCheckedEventArgs e)
{
UpdateExportItemsCount();
}
private void lvwStorageAccounts_ItemChecked(object sender, ItemCheckedEventArgs e)
{
UpdateExportItemsCount();
}
private void lvwVirtualMachines_ItemChecked(object sender, ItemCheckedEventArgs e)
{
UpdateExportItemsCount();
if (app.Default.AutoSelectDependencies)
{
if (e.Item.Checked)
{
AutoSelectDependencies(e);
}
}
}
private void UpdateExportItemsCount()
{
int numofobjects = lvwVirtualNetworks.CheckedItems.Count + lvwVirtualMachines.CheckedItems.Count;
btnExport.Text = "Export " + numofobjects.ToString() + " objects";
}
private void btnChoosePath_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog.ShowDialog();
if (result == DialogResult.OK)
txtDestinationFolder.Text = folderBrowserDialog.SelectedPath;
}
private void txtDestinationFolder_TextChanged(object sender, EventArgs e)
{
if (txtDestinationFolder.Text == "")
btnExport.Enabled = false;
else
btnExport.Enabled = true;
}
private void btnExport_Click(object sender, EventArgs e)
{
btnExport.Enabled = false;
Hashtable teleinfo = new Hashtable();
teleinfo.Add("Region", cmbRegion.Text);
teleinfo.Add("AccessKey", accessKeyID);
var artefacts = new AWSArtefacts();
foreach (var selectedItem in lvwVirtualNetworks.CheckedItems)
{
var listItem = (ListViewItem)selectedItem;
artefacts.VirtualNetworks.Add(new VPC(listItem.Text, listItem.SubItems[1].Text));
}
foreach (var selectedItem in lvwVirtualMachines.CheckedItems)
{
var listItem = (ListViewItem)selectedItem;
artefacts.Instances.Add(new Ec2Instance(listItem.Text,listItem.SubItems[1].Text));
}
if (!Directory.Exists(txtDestinationFolder.Text))
{
MessageBox.Show("The chosen output folder does not exist.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
// If save selection option is enabled
if (app.Default.SaveSelection)
{
lblStatus.Text = "BUSY: Reading saved selection";
_saveSelectionProvider.Save(cmbRegion.Text, lvwVirtualNetworks, lvwVirtualMachines);
}
var templateWriter = new StreamWriter(Path.Combine(txtDestinationFolder.Text, "export.json"));
//var blobDetailWriter = new StreamWriter(Path.Combine(txtDestinationFolder.Text, "copyblobdetails.json"));
_templateGenerator.GenerateTemplate(artefacts, _awsObjectRetriever, templateWriter, teleinfo);
MessageBox.Show("Template has been generated successfully.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
btnExport.Enabled = true;
}
private void writeLog(string function, string message)
{
string logfilepath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MIGAZ-" + string.Format("{0:yyyyMMdd}", DateTime.Now) + ".log";
string text = DateTime.Now.ToString() + " " + function + " " + message + Environment.NewLine;
File.AppendAllText(logfilepath, text);
}
private void NewVersionAvailable()
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.migaz.tools/v1/version/AWStoARM");
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
string version = "\"" + Assembly.GetEntryAssembly().GetName().Version.ToString() + "\"";
string availableversion = result.ToString();
if (version != availableversion)
{
DialogResult dialogresult = MessageBox.Show("New version " + availableversion + " is available at http://aka.ms/MIGAZ", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception exception)
{
DialogResult dialogresult = MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnOptions_Click(object sender, EventArgs e)
{
Forms.formOptions formoptions = new Forms.formOptions();
formoptions.ShowDialog(this);
}
private void AutoSelectDependencies(ItemCheckedEventArgs listViewRow)
{
string InstanceId = listViewRow.Item.ListView.Items[listViewRow.Item.Index].SubItems[0].Text;
var availableInstances = _awsObjectRetriever.Instances;
//var selectedVolumes;
if (InstanceId != null)
{
//var selectedInstances = availableInstances.Reservations[0].Instances.Find(x => x.InstanceId == InstanceId);
var selectedInstances = _awsObjectRetriever.getInstancebyId(InstanceId);
foreach (ListViewItem virtualNetwork in lvwVirtualNetworks.Items)
{
if (selectedInstances.Instances[0].VpcId == virtualNetwork.SubItems[0].Text)
{
virtualNetwork.Checked = true;
virtualNetwork.Selected = true;
}
}
}
}
private void cmbRegion_SelectedIndexChanged(object sender, EventArgs e)
{
if(cmbRegion.Enabled == true)
{
//Load the Region Items
Load_Items();
}
// If save selection option is enabled
if (app.Default.SaveSelection)
{
lblStatus.Text = "BUSY: Reading saved selection";
_saveSelectionProvider.Read(cmbRegion.Text,ref lvwVirtualNetworks, ref lvwVirtualMachines);
}
}
private void Load_Items()
{
writeLog("GetToken_Click", "Start");
lvwVirtualNetworks.Items.Clear();
lvwVirtualMachines.Items.Clear();
createEC2Client();
instResponse = getEC2Instances();
Application.DoEvents();
//lblStatus.Text = "BUSY: Getting the VPC details";
vpcResponse = getVPCs();
Application.DoEvents();
//List Instances
if (instResponse != null)
{
lblStatus.Text = "BUSY: Processing Instances";
if (instResponse.Reservations.Count > 0)
{
foreach (var instanceResp in instResponse.Reservations)
{
foreach (var instance in instanceResp.Instances)
{
ListViewItem listItem = new ListViewItem(instance.InstanceId);
string name = "";
foreach (var tag in instance.Tags)
{
if (tag.Key == "Name")
{
name = tag.Value;
}
}
listItem.SubItems.AddRange(new[] { name });
lvwVirtualMachines.Items.Add(listItem);
Application.DoEvents();
}
}
}
//List VPCs
lblStatus.Text = "BUSY: Processing VPC";
foreach (var vpc in vpcResponse.Vpcs)
{
ListViewItem listItem = new ListViewItem(vpc.VpcId);
string VpcName = "";
foreach (var tag in vpc.Tags)
{
if (tag.Key == "Name")
{
VpcName = tag.Value;
}
}
listItem.SubItems.AddRange(new[] { VpcName });
lvwVirtualNetworks.Items.Add(listItem);
Application.DoEvents();
}
}
btnChoosePath.Enabled = true;
lblStatus.Text = "Ready";
}
private void lvwVirtualMachines_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
| 34.17207 | 205 | 0.554404 | [
"MIT"
] | Azure/migAz | aws/source/MIGAZ/Forms/Window.cs | 13,703 | C# |
// Url:https://leetcode.com/problems/partition-array-into-disjoint-intervals
/*
915. Partition Array into Disjoint Intervals
Medium
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
*/
using System;
namespace InterviewPreperationGuide.Core.LeetCode.problem915 {
public class Solution {
public void Init () {
Console.WriteLine ();
}
// Time: O ()
// Space: O ()
public int PartitionDisjoint (int[] A) {
return 0;
}
}
} | 17.52381 | 103 | 0.647645 | [
"MIT"
] | tarunbatta/ipg | core/leetcode/915.cs | 1,104 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class inkScrollAreaWidget : inkCompoundWidget
{
[Ordinal(0)] [RED("constrainContentPosition")] public CBool ConstrainContentPosition { get; set; }
[Ordinal(1)] [RED("fitToContentDirection")] public CEnum<inkFitToContentDirection> FitToContentDirection { get; set; }
[Ordinal(2)] [RED("horizontalScrolling")] public CFloat HorizontalScrolling { get; set; }
[Ordinal(3)] [RED("useInternalMask")] public CBool UseInternalMask { get; set; }
[Ordinal(4)] [RED("verticalScrolling")] public CFloat VerticalScrolling { get; set; }
public inkScrollAreaWidget(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 40.85 | 122 | 0.72705 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/inkScrollAreaWidget.cs | 798 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Northwind.Application.Rooms.Commands;
using Northwind.Application.Rooms.Models;
using Northwind.Application.Rooms.Queries;
namespace Northwind.WebUI.Controllers
{
public class RoomsController : BaseController
{
// GET api/rooms/getall
[HttpGet]
public async Task<ActionResult<RoomListModel>> GetAll()
{
return Ok(await Mediator.Send(new GetRoomsQuery()));
}
// GET api/rooms/get/5
[HttpGet("{id}")]
public async Task<ActionResult<RoomDetailsModel>> Get(int id)
{
return Ok(await Mediator.Send(new GetRoomDetailsQuery { RoomId = id }));
}
// GET api/rooms/get/5
[HttpGet("{id}")]
public async Task<ActionResult<RoomDetailsModel>> GetCalendar(int id)
{
return Ok(await Mediator.Send(new GetRoomCalendarQuery { RoomId = id }));
}
// POST api/rooms/create
[HttpPost]
public async Task<IActionResult> Create([FromBody]CreateRoomCommand command)
{
await Mediator.Send(command);
return NoContent();
}
// PUT api/rooms/update/5
[HttpPut("{id}")]
public async Task<IActionResult> Update(int id, [FromBody] UpdateRoomCommand command)
{
command.RoomId = id;
await Mediator.Send(command);
return NoContent();
}
// DELETE api/rooms/delete/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
await Mediator.Send(new DeleteRoomCommand { RoomId = id });
return NoContent();
}
}
}
| 28.442623 | 93 | 0.594813 | [
"MIT"
] | aquapirat/IntivePatronage3 | Northwind.WebUI/Controllers/RoomsController.cs | 1,737 | C# |
using GitDeployPack.Extensions;
using GitDeployPack.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace GitDeployPack.Core.ProjectParser
{
public class ProjectDiffer : IProjectDiffer
{
private string referencePattern = @"<HintPath>(?<key>.*?).dll</HintPath>";
private readonly Options options;
private IGitCommandHelper _gitCommandHelper;
public IGitCommandHelper GitCommandHelper => _gitCommandHelper;
public Options Options => options;
public ProjectDiffer(IGitCommandHelper gitCommandHelper,
Options options)
{
this._gitCommandHelper = gitCommandHelper;
this.options = options;
}
public void Diff(ProjectDescription project)
{
var projectChangedContent = GitCommandHelper.CompareFile(Options.OriginRepository, options.NewRepository, options.GitWorkPath, project.FullName);
foreach (var item in projectChangedContent)
{
if (item.StartsWith("+"))
{
var mc = Regex.Match(item, referencePattern);
if (mc.Success)
{
var referassembly = mc.Groups["key"].Value;
project.ReferenceAssembly.Add($"{referassembly}.dll");
}
}
}
}
}
}
| 33.577778 | 157 | 0.60953 | [
"Apache-2.0"
] | alivehim/GitDeployPack | src/GitDeployPack.Core/ProjectParser/ProjectDiffer.cs | 1,513 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.IO
{
public partial class FileLoadException
{
// Do not delete: this is invoked from native code.
private FileLoadException(string? fileName, int hResult)
: base(null)
{
HResult = hResult;
FileName = fileName;
_message = FormatFileLoadExceptionMessage(FileName, HResult);
}
internal static string FormatFileLoadExceptionMessage(string? fileName, int hResult)
{
string? format = null;
GetFileLoadExceptionMessage(hResult, new StringHandleOnStack(ref format));
string? message = null;
if (hResult == System.HResults.COR_E_BADEXEFORMAT)
message = SR.Arg_BadImageFormatException;
else
GetMessageForHR(hResult, new StringHandleOnStack(ref message));
return string.Format(format!, fileName, message);
}
[LibraryImport(RuntimeHelpers.QCall)]
private static partial void GetFileLoadExceptionMessage(int hResult, StringHandleOnStack retString);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "FileLoadException_GetMessageForHR")]
private static partial void GetMessageForHR(int hresult, StringHandleOnStack retString);
}
}
| 36.756098 | 108 | 0.676841 | [
"MIT"
] | AUTOMATE-2001/runtime | src/coreclr/System.Private.CoreLib/src/System/IO/FileLoadException.CoreCLR.cs | 1,507 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IAPManager.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.IAP
{
using System;
#if WINDOWS_STORE || WINDOWS_PHONE
using Windows.ApplicationModel.Store;
#endif
public static class IAPManager
{
public static Action<string> OnBuyFeature;
public static Action<string> OnSimulateBuyFeature;
public static Action<string> OnPurchaseSucceeded;
public static Action<string> OnPurchaseFailed;
/// <summary>
/// Whether to use local debug license information instead of the current user account.
/// </summary>
/// <see
/// cref="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.applicationmodel.store.currentappsimulator.aspx" />
public static bool Debug { get; set; }
#if WINDOWS_STORE || WINDOWS_PHONE
#region Static Fields
private static LicenseInformation licenseInformation;
#endregion
#region Public Methods and Operators
public static bool BuyFeature(string key)
{
ProductLicense productLicense = licenseInformation.ProductLicenses[key];
if (productLicense == null)
{
throw new ArgumentException("Unknown product: " + key, "key");
}
if (!productLicense.IsActive)
{
// The customer doesn't own this feature, so show the purchase dialog.
if (Debug)
{
var handler = OnSimulateBuyFeature;
if (handler != null)
{
handler(key);
}
}
else
{
var handler = OnBuyFeature;
if (handler != null)
{
handler(key);
}
}
// Check the license state to determine if the in-app purchase was successful.
return HasFeature(key);
}
return true;
}
public static bool HasFeature(string key)
{
if (licenseInformation == null)
{
throw new InvalidOperationException("IAP manager not initialized. Call Init() first.");
}
ProductLicense productLicense = licenseInformation.ProductLicenses[key];
if (productLicense == null)
{
throw new ArgumentException("Unknown product: " + key, "key");
}
return productLicense.IsActive;
}
public static void Init()
{
#if DEBUG
licenseInformation = Debug ? CurrentAppSimulator.LicenseInformation : CurrentApp.LicenseInformation;
#else
licenseInformation = CurrentApp.LicenseInformation;
#endif
}
#endregion
#else
#region Public Methods and Operators
public static bool BuyFeature(string key)
{
throw new NotImplementedException();
}
public static bool HasFeature(string key)
{
throw new NotImplementedException();
}
public static void Init()
{
}
#endregion
#endif
}
} | 28.412698 | 137 | 0.511173 | [
"MIT"
] | SlashGames/slash-framework | Source/Slash.IAP/Source/IAPManager.cs | 3,582 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using UnicornNet.Data;
namespace UnicornNet
{
public class Unicorn : IDisposable
{
private readonly Dictionary<int, UnicornCallbackData> _callbacks;
private int _callbackId;
public Unicorn(UcArch arch, UcMode mode)
{
_callbacks = new Dictionary<int, UnicornCallbackData>();
_callbackId = 0;
var result = Marshal.AllocHGlobal(Marshal.SizeOf<IntPtr>());
var err = UcNative.UcOpen(arch, mode, result);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException($"Failed to create native Unicorn instance, error {err}.", err);
}
Handle = (IntPtr) Marshal.PtrToStructure(result, typeof(IntPtr));
}
public IntPtr Handle { get; }
public ulong Query(UcQueryType type)
{
var err = UcNative.UcQuery(Handle, type, out var result);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
return result;
}
public UcErr Errno()
{
return UcNative.UcErrno(Handle);
}
public void RegWrite(int registerId, ulong data)
{
var err = UcNative.UcRegWrite(Handle, registerId, ref data);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public ulong RegRead(int registerId)
{
var err = UcNative.UcRegRead(Handle, registerId, out var result);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
return result;
}
public void MemWrite(ulong address, Stream stream, int size)
{
const int bufferSize = 8192;
var remaining = size;
var buffer = new byte[bufferSize];
while (remaining > 0)
{
var target = Math.Min(remaining, bufferSize);
var read = stream.Read(buffer, 0, target);
if (read != target)
{
throw new UcException("UnicornNet: Unable to read correct amount from stream.", UcErr.UC_ERR_ARG);
}
MemWrite(address, buffer, (ulong) target);
address += (ulong) read;
remaining -= read;
}
if (remaining != 0)
{
throw new UcException("UnicornNet: Unable to read full size from stream.", UcErr.UC_ERR_ARG);
}
}
public void MemWrite(ulong address, byte[] bytes)
{
MemWrite(address, bytes, (ulong) bytes.Length);
}
public unsafe void MemWrite(ulong address, byte[] bytes, ulong length)
{
fixed (byte* pBytes = bytes)
{
var err = UcNative.UcMemWrite(Handle, address, pBytes, length);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
}
public unsafe void MemWrite(ulong address, Span<byte> bytes)
{
fixed (byte* pBytes = bytes)
{
var err = UcNative.UcMemWrite(Handle, address, pBytes, (ulong) bytes.Length);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
}
public unsafe byte[] MemRead(ulong address, ulong size)
{
var result = new byte[size];
fixed (byte* pBytes = result)
{
var err = UcNative.UcMemRead(Handle, address, pBytes, size);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
return result;
}
public unsafe void MemRead(ulong address, ulong size, Span<byte> dest)
{
fixed (byte* destPtr = dest)
{
var err = UcNative.UcMemRead(Handle, address, destPtr, size);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
}
public void EmuStart(ulong begin, ulong until, ulong timeout = 0, ulong size = 0)
{
var err = UcNative.UcEmuStart(Handle, begin, until, timeout, size);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public void EmuStop()
{
var err = UcNative.UcEmuStop(Handle);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
private IntPtr HookAdd(UcHookType type, Delegate callback, Delegate userCallback, object userData = null, ulong begin = 1, ulong end = 0)
{
var callbackId = _callbackId++;
var callbackData = new UnicornCallbackData(callback, userCallback, userData);
var err = UcNative.UcHookAdd(Handle, out var result, type, callback, new IntPtr(callbackId), begin, end);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
_callbacks.Add(callbackId, callbackData);
return result;
}
public IntPtr HookCode(CallbackHookCodeUser callback, object userData = null, ulong begin = 1, ulong end = 0)
{
return HookAdd(UcHookType.UC_HOOK_CODE, (CallbackHookCode) HookCodeCallback, callback, userData, begin, end);
}
public IntPtr HookBlock(CallbackHookCodeUser callback, object userData = null, ulong begin = 1, ulong end = 0)
{
return HookAdd(UcHookType.UC_HOOK_BLOCK, (CallbackHookCode) HookCodeCallback, callback, userData, begin, end);
}
private void HookCodeCallback(IntPtr uc, ulong address, int size, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
((CallbackHookCodeUser) callbackData.UserCallback)(this, address, size, callbackData.UserData);
}
public IntPtr HookIntr(CallbackHookIntrUser callback, object userData = null, ulong begin = 1, ulong end = 0)
{
return HookAdd(UcHookType.UC_HOOK_INTR, (CallbackHookIntr) HookIntrCallback, callback, userData, begin, end);
}
private void HookIntrCallback(IntPtr uc, uint intno, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
((CallbackHookIntrUser) callbackData.UserCallback)(this, intno, callbackData.UserData);
}
public IntPtr HookInsnInvalid(CallbackHookInsnInvalidUser callback, object userData = null, ulong begin = 1, ulong end = 0)
{
return HookAdd(UcHookType.UC_HOOK_INSN_INVALID, (CallbackHookInsnInvalid) HookInsnInvalidCallback, callback, userData, begin, end);
}
private bool HookInsnInvalidCallback(IntPtr uc, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
return ((CallbackHookInsnInvalidUser) callbackData.UserCallback)(this, callbackData.UserData);
}
public IntPtr HookMem(CallbackHookMemUser callback, UcHookTypeMem hookType, object userData = null, ulong begin = 1, ulong end = 0)
{
return HookAdd((UcHookType) hookType, (CallbackHookMem) HookMemCallback, callback, userData, begin, end);
}
private void HookMemCallback(IntPtr uc, UcMemType type, ulong address, int size, long value, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
((CallbackHookMemUser) callbackData.UserCallback)(this, type, address, size, value, callbackData.UserData);
}
public IntPtr HookMemEvent(CallbackEventMemUser callback, UcHookTypeMemInvalid hookType, object userData = null, ulong begin = 1, ulong end = 0)
{
return HookAdd((UcHookType) hookType, (CallbackEventMem) HookMemEventCallback, callback, userData, begin, end);
}
private bool HookMemEventCallback(IntPtr uc, UcMemType type, ulong address, int size, long value, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
return ((CallbackEventMemUser) callbackData.UserCallback)(this, type, address, size, value, callbackData.UserData);
}
public void HookDel(IntPtr hookHandle)
{
var err = UcNative.UcHookDel(Handle, hookHandle);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public void MemMap(ulong address, ulong size, UcProt prot = UcProt.UC_PROT_ALL)
{
var err = UcNative.UcMemMap(Handle, address, size, prot);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public void MemMapPtr(ulong address, ulong size, IntPtr ptr, UcProt perms = UcProt.UC_PROT_ALL)
{
var err = UcNative.UcMemMapPtr(Handle, address, size, perms, ptr);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public void MemUnmap(ulong address, ulong size)
{
var err = UcNative.UcMemUnmap(Handle, address, size);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public void MemProtect(ulong address, ulong size, UcProt perms = UcProt.UC_PROT_ALL)
{
var err = UcNative.UcMemProtect(Handle, address, size, perms);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public IEnumerable<UcMemRegion> MemRegions()
{
var err = UcNative.UcMemRegions(Handle, out var regions, out var count);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
var size = Marshal.SizeOf<UcMemRegion>();
var result = new UcMemRegion[count];
for (var i = 0; i < count; i++)
{
yield return Marshal.PtrToStructure<UcMemRegion>(regions + (i * size));
}
}
public IntPtr ContextAlloc()
{
var err = UcNative.UcContextAlloc(Handle, out var context);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
return context;
}
/// <summary>
/// Free the memory allocated by uc_context_alloc & uc_mem_regions.
/// </summary>
/// <param name="mem">
/// memory allocated by uc_context_alloc (returned in *context),
/// or by uc_mem_regions (returned in *regions)
/// </param>
public void Free(IntPtr mem)
{
var err = UcNative.UcFree(mem);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public void ContextSave(IntPtr context)
{
var err = UcNative.UcContextSave(Handle, context);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public void ContextRestore(IntPtr context)
{
var err = UcNative.UcContextRestore(Handle, context);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException(err);
}
}
public ulong ContextSize(IntPtr context)
{
return UcNative.UcContextSize(Handle);
}
public void Dispose()
{
var err = UcNative.UcClose(Handle);
if (err != UcErr.UC_ERR_OK)
{
throw new UcException($"Failed to close native Unicorn instance, error {err}.", err);
}
}
public delegate void CallbackHookCode(IntPtr uc, ulong address, int size, IntPtr userData);
public delegate void CallbackHookCodeUser(Unicorn uc, ulong address, int size, object userData);
public delegate void CallbackHookIntr(IntPtr uc, uint intno, IntPtr userData);
public delegate void CallbackHookIntrUser(Unicorn uc, uint intno, object userData);
public delegate bool CallbackHookInsnInvalid(IntPtr uc, IntPtr userData);
public delegate bool CallbackHookInsnInvalidUser(Unicorn uc, object userData);
public delegate void CallbackHookMem(IntPtr uc, UcMemType type, ulong address, int size, long value, IntPtr userData);
public delegate void CallbackHookMemUser(Unicorn uc, UcMemType type, ulong address, int size, long value, object userData);
public delegate bool CallbackEventMem(IntPtr uc, UcMemType type, ulong address, int size, long value, IntPtr userData);
public delegate bool CallbackEventMemUser(Unicorn uc, UcMemType type, ulong address, int size, long value, object userData);
}
} | 35.527559 | 152 | 0.554891 | [
"MIT"
] | AeonLucid/UnicornNet | src/UnicornNet/Unicorn.cs | 13,536 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using TicketNow.Movies.Api.Mappers;
using TicketNow.Movies.Core.Services;
using TicketNow.Common;
using System.Threading.Tasks;
namespace TicketNow.Movies.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class MoviesController : ControllerBase
{
private readonly ILogger<MoviesController> _logger;
private readonly IMovieService _movieService;
private readonly IMovieMapper _movieMapper;
public MoviesController(ILogger<MoviesController> logger, IMovieService movieService, IMovieMapper movieMapper)
{
_logger = logger;
_movieService = movieService;
_movieMapper = movieMapper;
}
[HttpGet]
public async Task<IActionResult> GetAsync()
{
var movies = await _movieService.FindAllAsync();
return Ok(movies.ConvertAll(_movieMapper.ToDto));
}
}
}
| 29.969697 | 119 | 0.687563 | [
"MIT"
] | jakemoresca/TicketNowNetCore | TicketNow.Movies.Api/Controllers/MoviesController.cs | 991 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _05_MagicExchanWord
{
public class StartUp
{
public static void Main()
{
string input = Console.ReadLine();
string[] words = input.Split().ToArray();
char[] firstWord = words[0].ToCharArray();
char[] secondWoed = words[1].ToCharArray();
char[] clearFirst = firstWord.Distinct().ToArray();
char[] clearSecond = secondWoed.Distinct().ToArray();
if (clearFirst.Length==clearSecond.Length)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
}
} | 24.322581 | 65 | 0.522546 | [
"MIT"
] | MrPIvanov/SoftUni | 02-Progr Fundamentals/24-Strings and Text Processing - Exercises/24-StringTextExer/05-MagicExchanWord/StartUp.cs | 756 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
public partial class JsonWriteSettings : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsDefined(FilePattern))
{
writer.WritePropertyName("filePattern");
writer.WriteStringValue(FilePattern.Value.ToString());
}
writer.WritePropertyName("type");
writer.WriteStringValue(Type);
foreach (var item in AdditionalProperties)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
internal static JsonWriteSettings DeserializeJsonWriteSettings(JsonElement element)
{
Optional<JsonWriteFilePattern> filePattern = default;
string type = default;
IDictionary<string, object> additionalProperties = default;
Dictionary<string, object> additionalPropertiesDictionary = new Dictionary<string, object>();
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("filePattern"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
filePattern = new JsonWriteFilePattern(property.Value.GetString());
continue;
}
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject());
}
additionalProperties = additionalPropertiesDictionary;
return new JsonWriteSettings(type, additionalProperties, Optional.ToNullable(filePattern));
}
}
}
| 36.53125 | 105 | 0.582121 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/JsonWriteSettings.Serialization.cs | 2,338 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
namespace cfg.item
{
public sealed partial class InteractionItem : item.ItemExtra
{
public InteractionItem(ByteBuf _buf) : base(_buf)
{
if(_buf.ReadBool()){ AttackNum = _buf.ReadInt(); } else { AttackNum = null; }
HoldingStaticMesh = _buf.ReadString();
HoldingStaticMeshMat = _buf.ReadString();
}
public InteractionItem(int id, int? attack_num, string holding_static_mesh, string holding_static_mesh_mat ) : base(id)
{
this.AttackNum = attack_num;
this.HoldingStaticMesh = holding_static_mesh;
this.HoldingStaticMeshMat = holding_static_mesh_mat;
}
public static InteractionItem DeserializeInteractionItem(ByteBuf _buf)
{
return new item.InteractionItem(_buf);
}
public readonly int? AttackNum;
public readonly string HoldingStaticMesh;
public readonly string HoldingStaticMeshMat;
public const int ID = 640937802;
public override int GetTypeId() => ID;
public override void Resolve(Dictionary<string, object> _tables)
{
base.Resolve(_tables);
OnResolveFinish(_tables);
}
partial void OnResolveFinish(Dictionary<string, object> _tables);
public override string ToString()
{
return "{ "
+ "Id:" + Id + ","
+ "AttackNum:" + AttackNum + ","
+ "HoldingStaticMesh:" + HoldingStaticMesh + ","
+ "HoldingStaticMeshMat:" + HoldingStaticMeshMat + ","
+ "}";
}
}
}
| 28.358209 | 125 | 0.603684 | [
"MIT"
] | HFX-93/luban_examples | Projects/Csharp_ET_bin/Unity/Assets/Model/Generate/Luban_Config/item/InteractionItem.cs | 1,900 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Damagable : MonoBehaviour
{
public int fractionId;
public virtual void Die()
{
Debug.Log(":D");
var rb = GetComponent<Rigidbody>();
var collider = GetComponent<Collider>();
collider.enabled = false;
rb.useGravity = true;
rb.constraints = RigidbodyConstraints.None;
rb.drag = 0.0f;
rb.mass = 50.0f;
Destroy(gameObject, 3);
Destroy(this);
}
}
| 21.36 | 51 | 0.610487 | [
"MIT"
] | Risist/BloodVillage | Assets/Damagable.cs | 536 | C# |
using UnityEngine;
using System;
using AppodealAds.Unity.Api;
using AppodealAds.Unity.Common;
using AOT;
#if UNITY_IPHONE
namespace AppodealAds.Unity.iOS {
public class AppodealAdsClient : IAppodealAdsClient {
private const int AppodealAdTypeInterstitial = 1 << 0;
private const int AppodealAdTypeBanner = 1 << 2;
private const int AppodealAdTypeRewardedVideo = 1 << 4;
private const int AppodealAdTypeNonSkippableVideo = 1 << 6;
private const int AppodealShowStyleInterstitial = 1;
private const int AppodealShowStyleBannerTop = 4;
private const int AppodealShowStyleBannerBottom = 8;
private const int AppodealShowStyleRewardedVideo = 16;
private const int AppodealShowStyleNonSkippableVideo = 32;
#region Singleton
private AppodealAdsClient() { }
private static readonly AppodealAdsClient instance = new AppodealAdsClient();
public static AppodealAdsClient Instance {
get {
return instance;
}
}
#endregion
public void requestAndroidMPermissions(IPermissionGrantedListener listener) {
// not supported on ios
}
private static IInterstitialAdListener interstitialListener;
private static INonSkippableVideoAdListener nonSkippableVideoListener;
private static IRewardedVideoAdListener rewardedVideoListener;
private static IBannerAdListener bannerListener;
#region Interstitial Delegate
[MonoPInvokeCallback (typeof (AppodealInterstitialDidLoadCallback))]
private static void interstitialDidLoad (bool isPrecache) {
if (AppodealAdsClient.interstitialListener != null) {
AppodealAdsClient.interstitialListener.onInterstitialLoaded(isPrecache);
}
}
[MonoPInvokeCallback (typeof (AppodealInterstitialCallbacks))]
private static void interstitialDidFailToLoad () {
if (AppodealAdsClient.interstitialListener != null) {
AppodealAdsClient.interstitialListener.onInterstitialFailedToLoad();
}
}
[MonoPInvokeCallback (typeof (AppodealInterstitialCallbacks))]
private static void interstitialDidClick () {
if (AppodealAdsClient.interstitialListener != null) {
AppodealAdsClient.interstitialListener.onInterstitialClicked();
}
}
[MonoPInvokeCallback (typeof (AppodealInterstitialCallbacks))]
private static void interstitialDidDismiss () {
if (AppodealAdsClient.interstitialListener != null) {
AppodealAdsClient.interstitialListener.onInterstitialClosed();
}
}
[MonoPInvokeCallback (typeof (AppodealInterstitialCallbacks))]
private static void interstitialWillPresent () {
if (AppodealAdsClient.interstitialListener != null) {
AppodealAdsClient.interstitialListener.onInterstitialShown();
}
}
public void setInterstitialCallbacks(IInterstitialAdListener listener) {
AppodealAdsClient.interstitialListener = listener;
AppodealObjCBridge.AppodealSetInterstitialDelegate(
AppodealAdsClient.interstitialDidLoad,
AppodealAdsClient.interstitialDidFailToLoad,
AppodealAdsClient.interstitialDidClick,
AppodealAdsClient.interstitialDidDismiss,
AppodealAdsClient.interstitialWillPresent
);
}
#endregion
#region Non Skippable Video Delegate
[MonoPInvokeCallback (typeof (AppodealNonSkippableVideoCallbacks))]
private static void nonSkippableVideoDidLoadAd() {
if (AppodealAdsClient.nonSkippableVideoListener != null) {
AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoLoaded();
}
}
[MonoPInvokeCallback (typeof (AppodealNonSkippableVideoCallbacks))]
private static void nonSkippableVideoDidFailToLoadAd() {
if (AppodealAdsClient.nonSkippableVideoListener != null) {
AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoFailedToLoad();
}
}
[MonoPInvokeCallback (typeof (AppodealNonSkippableVideoDidDismissCallback))]
private static void nonSkippableVideoWillDismiss(bool isFinished) {
if (AppodealAdsClient.nonSkippableVideoListener != null) {
AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoClosed(isFinished);
}
}
[MonoPInvokeCallback (typeof (AppodealNonSkippableVideoCallbacks))]
private static void nonSkippableVideoDidFinish() {
if (AppodealAdsClient.nonSkippableVideoListener != null) {
AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoFinished();
}
}
[MonoPInvokeCallback (typeof (AppodealNonSkippableVideoCallbacks))]
private static void nonSkippableVideoDidPresent() {
if (AppodealAdsClient.nonSkippableVideoListener != null) {
AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoShown();
}
}
public void setNonSkippableVideoCallbacks(INonSkippableVideoAdListener listener) {
AppodealAdsClient.nonSkippableVideoListener = listener;
AppodealObjCBridge.AppodealSetNonSkippableVideoDelegate(
AppodealAdsClient.nonSkippableVideoDidLoadAd,
AppodealAdsClient.nonSkippableVideoDidFailToLoadAd,
AppodealAdsClient.nonSkippableVideoWillDismiss,
AppodealAdsClient.nonSkippableVideoDidFinish,
AppodealAdsClient.nonSkippableVideoDidPresent
);
}
#endregion
#region Rewarded Video Delegate
[MonoPInvokeCallback (typeof (AppodealRewardedVideoCallbacks))]
private static void rewardedVideoDidLoadAd() {
if (AppodealAdsClient.rewardedVideoListener != null) {
AppodealAdsClient.rewardedVideoListener.onRewardedVideoLoaded();
}
}
[MonoPInvokeCallback (typeof (AppodealRewardedVideoCallbacks))]
private static void rewardedVideoDidFailToLoadAd() {
if (AppodealAdsClient.rewardedVideoListener != null) {
AppodealAdsClient.rewardedVideoListener.onRewardedVideoFailedToLoad();
}
}
[MonoPInvokeCallback (typeof (AppodealRewardedVideoDidDismissCallback))]
private static void rewardedVideoWillDismiss(bool isFinished) {
if (AppodealAdsClient.rewardedVideoListener != null) {
AppodealAdsClient.rewardedVideoListener.onRewardedVideoClosed(isFinished);
}
}
[MonoPInvokeCallback (typeof (AppodealRewardedVideoDidFinishCallback))]
private static void rewardedVideoDidFinish(int amount, string name) {
if (AppodealAdsClient.rewardedVideoListener != null) {
AppodealAdsClient.rewardedVideoListener.onRewardedVideoFinished(amount, name);
}
}
[MonoPInvokeCallback (typeof (AppodealRewardedVideoCallbacks))]
private static void rewardedVideoDidPresent() {
if (AppodealAdsClient.rewardedVideoListener != null) {
AppodealAdsClient.rewardedVideoListener.onRewardedVideoShown();
}
}
public void setRewardedVideoCallbacks(IRewardedVideoAdListener listener) {
AppodealAdsClient.rewardedVideoListener = listener;
AppodealObjCBridge.AppodealSetRewardedVideoDelegate(
AppodealAdsClient.rewardedVideoDidLoadAd,
AppodealAdsClient.rewardedVideoDidFailToLoadAd,
AppodealAdsClient.rewardedVideoWillDismiss,
AppodealAdsClient.rewardedVideoDidFinish,
AppodealAdsClient.rewardedVideoDidPresent
);
}
#endregion
#region Banner Delegate
[MonoPInvokeCallback (typeof (AppodealBannerDidLoadCallback))]
private static void bannerDidLoadAd(bool isPrecache) {
if (AppodealAdsClient.bannerListener != null) {
AppodealAdsClient.bannerListener.onBannerLoaded(isPrecache);
}
}
[MonoPInvokeCallback (typeof (AppodealBannerCallbacks))]
private static void bannerDidFailToLoadAd() {
if (AppodealAdsClient.bannerListener != null) {
AppodealAdsClient.bannerListener.onBannerFailedToLoad();
}
}
[MonoPInvokeCallback (typeof (AppodealBannerCallbacks))]
private static void bannerDidClick () {
if (AppodealAdsClient.bannerListener != null) {
AppodealAdsClient.bannerListener.onBannerClicked();
}
}
[MonoPInvokeCallback (typeof (AppodealBannerCallbacks))]
private static void bannerDidShow () {
if (AppodealAdsClient.bannerListener != null) {
AppodealAdsClient.bannerListener.onBannerShown();
}
}
[MonoPInvokeCallback (typeof (AppodealBannerViewDidLoadCallback))]
private static void bannerViewDidLoadAd(bool isPrecache) {
if (AppodealAdsClient.bannerListener != null) {
AppodealAdsClient.bannerListener.onBannerLoaded(isPrecache);
}
}
[MonoPInvokeCallback (typeof (AppodealBannerViewCallbacks))]
private static void bannerViewDidFailToLoadAd() {
if (AppodealAdsClient.bannerListener != null) {
AppodealAdsClient.bannerListener.onBannerFailedToLoad();
}
}
[MonoPInvokeCallback (typeof (AppodealBannerViewCallbacks))]
private static void bannerViewDidClick () {
if (AppodealAdsClient.bannerListener != null) {
AppodealAdsClient.bannerListener.onBannerClicked();
}
}
public void setBannerCallbacks(IBannerAdListener listener) {
AppodealAdsClient.bannerListener = listener;
AppodealObjCBridge.AppodealSetBannerDelegate(
AppodealAdsClient.bannerDidLoadAd,
AppodealAdsClient.bannerDidFailToLoadAd,
AppodealAdsClient.bannerDidClick,
AppodealAdsClient.bannerDidShow);
AppodealObjCBridge.AppodealSetBannerViewDelegate(
AppodealAdsClient.bannerViewDidLoadAd,
AppodealAdsClient.bannerViewDidFailToLoadAd,
AppodealAdsClient.bannerViewDidClick);
}
#endregion
private int nativeAdTypesForType(int adTypes) {
int nativeAdTypes = 0;
if ((adTypes & Appodeal.INTERSTITIAL) > 0) {
nativeAdTypes |= AppodealAdTypeInterstitial;
}
if ((adTypes & Appodeal.BANNER) > 0 ||
(adTypes & Appodeal.BANNER_VIEW) > 0 ||
(adTypes & Appodeal.BANNER_TOP) > 0 ||
(adTypes & Appodeal.BANNER_BOTTOM) > 0) {
nativeAdTypes |= AppodealAdTypeBanner;
}
if ((adTypes & Appodeal.REWARDED_VIDEO) > 0) {
nativeAdTypes |= AppodealAdTypeRewardedVideo;
}
if ((adTypes & Appodeal.NON_SKIPPABLE_VIDEO) > 0) {
nativeAdTypes |= AppodealAdTypeNonSkippableVideo;
}
return nativeAdTypes;
}
private int nativeShowStyleForType(int adTypes) {
if ((adTypes & Appodeal.INTERSTITIAL) > 0) {
return AppodealShowStyleInterstitial;
}
if ((adTypes & Appodeal.BANNER_TOP) > 0) {
return AppodealShowStyleBannerTop;
}
if ((adTypes & Appodeal.BANNER_BOTTOM) > 0) {
return AppodealShowStyleBannerBottom;
}
if ((adTypes & Appodeal.REWARDED_VIDEO) > 0) {
return AppodealShowStyleRewardedVideo;
}
if ((adTypes & Appodeal.NON_SKIPPABLE_VIDEO) > 0) {
return AppodealShowStyleNonSkippableVideo;
}
return 0;
}
public void initialize(string appKey, int adTypes) {
AppodealObjCBridge.AppodealInitializeWithTypes(appKey, nativeAdTypesForType(adTypes), Appodeal.getPluginVersion());
}
public bool show(int adTypes) {
return AppodealObjCBridge.AppodealShowAd(nativeShowStyleForType(adTypes));
}
public bool show(int adTypes, string placement) {
return AppodealObjCBridge.AppodealShowAdforPlacement(nativeShowStyleForType(adTypes), placement);
}
public bool showBannerView(int YAxis, int XGravity, string Placement) {
return AppodealObjCBridge.AppodealShowBannerAdViewforPlacement(YAxis, XGravity, Placement);
}
public bool isLoaded(int adTypes) {
return AppodealObjCBridge.AppodealIsReadyWithStyle(nativeShowStyleForType(adTypes));
}
public void cache(int adTypes) {
AppodealObjCBridge.AppodealCacheAd(nativeAdTypesForType(adTypes));
}
public void setAutoCache(int adTypes, bool autoCache) {
AppodealObjCBridge.AppodealSetAutocache(autoCache, nativeAdTypesForType(adTypes));
}
public void hide(int adTypes) {
if ((nativeAdTypesForType(adTypes) & AppodealAdTypeBanner) > 0) {
AppodealObjCBridge.AppodealHideBanner();
}
}
public void hideBannerView() {
AppodealObjCBridge.AppodealHideBannerView();
}
public bool isPrecache(int adTypes) {
return false;
}
public void onResume() { } // handled by SDK
public void setSmartBanners(bool value) {
AppodealObjCBridge.setSmartBanners(value);
}
public void setBannerAnimation(bool value) {
AppodealObjCBridge.setBannerAnimation(value);
}
public void setBannerBackground(bool value) {
AppodealObjCBridge.setBannerBackground(value);
}
public void setTabletBanners(bool value) {
// Handled by os
}
public void setTesting(bool test) {
AppodealObjCBridge.AppodealSetTestingEnabled(test);
}
public void setLogLevel(Appodeal.LogLevel level) {
switch(level) {
case Appodeal.LogLevel.None: {
AppodealObjCBridge.AppodealSetLogLevel(1);
break;
}
case Appodeal.LogLevel.Debug: {
AppodealObjCBridge.AppodealSetLogLevel(2);
break;
}
case Appodeal.LogLevel.Verbose: {
AppodealObjCBridge.AppodealSetLogLevel(3);
break;
}
}
}
public void setChildDirectedTreatment(bool value) {
AppodealObjCBridge.AppodealSetChildDirectedTreatment(value);
}
public void disableNetwork(String network) {
AppodealObjCBridge.AppodealDisableNetwork(network);
}
public void disableNetwork(String network, int adTypes) {
AppodealObjCBridge.AppodealDisableNetworkForAdTypes(network, adTypes);
}
public void disableLocationPermissionCheck() {
AppodealObjCBridge.AppodealDisableLocationPermissionCheck();
}
public void disableWriteExternalStoragePermissionCheck() {
// Not supported for iOS SDK
}
public void muteVideosIfCallsMuted(bool value) {
// Not supported for iOS SDK
}
public void showTestScreen() {
// Not supported for iOS SDK
}
public string getVersion() {
return AppodealObjCBridge.AppodealGetVersion();
}
public bool canShow(int adTypes, string placement) {
return AppodealObjCBridge.AppodealCanShowWithPlacement(nativeShowStyleForType(adTypes), placement);
}
public bool canShow(int adTypes) {
return AppodealObjCBridge.AppodealCanShow(nativeShowStyleForType(adTypes));
}
public string getRewardCurrency(string placement) {
return AppodealObjCBridge.AppodealGetRewardCurrency(placement);
}
public int getRewardAmount(string placement) {
return AppodealObjCBridge.AppodealGetRewardAmount(placement);
}
public string getRewardCurrency() {
return AppodealObjCBridge.AppodealGetRewardCurrency("");
}
public int getRewardAmount() {
return AppodealObjCBridge.AppodealGetRewardAmount("");
}
public void setCustomRule(string name, bool value) {
AppodealObjCBridge.setCustomSegmentBool(name, value);
}
public void setCustomRule(string name, int value) {
AppodealObjCBridge.setCustomSegmentInt(name, value);
}
public void setCustomRule(string name, double value) {
AppodealObjCBridge.setCustomSegmentDouble(name, value);
}
public void setCustomRule(string name, string value) {
AppodealObjCBridge.setCustomSegmentString(name, value);
}
public void setTriggerOnLoadedOnPrecache(int adTypes, Boolean onLoadedTriggerBoth) {
// Not supported for iOS SDK
}
//User Settings
public void getUserSettings() {
// No additional state change required on iOS
}
public void setUserId(string id) {
AppodealObjCBridge.AppodealSetUserId(id);
}
public void setAge(int age) {
AppodealObjCBridge.AppodealSetUserAge(age);
}
public void setGender(UserSettings.Gender gender) {
switch(gender) {
case UserSettings.Gender.OTHER: {
AppodealObjCBridge.AppodealSetUserGender(0);
break;
}
case UserSettings.Gender.MALE: {
AppodealObjCBridge.AppodealSetUserGender(1);
break;
}
case UserSettings.Gender.FEMALE: {
AppodealObjCBridge.AppodealSetUserGender(2);
break;
}
}
}
public void trackInAppPurchase(double amount, string currency) {
AppodealObjCBridge.trackInAppPurchase(amount, currency);
}
}
}
#endif | 31.015905 | 118 | 0.763925 | [
"MIT"
] | MedAnisBenSalah/2448 | Assets/Appodeal/Platforms/iOS/AppodealAdsClient.cs | 15,603 | C# |
namespace dotless.Core.Parser.Infrastructure
{
using System.Collections.Generic;
using Importers;
using Nodes;
using Tree;
public class DefaultNodeProvider : INodeProvider
{
public Element Element(Combinator combinator, Node value, NodeLocation location)
{
return new Element(combinator, value) { Location = location };
}
public Combinator Combinator(string value, NodeLocation location)
{
return new Combinator(value) { Location = location };
}
public Selector Selector(NodeList<Element> elements, NodeLocation location)
{
return new Selector(elements) { Location = location };
}
public Rule Rule(string name, Node value, NodeLocation location)
{
return new Rule(name, value) { Location = location };
}
public Rule Rule(string name, Node value, bool variadic, NodeLocation location)
{
return new Rule(name, value, variadic) { Location = location };
}
public Ruleset Ruleset(NodeList<Selector> selectors, NodeList rules, NodeLocation location)
{
return new Ruleset(selectors, rules) { Location = location };
}
public CssFunction CssFunction(string name, Node value, NodeLocation location)
{
return new CssFunction() { Name = name, Value = value, Location = location };
}
public Alpha Alpha(Node value, NodeLocation location)
{
return new Alpha(value) { Location = location };
}
public Call Call(string name, NodeList<Node> arguments, NodeLocation location)
{
return new Call(name, arguments) { Location = location };
}
public Color Color(string rgb, NodeLocation location)
{
var color = Tree.Color.FromHex(rgb);
color.Location = location;
return color;
}
public Keyword Keyword(string value, NodeLocation location)
{
return new Keyword(value) { Location = location };
}
public Number Number(string value, string unit, NodeLocation location)
{
return new Number(value, unit) { Location = location };
}
public Shorthand Shorthand(Node first, Node second, NodeLocation location)
{
return new Shorthand(first, second) { Location = location };
}
public Variable Variable(string name, NodeLocation location)
{
return new Variable(name) { Location = location };
}
public Url Url(Node value, IImporter importer, NodeLocation location)
{
return new Url(value, importer) { Location = location };
}
public Script Script(string script, NodeLocation location)
{
return new Script(script) { Location = location };
}
public GuardedRuleset GuardedRuleset(NodeList<Selector> selectors, NodeList rules, Condition condition, NodeLocation location)
{
return new GuardedRuleset(selectors, rules, condition) { Location = location };
}
public MixinCall MixinCall(NodeList<Element> elements, List<NamedArgument> arguments, bool important, NodeLocation location)
{
return new MixinCall(elements, arguments, important) { Location = location };
}
public MixinDefinition MixinDefinition(string name, NodeList<Rule> parameters, NodeList rules, Condition condition, bool variadic, NodeLocation location)
{
return new MixinDefinition(name, parameters, rules, condition, variadic) { Location = location };
}
public Import Import(Url path, Value features, ImportOptions option, NodeLocation location)
{
return new Import(path, features, option) { Location = location };
}
public Import Import(Quoted path, Value features, ImportOptions option, NodeLocation location)
{
return new Import(path, features, option) { Location = location };
}
public Directive Directive(string name, string identifier, NodeList rules, NodeLocation location)
{
return new Directive(name, identifier, rules) { Location = location };
}
public Media Media(NodeList rules, Value features, NodeLocation location)
{
return new Media(features, rules) { Location = location };
}
public KeyFrame KeyFrame(NodeList identifier, NodeList rules, NodeLocation location)
{
return new KeyFrame(identifier, rules) { Location = location };
}
public Directive Directive(string name, Node value, NodeLocation location)
{
return new Directive(name, value) { Location = location };
}
public Expression Expression(NodeList expression, NodeLocation location)
{
return new Expression(expression) { Location = location };
}
public Value Value(IEnumerable<Node> values, string important, NodeLocation location)
{
return new Value(values, important) { Location = location };
}
public Operation Operation(string operation, Node left, Node right, NodeLocation location)
{
return new Operation(operation, left, right) { Location = location };
}
public Assignment Assignment(string key, Node value, NodeLocation location)
{
return new Assignment(key, value) {Location = location};
}
public Comment Comment(string value, NodeLocation location)
{
return new Comment(value) { Location = location };
}
public TextNode TextNode(string contents, NodeLocation location)
{
return new TextNode(contents) { Location = location };
}
public Quoted Quoted(string value, string contents, bool escaped, NodeLocation location)
{
return new Quoted(value, contents, escaped) { Location = location };
}
public Extend Extend(List<Selector> exact, List<Selector> partial, NodeLocation location)
{
return new Extend(exact,partial) { Location = location };
}
public Node Attribute(Node key, Node op, Node val, NodeLocation location)
{
return new Attribute(key, op, val) { Location = location };
}
public Paren Paren(Node value, NodeLocation location)
{
return new Paren(value) { Location = location };
}
public Condition Condition(Node left, string operation, Node right, bool negate, NodeLocation location)
{
return new Condition(left, operation, right, negate) { Location = location };
}
#if CSS3EXPERIMENTAL
public RepeatEntity RepeatEntity(Node value, Node repeatCount, int index)
{
return new RepeatEntity(value, repeatCount) { Location = location };
}
#endif
}
} | 35.742424 | 161 | 0.620461 | [
"Apache-2.0"
] | MultinetInteractive/dotless | src/dotless.Core/Parser/Infrastructure/DefaultNodeProvider.cs | 7,077 | 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.Functions.Models.Api20190801
{
using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell;
/// <summary>Site resource specific properties</summary>
[System.ComponentModel.TypeConverter(typeof(SitePropertiesTypeConverter))]
public partial class SiteProperties
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteProperties"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteProperties" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteProperties DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new SiteProperties(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteProperties"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteProperties" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new SiteProperties(content);
}
/// <summary>
/// Creates a new instance of <see cref="SiteProperties" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="SiteProperties" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteProperties"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal SiteProperties(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("HostingEnvironmentProfile"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfile = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IHostingEnvironmentProfile) content.GetValueForProperty("HostingEnvironmentProfile",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfile, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.HostingEnvironmentProfileTypeConverter.ConvertFrom);
}
if (content.Contains("CloningInfo"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfo = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ICloningInfo) content.GetValueForProperty("CloningInfo",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfo, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.CloningInfoTypeConverter.ConvertFrom);
}
if (content.Contains("SlotSwapStatus"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatus = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotSwapStatus) content.GetValueForProperty("SlotSwapStatus",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatus, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SlotSwapStatusTypeConverter.ConvertFrom);
}
if (content.Contains("State"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).State, global::System.Convert.ToString);
}
if (content.Contains("HostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostName = (string[]) content.GetValueForProperty("HostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostName, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("RepositorySiteName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).RepositorySiteName = (string) content.GetValueForProperty("RepositorySiteName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).RepositorySiteName, global::System.Convert.ToString);
}
if (content.Contains("UsageState"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).UsageState = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.UsageState?) content.GetValueForProperty("UsageState",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).UsageState, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.UsageState.CreateFrom);
}
if (content.Contains("Enabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).Enabled = (bool?) content.GetValueForProperty("Enabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).Enabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("EnabledHostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).EnabledHostName = (string[]) content.GetValueForProperty("EnabledHostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).EnabledHostName, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("AvailabilityState"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).AvailabilityState = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.SiteAvailabilityState?) content.GetValueForProperty("AvailabilityState",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).AvailabilityState, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.SiteAvailabilityState.CreateFrom);
}
if (content.Contains("HostNameSslState"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostNameSslState = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IHostNameSslState[]) content.GetValueForProperty("HostNameSslState",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostNameSslState, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IHostNameSslState>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.HostNameSslStateTypeConverter.ConvertFrom));
}
if (content.Contains("ServerFarmId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ServerFarmId = (string) content.GetValueForProperty("ServerFarmId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ServerFarmId, global::System.Convert.ToString);
}
if (content.Contains("Reserved"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).Reserved = (bool?) content.GetValueForProperty("Reserved",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).Reserved, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("IsXenon"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).IsXenon = (bool?) content.GetValueForProperty("IsXenon",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).IsXenon, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("HyperV"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HyperV = (bool?) content.GetValueForProperty("HyperV",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HyperV, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("LastModifiedTimeUtc"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).LastModifiedTimeUtc = (global::System.DateTime?) content.GetValueForProperty("LastModifiedTimeUtc",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).LastModifiedTimeUtc, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("TrafficManagerHostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).TrafficManagerHostName = (string[]) content.GetValueForProperty("TrafficManagerHostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).TrafficManagerHostName, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("ScmSiteAlsoStopped"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ScmSiteAlsoStopped = (bool?) content.GetValueForProperty("ScmSiteAlsoStopped",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ScmSiteAlsoStopped, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("TargetSwapSlot"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).TargetSwapSlot = (string) content.GetValueForProperty("TargetSwapSlot",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).TargetSwapSlot, global::System.Convert.ToString);
}
if (content.Contains("ClientAffinityEnabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientAffinityEnabled = (bool?) content.GetValueForProperty("ClientAffinityEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientAffinityEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("ClientCertEnabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientCertEnabled = (bool?) content.GetValueForProperty("ClientCertEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientCertEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("ClientCertExclusionPath"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientCertExclusionPath = (string) content.GetValueForProperty("ClientCertExclusionPath",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientCertExclusionPath, global::System.Convert.ToString);
}
if (content.Contains("HostNamesDisabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostNamesDisabled = (bool?) content.GetValueForProperty("HostNamesDisabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostNamesDisabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("OutboundIPAddress"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).OutboundIPAddress = (string) content.GetValueForProperty("OutboundIPAddress",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).OutboundIPAddress, global::System.Convert.ToString);
}
if (content.Contains("PossibleOutboundIPAddress"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).PossibleOutboundIPAddress = (string) content.GetValueForProperty("PossibleOutboundIPAddress",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).PossibleOutboundIPAddress, global::System.Convert.ToString);
}
if (content.Contains("ContainerSize"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ContainerSize = (int?) content.GetValueForProperty("ContainerSize",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ContainerSize, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
}
if (content.Contains("DailyMemoryTimeQuota"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).DailyMemoryTimeQuota = (int?) content.GetValueForProperty("DailyMemoryTimeQuota",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).DailyMemoryTimeQuota, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
}
if (content.Contains("SuspendedTill"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SuspendedTill = (global::System.DateTime?) content.GetValueForProperty("SuspendedTill",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SuspendedTill, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("MaxNumberOfWorker"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).MaxNumberOfWorker = (int?) content.GetValueForProperty("MaxNumberOfWorker",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).MaxNumberOfWorker, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
}
if (content.Contains("ResourceGroup"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ResourceGroup = (string) content.GetValueForProperty("ResourceGroup",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ResourceGroup, global::System.Convert.ToString);
}
if (content.Contains("IsDefaultContainer"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).IsDefaultContainer = (bool?) content.GetValueForProperty("IsDefaultContainer",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).IsDefaultContainer, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("DefaultHostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).DefaultHostName = (string) content.GetValueForProperty("DefaultHostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).DefaultHostName, global::System.Convert.ToString);
}
if (content.Contains("HttpsOnly"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HttpsOnly = (bool?) content.GetValueForProperty("HttpsOnly",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HttpsOnly, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("RedundancyMode"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).RedundancyMode = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.RedundancyMode?) content.GetValueForProperty("RedundancyMode",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).RedundancyMode, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.RedundancyMode.CreateFrom);
}
if (content.Contains("InProgressOperationId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).InProgressOperationId = (string) content.GetValueForProperty("InProgressOperationId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).InProgressOperationId, global::System.Convert.ToString);
}
if (content.Contains("SiteConfig"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SiteConfig = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfig) content.GetValueForProperty("SiteConfig",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SiteConfig, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteConfigTypeConverter.ConvertFrom);
}
if (content.Contains("HostingEnvironmentProfileId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileId = (string) content.GetValueForProperty("HostingEnvironmentProfileId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileId, global::System.Convert.ToString);
}
if (content.Contains("HostingEnvironmentProfileName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileName = (string) content.GetValueForProperty("HostingEnvironmentProfileName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileName, global::System.Convert.ToString);
}
if (content.Contains("HostingEnvironmentProfileType"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileType = (string) content.GetValueForProperty("HostingEnvironmentProfileType",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileType, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoCorrelationId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCorrelationId = (string) content.GetValueForProperty("CloningInfoCorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCorrelationId, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoHostingEnvironment"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoHostingEnvironment = (string) content.GetValueForProperty("CloningInfoHostingEnvironment",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoHostingEnvironment, global::System.Convert.ToString);
}
if (content.Contains("SlotSwapStatusTimestampUtc"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusTimestampUtc = (global::System.DateTime?) content.GetValueForProperty("SlotSwapStatusTimestampUtc",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusTimestampUtc, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("CloningInfoOverwrite"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoOverwrite = (bool?) content.GetValueForProperty("CloningInfoOverwrite",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoOverwrite, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("CloningInfoCloneCustomHostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCloneCustomHostName = (bool?) content.GetValueForProperty("CloningInfoCloneCustomHostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCloneCustomHostName, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("CloningInfoCloneSourceControl"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCloneSourceControl = (bool?) content.GetValueForProperty("CloningInfoCloneSourceControl",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCloneSourceControl, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("CloningInfoSourceWebAppId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoSourceWebAppId = (string) content.GetValueForProperty("CloningInfoSourceWebAppId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoSourceWebAppId, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoSourceWebAppLocation"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoSourceWebAppLocation = (string) content.GetValueForProperty("CloningInfoSourceWebAppLocation",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoSourceWebAppLocation, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoAppSettingsOverride"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoAppSettingsOverride = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ICloningInfoAppSettingsOverrides) content.GetValueForProperty("CloningInfoAppSettingsOverride",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoAppSettingsOverride, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.CloningInfoAppSettingsOverridesTypeConverter.ConvertFrom);
}
if (content.Contains("CloningInfoConfigureLoadBalancing"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoConfigureLoadBalancing = (bool?) content.GetValueForProperty("CloningInfoConfigureLoadBalancing",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoConfigureLoadBalancing, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("CloningInfoTrafficManagerProfileId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoTrafficManagerProfileId = (string) content.GetValueForProperty("CloningInfoTrafficManagerProfileId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoTrafficManagerProfileId, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoTrafficManagerProfileName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoTrafficManagerProfileName = (string) content.GetValueForProperty("CloningInfoTrafficManagerProfileName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoTrafficManagerProfileName, global::System.Convert.ToString);
}
if (content.Contains("SlotSwapStatusSourceSlotName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusSourceSlotName = (string) content.GetValueForProperty("SlotSwapStatusSourceSlotName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusSourceSlotName, global::System.Convert.ToString);
}
if (content.Contains("SlotSwapStatusDestinationSlotName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusDestinationSlotName = (string) content.GetValueForProperty("SlotSwapStatusDestinationSlotName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusDestinationSlotName, global::System.Convert.ToString);
}
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteProperties"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal SiteProperties(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("HostingEnvironmentProfile"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfile = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IHostingEnvironmentProfile) content.GetValueForProperty("HostingEnvironmentProfile",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfile, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.HostingEnvironmentProfileTypeConverter.ConvertFrom);
}
if (content.Contains("CloningInfo"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfo = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ICloningInfo) content.GetValueForProperty("CloningInfo",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfo, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.CloningInfoTypeConverter.ConvertFrom);
}
if (content.Contains("SlotSwapStatus"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatus = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISlotSwapStatus) content.GetValueForProperty("SlotSwapStatus",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatus, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SlotSwapStatusTypeConverter.ConvertFrom);
}
if (content.Contains("State"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).State, global::System.Convert.ToString);
}
if (content.Contains("HostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostName = (string[]) content.GetValueForProperty("HostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostName, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("RepositorySiteName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).RepositorySiteName = (string) content.GetValueForProperty("RepositorySiteName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).RepositorySiteName, global::System.Convert.ToString);
}
if (content.Contains("UsageState"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).UsageState = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.UsageState?) content.GetValueForProperty("UsageState",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).UsageState, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.UsageState.CreateFrom);
}
if (content.Contains("Enabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).Enabled = (bool?) content.GetValueForProperty("Enabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).Enabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("EnabledHostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).EnabledHostName = (string[]) content.GetValueForProperty("EnabledHostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).EnabledHostName, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("AvailabilityState"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).AvailabilityState = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.SiteAvailabilityState?) content.GetValueForProperty("AvailabilityState",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).AvailabilityState, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.SiteAvailabilityState.CreateFrom);
}
if (content.Contains("HostNameSslState"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostNameSslState = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IHostNameSslState[]) content.GetValueForProperty("HostNameSslState",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostNameSslState, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IHostNameSslState>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.HostNameSslStateTypeConverter.ConvertFrom));
}
if (content.Contains("ServerFarmId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ServerFarmId = (string) content.GetValueForProperty("ServerFarmId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ServerFarmId, global::System.Convert.ToString);
}
if (content.Contains("Reserved"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).Reserved = (bool?) content.GetValueForProperty("Reserved",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).Reserved, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("IsXenon"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).IsXenon = (bool?) content.GetValueForProperty("IsXenon",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).IsXenon, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("HyperV"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HyperV = (bool?) content.GetValueForProperty("HyperV",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HyperV, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("LastModifiedTimeUtc"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).LastModifiedTimeUtc = (global::System.DateTime?) content.GetValueForProperty("LastModifiedTimeUtc",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).LastModifiedTimeUtc, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("TrafficManagerHostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).TrafficManagerHostName = (string[]) content.GetValueForProperty("TrafficManagerHostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).TrafficManagerHostName, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString));
}
if (content.Contains("ScmSiteAlsoStopped"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ScmSiteAlsoStopped = (bool?) content.GetValueForProperty("ScmSiteAlsoStopped",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ScmSiteAlsoStopped, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("TargetSwapSlot"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).TargetSwapSlot = (string) content.GetValueForProperty("TargetSwapSlot",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).TargetSwapSlot, global::System.Convert.ToString);
}
if (content.Contains("ClientAffinityEnabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientAffinityEnabled = (bool?) content.GetValueForProperty("ClientAffinityEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientAffinityEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("ClientCertEnabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientCertEnabled = (bool?) content.GetValueForProperty("ClientCertEnabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientCertEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("ClientCertExclusionPath"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientCertExclusionPath = (string) content.GetValueForProperty("ClientCertExclusionPath",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ClientCertExclusionPath, global::System.Convert.ToString);
}
if (content.Contains("HostNamesDisabled"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostNamesDisabled = (bool?) content.GetValueForProperty("HostNamesDisabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostNamesDisabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("OutboundIPAddress"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).OutboundIPAddress = (string) content.GetValueForProperty("OutboundIPAddress",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).OutboundIPAddress, global::System.Convert.ToString);
}
if (content.Contains("PossibleOutboundIPAddress"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).PossibleOutboundIPAddress = (string) content.GetValueForProperty("PossibleOutboundIPAddress",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).PossibleOutboundIPAddress, global::System.Convert.ToString);
}
if (content.Contains("ContainerSize"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ContainerSize = (int?) content.GetValueForProperty("ContainerSize",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ContainerSize, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
}
if (content.Contains("DailyMemoryTimeQuota"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).DailyMemoryTimeQuota = (int?) content.GetValueForProperty("DailyMemoryTimeQuota",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).DailyMemoryTimeQuota, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
}
if (content.Contains("SuspendedTill"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SuspendedTill = (global::System.DateTime?) content.GetValueForProperty("SuspendedTill",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SuspendedTill, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("MaxNumberOfWorker"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).MaxNumberOfWorker = (int?) content.GetValueForProperty("MaxNumberOfWorker",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).MaxNumberOfWorker, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
}
if (content.Contains("ResourceGroup"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ResourceGroup = (string) content.GetValueForProperty("ResourceGroup",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).ResourceGroup, global::System.Convert.ToString);
}
if (content.Contains("IsDefaultContainer"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).IsDefaultContainer = (bool?) content.GetValueForProperty("IsDefaultContainer",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).IsDefaultContainer, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("DefaultHostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).DefaultHostName = (string) content.GetValueForProperty("DefaultHostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).DefaultHostName, global::System.Convert.ToString);
}
if (content.Contains("HttpsOnly"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HttpsOnly = (bool?) content.GetValueForProperty("HttpsOnly",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HttpsOnly, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("RedundancyMode"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).RedundancyMode = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.RedundancyMode?) content.GetValueForProperty("RedundancyMode",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).RedundancyMode, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.RedundancyMode.CreateFrom);
}
if (content.Contains("InProgressOperationId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).InProgressOperationId = (string) content.GetValueForProperty("InProgressOperationId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).InProgressOperationId, global::System.Convert.ToString);
}
if (content.Contains("SiteConfig"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SiteConfig = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISiteConfig) content.GetValueForProperty("SiteConfig",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SiteConfig, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.SiteConfigTypeConverter.ConvertFrom);
}
if (content.Contains("HostingEnvironmentProfileId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileId = (string) content.GetValueForProperty("HostingEnvironmentProfileId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileId, global::System.Convert.ToString);
}
if (content.Contains("HostingEnvironmentProfileName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileName = (string) content.GetValueForProperty("HostingEnvironmentProfileName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileName, global::System.Convert.ToString);
}
if (content.Contains("HostingEnvironmentProfileType"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileType = (string) content.GetValueForProperty("HostingEnvironmentProfileType",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).HostingEnvironmentProfileType, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoCorrelationId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCorrelationId = (string) content.GetValueForProperty("CloningInfoCorrelationId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCorrelationId, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoHostingEnvironment"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoHostingEnvironment = (string) content.GetValueForProperty("CloningInfoHostingEnvironment",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoHostingEnvironment, global::System.Convert.ToString);
}
if (content.Contains("SlotSwapStatusTimestampUtc"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusTimestampUtc = (global::System.DateTime?) content.GetValueForProperty("SlotSwapStatusTimestampUtc",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusTimestampUtc, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified));
}
if (content.Contains("CloningInfoOverwrite"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoOverwrite = (bool?) content.GetValueForProperty("CloningInfoOverwrite",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoOverwrite, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("CloningInfoCloneCustomHostName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCloneCustomHostName = (bool?) content.GetValueForProperty("CloningInfoCloneCustomHostName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCloneCustomHostName, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("CloningInfoCloneSourceControl"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCloneSourceControl = (bool?) content.GetValueForProperty("CloningInfoCloneSourceControl",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoCloneSourceControl, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("CloningInfoSourceWebAppId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoSourceWebAppId = (string) content.GetValueForProperty("CloningInfoSourceWebAppId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoSourceWebAppId, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoSourceWebAppLocation"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoSourceWebAppLocation = (string) content.GetValueForProperty("CloningInfoSourceWebAppLocation",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoSourceWebAppLocation, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoAppSettingsOverride"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoAppSettingsOverride = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ICloningInfoAppSettingsOverrides) content.GetValueForProperty("CloningInfoAppSettingsOverride",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoAppSettingsOverride, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.CloningInfoAppSettingsOverridesTypeConverter.ConvertFrom);
}
if (content.Contains("CloningInfoConfigureLoadBalancing"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoConfigureLoadBalancing = (bool?) content.GetValueForProperty("CloningInfoConfigureLoadBalancing",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoConfigureLoadBalancing, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("CloningInfoTrafficManagerProfileId"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoTrafficManagerProfileId = (string) content.GetValueForProperty("CloningInfoTrafficManagerProfileId",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoTrafficManagerProfileId, global::System.Convert.ToString);
}
if (content.Contains("CloningInfoTrafficManagerProfileName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoTrafficManagerProfileName = (string) content.GetValueForProperty("CloningInfoTrafficManagerProfileName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).CloningInfoTrafficManagerProfileName, global::System.Convert.ToString);
}
if (content.Contains("SlotSwapStatusSourceSlotName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusSourceSlotName = (string) content.GetValueForProperty("SlotSwapStatusSourceSlotName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusSourceSlotName, global::System.Convert.ToString);
}
if (content.Contains("SlotSwapStatusDestinationSlotName"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusDestinationSlotName = (string) content.GetValueForProperty("SlotSwapStatusDestinationSlotName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.ISitePropertiesInternal)this).SlotSwapStatusDestinationSlotName, global::System.Convert.ToString);
}
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Site resource specific properties
[System.ComponentModel.TypeConverter(typeof(SitePropertiesTypeConverter))]
public partial interface ISiteProperties
{
}
} | 105.611111 | 620 | 0.736692 | [
"MIT"
] | AlanFlorance/azure-powershell | src/Functions/generated/api/Models/Api20190801/SiteProperties.PowerShell.cs | 58,374 | C# |
using Sandbox;
using Sandbox.UI;
using Sandbox.UI.Construct;
public class Scoreboard : Sandbox.UI.Scoreboard<ScoreboardEntry>
{
public Scoreboard()
{
StyleSheet.Load("swb_base/deathmatch_dep/ui/scss/Scoreboard.scss");
}
protected override void AddHeader()
{
Header = Add.Panel("header");
Header.Add.Label("player", "name");
Header.Add.Label("kills", "kills");
Header.Add.Label("deaths", "deaths");
Header.Add.Label("ping", "ping");
}
}
public class ScoreboardEntry : Sandbox.UI.ScoreboardEntry
{
}
| 21.333333 | 75 | 0.645833 | [
"MIT"
] | BullyHunter32/simple-weapon-base | code/swb_base/deathmatch_dep/ui/Scoreboard.cs | 578 | C# |
using System;
namespace TrackReader.Services
{
public interface IHookService : IDisposable
{
void InstallHooks();
void ReleaseHooks();
}
}
| 15.363636 | 47 | 0.64497 | [
"MIT"
] | Twinki14/TrackReader | src/TrackReader/Services/Interfaces/IHookService.cs | 171 | C# |
using NUnit.Framework;
using System;
using Workshopping;
using Workshopping.MigrantCoder;
using Handelabra.Sentinels.Engine.Model;
using Handelabra.Sentinels.Engine.Controller;
using System.Linq;
using System.Collections;
using Handelabra.Sentinels.UnitTest;
using Workshopping.TheBaddies;
using System.Collections.Generic;
namespace MyModTest
{
[TestFixture()]
public class VariantTest : BaseTest
{
protected HeroTurnTakerController migrant { get { return FindHero("MigrantCoder"); } }
[Test()]
public void TestBunkerVariant()
{
SetupGameController("BaronBlade", "Bunker/Workshopping.WaywardBunkerCharacter", "Megalopolis");
StartGame();
Assert.IsTrue(bunker.CharacterCard.IsPromoCard);
Assert.AreEqual("WaywardBunkerCharacter", bunker.CharacterCard.PromoIdentifierOrIdentifier);
Assert.AreEqual(30, bunker.CharacterCard.MaximumHitPoints);
GoToUsePowerPhase(bunker);
// Use the power, it draws 2 cards not 1!
QuickHandStorage(bunker);
UsePower(bunker);
QuickHandCheck(2);
}
[Test()]
public void TestTheSentinelsVariant()
{
var promos = new Dictionary<string, string>();
promos.Add("TheSentinelsInstructions", "Workshopping.TheSerpentinelsInstructions");
promos.Add("DrMedicoCharacter", "Workshopping.DrMedicobraCharacter");
promos.Add("WritheCharacter", "Workshopping.MainsnakeCharacter");
promos.Add("MainstayCharacter", "Workshopping.TheIdealizardCharacter");
promos.Add("TheIdealistCharacter", "Workshopping.TheIdealizardCharacter");
SetupGameController(new string[] { "BaronBlade", "TheSentinels", "Megalopolis" }, false, promos);
StartGame();
var instructions = GetCard("TheSentinelsInstructions");
Assert.IsTrue(instructions.IsPromoCard);
var medico = GetCard("DrMedicoCharacter");
Assert.AreEqual("DrMedicobraCharacter", medico.PromoIdentifierOrIdentifier);
Assert.AreEqual(15, medico.MaximumHitPoints);
GoToUsePowerPhase(sentinels);
// Use the power on Mainstay for 3 damage
var mainstay = GetCard("MainstayCharacter");
DecisionSelectTarget = GetMobileDefensePlatform().Card;
QuickHPStorage(DecisionSelectTarget);
UsePower(mainstay);
QuickHPCheck(-3);
}
[Test()]
public void TestSkyScraperVariant()
{
var promos = new Dictionary<string, string>();
promos.Add("SkyScraper", "Workshopping.CentristSkyScraperNormalCharacter");
SetupGameController(new string[] { "BaronBlade", "SkyScraper", "Megalopolis" }, false, promos);
StartGame();
Assert.IsNotNull(sky);
Assert.IsInstanceOf(typeof(Workshopping.SkyScraper.CentristSkyScraperNormalCharacterCardController), sky.CharacterCardController);
Assert.AreEqual(30, sky.CharacterCard.HitPoints);
// Huge and tiny should be off to the side.
Assert.AreEqual(2, sky.TurnTaker.OffToTheSide.NumberOfCards);
var tiny = GetCard("SkyScraperTinyCharacter");
var tinyCC = GetCardController(tiny);
AssertOffToTheSide(tiny);
Assert.IsInstanceOf(typeof(Workshopping.SkyScraper.CentristSkyScraperTinyCharacterCardController), tinyCC);
var huge = GetCard("SkyScraperHugeCharacter");
var hugeCC = GetCardController(huge);
AssertOffToTheSide(huge);
Assert.IsInstanceOf(typeof(Workshopping.SkyScraper.CentristSkyScraperHugeCharacterCardController), hugeCC);
GoToPlayCardPhase(sky);
// Normal power draws 3 and goes huge.
QuickHandStorage(sky);
UsePower(sky);
QuickHandCheck(3);
Assert.IsInstanceOf(typeof(Workshopping.SkyScraper.CentristSkyScraperHugeCharacterCardController), sky.CharacterCardController);
// Go huge!
QuickHPStorage(GetMobileDefensePlatform().Card, sky.CharacterCard);
UsePower(sky);
QuickHPCheck(-1, -1);
}
[Test()]
public void TestSkyScraperVariant_RepresentativeOfEarth()
{
var promos = new Dictionary<string, string>();
SetupGameController(new string[] { "BaronBlade", "Legacy", "TheCelestialTribunal" }, false, promos);
StartGame();
SelectFromBoxForNextDecision("Workshopping.CentristSkyScraperHugeCharacter", "SkyScraper");
var earth = PlayCard("RepresentativeOfEarth");
var rep = GetCard("SkyScraperHugeCharacter");
var repCC = FindCardController(rep);
AssertIsInPlay(rep);
AssertNextToCard(rep, earth);
AssertMaximumHitPoints(rep, 10);
Assert.IsTrue(rep.IsHeroCharacterCard);
Assert.IsTrue(rep.IsTarget && rep.IsHero);
Assert.IsFalse(rep.IsEnvironment);
Assert.IsInstanceOf(typeof(Workshopping.SkyScraper.CentristSkyScraperHugeCharacterCardController), repCC);
// Make sure the other sizes loaded too, off to the side
AssertNumberOfCardsAtLocation(env.TurnTaker.OffToTheSide, 2);
var tiny = GetCard("SkyScraperTinyCharacter");
var tinyCC = FindCardController(tiny);
Assert.IsInstanceOf(typeof(Workshopping.SkyScraper.CentristSkyScraperTinyCharacterCardController), tinyCC);
var normal = GetCard("SkyScraperNormalCharacter");
var normalCC = FindCardController(normal);
Assert.IsInstanceOf(typeof(Workshopping.SkyScraper.CentristSkyScraperNormalCharacterCardController), normalCC);
}
[Test]
public void TestSkyScraperVariant_CompletionistGuiseCharacter()
{
var promos = new Dictionary<string, string>();
promos["Guise"] = "CompletionistGuiseCharacter";
SetupGameController(new string[] { "BaronBlade", "SkyScraper", "Guise", "Legacy", "TheWraith", "Unity", "Megalopolis" }, false, promos);
StartGame();
RemoveVillainCards();
var mono = PlayCard("ThorathianMonolith");
DestroyCard(mono);
// Examine the state of each of the size cards
// Old cards should be owned by Guise now
// New cards should be owned by SkyScraper
var skyHuge = sky.CharacterCard;
var skyNormal = GetCard("SkyScraperNormalCharacter");
var skyTiny = GetCard("SkyScraperTinyCharacter");
SelectCardsForNextDecision(sky.CharacterCard, guise.CharacterCard, legacy.CharacterCard, wraith.CharacterCard, unity.CharacterCard);
SelectFromBoxForNextDecision("Workshopping.CentristSkyScraperHugeCharacter", "SkyScraper");
UsePower(guise);
var variantHuge = sky.CharacterCard;
var variantNormal = sky.TurnTaker.OffToTheSide.Cards.Where(c => c.Identifier == "SkyScraperNormalCharacter").FirstOrDefault();
var variantTiny = sky.TurnTaker.OffToTheSide.Cards.Where(c => c.Identifier == "SkyScraperTinyCharacter").FirstOrDefault();
AssertAtLocation(skyHuge, guise.CharacterCard.UnderLocation);
AssertAtLocation(skyNormal, guise.TurnTaker.OffToTheSide);
AssertAtLocation(skyTiny, guise.TurnTaker.OffToTheSide);
Assert.AreEqual("Workshopping.CentristSkyScraperHugeCharacter", variantHuge.QualifiedPromoIdentifierOrIdentifier);
Assert.AreEqual("Workshopping.CentristSkyScraperNormalCharacter", variantNormal.QualifiedPromoIdentifierOrIdentifier);
Assert.AreEqual("Workshopping.CentristSkyScraperTinyCharacter", variantTiny.QualifiedPromoIdentifierOrIdentifier);
// The new SkyScraper should be the same size and change sizes normally
Assert.AreEqual("Workshopping.CentristSkyScraperHugeCharacter", sky.CharacterCard.QualifiedPromoIdentifierOrIdentifier);
PlayCard("UndetectableRelinking");
Assert.AreEqual(sky.CharacterCard, variantTiny);
PlayCard("ThorathianMonolith");
Assert.AreEqual(sky.CharacterCard, variantHuge);
// If Guise replaces her again, it should switch back to the old variant (without changing size)
var prop = PlayCard("Proportionist");
SelectCardsForNextDecision(sky.CharacterCard, guise.CharacterCard, legacy.CharacterCard, wraith.CharacterCard, unity.CharacterCard, baron.CharacterCard);
SelectFromBoxForNextDecision("SkyScraperHugeCharacter", "SkyScraper");
QuickHandStorage(sky);
UsePower(guise);
QuickHandCheckZero(); // Proportionist should not trigger
AssertAtLocation(skyHuge, sky.TurnTaker.PlayArea);
AssertAtLocation(variantHuge, guise.CharacterCard.UnderLocation);
Assert.AreEqual(skyHuge, sky.CharacterCard); // The old variant should have been switched back in
// SkyScraper should be able to switch sizes normally
ResetDecisions();
PlayCard("UndetectableRelinking");
Assert.AreEqual("SkyScraperTinyCharacter", sky.CharacterCard.PromoIdentifierOrIdentifier);
}
[Test]
public void TestSkyScraperVariant_CompletionistGuiseCharacter_Extremist()
{
var promos = new Dictionary<string, string>();
promos["Guise"] = "CompletionistGuiseCharacter";
SetupGameController(new string[] { "BaronBlade", "SkyScraper", "Guise", "Legacy", "TheWraith", "Unity", "Megalopolis" }, false, promos);
StartGame();
RemoveVillainCards();
var mono = PlayCard("ThorathianMonolith");
DestroyCard(mono);
// Examine the state of each of the size cards
// Old cards should be owned by Guise now
// New cards should be owned by SkyScraper
var skyHuge = sky.CharacterCard;
var skyNormal = GetCard("SkyScraperNormalCharacter");
var skyTiny = GetCard("SkyScraperTinyCharacter");
SelectCardsForNextDecision(sky.CharacterCard, guise.CharacterCard, legacy.CharacterCard, wraith.CharacterCard, unity.CharacterCard);
SelectFromBoxForNextDecision("Workshopping.CentristSkyScraperHugeCharacter", "SkyScraper");
UsePower(guise);
var variantHuge = sky.CharacterCard;
var variantNormal = sky.TurnTaker.OffToTheSide.Cards.Where(c => c.Identifier == "SkyScraperNormalCharacter").FirstOrDefault();
var variantTiny = sky.TurnTaker.OffToTheSide.Cards.Where(c => c.Identifier == "SkyScraperTinyCharacter").FirstOrDefault();
AssertAtLocation(skyHuge, guise.CharacterCard.UnderLocation);
AssertAtLocation(skyNormal, guise.TurnTaker.OffToTheSide);
AssertAtLocation(skyTiny, guise.TurnTaker.OffToTheSide);
Assert.AreEqual("Workshopping.CentristSkyScraperHugeCharacter", variantHuge.QualifiedPromoIdentifierOrIdentifier);
Assert.AreEqual("Workshopping.CentristSkyScraperNormalCharacter", variantNormal.QualifiedPromoIdentifierOrIdentifier);
Assert.AreEqual("Workshopping.CentristSkyScraperTinyCharacter", variantTiny.QualifiedPromoIdentifierOrIdentifier);
// Now switch to Extremist. Guise should have both regular and centrist huge under him.
SelectCardsForNextDecision(sky.CharacterCard, guise.CharacterCard, legacy.CharacterCard, wraith.CharacterCard, unity.CharacterCard, baron.CharacterCard);
SelectFromBoxForNextDecision("ExtremistSkyScraperHugeCharacter", "SkyScraper");
UsePower(guise);
AssertAtLocation(skyHuge, guise.CharacterCard.UnderLocation);
AssertAtLocation(variantHuge, guise.CharacterCard.UnderLocation);
var extremistHuge = sky.CharacterCard;
Assert.AreEqual("ExtremistSkyScraperHugeCharacter", extremistHuge.QualifiedPromoIdentifierOrIdentifier);
}
[Test]
public void TestSkyScraperVariant_CompletionistGuiseCharacter_Extremist2()
{
var promos = new Dictionary<string, string>();
promos["Guise"] = "CompletionistGuiseCharacter";
SetupGameController(new string[] { "BaronBlade", "SkyScraper", "Guise", "Legacy", "TheWraith", "Unity", "Megalopolis" }, false, promos);
StartGame();
RemoveVillainCards();
// Switch out normal sky-scraper.
// Examine the state of each of the size cards
// Old cards should be owned by Guise now
// New cards should be owned by SkyScraper
var skyNormal = sky.CharacterCard;
var skyHuge = GetCard("SkyScraperHugeCharacter");
var skyTiny = GetCard("SkyScraperTinyCharacter");
SelectCardsForNextDecision(sky.CharacterCard, guise.CharacterCard, legacy.CharacterCard, wraith.CharacterCard, unity.CharacterCard);
SelectFromBoxForNextDecision("Workshopping.CentristSkyScraperNormalCharacter", "SkyScraper");
UsePower(guise);
var variantNormal = sky.CharacterCard;
var variantHuge = sky.TurnTaker.OffToTheSide.Cards.Where(c => c.Identifier == "SkyScraperHugeCharacter").FirstOrDefault();
var variantTiny = sky.TurnTaker.OffToTheSide.Cards.Where(c => c.Identifier == "SkyScraperTinyCharacter").FirstOrDefault();
AssertAtLocation(skyHuge, guise.TurnTaker.OffToTheSide);
AssertAtLocation(skyNormal, guise.CharacterCard.UnderLocation);
AssertAtLocation(skyTiny, guise.TurnTaker.OffToTheSide);
Assert.AreEqual("Workshopping.CentristSkyScraperHugeCharacter", variantHuge.QualifiedPromoIdentifierOrIdentifier);
Assert.AreEqual("Workshopping.CentristSkyScraperNormalCharacter", variantNormal.QualifiedPromoIdentifierOrIdentifier);
Assert.AreEqual("Workshopping.CentristSkyScraperTinyCharacter", variantTiny.QualifiedPromoIdentifierOrIdentifier);
// Switch to variant huge.
PlayCard("ThorathianMonolith");
// Now switch to Extremist. Guise should have regular normal size and centrist huge size under him now.
SelectCardsForNextDecision(sky.CharacterCard, guise.CharacterCard, legacy.CharacterCard, wraith.CharacterCard, unity.CharacterCard, baron.CharacterCard);
SelectFromBoxForNextDecision("ExtremistSkyScraperHugeCharacter", "SkyScraper");
UsePower(guise);
AssertAtLocation(skyNormal, guise.CharacterCard.UnderLocation);
AssertAtLocation(variantHuge, guise.CharacterCard.UnderLocation);
var extremistHuge = sky.CharacterCard;
var extremistNormal = sky.TurnTaker.OffToTheSide.Cards.Where(c => c.Identifier == "SkyScraperNormalCharacter").FirstOrDefault();
var extremistTiny = sky.TurnTaker.OffToTheSide.Cards.Where(c => c.Identifier == "SkyScraperTinyCharacter").FirstOrDefault();
Assert.AreEqual("ExtremistSkyScraperHugeCharacter", extremistHuge.QualifiedPromoIdentifierOrIdentifier);
Assert.AreEqual("ExtremistSkyScraperNormalCharacter", extremistNormal.QualifiedPromoIdentifierOrIdentifier);
Assert.AreEqual("ExtremistSkyScraperTinyCharacter", extremistTiny.QualifiedPromoIdentifierOrIdentifier);
}
[Test()]
public void TestBaronBladeVariant()
{
SetupGameController("BaronBlade/Workshopping.BaronJeremyCharacter", "Legacy", "Workshopping.MigrantCoder", "Tachyon", "Megalopolis");
QuickHPStorage(baron, legacy, migrant, tachyon);
StartGame();
AssertNumberOfCardsInPlay("BladeBattalion", 4);
// H damage to all hero targets (plus nemesis bonus) at start of villain turn
QuickHPCheck(0, -4, -4, -3);
GoToEndOfTurn(baron);
// Next turn he flips because of no minions
DestroyCards(c => c.IsMinion);
GoToEndOfTurn(baron);
AssertFlipped(baron);
}
}
}
| 52.644013 | 165 | 0.681687 | [
"MIT"
] | Handelabra/WorkshopSample | MyModTest/VariantTest.cs | 16,269 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace Maydear.SFExpress
{
/// <summary>
/// 订单结果查询类型
/// </summary>
[Description("订单结果查询类型")]
public enum OrderSearchType
{
/// <summary>
/// 正常单据查询,,传入的orderid为正向定单号
/// </summary>
[Description("正常单据")]
Normal =1,
/// <summary>
/// 退货单查询,传入的orderid为退货原始订单号
/// </summary>
[Description("退货单据")]
Returned = 2,
}
}
| 19.37037 | 36 | 0.554493 | [
"Apache-2.0"
] | Maydear/Maydear-SFExpress | src/Maydear.SFExpress/OrderSearchType.cs | 633 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OSA.Data;
namespace OSA.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20200329132748_ChangeCompanyNameMaxLengthTo80")]
partial class ChangeCompanyNameMaxLengthTo80
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.2")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("OSA.Data.Models.ApplicationRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("OSA.Data.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("OSA.Data.Models.AvailableStock", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<decimal>("AveragePrice")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("BookValue")
.HasColumnType("decimal(18,2)");
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("StockName")
.IsRequired()
.HasColumnType("nvarchar(20)")
.HasMaxLength(20);
b.Property<decimal>("TotalPurchasedAmount")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalPurchasedPrice")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalSoldPrice")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.ToTable("AvailableStocks");
});
modelBuilder.Entity("OSA.Data.Models.BookValue", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<decimal>("Price")
.HasColumnType("decimal(18,2)");
b.Property<string>("StockName")
.IsRequired()
.HasColumnType("nvarchar(20)")
.HasMaxLength(20);
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.ToTable("BookValues");
});
modelBuilder.Entity("OSA.Data.Models.CashBook", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<decimal>("TotalInvoicePricesCost")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalProfit")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalSalaryCost")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalStockExternalCost")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.ToTable("CashBooks");
});
modelBuilder.Entity("OSA.Data.Models.Company", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Bulstat")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(80)")
.HasMaxLength(80);
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("UserId");
b.ToTable("Companies");
});
modelBuilder.Entity("OSA.Data.Models.ExpenseBook", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<decimal>("Profit")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalBookValue")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalExternalCost")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalSalaryCost")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalStockCost")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.ToTable("ExpenseBooks");
});
modelBuilder.Entity("OSA.Data.Models.Invoice", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("InvoiceNumber")
.IsRequired()
.HasColumnType("nvarchar(15)")
.HasMaxLength(15);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("SupplierId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.HasIndex("SupplierId");
b.ToTable("Invoices");
});
modelBuilder.Entity("OSA.Data.Models.ProductionInvoice", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<decimal>("ExternalCost")
.HasColumnType("decimal(18,2)");
b.Property<string>("InvoiceNumber")
.IsRequired()
.HasColumnType("nvarchar(15)")
.HasMaxLength(15);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<decimal>("StockCost")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.ToTable("ProductionInvoices");
});
modelBuilder.Entity("OSA.Data.Models.Purchase", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("StockName")
.IsRequired()
.HasColumnType("nvarchar(20)")
.HasMaxLength(20);
b.Property<decimal>("TotalPrice")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("TotalQuantity")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.ToTable("Purchases");
});
modelBuilder.Entity("OSA.Data.Models.Receipt", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("ReceiptNumber")
.IsRequired()
.HasColumnType("nvarchar(15)")
.HasMaxLength(15);
b.Property<decimal>("Salary")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.ToTable("Receipts");
});
modelBuilder.Entity("OSA.Data.Models.Sale", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("ProfitPercent")
.HasColumnType("int");
b.Property<string>("StockName")
.IsRequired()
.HasColumnType("nvarchar(20)")
.HasMaxLength(20);
b.Property<decimal>("TotalPrice")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.ToTable("Sales");
});
modelBuilder.Entity("OSA.Data.Models.Setting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Settings");
});
modelBuilder.Entity("OSA.Data.Models.Stock", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("InvoiceId")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(20)")
.HasMaxLength(20);
b.Property<decimal>("Price")
.HasColumnType("decimal(18,2)");
b.Property<decimal>("Quantity")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("InvoiceId");
b.HasIndex("IsDeleted");
b.ToTable("Stocks");
});
modelBuilder.Entity("OSA.Data.Models.Supplier", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Bulstat")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(80)")
.HasMaxLength(80);
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("IsDeleted");
b.ToTable("Suppliers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("OSA.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("OSA.Data.Models.ApplicationUser", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("OSA.Data.Models.ApplicationUser", null)
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("OSA.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("OSA.Data.Models.ApplicationUser", null)
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("OSA.Data.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.AvailableStock", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany()
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.BookValue", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany()
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.CashBook", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany()
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.Company", b =>
{
b.HasOne("OSA.Data.Models.ApplicationUser", "User")
.WithMany("Companies")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.ExpenseBook", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany()
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.Invoice", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany("Invoices")
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("OSA.Data.Models.Supplier", "Supplier")
.WithMany("Invoices")
.HasForeignKey("SupplierId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.ProductionInvoice", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany("ProductionInvoices")
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.Purchase", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany()
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.Receipt", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany("Receipts")
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.Sale", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany()
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.Stock", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany()
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("OSA.Data.Models.Invoice", "Invoice")
.WithMany("Stocks")
.HasForeignKey("InvoiceId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("OSA.Data.Models.Supplier", b =>
{
b.HasOne("OSA.Data.Models.Company", "Company")
.WithMany("Suppliers")
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.349349 | 125 | 0.438245 | [
"MIT"
] | krasizorbov/OSA | Data/OSA.Data/Migrations/20200329132748_ChangeCompanyNameMaxLengthTo80.Designer.cs | 36,315 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
namespace Azure.ResourceManager.Compute.Models
{
/// <summary> Capture Virtual Machine parameters. </summary>
public partial class VirtualMachineCaptureParameters
{
/// <summary> Initializes a new instance of VirtualMachineCaptureParameters. </summary>
/// <param name="vhdPrefix"> The captured virtual hard disk's name prefix. </param>
/// <param name="destinationContainerName"> The destination container name. </param>
/// <param name="overwriteVhds"> Specifies whether to overwrite the destination virtual hard disk, in case of conflict. </param>
/// <exception cref="ArgumentNullException"> <paramref name="vhdPrefix"/> or <paramref name="destinationContainerName"/> is null. </exception>
public VirtualMachineCaptureParameters(string vhdPrefix, string destinationContainerName, bool overwriteVhds)
{
if (vhdPrefix == null)
{
throw new ArgumentNullException(nameof(vhdPrefix));
}
if (destinationContainerName == null)
{
throw new ArgumentNullException(nameof(destinationContainerName));
}
VhdPrefix = vhdPrefix;
DestinationContainerName = destinationContainerName;
OverwriteVhds = overwriteVhds;
}
/// <summary> The captured virtual hard disk's name prefix. </summary>
public string VhdPrefix { get; }
/// <summary> The destination container name. </summary>
public string DestinationContainerName { get; }
/// <summary> Specifies whether to overwrite the destination virtual hard disk, in case of conflict. </summary>
public bool OverwriteVhds { get; }
}
}
| 43.090909 | 150 | 0.666667 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/VirtualMachineCaptureParameters.cs | 1,896 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.5485
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by xsd, Version=2.0.50727.3038.
//
namespace CprBroker.Schemas.Part {
using System.Xml.Serialization;
using CprBroker.Schemas;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("SchemaGeneration", "1.0.0.0")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://rep.oio.dk/bbr.dk/xml/schemas/2006/09/30/")]
[System.Xml.Serialization.XmlRootAttribute("AddressCoordinateQualityClassCode", Namespace="http://rep.oio.dk/bbr.dk/xml/schemas/2006/09/30/", IsNullable=false)]
public enum AddressCoordinateQualityClassCodeType {
/// <remarks/>
A,
/// <remarks/>
B,
/// <remarks/>
U,
}
} | 34.057143 | 164 | 0.557886 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | OS2CPRbroker/CPRbroker | PART/Source/Core/Schemas/OIOXSD/BBR_AddressCoordinateQualityClassCode.designer.cs | 1,192 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ConsoleGameEngine {
public static class Input {
public static InputKey esc = new InputKey(Key.Escape);
public static InputKey confirm = new InputKey(Key.Enter);
public static InputKey space = new InputKey(Key.Space);
public static InputKey tab = new InputKey(Key.Tab);
public static InputKey up = new InputKey(Key.Up, Key.W);
public static InputKey w = new InputKey(Key.W);
public static InputKey arrowUp = new InputKey(Key.Up);
public static InputKey down = new InputKey(Key.Down, Key.S);
public static InputKey s = new InputKey(Key.S);
public static InputKey arrowDown = new InputKey(Key.Down);
public static InputKey left = new InputKey(Key.Left, Key.A);
public static InputKey a = new InputKey(Key.A);
public static InputKey arrowLeft = new InputKey(Key.Left);
public static InputKey right = new InputKey(Key.Right, Key.D);
public static InputKey d = new InputKey(Key.D);
public static InputKey arrowRight = new InputKey(Key.Right);
public static InputKey q = new InputKey(Key.PageUp, Key.Q);
public static InputKey e = new InputKey(Key.PageDown, Key.E);
public static InputKey comma = new InputKey(Key.OemComma);
public static InputKey period = new InputKey(Key.OemPeriod);
public static InputKey r = new InputKey(Key.R);
public static InputKey p = new InputKey(Key.P);
public static InputKey y = new InputKey(Key.Y);
public static InputKey x = new InputKey(Key.X);
public static InputKey b = new InputKey(Key.B);
public static InputKey nLeft = new InputKey(Key.NumPad4);
public static InputKey nRight = new InputKey(Key.NumPad6);
public static InputKey nDown = new InputKey(Key.NumPad2);
public static InputKey nUp = new InputKey(Key.NumPad8);
public static InputKey[] allKeys = new InputKey[] {
esc,confirm,space,tab,up,w,arrowUp,down,s,arrowDown,left,a,arrowLeft,right,d,arrowRight,q,e,comma,period,r,nLeft,nRight,nDown,nUp,b
};
public static void Update() {
esc.Evaluate();
confirm.Evaluate();
space.Evaluate();
tab.Evaluate();
up.Evaluate();
w.Evaluate();
arrowUp.Evaluate();
down.Evaluate();
s.Evaluate();
arrowDown.Evaluate();
left.Evaluate();
a.Evaluate();
arrowLeft.Evaluate();
right.Evaluate();
d.Evaluate();
arrowRight.Evaluate();
q.Evaluate();
e.Evaluate();
comma.Evaluate();
period.Evaluate();
r.Evaluate();
p.Evaluate();
y.Evaluate();
x.Evaluate();
nLeft.Evaluate();
nRight.Evaluate();
nDown.Evaluate();
nUp.Evaluate();
b.Evaluate();
}
public static void CancelAll() {
foreach(var k in allKeys) {
k.isDown = false;
k.isUp = false;
k.isPressed = false;
}
}
public static bool AnyKeyDown() {
return KeysDown().Any();
}
static IEnumerable<Key> KeysDown() {
foreach (Key key in Enum.GetValues(typeof(Key))) {
if (key != Key.None && Keyboard.IsKeyDown(key))
yield return key;
}
}
}
}
| 31.295918 | 134 | 0.699381 | [
"MIT"
] | D3TONAT0R/Raytracer | Input.cs | 3,069 | C# |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using QueryBuilder.Contract;
using QueryBuilder.Entities;
using QueryBuilder.Extension.Queryable;
namespace QueryBuilder.Generator
{
internal class PgQuerySelectGenerator
{
private readonly PgQueryNode _node;
private readonly IPgQueryNameProvider _nameProvider;
private record SelectElement(string Sql, string As);
public PgQuerySelectGenerator(PgQueryNode node, IPgQueryNameProvider nameProvider)
{
_node = node ?? throw new ArgumentNullException(nameof(node));
_nameProvider = nameProvider ?? throw new ArgumentNullException(nameof(nameProvider));
}
public StringBuilder Execute()
{
var query = new StringBuilder("SELECT ");
var isDistinct = _node.Method == nameof(PgQueryableSelectExtension.SelectDistinct)
|| _node.Method == nameof(PgQueryableSelectExtension.SelectDistinctOn);
if (isDistinct)
{
query.Append("DISTINCT ");
}
if (_node.Expressions.Count == 2)
{
var distinctOnElements = Parse(_node.Expressions[1]);
query.Append($"ON ({string.Join(", ", distinctOnElements.Select(x => x.Sql))}) ");
}
var elements = Parse(_node.Expressions[0]);
query.Append(string.Join(", ", elements.Select(x => $"{x.Sql} AS \"{x.As}\"")));
query.Append(' ');
return query;
}
private SelectElement[] Parse(LambdaExpression expression)
{
return expression.Body switch
{
NewExpression newExpression => ParseNewExpression(newExpression),
ParameterExpression parameterExpression => ParseParameterExpression(parameterExpression),
MemberExpression memberExpression => ParseMemberExpression(memberExpression),
UnaryExpression unaryExpression => ParseUnaryExpression(unaryExpression),
_ => throw new NotImplementedException()
};
}
private SelectElement[] ParseUnaryExpression(UnaryExpression unaryExpression)
{
return ParseMemberExpression((unaryExpression.Operand as MemberExpression)!);
}
private SelectElement[] ParseMemberExpression(MemberExpression memberExpression)
{
var memberName = memberExpression.Member.Name;
var tableName = _nameProvider.GetTableName(memberExpression);
return new[] {new SelectElement($"{tableName}.\"{memberName}\"", memberName)};
}
private SelectElement[] ParseParameterExpression(ParameterExpression expression)
{
SelectElement[] selectElements;
var propertyInfos = expression.Type.GetProperties();
if (expression.Type.IsGenericType)
{
selectElements = propertyInfos
.Select(x => new {x.Name, Type = x.PropertyType})
.SelectMany(x => x.Type.GetProperties(),
(x, pi) => new
{
TableName = _nameProvider.GetTableName($"{expression}.{x.Name}"),
PropertyName = pi.Name
})
.Select(x => new SelectElement($"{x.TableName}.\"{x.PropertyName}\"", x.PropertyName))
.ToArray();
}
else
{
var tableName = _nameProvider.GetTableName(expression);
selectElements = propertyInfos
.Select(x => new SelectElement($"{tableName}.\"{x.Name}\"", x.Name))
.ToArray();
}
return selectElements;
}
private SelectElement[] ParseNewExpression(NewExpression expression)
{
var count = expression.Arguments.Count;
var selects = new SelectElement[count];
for (var i = 0; i < count; i++)
{
selects[i] = ParseNewExpressionArgument(expression.Arguments[i], expression.Members[i]);
}
return selects;
}
private SelectElement ParseNewExpressionArgument(Expression arg, MemberInfo member)
{
switch (arg)
{
case MemberExpression memberExpression:
var tableName = _nameProvider.GetTableName(memberExpression);
return new SelectElement($"{tableName}.\"{memberExpression.Member.Name}\"", member.Name);
case MethodCallExpression methodCallExpression:
var memExpression = (MemberExpression) methodCallExpression.Arguments[0];
var memberName = memExpression.Member.Name;
return new SelectElement(memberName, member.Name);
default:
throw new NotImplementedException();
}
}
}
} | 39.828125 | 109 | 0.580424 | [
"MIT"
] | Nemo-Illusionist/PostgresqlQueryBuilder | QueryBuilder/Generator/PgQuerySelectGenerator.cs | 5,098 | 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("cdmdotnet.Performance")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("cdmdotnet.Performance")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("169e7d9a-0db9-4346-88ea-612f80115ab8")]
// 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.216216 | 84 | 0.747525 | [
"MIT"
] | cdmdotnet/performance | cdmdotnet.Performance/Properties/AssemblyInfo.cs | 1,417 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Plannoy.Domain.Establishment
{
public class EstablishmentNotFoundException : Exception
{
public EstablishmentNotFoundException() : base("Establishment Not found")
{
}
}
}
| 20.428571 | 81 | 0.702797 | [
"MIT"
] | douglasramos/plannoy | src/Domain/Establishment/EstablishmentNotFoundException.cs | 288 | C# |
using System;
namespace AzerothWarsCSharp.MacroTools.Frames
{
public class FrameEventArgs : EventArgs
{
public Frame Frame { get; }
public FrameEventArgs(Frame frame)
{
Frame = frame;
}
}
} | 16 | 45 | 0.651786 | [
"MIT"
] | YakaryBovine/AzerothWarsCSharp | src/AzerothWarsCSharp.MacroTools/Frames/FrameEventArgs.cs | 226 | 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 fis-2020-12-01.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.FIS.Model
{
/// <summary>
/// This is the response object from the DeleteExperimentTemplate operation.
/// </summary>
public partial class DeleteExperimentTemplateResponse : AmazonWebServiceResponse
{
private ExperimentTemplate _experimentTemplate;
/// <summary>
/// Gets and sets the property ExperimentTemplate.
/// <para>
/// Information about the experiment template.
/// </para>
/// </summary>
public ExperimentTemplate ExperimentTemplate
{
get { return this._experimentTemplate; }
set { this._experimentTemplate = value; }
}
// Check to see if ExperimentTemplate property is set
internal bool IsSetExperimentTemplate()
{
return this._experimentTemplate != null;
}
}
} | 30.578947 | 101 | 0.679862 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/FIS/Generated/Model/DeleteExperimentTemplateResponse.cs | 1,743 | C# |
using System;
using System.Threading;
using GHIElectronics.TinyCLR.Devices.Gpio;
using Meadow.Peripherals.Sensors.Distance;
namespace Meadow.TinyCLR.Sensors.Distance
{
/// <summary>
/// HYSRF05 Distance Sensor
/// </summary>
public class Hysrf05 : IRangeFinder
{
#region Properties
/// <summary>
/// Returns current distance detected in cm.
/// </summary>
public float CurrentDistance { get; private set; } = -1;
/// <summary>
/// Minimum valid distance in cm (CurrentDistance returns -1 if below).
/// </summary>
public float MinimumDistance => 2;
/// <summary>
/// Maximum valid distance in cm (CurrentDistance returns -1 if above).
/// </summary>
public float MaximumDistance => 450;
/// <summary>
/// Raised when an received a rebound trigger signal
/// </summary>
public event DistanceEventHandler DistanceDetected;
#endregion
#region Member variables / fields
/// <summary>
/// Trigger Pin.
/// </summary>
protected GpioPin triggerPort;
/// <summary>
/// Echo Pin.
/// </summary>
protected GpioPin echoPort;
protected long tickStart;
#endregion
#region Constructors
/// <summary>
/// Create a new HYSRF05 object with a IO Device
/// HSSRF05 must be running the default 4/5 pin mode
/// 3 pin mode is not supported on Meadow
/// </summary>
/// <param name="triggerPin"></param>
/// <param name="echoPin"></param>
public Hysrf05(int triggerPin, int echoPin)
{
//this(device.CreateDigitalOutputPort(triggerPin, false),
// device.CreateDigitalInputPort(echoPin, InterruptMode.EdgeBoth))
var gpio = GpioController.GetDefault();
var trigger = gpio.OpenPin(triggerPin);
trigger.SetDriveMode(GpioPinDriveMode.Output);
trigger.Write(GpioPinValue.Low);
var echo = gpio.OpenPin(echoPin);
echo.SetDriveMode(GpioPinDriveMode.InputPullUp);
Setup(trigger, echo);
}
/// <summary>
/// Create a new HYSRF05 object and hook up the interrupt handler
/// HSSRF05 must be running the default 4/5 pin mode
/// 3 pin mode is not supported on Meadow
/// </summary>
/// <param name="triggerPort"></param>
/// <param name="echoPort"></param>
public Hysrf05(GpioPin triggerPort, GpioPin echoPort)
{
Setup(triggerPort, echoPort);
}
void Setup(GpioPin triggerPort, GpioPin echoPort)
{
this.triggerPort = triggerPort;
this.echoPort = echoPort;
this.echoPort.ValueChanged += EchoPort_ValueChanged;
}
private void EchoPort_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
{
if (echoPort.Read() == GpioPinValue.High) //echo is high
{
tickStart = DateTime.Now.Ticks;
return;
}
// Calculate Difference
float elapsed = DateTime.Now.Ticks - tickStart;
// Return elapsed ticks
// x10 for ticks to micro sec
// divide by 58 for cm (assume speed of sound is 340m/s)
CurrentDistance = elapsed / 580f;
if (CurrentDistance < MinimumDistance || CurrentDistance > MaximumDistance)
CurrentDistance = -1;
DistanceDetected?.Invoke(this, new DistanceEventArgs(CurrentDistance));
}
#endregion
/// <summary>
/// Sends a trigger signal
/// </summary>
public void MeasureDistance()
{
CurrentDistance = -1;
// Raise trigger port to high for 10+ micro-seconds
triggerPort.Write(GpioPinValue.High);// = true;
Thread.Sleep(1); //smallest amount of time we can wait
// Start Clock
tickStart = DateTime.Now.Ticks;
// Trigger device to measure distance via sonic pulse
triggerPort.Write(GpioPinValue.Low);// = false;
}
}
} | 30.741007 | 90 | 0.572432 | [
"Apache-2.0"
] | Gravicode/TinyCLR.Drivers | src/Sensors.Distance.HYSRF05/HYSRF05.cs | 4,273 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using routingdeal.Models;
namespace routingdeal.Business
{
public class RoutingDao
{
public string ConnectionString { get; set; }
private string AuxPathFileDb { get; set; }
public RoutingDao(string Connection, string auxPathFileDb)
{
ConnectionString = Connection;
AuxPathFileDb = auxPathFileDb;
}
private MySqlConnection Get()
{
return new MySqlConnection(ConnectionString);
}
public async Task<ResponseDeal> AddRoutingDeal(RequestDeal data)
{
var model = new Deal();
var result = new ResponseDeal();
try
{
var path = @AuxPathFileDb.Replace("wwwroot/", "");
var db = System.IO.File.ReadAllLines(path);
var id = 0;
foreach (var item in db)
{
var line = item.Split("|");
id = int.Parse(line[0]);
}
id += 1;
var insert = $"{id}|{data.Name}|{data.InvoiceKey}|true|{data.Url}|{data.Template}|{data.Type}|{data.RequestTemplate}|{data.NumRequest}";
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(insert);
}
model.Id = id;
model.Name = data.Name;
model.InvoiceKey = data.InvoiceKey;
model.State = true;
model.Url = data.Url;
model.Type = data.Type;
model.Template = data.Template;
model.RequestTemplate = data.RequestTemplate;
model.NumRequest = data.NumRequest;
result.Code = 200;
result.Data = model;
result.Message = "OK";
/*using (var conn = Get())
{
conn.Open();
var cmd = new MySqlCommand($"insert into tbl_deal (name, invoicekey, state, template, url) values('{data.Name}', '{data.InvoiceKey}',1, '{data.Template}', '{data.Url}')", conn);
var reader = cmd.ExecuteNonQuery();
result.Code = 200;
result.Data = new Deal()
{
Id = cmd.LastInsertedId,
Name = data.Name,
InvoiceKey = data.InvoiceKey,
State = true,
Template = data.Template,
Url = data.Url,
};
result.Message = "OK";
}*/
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.Message;
result.Data = null;
}
return await Task.Run(() => result);
}
public async Task<ResponseDeal> GetRoutingDeal(string invoicekey)
{
var model = new Deal();
var result = new ResponseDeal();
try
{
var db = System.IO.File.ReadAllLines(@AuxPathFileDb.Replace("wwwroot/", ""));
foreach (var item in db)
{
var line = item.Split("|");
if (line[2] == invoicekey)
{
model.Id = long.Parse(line[0]);
model.Name = line[1];
model.InvoiceKey = line[2];
model.State = bool.Parse(line[3]);
model.Url = line[4];
model.Template = line[5];
model.Type = line[6];
model.RequestTemplate = line[7];
model.NumRequest = int.Parse(line[8]);
break;
}
}
result.Code = 200;
result.Data = model;
result.Message = "OK";
/*using (var conn = Get())
{
conn.Open();
var cmd = new MySqlCommand($"select id, name, invoicekey, state, template, url, type, requesttemplate, numrequest from tbl_deal where invoicekey = '{invoicekey}'", conn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
model.Id = reader.GetInt64("id");
model.Name = reader.GetString("name");
model.InvoiceKey = reader.GetString("invoicekey");
model.State = reader.GetBoolean("state");
model.Template = reader.GetString("template");
model.Url = reader.GetString("url");
model.Type = reader.GetString("type");
model.RequestTemplate = reader.GetString("requesttemplate");
model.NumRequest = reader.GetInt32("numrequest");
}
}
result.Code = 200;
result.Data = model;
result.Message = "OK";
}*/
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.Message;
result.Data = null;
}
return await Task.Run(() => result);
}
public async Task<ResponseUpdate> UpdateRoutingDeal(RequestUpdate data)
{
var model = new Deal();
var result = new ResponseUpdate();
try
{
using (var conn = Get())
{
conn.Open();
var cmd = new MySqlCommand($"update tbl_deal set state={data.State}, url='{data.Url}', template='{data.Template}' where invoicekey = '{data.InvoiceKey}'", conn);
var reader = cmd.ExecuteNonQuery();
result.Code = 200;
result.Data = new UpdateDeal()
{
InvoiceKey = data.InvoiceKey,
State = true,
};
result.Message = "OK";
}
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.Message;
result.Data = null;
}
return await Task.Run(() => result);
}
}
} | 35.744792 | 197 | 0.430861 | [
"MIT"
] | Joac89/Microservicios | routingdeal/Business/RoutingDao.cs | 6,863 | C# |
// Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code - do not edit
using Google.Ads.GoogleAds.V1.Errors;
using System.Collections.Generic;
using Google.Protobuf.WellKnownTypes;
namespace Google.Ads.GoogleAds.V1.Services
{
public sealed partial class MutateCustomerNegativeCriteriaResponse
{
/// <summary>
/// Gets a GoogleAdsFailure instance that combines all the errors
/// from a failed API call.
/// </summary>
public GoogleAdsFailure PartialFailure
{
get
{
if (this.PartialFailureError == null)
{
return null;
}
GoogleAdsFailure retval = new GoogleAdsFailure();
foreach (Any any in this.PartialFailureError.Details)
{
GoogleAdsFailure failure = any.Unpack<GoogleAdsFailure>();
retval.Errors.AddRange(failure.Errors);
}
return retval;
}
}
}
}
| 34.361702 | 78 | 0.626006 | [
"Apache-2.0"
] | chrisdunelm/google-ads-dotnet | src/V1/Stubs/MutateCustomerNegativeCriteriaResponsePartialFailureSupport.cs | 1,615 | C# |
using System.ComponentModel.DataAnnotations;
namespace GigsApplication.Core.Models
{
public class Following
{
[Key]
public string FollowerId { get; set; }
[Key]
public string FolloweeId { get; set; }
public ApplicationUser Follower { get; set; }
public ApplicationUser Followee { get; set; }
}
} | 25.5 | 53 | 0.633053 | [
"Apache-2.0"
] | mohamedabotir/SongShare | GigsApplication/Core/Models/Following.cs | 359 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataQI.Dapper.FastCrud.Test.Repository.Products
{
[Table("PRODUCT")]
public class Product
{
[Key]
[Column("PRODUCT_ID")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column("ACTIVE")]
public bool Active { get; set; }
[Column("EAN")]
public string Ean { get; set; }
[Column("REFERENCE")]
public string Reference { get; set; }
[Column("NAME")]
public string Name { get; set; }
[Column("DEPARTMENT")]
public string Department { get; set; }
[Column("PRICE")]
public decimal Price { get; set; }
[Column("LIST_PRICE")]
public decimal ListPrice { get; set; }
[Column("KEYWORDS")]
public string Keywords { get; set; }
[Column("STOCK")]
public decimal Stock { get; set; }
[Column("DATE_REGISTER")]
public DateTime DateRegister { get; set; }
}
} | 24.733333 | 61 | 0.583109 | [
"MIT"
] | henrique-gouveia/DataQI.Dapper.FastCrud | test/DataQI.Dapper.FastCrud.Test/Repository/Products/Product.cs | 1,113 | C# |
using System;
using System.Net;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Interfaced;
using Akka.Interfaced.LogFilter;
using Akka.Interfaced.SlimServer;
using Common.Logging;
using Domain;
namespace GameServer
{
[Log]
[ResponsiveException(typeof(ResultException))]
public class UserLoginActor : InterfacedActor, IUserLogin
{
private readonly ILog _logger;
private readonly ClusterNodeContext _clusterContext;
private readonly ActorBoundChannelRef _channel;
public UserLoginActor(ClusterNodeContext clusterContext, ActorBoundChannelRef channel, EndPoint clientRemoteEndPoint)
{
_logger = LogManager.GetLogger($"UserLoginActor({clientRemoteEndPoint})");
_clusterContext = clusterContext;
_channel = channel;
}
async Task<Tuple<long, IUserInitiator>> IUserLogin.Login(string id, string password)
{
if (id == null)
throw new ResultException(ResultCodeType.ArgumentError, nameof(id));
if (password == null)
throw new ResultException(ResultCodeType.ArgumentError, nameof(password));
// verify crendential
var account = await Authenticator.AuthenticateAsync(id, password);
if (account == null)
throw new ResultException(ResultCodeType.LoginCredentialError);
// try to create user actor with user-id
var user = await _clusterContext.UserTable.WithTimeout(TimeSpan.FromSeconds(30)).GetOrCreate(account.UserId, null);
if (user.Actor == null)
throw new ResultException(ResultCodeType.InternalError);
if (user.Created == false)
throw new ResultException(ResultCodeType.LoginAlreadyLoginedError);
// bound actor to this channel or new channel on user gateway
IRequestTarget boundTarget;
try
{
boundTarget = await _channel.BindActorOrOpenChannel(
user.Actor, new TaggedType[] { typeof(IUserInitiator) },
ActorBindingFlags.OpenThenNotification | ActorBindingFlags.CloseThenStop | ActorBindingFlags.StopThenCloseChannel,
"UserGateway", null);
}
catch (Exception e)
{
_logger.Error($"BindActorOrOpenChannel error (UserId={account.UserId})", e);
user.Actor.Tell(InterfacedPoisonPill.Instance);
throw new ResultException(ResultCodeType.InternalError);
}
// once login done, stop this
Self.Tell(InterfacedPoisonPill.Instance);
return Tuple.Create(account.UserId, (IUserInitiator)boundTarget.Cast<UserInitiatorRef>());
}
}
}
| 40.028571 | 134 | 0.647395 | [
"MIT"
] | SaladLab/TicTacToe | src/GameServer/UserLoginActor.cs | 2,804 | 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 Microsoft.Diagnostics.Runtime;
using System;
using System.Runtime.InteropServices;
using Architecture = System.Runtime.InteropServices.Architecture;
namespace Microsoft.Diagnostics.DebugServices.Implementation
{
/// <summary>
/// ITarget implementation for the ClrMD IDataReader
/// </summary>
public class TargetFromDataReader : Target
{
private readonly IDataReader _dataReader;
/// <summary>
/// Create a target instance from IDataReader
/// </summary>
/// <param name="dataReader">IDataReader</param>
/// <param name="targetOS">target operating system</param>
/// <param name="host">the host instance</param>
/// <param name="id">target id</param>
/// <param name="dumpPath">path of dump for this target</param>
public TargetFromDataReader(IDataReader dataReader, OSPlatform targetOS, IHost host, int id, string dumpPath)
: base(host, id, dumpPath)
{
_dataReader = dataReader;
OperatingSystem = targetOS;
IsDump = true;
OnFlushEvent.Register(dataReader.FlushCachedData);
Architecture = dataReader.Architecture switch
{
Microsoft.Diagnostics.Runtime.Architecture.Amd64 => Architecture.X64,
Microsoft.Diagnostics.Runtime.Architecture.X86 => Architecture.X86,
Microsoft.Diagnostics.Runtime.Architecture.Arm => Architecture.Arm,
Microsoft.Diagnostics.Runtime.Architecture.Arm64 => Architecture.Arm64,
_ => throw new PlatformNotSupportedException($"{dataReader.Architecture}"),
};
if (dataReader.ProcessId != -1) {
ProcessId = (uint)dataReader.ProcessId;
}
// Add the thread, memory, and module services
ServiceProvider.AddServiceFactory<IThreadService>(() => new ThreadServiceFromDataReader(this, _dataReader));
ServiceProvider.AddServiceFactory<IModuleService>(() => new ModuleServiceFromDataReader(this, _dataReader));
ServiceProvider.AddServiceFactory<IMemoryService>(() => {
IMemoryService memoryService = new MemoryServiceFromDataReader(_dataReader);
if (IsDump && Host.HostType == HostType.DotnetDump)
{
memoryService = new ImageMappingMemoryService(this, memoryService);
}
return memoryService;
});
}
}
}
| 43.238095 | 120 | 0.642438 | [
"MIT"
] | JongHeonChoi/diagnostics | src/Microsoft.Diagnostics.DebugServices.Implementation/TargetFromDataReader.cs | 2,724 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Practices.ObjectBuilder2.Tests.Utility
{
internal class ActivatorCreationStrategy : BuilderStrategy
{
/// <summary>
/// Called during the chain of responsibility for a build operation. The
/// PreBuildUp method is called when the chain is being executed in the
/// forward direction.
/// </summary>
/// <param name="context">Context of the build operation.</param>
public override void PreBuildUp(IBuilderContext context)
{
if (context.Existing == null)
{
context.Existing = Activator.CreateInstance(context.BuildKey.Type);
}
}
}
}
| 33.846154 | 122 | 0.654545 | [
"Apache-2.0",
"MIT"
] | drcarver/unity | source/Unity/Tests/ObjectBuilder/Utility/ActivatorCreationStrategy.cs | 882 | C# |
using MutantCommon;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace TestComponents
{
public abstract class TestRunner : ITestRunner
{
public string ToolName = "";
public int testCaseCount = 0;
public abstract bool RunExternalTestToolForSolution(string inputFile, string outputFile, ISet<Unittest> tests);
public abstract Task<bool> RunExternalTestToolForSolutionAsync(string inputFile, string outputFile, ISet<Unittest> tests);
public abstract TestResult ProcessResultFile(string fileName);
public TestResult TestSolution(string inputFile, string outputFile, ISet<Unittest> tests)
{
RunExternalTestToolForSolution(inputFile, outputFile, tests);
return ProcessResultFile(outputFile);
}
public async Task<TestResult> TestSolutionAsync(string inputFile, string outputFile, ISet<Unittest> tests)
{
await RunExternalTestToolForSolutionAsync(inputFile, outputFile, tests);
return ProcessResultFile(outputFile);
}
}
}
| 39.178571 | 130 | 0.713765 | [
"MIT"
] | mstewart1972/MutationTestingWithDeepParallelReinforcementLearning | TestComponents/TestRunner.cs | 1,099 | C# |
using ags_client.Resources.GeometryService;
using ags_client.Types.Geometry;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ags_client.Requests.GeometryService
{
public class BufferRequest<TG> : BaseRequest
where TG : IRestGeometry
{
public Geometries<TG> geometries { get; set; }
public SpatialReference inSR { get; set; }
public SpatialReference outSR { get; set; }
public SpatialReference bufferSR { get; set; }
public List<double> distances { get; set; }
public int? unit { get; set; } /* See esriSRUnitType Constants and esriSRUnit2Type Constants */
public bool? unionResults { get; set; }
public bool? geodesic { get; set; }
const string resource = "buffer";
public BufferResource<Polygon> Execute(AgsClient client, GeometryServiceResource parent)
{
string resourcePath = $"{parent.resourcePath}/{resource}";
return (BufferResource<Polygon>)Execute(client, resourcePath);
}
public async Task<BufferResource<Polygon>> ExecuteAsync(AgsClient client, GeometryServiceResource parent)
{
string resourcePath = $"{parent.resourcePath}/{resource}";
var request = createRequest(resourcePath);
return await client.ExecuteAsync<BufferResource<Polygon>>(request, Method.POST);
}
public override BaseResponse Execute(AgsClient client, string resourcePath)
{
var request = createRequest(resourcePath);
return client.Execute<BufferResource<Polygon>>(request, Method.POST);
}
private RestRequest createRequest(string resourcePath)
{
var request = new RestRequest(resourcePath) { Method = Method.POST };
var jss = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
if (geometries != null)
request.AddParameter("geometries", JsonConvert.SerializeObject(geometries, jss));
if (inSR != null)
request.AddParameter("inSR", inSR.wkid);
if (outSR != null)
request.AddParameter("outSR", outSR.wkid);
if (bufferSR != null)
request.AddParameter("bufferSR", bufferSR.wkid);
if ((distances != null) && (distances.Count > 0))
request.AddParameter("distances", String.Join(",", distances));
if (unit.HasValue)
request.AddParameter("unit", unit);
if (unionResults.HasValue)
request.AddParameter("unionResults", unionResults.Value ? "true" : "false");
if (geodesic.HasValue)
request.AddParameter("geodesic", geodesic.Value ? "true" : "false");
request.AddParameter("f", "json");
return request;
}
}
}
| 39.689189 | 113 | 0.627852 | [
"MIT"
] | nef001/ags-client | ags-client/Requests/GeometryService/BufferRequest.cs | 2,939 | C# |
using Windows.Storage;
namespace BleLab.Utils.Keeper
{
public class AppContainerKeeperStorage : IKeeperStorage
{
private readonly ApplicationDataContainer _container;
public AppContainerKeeperStorage(ApplicationDataContainer container = null)
{
if (container == null)
container = ApplicationData.Current.LocalSettings;
_container = container;
}
public virtual bool HasKey(string key)
{
return _container.Values.ContainsKey(key);
}
public virtual object GetValue(string key)
{
return _container.Values[key];
}
public virtual void SetValue(string key, object value)
{
_container.Values[key] = value;
}
}
} | 25.0625 | 83 | 0.608479 | [
"MIT"
] | GlennRice83/BleLab | BleLab/Utils/Keeper/AppContainerKeeperStorage.cs | 804 | C# |
using System.Web;
using System.Web.Mvc;
namespace CoachLancer.Web
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 20.071429 | 81 | 0.626335 | [
"MIT"
] | ikonomov17/CoachLancer | CoachLancer/CoachLancer.Web/App_Start/FilterConfig.cs | 283 | C# |
using System;
using System.IO;
namespace AssetsTools.NET
{
public class BundleReplacerFromStream : BundleReplacer
{
private readonly string oldName;
private readonly string newName;
private readonly bool hasSerializedData;
private readonly Stream stream;
private readonly long offset;
private readonly long size;
private readonly int bundleListIndex;
public BundleReplacerFromStream(string oldName, string newName, bool hasSerializedData, Stream stream, long offset, long size, int bundleListIndex = -1)
{
this.oldName = oldName;
if (newName == null)
this.newName = oldName;
else
this.newName = newName;
this.hasSerializedData = hasSerializedData;
this.stream = stream;
this.offset = offset;
if (size == -1)
this.size = stream.Length;
else
this.size = size;
this.bundleListIndex = bundleListIndex;
}
public override BundleReplacementType GetReplacementType()
{
return BundleReplacementType.AddOrModify;
}
public override int GetBundleListIndex()
{
return bundleListIndex;
}
public override string GetOriginalEntryName()
{
return oldName;
}
public override string GetEntryName()
{
return newName;
}
public override long GetSize()
{
return size;
}
public override bool Init(AssetsFileReader entryReader, long entryPos, long entrySize, ClassDatabaseFile typeMeta = null)
{
return true;
}
public override void Uninit()
{
return;
}
public override long Write(AssetsFileWriter writer)
{
byte[] assetData = new byte[size];
stream.Read(assetData, (int)offset, (int)size);
writer.Write(assetData);
return writer.Position;
}
public override long WriteReplacer(AssetsFileWriter writer)
{
writer.Write((short)2); //replacer type
writer.Write((byte)0); //file type (0 bundle, 1 assets)
writer.WriteCountStringInt16(oldName);
writer.WriteCountStringInt16(newName);
writer.Write(hasSerializedData);
writer.Write(GetSize());
Write(writer);
return writer.Position;
}
public override bool HasSerializedData()
{
return hasSerializedData;
}
}
}
| 31.447059 | 160 | 0.572391 | [
"Unlicense"
] | DigitalzombieTLD/AudioCore | AssetTools/Standard/BundleReplacer/BundleReplacerFromStream.cs | 2,675 | C# |
using System;
using VDS.RDF;
using VDS.RDF.Parsing;
using VDS.RDF.Query;
namespace NetRdf
{
class Program
{
static void Main(string[] args)
{
// For simple queries:
//First we need an instance of the SparqlQueryParser
SparqlQueryParser parser = new SparqlQueryParser();
//For complex queries
//Create a Parameterized String
SparqlParameterizedString queryString = new SparqlParameterizedString();
//Add a namespace declaration
queryString.Namespaces.AddNamespace("ex", new Uri("http://www.w3.org/ns/dcat#"));
//Set the SPARQL command
//For more complex queries we can do this in multiple lines by using += on the
//CommandText property
//Note we can use @name style parameters here
queryString.CommandText = "SELECT * WHERE { ?s ex:property @value }";
//Inject a Value for the parameter
queryString.SetUri("value", new Uri("http://example.org/value"));
//When we call ToString() we get the full command text with namespaces appended as PREFIX
//declarations and any parameters replaced with their declared values
Console.WriteLine(queryString.ToString());
//We can turn this into a query by parsing it as in our previous example
SparqlQueryParser p = new SparqlQueryParser();
SparqlQuery query = p.ParseFromString(queryString);
IGraph g = new Graph();
g.LoadFromFile("dcat-ap_2.0.1.rdf");
foreach (Triple t in g.Triples)
{
Console.WriteLine(string.Concat("PREDICATE: ", t.Predicate));
Console.WriteLine(string.Concat("SUBJECT: ", t.Subject));
Console.WriteLine(string.Concat("OBJECT: ", t.Object));
}
TurtleParser turtleParser = new TurtleParser();
Graph graph = new Graph();
graph.LoadFromFile("dcat-ap_2.0.1.rdf");
var ds = graph.GetUriNode("dct:title");
}
}
}
| 32.227273 | 101 | 0.595675 | [
"Apache-2.0"
] | alireza1111/XmlSchemaClassGenerator | NetRdf/Program.cs | 2,129 | C# |
using GenshinPray.Exceptions;
using GenshinPray.Service;
using GenshinPray.Service.PrayService;
namespace GenshinPray.Controllers.Api
{
public abstract class BasePrayController<T> : BaseController where T : BasePrayService, new()
{
protected T basePrayService;
protected AuthorizeService authorizeService;
protected MemberService memberService;
protected GoodsService goodsService;
protected PrayRecordService prayRecordService;
protected MemberGoodsService memberGoodsService;
public BasePrayController()
{
this.basePrayService = new T();
this.authorizeService = new AuthorizeService();
this.memberService = new MemberService();
this.goodsService = new GoodsService();
this.prayRecordService = new PrayRecordService();
this.memberGoodsService = new MemberGoodsService();
}
protected string GetAuthCode()
{
return HttpContext.Request.Headers["authorzation"];
}
protected void CheckImgWidth(int imgWidth)
{
if (imgWidth < 0 || imgWidth > 1920) throw new ParamException("图片宽度只能设定在0~1920之间");
}
}
}
| 30.975 | 97 | 0.658596 | [
"MIT"
] | baimianxiao/GenshinPray | GenshinPray/Controllers/Api/BasePrayController.cs | 1,263 | C# |
// Copyright (c) 2020 Yann Crumeyrolle. All rights reserved.
// Licensed under the MIT license. See LICENSE in the project root for license information.
namespace JsonWebToken
{
/// <summary>Defines an encrypted JWT with a <see cref="JwsDescriptor"/> payload.</summary>
public sealed partial class JweDescriptor : JweDescriptorBase<JwsDescriptor>
{
private JwsDescriptor? _payload;
/// <summary>Initializes a new instance of the <see cref="JweDescriptor"/> class.</summary>
public JweDescriptor(Jwk encryptionKey, KeyManagementAlgorithm alg, EncryptionAlgorithm enc, CompressionAlgorithm? zip = null, string? typ = null, string? cty = Constants.Jwt)
: base(encryptionKey, alg, enc, zip, typ, cty)
{
}
/// <inheritdoc/>
public override JwsDescriptor Payload
{
get
{
if (_payload is null)
{
ThrowHelper.ThrowInvalidOperationException_NotInitialized(ExceptionArgument.payload);
}
return _payload;
}
set
{
if (value is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
_payload = value;
}
}
/// <inheritdoc/>
public override void Validate()
{
if (_payload is not null)
{
_payload.Validate();
}
}
}
}
| 30.45098 | 183 | 0.553767 | [
"MIT"
] | uruk-project/Jwt | src/JsonWebToken/Writer/JweDescriptor.cs | 1,555 | C# |
using System;
using System.Net.Http;
using BTCPayServer.AtomicSwaps;
namespace BTCPayServer.Services
{
public class AtomicSwapClientFactory
{
public AtomicSwapClientFactory(IHttpClientFactory httpClientFactory)
{
HttpClientFactory = httpClientFactory;
}
public IHttpClientFactory HttpClientFactory { get; }
public AtomicSwapClient Create(Uri serverUri)
{
var client = new AtomicSwapClient(serverUri);
client.SetClient(HttpClientFactory.CreateClient());
return client;
}
}
}
| 24.75 | 76 | 0.664983 | [
"MIT"
] | queilawithaQ/btcpayserver | BTCPayServer/Services/AtomicSwapClientFactory.cs | 596 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.