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 (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.CloudMine.Core.Collectors.Authentication;
using System.Net.Http;
using System.Threading.Tasks;
namespace Microsoft.CloudMine.Core.Collectors.Web
{
public interface IRateLimiter
{
Task UpdateRetryAfterAsync(string identity, string requestUrl, HttpResponseMessage response);
Task UpdateStatsAsync(string identity, string requestUrl, HttpResponseMessage response);
Task WaitIfNeededAsync(IAuthentication authentication);
}
}
| 32.470588 | 101 | 0.778986 | [
"MIT"
] | dorfire/CEDAR.Core.Collector | Core.Collectors/Web/IRateLimiter.cs | 554 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ufiles.Models;
namespace ufiles.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 24.947368 | 113 | 0.611814 | [
"MIT"
] | larryw3i/ufiles | ufiles/Controllers/HomeController.cs | 950 | C# |
using addon365.FindMatch360.Models.Masters;
using addon365.FindMatch360.Models.MatrimonyProfileModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace addon365.FindMatch360.ViewModels
{
public class ProfileViewModel
{
public Guid MatrimonyProfileId { get; set; }
#region Person basic Details
public String Name { get; set; }
//https://www.youtube.com/watch?v=QpJvqiHl1Fo
public byte Gender { get; set; }
public DateTime DateandTimeOfBirth { get; set; }
public string? MaritalStatusMasterId { get; set; }
public IEnumerable<MaritalStatusMaster> MaritalStatusMasters { get; set; }
public byte BodyType { get; set; }
public string Weight { get; set; }
public string Height { get; set; }
public string SkinColor { get; set; }
public Boolean AnyDisability { get; set; }
public string DisabilityDescription { get; set; }
#endregion
#region Life style
public byte EatingHabit { get; set; }
public byte Drinking { get; set; }
public byte Smoking { get; set; }
#endregion
#region Education Details
public string HigherEducationsId { get; set; }
public IEnumerable<EducationMaster> Educations { get; set; }
#endregion
#region JobDetails
public string EmployeedInMasterId { get; set; }
public IEnumerable<EmployeedInMaster> EmployeedInLst { get; set; }
public string OccupationMasterId { get; set; }
public IEnumerable<OccupationMaster> Occupations { get; set; }
public string WorkingAddress { get; set; }
public string MonthlyRevenue { get; set; }
#endregion
#region ReligionDetails
public string ReligionMasterId { get; set; }
public IEnumerable<ReligionMaster> Religions { get; set; }
public string MotherTongueMasterId { get; set; }
public IEnumerable<MotherTongueMaster> MotherTongues { get; set; }
public string CasteMasterId { get; set; }
public IEnumerable<CasteMaster> Castes { get; set; }
public string SubCasteMasterId { get; set; }
public IEnumerable<SubCasteMaster> SubCastes { get; set; }
public string GothramMasterId { get; set; }
public IEnumerable<GothramMaster> Gothrams { get; set; }
#endregion
#region Horoscope Details
public string Star { get; set; }
public string Rasi { get; set; }
public string Lagnam { get; set; }
public string TimeofBirth { get; set; }
public string PlaceOfBirth { get; set; }
#endregion
#region Family Information
public string FamilyStatusMasterId { get; set; }
public IEnumerable<FamilyStatusMaster> FamilyStatuses { get; set; }
public string FamilyTypeMasterId { get; set; }
public IEnumerable<FamilyTypeMaster> FamilyTypes { get; set; }
public string FamilyValuesMasterId { get; set; }
public IEnumerable<FamilyValuesMaster> FamilyValues { get; set; }
public string FatherName { get; set; }
public string FatherQualification { get; set; }
public string FatherJob { get; set; }
public string MotherName { get; set; }
public string MotherQualification { get; set; }
public string MotherJob { get; set; }
public string NativeDistrict { get; set; }
public string ContactPerson { get; set; }
public string Address { get; set; }
public string PhoneNo { get; set; }
public string MobileNo { get; set; }
public string EmailId { get; set; }
public short BirthNumberinFamily { get; set; }
public short Brothers { get; set; }
public short MarriedBrothers { get; set; }
public short Sisters { get; set; }
public short MarriedSisters { get; set; }
#endregion
#region Preferences
public byte FromAge { get; set; }
public byte UptoAge { get; set; }
#endregion
#region Login
public string LoginEMailId { get; set; }
#endregion
}
}
| 35.923729 | 82 | 0.631989 | [
"Apache-2.0"
] | addon365/FindMatch360 | Src/Web/addon365.FindMatch360 - Copy/ViewModels/ProfileViewModel.cs | 4,241 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Square.Http.Client;
using Square;
using Square.Utilities;
namespace Square.Models
{
public class SearchSubscriptionsResponse
{
public SearchSubscriptionsResponse(IList<Models.Error> errors = null,
IList<Models.Subscription> subscriptions = null,
string cursor = null)
{
Errors = errors;
Subscriptions = subscriptions;
Cursor = cursor;
}
[JsonIgnore]
public HttpContext Context { get; internal set; }
/// <summary>
/// Information about errors encountered during the request.
/// </summary>
[JsonProperty("errors", NullValueHandling = NullValueHandling.Ignore)]
public IList<Models.Error> Errors { get; }
/// <summary>
/// The search result.
/// </summary>
[JsonProperty("subscriptions", NullValueHandling = NullValueHandling.Ignore)]
public IList<Models.Subscription> Subscriptions { get; }
/// <summary>
/// When a response is truncated, it includes a cursor that you can
/// use in a subsequent request to fetch the next set of subscriptions.
/// If empty, this is the final response.
/// For more information, see [Pagination](https://developer.squareup.com/docs/working-with-apis/pagination).
/// </summary>
[JsonProperty("cursor", NullValueHandling = NullValueHandling.Ignore)]
public string Cursor { get; }
public override string ToString()
{
var toStringOutput = new List<string>();
this.ToString(toStringOutput);
return $"SearchSubscriptionsResponse : ({string.Join(", ", toStringOutput)})";
}
protected void ToString(List<string> toStringOutput)
{
toStringOutput.Add($"Errors = {(Errors == null ? "null" : $"[{ string.Join(", ", Errors)} ]")}");
toStringOutput.Add($"Subscriptions = {(Subscriptions == null ? "null" : $"[{ string.Join(", ", Subscriptions)} ]")}");
toStringOutput.Add($"Cursor = {(Cursor == null ? "null" : Cursor == string.Empty ? "" : Cursor)}");
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (obj == this)
{
return true;
}
return obj is SearchSubscriptionsResponse other &&
((Context == null && other.Context == null) || (Context?.Equals(other.Context) == true)) &&
((Errors == null && other.Errors == null) || (Errors?.Equals(other.Errors) == true)) &&
((Subscriptions == null && other.Subscriptions == null) || (Subscriptions?.Equals(other.Subscriptions) == true)) &&
((Cursor == null && other.Cursor == null) || (Cursor?.Equals(other.Cursor) == true));
}
public override int GetHashCode()
{
int hashCode = 1428079910;
if (Context != null)
{
hashCode += Context.GetHashCode();
}
if (Errors != null)
{
hashCode += Errors.GetHashCode();
}
if (Subscriptions != null)
{
hashCode += Subscriptions.GetHashCode();
}
if (Cursor != null)
{
hashCode += Cursor.GetHashCode();
}
return hashCode;
}
public Builder ToBuilder()
{
var builder = new Builder()
.Errors(Errors)
.Subscriptions(Subscriptions)
.Cursor(Cursor);
return builder;
}
public class Builder
{
private IList<Models.Error> errors;
private IList<Models.Subscription> subscriptions;
private string cursor;
public Builder Errors(IList<Models.Error> errors)
{
this.errors = errors;
return this;
}
public Builder Subscriptions(IList<Models.Subscription> subscriptions)
{
this.subscriptions = subscriptions;
return this;
}
public Builder Cursor(string cursor)
{
this.cursor = cursor;
return this;
}
public SearchSubscriptionsResponse Build()
{
return new SearchSubscriptionsResponse(errors,
subscriptions,
cursor);
}
}
}
} | 32.038217 | 132 | 0.517495 | [
"Apache-2.0"
] | HostMeApp/square-dotnet-sdk | Square/Models/SearchSubscriptionsResponse.cs | 5,030 | C# |
namespace School.Data.Repositories
{
using School.Models;
public interface ISubjectRepository : IDeletableEntityRepository<Subject>
{
}
}
| 18.222222 | 78 | 0.695122 | [
"MIT"
] | encounter12/AspNet-Mvc-School | School/School.Data/Repositories/ISubjectRepository.cs | 166 | C# |
using System.Reflection;
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("AWSSDK.IoTJobsDataPlane")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS IoT Jobs Data Plane. This release adds support for new the service called Iot Jobs. This client is built for the device SDK to use Iot Jobs Device specific APIs.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2018 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.0.4")] | 47.625 | 245 | 0.75 | [
"Apache-2.0"
] | awesomeunleashed/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/IoTJobsDataPlane/Properties/AssemblyInfo.cs | 1,524 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace org.zugferd.reader.ui
{
/// <summary>
/// Interaktionslogik für "App.xaml"
/// </summary>
public partial class App : Application
{
}
}
| 18.722222 | 42 | 0.703264 | [
"Apache-2.0"
] | mygit-steffen/ZUGFeRD-Reader | org.zugferd.reader.ui/App.xaml.cs | 340 | 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("RandomiseWordList")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("RandomiseWordList")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[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("9ef69a78-41eb-4833-99e2-9e1b22d42498")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.486486 | 85 | 0.731691 | [
"Apache-2.0"
] | 4-FLOSS-Free-Libre-Open-Source-Software/readablepassphrasegenerator | trunk/RandomiseWordList/Properties/AssemblyInfo.cs | 1,464 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Runtime.InteropServices.UnknownWrapper.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Runtime.InteropServices
{
sealed public partial class UnknownWrapper
{
#region Methods and constructors
public UnknownWrapper(Object obj)
{
}
#endregion
#region Properties and indexers
public Object WrappedObject
{
get
{
return default(Object);
}
}
#endregion
}
}
| 39.116667 | 463 | 0.758841 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/MsCorlib/Sources/System.Runtime.InteropServices.UnknownWrapper.cs | 2,347 | C# |
using Classifiers;
using System.Collections.Generic;
namespace SnaffCore.Config
{
public partial class Options
{
private void BuildFileContentRules()
{
/*
// TEST RULE for doc parsing
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be parsed as part of a test.",
RuleName = "DocParseTest",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepDocRegexGreen",
WordList = new List<string>()
{
".doc",".docx",".xls",".xlsx",".eml",".msg",".pdf",".ppt",".rtf"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are kind of interesting for purposes of this test.",
RuleName = "KeepDocRegexGreen",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Green,
WordList = new List<string>()
{
"password",
"prepared",
"security"
}
});
*/
// Python
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for python related strings.",
RuleName = "PyContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepPyRegexRed",
WordList = new List<string>()
{
// python
"\\.py"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepPyRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
// python
"mysql\\.connector\\.connect\\(", //python
"psycopg2\\.connect\\(", // python postgres
// generic tokens etc, same for most languages.
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"CREATE (USER|LOGIN) .{0,200} (IDENTIFIED BY|WITH PASSWORD)", // sql creds
"(xox[pboa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})", //Slack Token
"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}", //Slack Webhook
"aws[_\\-\\.]?key", // aws mnagic
"[_\\-\\.]?api[_\\-\\.]?key", // stuff
"[_\\-\\.]oauth\\s*=", // oauth stuff
"client_secret", // fun
"secret[_\\-\\.]?(key)?\\s*=",
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----",
"(\\s|\\\'|\\\"|\\^|=)(A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}(\\s|\\\'|\\\"|$)", // aws access key
}
});
// PHP
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for php related strings.",
RuleName = "phpContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepPhpRegexRed",
WordList = new List<string>()
{
// php
"\\.php",
"\\.phtml",
"\\.inc",
"\\.php3",
"\\.php5",
"\\.php7"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepPhpRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
// php
"mysql_connect\\s*\\(.*\\$.*\\)", // php
"mysql_pconnect\\s*\\(.*\\$.*\\)", // php
"mysql_change_user\\s*\\(.*\\$.*\\)", // php
"pg_connect\\s*\\(.*\\$.*\\)", // php
"pg_pconnect\\s*\\(.*\\$.*\\)", // php
// generic tokens etc, same for most languages.
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"CREATE (USER|LOGIN) .{0,200} (IDENTIFIED BY|WITH PASSWORD)", // sql creds
"(xox[pboa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})", //Slack Token
"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}", //Slack Webhook
"aws[_\\-\\.]?key", // aws mnagic
"[_\\-\\.]?api[_\\-\\.]?key", // stuff
"[_\\-\\.]oauth\\s*=", // oauth stuff
"client_secret", // fun
"secret[_\\-\\.]?(key)?\\s*=",
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----",
"(\\s|\\\'|\\\"|\\^|=)(A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}(\\s|\\\'|\\\"|$)", // aws access key
}
});
// CSharp
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for CSharp and ASP.NET related strings.",
RuleName = "csContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepCsRegexRed",
WordList = new List<string>()
{
// asp.net
"\\.aspx",
"\\.ashx",
"\\.asmx",
"\\.asp",
"\\.cshtml",
"\\.cs",
"\\.ascx"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepCsRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
// csharp
"connectionstring.{1,200}passw",
"validationkey\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"decryptionkey\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"CREATE (USER|LOGIN) .{0,200} (IDENTIFIED BY|WITH PASSWORD)", // sql creds
"(xox[pboa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})", //Slack Token
"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}", //Slack Webhook
"aws[_\\-\\.]?key", // aws mnagic
"[_\\-\\.]?api[_\\-\\.]?key", // stuff
"[_\\-\\.]oauth\\s*=", // oauth stuff
"client_secret", // fun
"secret[_\\-\\.]?(key)?\\s*=",
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----",
"(\\s|\\\'|\\\"|\\^|=)(A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}(\\s|\\\'|\\\"|$)", // aws access key
}
});
//Java
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for Java and ColdFusion related strings.",
RuleName = "javaContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepJavaRegexRed",
WordList = new List<string>()
{
// java
"\\.jsp",
"\\.do",
"\\.java",
// coldfusion
"\\.cfm",
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepJavaRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
// java
"\\.getConnection\\(\\\"jdbc\\:",
// generic tokens etc, same for most languages.
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"CREATE (USER|LOGIN) .{0,200} (IDENTIFIED BY|WITH PASSWORD)", // sql creds
"(xox[pboa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})", //Slack Token
"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}", //Slack Webhook
"aws[_\\-\\.]?key", // aws mnagic
"[_\\-\\.]?api[_\\-\\.]?key", // stuff
"[_\\-\\.]oauth\\s*=", // oauth stuff
"client_secret", // fun
"secret[_\\-\\.]?(key)?\\s*=",
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----",
"(\\s|\\\'|\\\"|\\^|=)(A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}(\\s|\\\'|\\\"|$)", // aws access key
}
});
// Ruby
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for Rubby related strings.",
RuleName = "rubyContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepRubyRegexRed",
WordList = new List<string>()
{
// ruby
"\\.rb"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepRubyRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
// ruby
"DBI\\.connect\\(",
// generic tokens etc, same for most languages.
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"CREATE (USER|LOGIN) .{0,200} (IDENTIFIED BY|WITH PASSWORD)", // sql creds
"(xox[pboa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})", //Slack Token
"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}", //Slack Webhook
"aws[_\\-\\.]?key", // aws mnagic
"[_\\-\\.]?api[_\\-\\.]?key", // stuff
"[_\\-\\.]oauth\\s*=", // oauth stuff
"client_secret", // fun
"secret[_\\-\\.]?(key)?\\s*=",
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----",
"(\\s|\\\'|\\\"|\\^|=)(A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}(\\s|\\\'|\\\"|$)", // aws access key
}
});
// Perl
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for Perl related strings.",
RuleName = "perlContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepPerlRegexRed",
WordList = new List<string>()
{
// perl
"\\.pl"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepPerlRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
// perl
"DBI\\-\\>connect\\(",
// generic tokens etc, same for most languages.
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"CREATE (USER|LOGIN) .{0,200} (IDENTIFIED BY|WITH PASSWORD)", // sql creds
"(xox[pboa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})", //Slack Token
"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}", //Slack Webhook
"aws[_\\-\\.]?key", // aws mnagic
"[_\\-\\.]?api[_\\-\\.]?key", // stuff
"[_\\-\\.]oauth\\s*=", // oauth stuff
"client_secret", // fun
"secret[_\\-\\.]?(key)?\\s*=",
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----",
"(\\s|\\\'|\\\"|\\^|=)(A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}(\\s|\\\'|\\\"|$)", // aws access key
}
});
// PowerShell
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for PowerShell related strings.",
RuleName = "psContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepPsRegexRed",
WordList = new List<string>()
{
// powershell
"\\.psd1",
"\\.psm1",
"\\.ps1",
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepPsRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
// PS
"net user ",
"psexec .{0,100} -p ",
"net use .{0,300} /user:",
"-SecureString",
"-AsPlainText",
"\\[Net.NetworkCredential\\]::new\\(",
// generic tokens etc, same for most languages.
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"CREATE (USER|LOGIN) .{0,00} (IDENTIFIED BY|WITH PASSWORD)", // sql creds
"(xox[pboa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})", //Slack Token
"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}", //Slack Webhook
"aws[_\\-\\.]?key", // aws mnagic
"[_\\-\\.]?api[_\\-\\.]?key", // stuff
"[_\\-\\.]oauth\\s*=", // oauth stuff
"client_secret", // fun
"secret[_\\-\\.]?(key)?\\s*=",
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----",
"(\\s|\\\'|\\\"|\\^|=)(A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}(\\s|\\\'|\\\"|$)", // aws access key
}
});
// Batch
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for cmd.exe/batch file related strings.",
RuleName = "cmdContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepCmdRegexRed",
WordList = new List<string>()
{
// cmd.exe
"\\.bat",
"\\.cmd"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepCmdRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
// cmd
// password variable in bat file
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
// creation of scheduled tasks with password
"schtasks.{1,300}(/rp\\s|/p\\s)",
// looking for net use or net user commands since these can contain credentials
"net user ",
"psexec .{0,100} -p ",
"net use .{0,300} /user:"
}
});
// bash/sh/zsh/etc
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for Bash related strings.",
RuleName = "bashContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepBashRegexRed",
WordList = new List<string>()
{
// bash, sh, zsh, etc
"\\.sh",
"\\.rc",
"\\.profile"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepBashRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
// bash
"sshpass.{1,300}-p", //SSH Password
// generic tokens etc, same for most languages.
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"CREATE (USER|LOGIN) .{0,200} (IDENTIFIED BY|WITH PASSWORD)", // sql creds
"(xox[pboa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})", //Slack Token
"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}", //Slack Webhook
"aws[_\\-\\.]?key", // aws mnagic
"[_\\-\\.]?api[_\\-\\.]?key", // stuff
"[_\\-\\.]oauth\\s*=", // oauth stuff
"client_secret", // fun
"secret[_\\-\\.]?(key)?\\s*=",
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----",
"(\\s|\\\'|\\\"|\\^|=)(A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}(\\s|\\\'|\\\"|$)", // aws access key
}
});
// Firefox/Thunderbird backups
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be searched for Firefox/Thunderbird backups related strings.",
RuleName = "browerContentByName",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileName,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepFFRegexRed",
WordList = new List<string>()
{
// Firefox/Thunderbird
"logins\\.json"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexes are very interesting.",
RuleName = "KeepFFRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
"\"encryptedPassword\":\"[A-Za-z0-9+/=]+\""
}
});
// vbscript etc
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Look inside unattend.xml files for actual values.",
RuleName = "Unattend.xml",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileName,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepUnattendXmlRegexRed",
WordList = new List<string>()
{
"unattend\\.xml",
"Autounattend\\.xml"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepUnattendXmlRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
"(?s)<AdministratorPassword>.{0,30}<Value>.*<\\/Value>",
"(?s)<AutoLogon>.{0,30}<Value>.*<\\/Value>"
}
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Look inside unattend.xml files for actual values.",
RuleName = "RDPFile",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepRdpPasswordRed",
WordList = new List<string>()
{
"\\.rdp"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with contents matching these regexen are very interesting.",
RuleName = "KeepRdpPasswordRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
"password 51:b"
}
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files with these extensions will be subjected to a generic search for keys and such.",
RuleName = "ConfigContentByExt",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepConfigRegexRed",
WordList = new List<string>()
{
"\\.yaml",
"\\.yml",
"\\.toml",
"\\.xml",
"\\.json",
"\\.config",
"\\.ini",
"\\.inf",
"\\.cnf",
"\\.conf",
"\\.properties",
"\\.env",
"\\.dist",
"\\.txt",
"\\.sql",
"\\.log",
"\\.sqlite",
"\\.sqlite3",
"\\.fdb"
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
RuleName = "KeepConfigRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
"sqlconnectionstring\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"connectionstring\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"validationkey\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"decryptionkey\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"passwo?r?d\\s*=\\s*[\\\'\\\"][^\\\'\\\"]....",
"CREATE (USER|LOGIN) .{0,200} (IDENTIFIED BY|WITH PASSWORD)", // sql creds
"(xox[pboa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})", //Slack Token
"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}", //Slack Webhook
"aws[_\\-\\.]?key", // aws mnagic
"[_\\-\\.]?api[_\\-\\.]?key", // stuff
"[_\\-\\.]oauth\\s*=", // oauth stuff
"client_secret", // fun
"secret[_\\-\\.]?(key)?\\s*=",
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----",
"(\\s|\\\'|\\\"|\\^|=)(A3T[A-Z0-9]|AKIA|AGPA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}(\\s|\\\'|\\\"|$)", // aws access key
// network device config
"NVRAM config last updated",
"enable password \\.",
"simple-bind authenticated encrypt",
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files ending like this will be grepped for private keys.",
RuleName = "CertContentByEnding",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileName,
WordListType = MatchListType.EndsWith,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepCertRegexRed",
WordList = new List<string>()
{
"_rsa", // test file created
"_dsa", // test file created
"_ed25519", // test file created
"_ecdsa" // test file created
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
RuleName = "KeepCertRegexRed",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Red,
WordList = new List<string>()
{
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----"
},
});
/*
this.ClassifierRules.Add(new ClassifierRule()
{
Description = "Files ending like this will be grepped for private keys.",
RuleName = "CertContentByEndingYellow",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.Relay,
RelayTarget = "KeepCertRegexRed",
WordList = new List<string>()
{
"\\.pem",
},
});
this.ClassifierRules.Add(new ClassifierRule()
{
RuleName = "KeepCertRegexYellow",
EnumerationScope = EnumerationScope.ContentsEnumeration,
MatchLocation = MatchLoc.FileContentAsString,
WordListType = MatchListType.Regex,
MatchAction = MatchAction.Snaffle,
Triage = Triage.Yellow,
WordList = new List<string>()
{
"-----BEGIN( RSA| OPENSSH| DSA| EC| PGP)? PRIVATE KEY( BLOCK)?-----"
},
});
*/
this.ClassifierRules.Add(
new ClassifierRule()
{
Description = "Files with these extensions will be parsed as x509 certificates to see if they have private keys.",
RuleName = "KeepCertContainsPrivKeyRed",
EnumerationScope = EnumerationScope.FileEnumeration,
MatchLocation = MatchLoc.FileExtension,
WordListType = MatchListType.Exact,
MatchAction = MatchAction.CheckForKeys,
Triage = Triage.Red,
WordList = new List<string>()
{
"\\.pem",
"\\.der", // test file created
"\\.pfx",
"\\.pk12",
"\\.p12",
"\\.pkcs12",
},
}
);
}
}
}
| 47.548023 | 139 | 0.448135 | [
"MIT"
] | MalwareExploit/Snaffler | SnaffCore/Config/DefaultRules/FileContentRules.cs | 33,664 | C# |
/**
* *************************************************
* Copyright (c) 2019, Grindrod Bank Limited
* License MIT: https://opensource.org/licenses/MIT
* **************************************************
*/
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace za.co.grindrodbank.a3s.Repositories
{
public class PaginatedRepository<T> : IPaginatedRepository<T> where T : class
{
public PaginatedRepository()
{
}
public async Task<PaginatedResult<T>> GetPaginatedListFromQueryAsync(IQueryable<T> query, int page, int pageSize)
{
// Set default page and page size for all paginated lists here.
// This should be pulled from configuration.
page = page == 0 ? 1 : page;
pageSize = pageSize == 0 ? 10 : pageSize;
var result = new PaginatedResult<T>
{
CurrentPage = page,
PageSize = pageSize,
RowCount = query.Count()
};
var pageCount = (double)result.RowCount / pageSize;
result.PageCount = (int)Math.Ceiling(pageCount);
var skip = (page - 1) * pageSize;
result.Results = await query.Skip(skip).Take(pageSize).ToListAsync();
return result;
}
}
}
| 30.931818 | 121 | 0.547392 | [
"MIT"
] | paulvancoller/A3S | src/za.co.grindrodbank.a3s/Repositories/PaginatedRepository.cs | 1,363 | C# |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class UMG : ModuleRules
{
public UMG(TargetInfo Target)
{
PrivateIncludePaths.AddRange(
new string[] {
"Runtime/UMG/Private" // For PCH includes (because they don't work with relative paths, yet)
})
;
PrivateDependencyModuleNames.AddRange(
new string[] {
"Core",
"CoreUObject",
"Engine",
"InputCore",
"Slate",
"SlateCore",
"ShaderCore",
"RenderCore",
"RHI",
}
);
PublicDependencyModuleNames.AddRange(
new string[] {
"HTTP",
"MovieScene",
"MovieSceneTracks",
}
);
PrivateIncludePathModuleNames.AddRange(
new string[] {
"ImageWrapper",
}
);
if (Target.Type != TargetRules.TargetType.Server)
{
PrivateIncludePathModuleNames.AddRange(
new string[] {
"SlateRHIRenderer",
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[] {
"ImageWrapper",
"SlateRHIRenderer",
}
);
};
}
}
| 19.733333 | 108 | 0.540541 | [
"BSD-2-Clause"
] | PopCap/GameIdea | Engine/Source/Runtime/UMG/UMG.Build.cs | 1,184 | C# |
// Copyright (c) 2021 Salim Mayaleh. All Rights Reserved
// Licensed under the BSD-3-Clause License
// Generated at 28.11.2021 14:05:29 by RaynetApiDocToDotnet.ApiDocParser, created by Salim Mayaleh.
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Maya.Raynet.Crm.Response.Put
{
public class StartACurrency
{
[JsonProperty("id", DefaultValueHandling = DefaultValueHandling.Ignore)]
public int Id { get; set; }
}
}
| 26.611111 | 100 | 0.730689 | [
"BSD-3-Clause"
] | mayaleh/Maya.Raynet.Crm | src/Maya.Raynet.Crm/Response/Put/StartACurrency.cs | 479 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WSTowers.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WSTowers.Android")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 35.967742 | 77 | 0.765919 | [
"MIT"
] | AnaLauraFeltrim/Projeto2Semestre | WSTowers/WSTowers.Android/Properties/AssemblyInfo.cs | 1,118 | C# |
using System.Drawing;
using CustomerRecognition.Forms;
using CustomerRecognition.Forms.Models;
using Xamarin.Forms;
namespace CustomerRecognition
{
public partial class App : Application
{
public static int ScreenWidth;
public static int ScreenHeight;
public static int CameraRatio;
public App()
{
InitializeComponent();
ServiceContainer.Register<ICreateOrderModel>(new CreateOrderModel());
ServiceContainer.Register<IOrdersModel>(new OrdersModel());
MainPage = new MainPage();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| 23.15 | 82 | 0.593952 | [
"MIT"
] | ClintFrancis/AzureSearchBot | Projects/CustomerRecognition/src/CustomerRecognition.Forms/App.xaml.cs | 928 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Roslynator.CSharp.CodeFixes;
using Roslynator.Testing.CSharp;
using Xunit;
namespace Roslynator.CSharp.Analysis.Tests
{
public class RCS1163UnusedParameterTests : AbstractCSharpDiagnosticVerifier<UnusedParameter.UnusedParameterAnalyzer, UnusedParameterCodeFixProvider>
{
public override DiagnosticDescriptor Descriptor { get; } = DiagnosticRules.UnusedParameter;
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UnusedParameter)]
public async Task Test_Method()
{
await VerifyDiagnosticAsync(@"
class C
{
void M([|object p|], __arglist)
{
}
}
"
);
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UnusedParameter)]
public async Task Test_Lambda()
{
await VerifyDiagnosticAndFixAsync(@"
using System;
class C
{
void M()
{
object _ = null;
Action<string> action = [|f|] => M();
}
}
", @"
using System;
class C
{
void M()
{
object _ = null;
Action<string> action = __ => M();
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UnusedParameter)]
public async Task TestNoDiagnostic_StackAllocArrayCreationExpression()
{
await VerifyNoDiagnosticAsync(@"
class C
{
unsafe void M(int length)
{
var memory = stackalloc byte[length];
}
}
", options: Options.WithAllowUnsafe(true));
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UnusedParameter)]
public async Task TestNoDiagnostic_PartialMethod()
{
await VerifyNoDiagnosticAsync(@"
partial class C
{
partial void M(object p);
partial void M(object p)
{
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UnusedParameter)]
public async Task TestNoDiagnostic_MethodReferencedAsMethodGroup()
{
await VerifyNoDiagnosticAsync(@"
using System;
class C
{
private void M(object p)
{
Action<object> action = M;
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UnusedParameter)]
public async Task TestNoDiagnostic_ContainsOnlyThrowNew()
{
await VerifyNoDiagnosticAsync(@"
using System;
class C
{
public C(object p)
{
throw new NotImplementedException();
}
public C(object p, object p2) => throw new NotImplementedException();
public string this[int index] => throw new NotImplementedException();
public string this[string index]
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string this[string index, string index2]
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}
public void Bar(object p) { throw new NotImplementedException(); }
public object Bar(object p1, object p2) => throw new NotImplementedException();
/// <summary>
/// ...
/// </summary>
/// <param name=""p1""></param>
/// <param name=""p2""></param>
public void Bar2(object p1, object p2) { throw new NotImplementedException(); }
public static C operator +(C left, C right)
{
throw new NotImplementedException();
}
public static explicit operator C(string value)
{
throw new NotImplementedException();
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UnusedParameter)]
public async Task TestNoDiagnostic_SwitchExpression()
{
await VerifyNoDiagnosticAsync(@"
using System;
class C
{
string M(StringSplitOptions options)
{
return options switch
{
_ => """"
};
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UnusedParameter)]
public async Task TestNoDiagnostic_Discard()
{
await VerifyNoDiagnosticAsync(@"
using System;
class C
{
void M(string _, string __, string _1)
{
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UnusedParameter)]
public async Task TestNoDiagnostic_ArgIterator()
{
await VerifyNoDiagnosticAsync(@"
using System;
class C
{
public static int GetCount(__arglist)
{
var argIterator = new ArgIterator(__arglist);
return argIterator.GetRemainingCount();
}
}
");
}
}
}
| 22.521531 | 160 | 0.632037 | [
"Apache-2.0"
] | JosefPihrt/Roslynator | src/Tests/Analyzers.Tests/RCS1163UnusedParameterTests.cs | 4,709 | C# |
using System;
using System.Collections.Generic;
namespace bellyful_proj.Models
{
public partial class MealInstock
{
public byte MealTypeId { get; set; }
public int InstockAmount { get; set; }
public MealType MealType { get; set; }
}
}
| 19.571429 | 46 | 0.653285 | [
"MIT"
] | PandasSIT/bellyful_proj | bellyful_proj_v.0.2/Models/MealInstock.cs | 276 | C# |
using System;
using Skewworks.NETMF;
namespace Skewworks.Gadgeteer.CP7Helper
{
public class CP7TouchHelper
{
#region Variables
private point _ptLast;
private point _ptDownAt;
private long _lgDownAt;
private TouchType _tt;
private bool _tDown;
private bool _cancelSwipe;
#endregion
#region Public Methods
public void CP7Pressed(point e)
{
_ptLast = e;
if (_ptLast.X < 800)
{
if (!_tDown)
{
_tDown = true;
_tt = TouchType.NoGesture;
_cancelSwipe = false;
_ptDownAt = _ptLast;
_lgDownAt = DateTime.Now.Ticks;
try
{
Core.RaiseTouchEvent(TouchType.TouchDown, _ptLast);
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{ }
}
else
{
if (!_cancelSwipe)
CalcDir(_ptLast);
try
{
Core.RaiseTouchEvent(TouchType.TouchMove, _ptLast);
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{ }
}
}
}
public void CP7Released()
{
_tDown = false;
if (!_cancelSwipe && _tt != TouchType.NoGesture)
CalcForce(_ptLast);
try
{
if (_ptLast.X > 800)
{
if (_ptLast.Y >= 0 && _ptLast.Y <= 50)
Core.RaiseButtonEvent((int)ButtonIDs.Home, false);
else if (_ptLast.Y >= 100 && _ptLast.Y <= 150)
Core.RaiseButtonEvent((int)ButtonIDs.Menu, false);
else if (_ptLast.Y >= 200 && _ptLast.Y <= 250)
Core.RaiseButtonEvent((int)ButtonIDs.Back, false);
}
else
Core.RaiseTouchEvent(TouchType.TouchUp, _ptLast);
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{ }
}
public void CP7HomePressed()
{
try
{
Core.RaiseButtonEvent((int)ButtonIDs.Home, true);
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{ }
}
public void CP7MenuPressed()
{
try
{
Core.RaiseButtonEvent((int)ButtonIDs.Menu, true);
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{ }
}
public void CP7BackPressed()
{
try
{
Core.RaiseButtonEvent((int)ButtonIDs.Back, true);
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{ }
}
#endregion
#region Private Methods
private void CalcDir(point e)
{
var sw = TouchType.NoGesture;
int d = (e.Y - _ptDownAt.Y);
if (d > 50)
{
sw = TouchType.GestureDown;
}
else if (d < -50)
{
sw = TouchType.GestureUp;
}
d = (e.X - _ptDownAt.X);
if (d > 50)
{
if (sw == TouchType.GestureUp)
{
sw = TouchType.GestureUpRight;
}
else if (sw == TouchType.GestureDown)
{
sw = TouchType.GestureDownRight;
}
else
{
sw = TouchType.GestureRight;
}
}
else if (d < -50)
{
if (sw == TouchType.GestureUp)
{
sw = TouchType.GestureUpLeft;
}
else if (sw == TouchType.GestureDown)
{
sw = TouchType.GestureDownLeft;
}
else
{
sw = TouchType.GestureLeft;
}
}
if (_tt == TouchType.NoGesture)
{
_tt = sw;
}
else if (_tt != sw)
{
_cancelSwipe = true;
}
}
private void CalcForce(point e)
{
// Calc by time alone
float dDiff = DateTime.Now.Ticks - _lgDownAt;
if (dDiff > TimeSpan.TicksPerSecond * .75)
{
return;
}
// 1.0 = < 1/7th second
dDiff = TimeSpan.TicksPerSecond / 7 / dDiff;
if (dDiff > 0.99)
{
dDiff = 0.99f;
}
else if (dDiff < 0)
{
dDiff = 0;
}
// Raise TouchEvent
Core.RaiseTouchEvent(_tt, e, dDiff);
}
#endregion
}
}
| 23.711538 | 70 | 0.42356 | [
"Apache-2.0"
] | osre77/Tinkr | Tinkr2/4.2/AphelionCore/AphelionCP7Helper/CP7TouchHelper.cs | 4,932 | C# |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CAIBruxaNpcDeath : CAIDeathTree
{
[Ordinal(1)] [RED("params")] public CHandle<CAINpcBruxaDeathParams> Params { get; set;}
public CAIBruxaNpcDeath(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIBruxaNpcDeath(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 31.2 | 128 | 0.730769 | [
"MIT"
] | DerinHalil/CP77Tools | CP77.CR2W/Types/W3/RTTIConvert/CAIBruxaNpcDeath.cs | 756 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace StarsectorLTool.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.6.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string starsector_path {
get {
return ((string)(this["starsector_path"]));
}
set {
this["starsector_path"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool ifAutoUpdate {
get {
return ((bool)(this["ifAutoUpdate"]));
}
set {
this["ifAutoUpdate"] = value;
}
}
}
}
| 36.313725 | 151 | 0.557235 | [
"Apache-2.0"
] | TruthOriginem/Starsector-L.Tool | Properties/Settings.Designer.cs | 1,960 | C# |
using System;
using Agiil.Domain.Tickets;
using Agiil.Domain.Tickets.Specs;
using Agiil.Domain.TicketSearch;
using Agiil.Tests.Attributes;
using CSF.Specifications;
using NUnit.Framework;
namespace Agiil.Tests.Tickets.Specs
{
[TestFixture, Parallelizable]
public class StoryPointsComparedToConstantValueSpecFactoryTests
{
[Test, AutoMoqData]
public void Equals_returns_an_equals_spec(Ticket ticket, StoryPointsComparedToConstantValueSpecFactory sut)
{
ticket.StoryPoints = 5;
Assert.That(() => sut.Equals(5).Matches(ticket), Is.True);
}
[Test, AutoMoqData]
public void NotEquals_returns_a_not_equals_spec(Ticket ticket, StoryPointsComparedToConstantValueSpecFactory sut)
{
ticket.StoryPoints = 5;
Assert.That(() => sut.NotEquals(5).Matches(ticket), Is.False);
}
[Test, AutoMoqData]
public void GreaterThan_returns_a_gt_spec(Ticket ticket, StoryPointsComparedToConstantValueSpecFactory sut)
{
ticket.StoryPoints = 5;
Assert.That(() => sut.GreaterThan(3).Matches(ticket), Is.True);
}
[Test, AutoMoqData]
public void GreaterThanOrEqual_returns_a_gte_spec(Ticket ticket, StoryPointsComparedToConstantValueSpecFactory sut)
{
ticket.StoryPoints = 5;
Assert.That(() => sut.GreaterThanOrEqual(5).Matches(ticket), Is.True);
}
[Test, AutoMoqData]
public void LessThan_returns_a_lt_spec(Ticket ticket, StoryPointsComparedToConstantValueSpecFactory sut)
{
ticket.StoryPoints = 5;
Assert.That(() => sut.LessThan(8).Matches(ticket), Is.True);
}
[Test, AutoMoqData]
public void LessThanOrEqual_returns_a_lte_spec(Ticket ticket, StoryPointsComparedToConstantValueSpecFactory sut)
{
ticket.StoryPoints = 5;
Assert.That(() => sut.LessThanOrEqual(5).Matches(ticket), Is.True);
}
[Test, AutoMoqData]
public void GetFromPredicateName_can_return_a_predicate_for_every_supported_name(StoryPointsComparedToConstantValueSpecFactory sut, int value)
{
var supportedPredicates = new[] {
PredicateName.Equals,
PredicateName.NotEquals,
PredicateName.GreaterThan,
PredicateName.GreaterThanOrEqual,
PredicateName.LessThan,
PredicateName.LessThanOrEqual,
};
foreach(var name in supportedPredicates)
Assert.That(() => sut.GetFromPredicateName(name, value), Is.Not.Null, $"A spec was returned for the predicate '{name}'");
}
}
}
| 37.972222 | 150 | 0.653621 | [
"MIT"
] | csf-dev/agiil | Tests/Agiil.Tests.Domain/Tickets/Specs/StoryPointsComparedToConstantValueSpecFactoryTests.cs | 2,736 | C# |
using DTORepository.Common;
using System;
namespace DTORepository.Attributes
{
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class IgnoreRetrievingForAttribute : Attribute
{
public ActionFlags actions = ActionFlags.None;
public IgnoreRetrievingForAttribute(ActionFlags actions)
{
this.actions = actions;
}
}
}
| 22.055556 | 65 | 0.692695 | [
"MIT"
] | theerapatcha/DTORepository | DTORepository/Attributes/IgnoreRetrievingForAttribute.cs | 399 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion: 4.0.30319.42000
//
// Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn
// der Code neu generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace IsoMaker.Properties
{
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder-Klasse
// über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der Option /str erneut aus, oder erstellen Sie Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("IsoMaker.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenlookups, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 41.152778 | 174 | 0.624705 | [
"MIT"
] | bastisk/Folder-To-Iso | IsoMaker/IsoMaker/Properties/Resources.Designer.cs | 2,973 | C# |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.QueryParsers;
using Lucene.Net.Store;
using NUnit.Framework;
using Version = Lucene.Net.Util.Version;
namespace Lucene.Net.Search.Vectorhighlight
{
static class Extensions
{
public static V Get<K, V>(this Dictionary<K, V> list, K key)
{
if (key == null) return default(V);
V v = default(V);
list.TryGetValue(key, out v);
return v;
}
}
public class HashSet<T> : Dictionary<T, T>
{
public void Add(T key)
{
base.Add(key, key);
}
}
}
| 29.555556 | 69 | 0.656642 | [
"Apache-2.0"
] | Anomalous-Software/Lucene.NET | test/contrib/FastVectorHighlighter/Support.cs | 1,598 | C# |
using LeetCode.Data;
namespace LeetCode
{
public class OddEvenLinkedList
{
public ListNode OddEvenList(ListNode head)
{
if (head == null)
{
return head;
}
ListNode odd = head;
ListNode oddEnd = odd;
ListNode even = head.next;
ListNode evenEnd = even;
ListNode node = even?.next;
int index = 3;
while (node != null)
{
if (index % 2 == 0)
{
evenEnd.next = node;
evenEnd = node;
}
else
{
oddEnd.next = node;
oddEnd = node;
}
node = node.next;
index++;
}
oddEnd.next = even;
if (evenEnd != null)
{
evenEnd.next = null;
}
return odd;
}
}
}
| 20.72 | 50 | 0.350386 | [
"MIT"
] | sergioescalera/LeetCode-Exercises | src/LeetCode/0328-OddEvenLinkedList.cs | 1,038 | C# |
using System;
using StatsdClient.Bufferize;
namespace StatsdClient
{
internal class MetricsSender
{
private readonly Telemetry _optionalTelemetry;
private readonly StatsBufferize _statsBufferize;
private readonly Serializers _serializers;
private readonly bool _truncateIfTooLong;
private readonly IStopWatchFactory _stopwatchFactory;
private readonly IRandomGenerator _randomGenerator;
internal MetricsSender(
StatsBufferize statsBufferize,
IRandomGenerator randomGenerator,
IStopWatchFactory stopwatchFactory,
Serializers serializers,
Telemetry optionalTelemetry,
bool truncateIfTooLong)
{
_stopwatchFactory = stopwatchFactory;
_statsBufferize = statsBufferize;
_randomGenerator = randomGenerator;
_optionalTelemetry = optionalTelemetry;
_serializers = serializers;
_truncateIfTooLong = truncateIfTooLong;
}
public void SendEvent(string title, string text, string alertType = null, string aggregationKey = null, string sourceType = null, int? dateHappened = null, string priority = null, string hostname = null, string[] tags = null, bool truncateIfTooLong = false)
{
truncateIfTooLong = truncateIfTooLong || _truncateIfTooLong;
var optionalSerializedMetric = _serializers.EventSerializer.Serialize(title, text, alertType, aggregationKey, sourceType, dateHappened, priority, hostname, tags, truncateIfTooLong);
Send(optionalSerializedMetric, () => _optionalTelemetry?.OnEventSent());
}
public void SendServiceCheck(string name, int status, int? timestamp = null, string hostname = null, string[] tags = null, string serviceCheckMessage = null, bool truncateIfTooLong = false)
{
truncateIfTooLong = truncateIfTooLong || _truncateIfTooLong;
var optionalSerializedMetric = _serializers.ServiceCheckSerializer.Serialize(name, status, timestamp, hostname, tags, serviceCheckMessage, truncateIfTooLong);
Send(optionalSerializedMetric, () => _optionalTelemetry?.OnServiceCheckSent());
}
public void SendMetric<T>(MetricType metricType, string name, T value, double sampleRate = 1.0, string[] tags = null)
{
if (_randomGenerator.ShouldSend(sampleRate))
{
var optionalSerializedMetric = _serializers.MetricSerializer.Serialize(metricType, name, value, sampleRate, tags);
Send(optionalSerializedMetric, () => _optionalTelemetry?.OnMetricSent());
}
}
public void Send(Action actionToTime, string statName, double sampleRate = 1.0, string[] tags = null)
{
var stopwatch = _stopwatchFactory.Get();
try
{
stopwatch.Start();
actionToTime();
}
finally
{
stopwatch.Stop();
SendMetric(MetricType.Timing, statName, stopwatch.ElapsedMilliseconds(), sampleRate, tags);
}
}
private void Send(SerializedMetric optionalSerializedMetric, Action onSuccess)
{
if (optionalSerializedMetric != null && _statsBufferize.Send(optionalSerializedMetric))
{
onSuccess();
}
else
{
_optionalTelemetry?.OnPacketsDroppedQueue();
}
}
}
}
| 44.325301 | 266 | 0.620549 | [
"MIT"
] | jdasilva-olo/dogstatsd-csharp-client | src/StatsdClient/MetricsSender.cs | 3,681 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OpenTMS.Server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 27.211538 | 106 | 0.652297 | [
"MIT"
] | fossabot/open-tms | src/OpenTMS.Server/Startup.cs | 1,415 | C# |
using Engine;
using Microsoft.Xna.Framework;
class Cloud : SpriteGameObject
{
Level level;
public Cloud(Level level) : base(null, TickTick.Depth_Background)
{
this.level = level;
Reset();
}
public override void Reset()
{
Randomize();
// give the cloud a starting position inside the level
localPosition.X = ExtendedGame.Random.Next(-sprite.Width, level.BoundingBox.Width);
}
void Randomize()
{
// set a random sprite and depth
float depth = TickTick.Depth_Background + (float)ExtendedGame.Random.NextDouble() * 0.2f;
sprite = new SpriteSheet("Sprites/Backgrounds/spr_cloud_" + ExtendedGame.Random.Next(1, 6), depth);
// set a random y-coordinate and speed
float y = ExtendedGame.Random.Next(100, 600) - sprite.Height;
float speed = ExtendedGame.Random.Next(10, 50);
if (ExtendedGame.Random.Next(2) == 0)
{
// go from right to left
localPosition = new Vector2(level.BoundingBox.Width, y);
velocity = new Vector2(-speed, 0);
}
else
{
// go from left to right
localPosition = new Vector2(-sprite.Width, y);
velocity = new Vector2(speed, 0);
}
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (velocity.X < 0 && localPosition.X < -sprite.Width)
Randomize();
else if (velocity.X > 0 && localPosition.X > level.BoundingBox.Width)
Randomize();
}
}
| 28.339286 | 107 | 0.591682 | [
"MIT"
] | egges/csharpgames | Code and Assets/26_FinishingGame/TickTickFinal/LevelObjects/Cloud.cs | 1,589 | C# |
#region Using directives
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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("CryptoLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("mlnlover11 Productions")]
[assembly: AssemblyProduct("CryptoLib")]
[assembly: AssemblyCopyright("Copyright (C) 2011-2012 mlnlover11 Productions")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible(false)]
// The assembly version has following format :
//
// Major.Minor.Build.Revision
//
// You can specify all the values or you can use the default the Revision and
// Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
| 34.25 | 79 | 0.763686 | [
"MIT"
] | Stevie-O/SharpLua | OLD.SharpLua/CryptoLib/Properties/AssemblyInfo.cs | 1,098 | C# |
using System;
using Alex.Interfaces;
using Alex.Networking.Java.Util;
namespace Alex.Networking.Java.Packets.Play
{
public class PlayerBlockPlacementPacket : Packet<PlayerBlockPlacementPacket>
{
public IVector3I Location;
public BlockFace Face;
public int Hand;
public IVector3 CursorPosition;
public bool InsideBlock;
public PlayerBlockPlacementPacket()
{
PacketId = 0x2E;
}
public override void Decode(MinecraftStream stream)
{
throw new NotImplementedException();
}
public override void Encode(MinecraftStream stream)
{
stream.WriteVarInt(Hand);
stream.WritePosition(Location);
switch (Face)
{
case BlockFace.Down:
stream.WriteVarInt(0);
break;
case BlockFace.Up:
stream.WriteVarInt(1);
break;
case BlockFace.North:
stream.WriteVarInt(2);
break;
case BlockFace.South:
stream.WriteVarInt(3);
break;
case BlockFace.West:
stream.WriteVarInt(4);
break;
case BlockFace.East:
stream.WriteVarInt(5);
break;
case BlockFace.None:
stream.WriteVarInt(1);
break;
}
stream.WriteFloat(CursorPosition.X);
stream.WriteFloat(CursorPosition.Y);
stream.WriteFloat(CursorPosition.Z);
stream.WriteBool(InsideBlock);
}
}
} | 17.364865 | 77 | 0.692607 | [
"MPL-2.0"
] | ConcreteMC/Alex | src/Networking/Alex.Networking.Java/Packets/Play/PlayerBlockPlacement.cs | 1,287 | C# |
using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using EPiServer.Shell.Services.Rest;
using Forte.EpiserverRedirects.Mapper;
using Forte.EpiserverRedirects.Model.RedirectRule;
using Forte.EpiserverRedirects.Repository;
namespace Forte.EpiserverRedirects.Menu
{
[RestStore("RedirectRuleStore")]
public class RedirectRuleStore : RestControllerBase
{
private readonly IRedirectRuleRepository _redirectRuleRepository;
private readonly IRedirectRuleMapper _redirectRuleMapper;
private readonly Guid _clearAllGuid = Guid.Parse("00000000-0000-0000-0000-000000000000");
public RedirectRuleStore(IRedirectRuleRepository redirectRuleRepository, IRedirectRuleMapper redirectRuleMapper)
{
_redirectRuleRepository = redirectRuleRepository;
_redirectRuleMapper = redirectRuleMapper;
}
public ActionResult Get(Guid id)
{
var redirect = _redirectRuleRepository.GetById(id);
if (redirect == null)
return null;
return Rest(_redirectRuleMapper.ModelToDto(redirect));
}
[HttpGet]
public ActionResult Get(Query query = null)
{
var redirects = _redirectRuleRepository
.GetAll()
.GetPageFromQuery(out var allRedirectsCount, query)
.Select(_redirectRuleMapper.ModelToDto);
HttpContext.Response.Headers.Add("Content-Range", $"0/{allRedirectsCount}");
return Rest(redirects);
}
[HttpPost]
public ActionResult Post(RedirectRuleDto dto)
{
if (!ViewData.ModelState.IsValid)
return null;
var newRedirectRule = _redirectRuleMapper.DtoToModel(dto);
newRedirectRule.FromManual();
newRedirectRule = _redirectRuleRepository.Add(newRedirectRule);
var newRedirectRuleDto = _redirectRuleMapper.ModelToDto(newRedirectRule);
return Rest(newRedirectRuleDto);
}
[HttpPut]
public ActionResult Put(RedirectRuleDto dto)
{
if (!ViewData.ModelState.IsValid)
return null;
var updatedRedirectRule = _redirectRuleMapper.DtoToModel(dto);
updatedRedirectRule = _redirectRuleRepository.Update(updatedRedirectRule);
var updatedRedirectRuleDto = _redirectRuleMapper.ModelToDto(updatedRedirectRule);
return Rest(updatedRedirectRuleDto);
}
[HttpDelete]
public ActionResult Delete(Guid id)
{
var deletedSuccessfully = id == _clearAllGuid
? _redirectRuleRepository.ClearAll()
: _redirectRuleRepository.Delete(id);
return deletedSuccessfully
? Rest(HttpStatusCode.OK)
: Rest(HttpStatusCode.Conflict);
}
}
}
| 33.164835 | 120 | 0.628231 | [
"MIT"
] | fortedigital/EPiAutoAlias | EpiserverRedirects/Menu/RedirectRuleStore.cs | 3,018 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AoC2021.utils;
using AoCHelper;
namespace AoC2021.Days
{
public sealed class Day14 : BaseDay
{
private readonly List<string> _stringInput;
private LinkedList<char> _polymer;
private Dictionary<string, char> _rules;
public Day14()
{
_stringInput = File.ReadAllLines(InputFilePath).ToList();
ParseInput();
}
private void ParseInput()
{
var blankIndex = _stringInput.FindIndex(str => str == "");
_polymer = new LinkedList<char>();
foreach (var c in _stringInput[0])
{
_polymer.AddLast(c);
}
_rules = new Dictionary<string, char>();
for (int i = blankIndex + 1; i < _stringInput.Count; i++)
{
var (pair, element, _) = _stringInput[i].Split("->");
_rules.Add(pair.Trim(), element.Trim()[0]);
}
}
public override ValueTask<string> Solve_1()
{
var steps = 10;
for (int i = 0; i < steps; i++)
{
var current = _polymer.First;
while (current != null)
{
var next = current.Next;
if (next == null)
{
break;
}
string currentPair = current.Value.ToString() + next.Value.ToString();
if (_rules.ContainsKey(currentPair))
{
_polymer.AddAfter(current, _rules[currentPair]);
}
current = next;
}
}
var counts = new Dictionary<char, int>();
foreach (var c in _polymer)
{
if (!counts.ContainsKey(c))
{
counts.Add(c, 0);
}
counts[c]++;
}
var mostCommon = counts.OrderByDescending(kvp => kvp.Value).First().Key;
var leastCommon = counts.OrderBy(kvp => kvp.Value).First().Key;
var mostCommonCount = counts[mostCommon];
var leastCommonCount = counts[leastCommon];
return new ValueTask<string>((mostCommonCount - leastCommonCount).ToString());
}
private Dictionary<string, long> CopyDictionary(Dictionary<string, long> original)
{
var copy = new Dictionary<string, long>();
foreach (var kvp in original)
{
copy.Add(kvp.Key, kvp.Value);
}
return copy;
}
public override ValueTask<string> Solve_2()
{
ParseInput();
var steps = 40;
var state = new Dictionary<string, long>();
foreach (var (key, _) in _rules)
{
state.Add(key, 0);
}
var current = _polymer.First;
while (current != null)
{
var next = current.Next;
if (next == null)
{
break;
}
string currentPair = current.Value.ToString() + next.Value.ToString();
if (!state.ContainsKey(currentPair))
{
Console.WriteLine($"{currentPair} not found!");
state.Add(currentPair, 0);
}
state[currentPair]++;
current = next;
}
var counts = new Dictionary<char, long>();
foreach (var c in _polymer)
{
if (!counts.ContainsKey(c))
{
counts.Add(c, 0);
}
counts[c]++;
}
for (int i = 0; i < steps; i++)
{
var newState = CopyDictionary(state);
foreach (var (key, _) in state)
{
string firstNewPair = key[0].ToString() + _rules[key].ToString();
string secondNewPair = _rules[key].ToString() + key[1].ToString();
newState[firstNewPair] += state[key];
newState[secondNewPair] += state[key];
if (!counts.ContainsKey(_rules[key]))
{
counts.Add(_rules[key], 0);
}
counts[_rules[key]] += state[key];
newState[key] -= state[key];
}
state = newState;
}
var mostCommon = counts.OrderByDescending(kvp => kvp.Value).First().Key;
var leastCommon = counts.OrderBy(kvp => kvp.Value).First().Key;
var mostCommonCount = counts[mostCommon];
var leastCommonCount = counts[leastCommon];
return new ValueTask<string>((mostCommonCount - leastCommonCount).ToString());
}
}
} | 27.185185 | 90 | 0.45543 | [
"MIT"
] | ketkev/AoC2021 | Days/Day14.cs | 5,140 | C# |
namespace Bloom.Browser.Modules.LibraryModule.ViewModels
{
/// <summary>
/// View model for GridView.xaml
/// </summary>
public class GridViewModel
{
}
}
| 17.9 | 57 | 0.631285 | [
"Apache-2.0"
] | RobDixonIII/Bloom | Browser/Bloom.Browser.Modules/Bloom.Browser.Modules.LibraryModule/ViewModels/GridViewModel.cs | 181 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
namespace Fakebook.Posts.RestApi.Services
{
public class BlobService : IBlobService
{
private readonly BlobServiceClient _blobServiceClient;
public BlobService(BlobServiceClient blobServiceClient)
{
_blobServiceClient = blobServiceClient;
}
/// <summary>
/// Uploads a blob, given a name, type, and filename.
/// </summary>
/// <param name="blobContainerName">Container name used for blob storage</param>
/// <param name="content">What is being stored</param>
/// <param name="contentType">Content type of what's being uploaded</param>
/// <param name="fileName">Name of file in blob storage</param>
/// <returns>Blob Client URI</returns>
public async Task<Uri> UploadFileBlobAsync(string blobContainerName, Stream content, string contentType, string fileName)
{
var containerClient = GetContainerClient(blobContainerName);
var blobClient = containerClient.GetBlobClient(fileName);
await blobClient.UploadAsync(content, new BlobHttpHeaders { ContentType = contentType });
return blobClient.Uri;
}
private BlobContainerClient GetContainerClient(string blobContainerName)
{
var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
containerClient.CreateIfNotExists(PublicAccessType.Blob);
return containerClient;
}
}
} | 35.369565 | 129 | 0.674862 | [
"MIT"
] | 2011-fakebook-project3/posts | Fakebook.Posts/Fakebook.Posts.RestApi/Services/BlobService.cs | 1,629 | C# |
using System;
using Xunit;
namespace DistributedDistributionSketch.Tests
{
public class DDSketchTests
{
[Fact]
public void DistributedDistributionSketchDefaultConstructorDoesNotThrow()
{
var sketch = new DistributedDistributionSketch();
Assert.Equal(sketch.ErrorFactor, sketch.ErrorFactor);
}
[Fact]
public void DistributedDistributionSketchConstructorZeroFiveDoesNotThrow()
{
var sketch = new DistributedDistributionSketch(0.5);
Assert.Equal(0.5, sketch.ErrorFactor);
}
[Fact]
public void DistributedDistributionSketchConstructorOneDoesNotThrow()
{
var sketch = new DistributedDistributionSketch(1.0);
Assert.Equal(1.0, sketch.ErrorFactor);
}
[Fact]
public void DistributedDistributionSketchConstructorNegativeErrorFactorThrows()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new DistributedDistributionSketch(-0.1));
}
[Fact]
public void DistributedDistributionSketchConstructorZeroErrorFactorThrows()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new DistributedDistributionSketch(0.0));
}
[Fact]
public void DistributedDistributionSketchConstructorOneOneErrorFactorThrows()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new DistributedDistributionSketch(1.1));
}
[Fact]
public void EmptySketchHasZeroCount()
{
var sketch = new DistributedDistributionSketch();
Assert.Equal(0, sketch.Count);
}
[Fact]
public void SketchWithOneInsertHasOneCount()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(4500);
Assert.Equal(1, sketch.Count);
}
[Fact]
public void SketchWithTwoInsertsHasTwoCount()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(4500);
sketch.Insert(5500);
Assert.Equal(2, sketch.Count);
}
[Fact]
public void SketchWithThreeInsertsHasThreeCount()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(4500);
sketch.Insert(5500);
sketch.Insert(6500);
Assert.Equal(3, sketch.Count);
}
[Fact]
public void SketchWithOneInsertHasCorrectMinimumAndMaximum()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(4500);
Assert.Equal(4500, sketch.Minimum);
Assert.Equal(4500, sketch.Maximum);
}
[Fact]
public void SketchWithTwoInsertsHasCorrectMinimumAndMaximum()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(4500);
sketch.Insert(5500);
Assert.Equal(4500, sketch.Minimum);
Assert.Equal(5500, sketch.Maximum);
}
[Fact]
public void SketchWithThreeInsertsHasCorrectMinimumAndMaximum()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(4500);
sketch.Insert(5500);
sketch.Insert(6500);
Assert.Equal(4500, sketch.Minimum);
Assert.Equal(6500, sketch.Maximum);
}
[Fact]
public void InsertSetInSketchYieldsCorrectState()
{
var sketch = new DistributedDistributionSketch();
var set = new double[] {4500, 5500, 6500};
sketch.Insert(set);
Assert.Equal(3, sketch.Count);
Assert.Equal(4500, sketch.Minimum);
Assert.Equal(6500, sketch.Maximum);
}
[Fact]
public void InsertRemarkableValuesInSketchYieldsCorrectState()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(double.MinValue);
sketch.Insert(double.MaxValue);
sketch.Insert(double.Epsilon);
sketch.Insert(2.0);
sketch.Insert(1.0);
sketch.Insert(0.5);
sketch.Insert(0.0);
sketch.Insert(-0.5);
sketch.Insert(-1.0);
sketch.Insert(-2.0);
Assert.Equal(10, sketch.Count);
Assert.Equal(double.MinValue, sketch.Minimum);
Assert.Equal(double.MaxValue, sketch.Maximum);
}
[Fact]
public void GetQuantileYieldsCorrectEstimation()
{
var sketch = new DistributedDistributionSketch();
var set = new double[]
{
100, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99
};
sketch.Insert(set);
Assert.Equal(100, sketch.Count);
Assert.Equal(1, sketch.Minimum);
Assert.Equal(100, sketch.Maximum);
Assert.Equal(sketch.Minimum, sketch.GetQuantile(0.0));
Assert.Equal(sketch.Maximum, sketch.GetQuantile(1.0));
Assert.True(Math.Abs(50.0 - sketch.GetQuantile(0.5)) < sketch.ErrorFactor * 50.0);
}
[Fact]
public void GetNegativeQuantileThrows()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(4500);
Assert.Throws<ArgumentOutOfRangeException>(() => sketch.GetQuantile(-0.1));
}
[Fact]
public void GetGreaterThanOneQuantileThrows()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(4500);
Assert.Throws<ArgumentOutOfRangeException>(() => sketch.GetQuantile(1.1));
}
[Fact]
public void GetQuantileFromEmptySketchThrows()
{
var sketch = new DistributedDistributionSketch();
Assert.Throws<InvalidOperationException>(() => sketch.GetQuantile(0.5));
}
[Fact]
public void GetQuantileForZeroValueYieldsCorrectResult()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(0);
Assert.Equal(0, sketch.GetQuantile(0.5));
}
[Fact]
public void GetQuantileForOneBigValueYieldsCorrectResult()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(1000000000);
Assert.Equal(999740604.37254822, sketch.GetQuantile(0.5));
}
[Fact]
public void SketchWithTNegativeValuesYieldsCorrectQuantile()
{
var sketch = new DistributedDistributionSketch();
sketch.Insert(-1000);
sketch.Insert(-1000000);
sketch.Insert(-1000000000);
Assert.Equal(-999493.67526358145, sketch.GetQuantile(0.5));
}
[Fact]
public void SketchQuantileForUniformDistributionLiesWithinExpectedError()
{
var distribution = TestUtils.GetUniformRandomDistribution(1000000, 500, 5000);
var sketch = new DistributedDistributionSketch();
sketch.Insert(distribution);
var approximateQuantile = sketch.GetQuantile(0.9);
var exactQuantile = TestUtils.GetExactQuantile(distribution, 0.9);
Assert.True(Math.Abs(exactQuantile - approximateQuantile) <= sketch.ErrorFactor * exactQuantile);
}
[Fact]
public void SketchQuantileForNormalDistributionLiesWithinExpectedError()
{
var distribution = TestUtils.GetStandardNormalRandomDistribution(1000000, 500, 5000);
var sketch = new DistributedDistributionSketch();
sketch.Insert(distribution);
var approximateQuantile = sketch.GetQuantile(0.9);
var exactQuantile = TestUtils.GetExactQuantile(distribution, 0.9);
Assert.True(Math.Abs(exactQuantile - approximateQuantile) <= sketch.ErrorFactor * exactQuantile);
}
[Fact]
public void SketchQuantileForLogNormalDistributionLiesWithinExpectedError()
{
var distribution = TestUtils.GetLogNormalRandomDistribution(1000000, 2.7, 3.7);
var sketch = new DistributedDistributionSketch();
sketch.Insert(distribution);
var approximateQuantile = sketch.GetQuantile(0.9);
var exactQuantile = distribution.GetExactQuantile(0.9);
Assert.True(Math.Abs(exactQuantile - approximateQuantile) <= sketch.ErrorFactor * exactQuantile);
}
[Fact]
public void MergingSketchesYieldsCorrectQuantiles()
{
var sketch1 = new DistributedDistributionSketch();
sketch1.Insert(-5);
sketch1.Insert(-3);
sketch1.Insert(-1);
sketch1.Insert(1);
sketch1.Insert(3);
sketch1.Insert(5);
var q1 = sketch1.GetQuantile(0.84);
var sketch2 = new DistributedDistributionSketch();
sketch2.Insert(-4);
sketch2.Insert(-2);
sketch2.Insert(0);
sketch2.Insert(2);
sketch2.Insert(4);
sketch2.Insert(6);
var q2 = sketch2.GetQuantile(0.84);
sketch1.Merge(sketch2);
var mergedQ = sketch1.GetQuantile(0.84);
Assert.Equal(3.0011629583492887, q1);
Assert.Equal(4.0028234008341412, q2);
Assert.Equal(4.0028234008341412, mergedQ);
}
[Fact]
public void MergingSketchWithDifferentErrorFactorThrowException()
{
var sketch1 = new DistributedDistributionSketch(0.1);
sketch1.Insert(-5);
var sketch2 = new DistributedDistributionSketch(0.01);
sketch2.Insert(-4);
Assert.Throws<ArgumentException>(() => sketch1.Merge(sketch2));
}
}
}
| 33.528125 | 110 | 0.563147 | [
"BSD-3-Clause"
] | alexandre-lecoq/DDSketch | DistributedDistributionSketch.Tests/DDSketchTests.cs | 10,729 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Contracts
{
[DataContract]
public class SwitchReport
{
[DataMember]
public DateTime Date { get; set; }
[DataMember]
public string EAN { get; set; }
}
}
| 19.157895 | 42 | 0.67033 | [
"MIT"
] | e11en/WFDemo | WF 4.5 Demo/Contracts/SwitchReport.cs | 366 | C# |
// <copyright file="Post.cs" company="Endjin Limited">
// Copyright (c) Endjin Limited. All rights reserved.
// </copyright>
namespace Stacker.Cli.Domain.WordPress
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Post
{
public Post()
{
this.Attachments = Enumerable.Empty<Attachment>();
this.Categories = Enumerable.Empty<Category>();
this.Tags = Enumerable.Empty<Tag>();
}
public IEnumerable<Attachment> Attachments { get; internal set; }
public Author Author { get; set; }
public string Body { get; set; }
public IEnumerable<Category> Categories { get; set; }
public string Excerpt { get; set; }
public Attachment FeaturedImage { get; set; }
public string Id { get; internal set; }
public string Link { get; set; }
public Dictionary<string, string> MetaData { get; set; }
public bool Promote { get; set; }
public DateTimeOffset PromoteUntil { get; set; } = DateTimeOffset.MaxValue;
public DateTimeOffset PublishedAtUtc { get; set; }
public string Slug { get; set; }
public string Status { get; internal set; }
public IEnumerable<Tag> Tags { get; set; }
public string Title { get; set; }
}
} | 26.057692 | 83 | 0.609594 | [
"Apache-2.0"
] | endjin/Endjin.Stacker | Solutions/Stacker.Cli/Domain/WordPress/Post.cs | 1,355 | C# |
using System.Reflection;
[assembly: AssemblyTitle("Composable.CQRS.Testing")]
[assembly: AssemblyProduct("Composable.CQRS.Testing")]
| 27 | 54 | 0.792593 | [
"Apache-2.0"
] | ManpowerNordic/Composable | Composable.CQRS.Testing/Properties/AssemblyInfo.cs | 137 | C# |
using System;
using FluentAssertions;
using WinTenDev.Zizi.Utils;
using Xunit;
namespace WinTenDev.Zizi.Tests;
public class TimeUtilTest
{
[Fact]
public void ConvertTimeZoneTest()
{
var currentDateUtc = DateTime.UtcNow;
var tzAsia = currentDateUtc.ConvertUtcTimeToTimeZone("SE Asia Standard Time").Should();
var tzPacific = currentDateUtc.ConvertUtcTimeToTimeZone("Pacific Standard Time");
}
} | 24.277778 | 95 | 0.729977 | [
"MIT"
] | WinTenDev/ZiziBot.NET | src/WinTenDev.Zizi.Tests/TimeUtilTest.cs | 439 | C# |
using System;
using System.Globalization;
using Avalonia.Data.Converters;
using Avalonia.Layout;
namespace WalletWasabi.Fluent.Converters
{
public class NavBarItemsListBoxAlignmentConverter : IValueConverter
{
public static readonly NavBarItemsListBoxAlignmentConverter Instance = new();
private NavBarItemsListBoxAlignmentConverter()
{
}
object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is int count)
{
return count == 0 ? VerticalAlignment.Top : VerticalAlignment.Bottom;
}
return null;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
} | 24.258065 | 106 | 0.769947 | [
"MIT"
] | alexseres/WalletWasabi | WalletWasabi.Fluent/Converters/NavBarItemsListBoxAlignmentConverter.cs | 752 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace SpeedifyG19Applet
{
/// <summary>
/// Logique d'interaction pour App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.666667 | 43 | 0.71131 | [
"MIT"
] | sidewinder94/SpeedifyG19Applet | SpeedifyG19Applet/App.xaml.cs | 338 | C# |
/*
// <copyright>
// dotNetRDF is free and open source software licensed under the MIT License
// -------------------------------------------------------------------------
//
// Copyright (c) 2009-2017 dotNetRDF Project (http://dotnetrdf.org/)
//
// 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.
// </copyright>
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using VDS.RDF.Parsing;
using VDS.RDF.Writing.Contexts;
namespace VDS.RDF.Writing
{
/// <summary>
/// Possible URI Reference Types
/// </summary>
internal enum UriRefType : int
{
/// <summary>
/// Must be a QName
/// </summary>
QName = 1,
/// <summary>
/// May be a QName or a URI
/// </summary>
QNameOrUri = 2,
/// <summary>
/// URI Reference
/// </summary>
UriRef = 3,
/// <summary>
/// URI
/// </summary>
Uri = 4
}
/// <summary>
/// Class containing constants for possible Compression Levels
/// </summary>
/// <remarks>These are intended as guidance only, Writer implementations are free to interpret these levels as they desire or to ignore them entirely and use their own levels</remarks>
public static class WriterCompressionLevel
{
/// <summary>
/// No Compression should be used (-1)
/// </summary>
public const int None = -1;
/// <summary>
/// Minimal Compression should be used (0)
/// </summary>
public const int Minimal = 0;
/// <summary>
/// Default Compression should be used (1)
/// </summary>
public const int Default = 1;
/// <summary>
/// Medium Compression should be used (3)
/// </summary>
public const int Medium = 3;
/// <summary>
/// More Compression should be used (5)
/// </summary>
public const int More = 5;
/// <summary>
/// High Compression should be used (10)
/// </summary>
public const int High = 10;
}
/// <summary>
/// Class containing constants for standardised Writer Error Messages
/// </summary>
public static class WriterErrorMessages
{
/// <summary>
/// Error message produced when a User attempts to serialize a Graph containing Graph Literals
/// </summary>
private const string GraphLiteralsUnserializableError = "Graph Literal Nodes are not serializable in {0}";
/// <summary>
/// Error message produced when a User attempts to serialize a Graph containing Unknown Node Types
/// </summary>
private const string UnknownNodeTypeUnserializableError = "Unknown Node Types cannot be serialized as {0}";
/// <summary>
/// Error message produced when a User attempts to serialize a Graph containing Triples with Literal Subjects
/// </summary>
private const string LiteralSubjectsUnserializableError = "Triples with a Literal Subject are not serializable in {0}";
/// <summary>
/// Error message produced when a User attempts to serialize a Graph containing Triples with Literal Predicates
/// </summary>
private const string LiteralPredicatesUnserializableError = "Triples with a Literal Predicate are not serializable in {0}";
/// <summary>
/// Error message produced when a User attempts to serialized a Graph containing Triples with Graph Literal Predicates
/// </summary>
private const string GraphLiteralPredicatesUnserializableError = "Triples with a Graph Literal Predicate are not serializable in {0}";
/// <summary>
/// Error message produced when a User attempts to serialize a Graph containing Triples with Blank Node Predicates
/// </summary>
private const string BlankPredicatesUnserializableError = "Triples with a Blank Node Predicate are not serializable in {0}";
/// <summary>
/// Error message produced when a User attempts to serialize a Graph containing URIs which cannot be reduced to a URIRef or QName as required by the serialization
/// </summary>
public const string UnreducablePropertyURIUnserializable = "Unable to serialize this Graph since a Property has an unreducable URI";
/// <summary>
/// Error message produced when a User attempts to serialize a Graph containing collections where a collection item has more than one rdf:first triple
/// </summary>
public const string MalformedCollectionWithMultipleFirsts = "This RDF Graph contains more than one rdf:first Triple for an Item in a Collection which means the Graph is not serializable";
/// <summary>
/// Error messages produced when errors occur in a multi-threaded writing process
/// </summary>
public const string ThreadedOutputError = "One/more errors occurred while outputting RDF in {0} using a multi-threaded writing process";
/// <summary>
/// Error message produced when a User attempts to serialize a Variable Node in a format which does not support it
/// </summary>
public const string VariableNodesUnserializableError = "Variable Nodes cannot be serialized as {0}";
/// <summary>
/// Gets an Error message indicating that Graph Literals are not serializable with the appropriate RDF format name inserted in the error
/// </summary>
/// <param name="format">RDF format (syntax)</param>
/// <returns></returns>
public static string GraphLiteralsUnserializable(string format)
{
return string.Format(GraphLiteralsUnserializableError, format);
}
/// <summary>
/// Gets an Error message indicating that Unknown Node Types are not serializable with the appropriate RDF format name inserted in the error
/// </summary>
/// <param name="format">RDF format (syntax)</param>
/// <returns></returns>
public static string UnknownNodeTypeUnserializable(string format)
{
return string.Format(UnknownNodeTypeUnserializableError, format);
}
/// <summary>
/// Gets an Error message indicating that Variable Nodes are not serializable with the appropriate RDF format name inserted in the error
/// </summary>
/// <param name="format">RDF format (syntax)</param>
/// <returns></returns>
public static string VariableNodesUnserializable(string format)
{
return string.Format(VariableNodesUnserializableError, format);
}
/// <summary>
/// Gets an Error message indicating that Literal Subjects are not serializable with the appropriate RDF format name inserted in the error
/// </summary>
/// <param name="format">RDF format (syntax)</param>
/// <returns></returns>
public static string LiteralSubjectsUnserializable(string format)
{
return string.Format(LiteralSubjectsUnserializableError, format);
}
/// <summary>
/// Gets an Error message indicating that Literal Predicates are not serializable with the appropriate RDF format name inserted in the error
/// </summary>
/// <param name="format">RDF format (syntax)</param>
/// <returns></returns>
public static string LiteralPredicatesUnserializable(string format)
{
return string.Format(LiteralPredicatesUnserializableError, format);
}
/// <summary>
/// Gets an Error message indicating that Graph Literal Predicates are not serializable with the appropriate RDF format name inserted in the error
/// </summary>
/// <param name="format">RDF format (syntax)</param>
/// <returns></returns>
public static string GraphLiteralPredicatesUnserializable(string format)
{
return string.Format(GraphLiteralPredicatesUnserializableError, format);
}
/// <summary>
/// Gets an Error message indicating that Blank Node Predicates are not serializable with the appropriate RDF format name inserted in the error
/// </summary>
/// <param name="format">RDF format (syntax)</param>
/// <returns></returns>
public static string BlankPredicatesUnserializable(string format)
{
return string.Format(BlankPredicatesUnserializableError, format);
}
/// <summary>
/// Gets an Error message indicating that a multi-threading writer process failed
/// </summary>
/// <param name="format">RDF format (syntax)</param>
/// <returns></returns>
public static string ThreadedOutputFailure(string format)
{
return string.Format(ThreadedOutputError, format);
}
}
/// <summary>
/// Indicates which Segment of a Triple Node Output is being generated for
/// </summary>
/// <remarks>
/// Used by Writers and Formatters to ensure restrictions on which Nodes can appear where in the syntax are enforced
/// </remarks>
public enum TripleSegment
{
/// <summary>
/// Subject of the Triple
/// </summary>
Subject,
/// <summary>
/// Predicate of the Triple
/// </summary>
Predicate,
/// <summary>
/// Object of the Triple
/// </summary>
Object
}
/// <summary>
/// Controls what type of collections
/// </summary>
public enum CollectionSearchMode
{
/// <summary>
/// Find all collections
/// </summary>
All,
/// <summary>
/// Find explicit collections only (those specified with Blank Node syntax)
/// </summary>
ExplicitOnly,
/// <summary>
/// Find implicit collections only (those using rdf:first and rdf:rest)
/// </summary>
ImplicitOnly
}
/// <summary>
/// Class used to store Collections as part of the writing process for Compressing Writers
/// </summary>
public class OutputRdfCollection
{
private bool _explicit;
private bool _written = false;
private List<Triple> _triples = new List<Triple>();
/// <summary>
/// Creates a new Instance of a Collection
/// </summary>
/// <param name="explicitCollection">Whether the collection is explicit (specified using square bracket notation) or implicit (specified using normal parentheses)</param>
public OutputRdfCollection(bool explicitCollection)
{
_explicit = explicitCollection;
}
/// <summary>
/// Gets whether this is an Explicit collection (specified using square bracket notation)
/// </summary>
public bool IsExplicit => _explicit;
/// <summary>
/// Gets/Sets whether the Collection has been written
/// </summary>
public bool HasBeenWritten
{
get => _written;
set => _written = value;
}
/// <summary>
/// Gets the Triples that make up the Collection
/// </summary>
public List<Triple> Triples => _triples;
}
/// <summary>
/// Possible Output Formats for Nodes
/// </summary>
public enum NodeFormat
{
/// <summary>
/// Format for NTriples
/// </summary>
NTriples,
/// <summary>
/// Format for Turtle
/// </summary>
Turtle,
/// <summary>
/// Format for Notation 3
/// </summary>
Notation3,
/// <summary>
/// Format for Uncompressed Turtle
/// </summary>
UncompressedTurtle,
/// <summary>
/// Format for Uncompressed Notation 3
/// </summary>
UncompressedNotation3
}
/// <summary>
/// Helper methods for writers
/// </summary>
public static class WriterHelper
{
private static string _uriEncodeForXmlPattern = @"&([^;&\s]*)(?=\s|$|&)";
/// <summary>
/// Determines whether a Blank Node ID is valid as-is when serialised in NTriple like syntaxes (Turtle/N3/SPARQL)
/// </summary>
/// <param name="id">ID to test</param>
/// <returns></returns>
/// <remarks>If false is returned then the writer will alter the ID in some way</remarks>
public static bool IsValidBlankNodeID(string id)
{
if (id == null)
{
// Can't be null
return false;
}
else if (id.Equals(string.Empty))
{
// Can't be empty
return false;
}
else
{
char[] cs = id.ToCharArray();
if (char.IsDigit(cs[0]) || cs[0] == '-' || cs[0] == '_')
{
// Can't start with a Digit, Hyphen or Underscore
return false;
}
else
{
// Otherwise OK
return true;
}
}
}
/// <summary>
/// Determines whether a Blank Node ID is valid as-is when serialised as NTriples
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static bool IsValidStrictBlankNodeID(string id)
{
if (id == null)
{
// Can't be null
return false;
}
else if (id.Equals(string.Empty))
{
// Can't be empty
return false;
}
else
{
// All characters must be alphanumeric and not start with a digit in NTriples
char[] cs = id.ToCharArray();
return char.IsLetter(cs[0]) && cs.All(c => char.IsLetterOrDigit(c) && c <= 127);
}
}
/// <summary>
/// Determines whether a given Uri refers to one of the Default Graph URIs assigned to the default Graph when parsing from some RDF dataset syntax
/// </summary>
/// <param name="u">Uri to test</param>
/// <returns></returns>
[Obsolete("No longer required since all code that uses 'magic' URIs to refer to the default graph has been removed from the API", true)]
public static bool IsDefaultGraph(Uri u)
{
return u == null;
}
/// <summary>
/// Helper method which finds Collections expressed in the Graph which can be compressed into concise collection syntax constructs in some RDF syntaxes
/// </summary>
/// <param name="g">Graph to find collections in</param>
/// <param name="triplesDone">Triple Collection in which Triples that have been output are to be listed</param>
[Obsolete("Use the alternative overloads of this method which take an ICollectionCompressingWriterContext instead", true)]
public static Dictionary<INode, OutputRdfCollection> FindCollections(IGraph g, BaseTripleCollection triplesDone)
{
throw new NotSupportedException("No longer supported");
}
/// <summary>
/// Helper method which finds Collections expressed in the Graph which can be compressed into concise collection syntax constructs in some RDF syntaxes
/// </summary>
/// <param name="context">Writer Context</param>
/// <param name="mode">Collection Search Mode</param>
public static void FindCollections(ICollectionCompressingWriterContext context, CollectionSearchMode mode)
{
// Prepare the RDF Nodes we need
INode first, rest, nil;
first = context.Graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfListFirst));
rest = context.Graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfListRest));
nil = context.Graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfListNil));
// First we're going to look for implicit collections we can represent using the
// brackets syntax of (a b c)
if (mode == CollectionSearchMode.All || mode == CollectionSearchMode.ImplicitOnly)
{
// Find all rdf:rest rdf:nil Triples
foreach (Triple t in context.Graph.GetTriplesWithPredicateObject(rest, nil))
{
// If has named list node cannot compress
if (t.Subject.NodeType != NodeType.Blank)
{
break;
}
// Build the collection recursively
OutputRdfCollection c = new OutputRdfCollection(false);
// Get the thing that is the rdf:first related to this rdf:rest
Triple[] firsts = context.Graph.GetTriplesWithSubjectPredicate(t.Subject, first).ToArray();//context.Graph.GetTriples(relfirstsel).Distinct();
Triple temp = null;
if (firsts.Length > 1)
{
// Strange error
throw new RdfOutputException(WriterErrorMessages.MalformedCollectionWithMultipleFirsts);
}
else if (firsts.Length == 1)
{
// Stick this item onto the Stack
temp = firsts[0];
c.Triples.Add(temp);
}
// See if this thing is the rdf:rest of anything else
do
{
Triple[] ts = context.Graph.GetTriplesWithPredicateObject(rest, firsts.First().Subject).ToArray();
// Stop when there isn't a rdf:rest
if (ts.Length == 0)
{
break;
}
foreach (Triple t2 in ts)
{
firsts = context.Graph.GetTriplesWithSubjectPredicate(t2.Subject, first).Distinct(new FullTripleComparer(new FastNodeComparer())).ToArray();
if (firsts.Length > 1)
{
// Strange error
throw new RdfOutputException(WriterErrorMessages.MalformedCollectionWithMultipleFirsts);
}
else if (firsts.Length == 1)
{
// Stick this item onto the Stack
temp = firsts[0];
// If Item is a named list node cannot compress
if (temp.Subject.NodeType != NodeType.Blank)
{
break;
}
c.Triples.Add(temp);
}
}
} while (true);
// Can only compress if every List Node has a Blank Node Subject
if (c.Triples.All(x => x.Subject.NodeType == NodeType.Blank))
{
context.Collections.Add(firsts[0].Subject, c);
}
}
}
// Now we want to look for explicit collections which are representable
// using Blank Node syntax [p1 o1; p2 o2; p3 o3]
if (mode == CollectionSearchMode.All || mode == CollectionSearchMode.ExplicitOnly)
{
List<IBlankNode> bnodes = context.Graph.Nodes.BlankNodes().ToList();
foreach (IBlankNode b in bnodes)
{
if (context.Collections.ContainsKey(b))
{
continue;
}
List<Triple> ts = context.Graph.GetTriples(b).ToList();
ts.RemoveAll(t => t.Predicate.Equals(first));
ts.RemoveAll(t => t.Predicate.Equals(rest));
if (ts.Count <= 1)
{
// This Blank Node is only used once
// Add an empty explicit collection - we'll interpret this as [] later
context.Collections.Add(b, new OutputRdfCollection(true));
}
else
{
if (context.Graph.GetTriplesWithObject(b).Count() == 1)
{
ts.RemoveAll(t => t.Object.Equals(b));
}
OutputRdfCollection c = new OutputRdfCollection(true);
c.Triples.AddRange(ts);
context.Collections.Add(b, c);
}
}
}
// If no collections found then no further processing
if (context.Collections.Count == 0)
{
return;
}
// Once we've found all the Collections we need to check which are actually eligible for compression
List<KeyValuePair<INode, OutputRdfCollection>> cs = context.Collections.ToList();
// 1 - If all the Triples pertaining to a particular Node are in the Collection then a collection is not eligible
foreach (KeyValuePair<INode, OutputRdfCollection> kvp in cs)
{
OutputRdfCollection c = kvp.Value;
if (c.IsExplicit)
{
// For explicit collections if all Triples mentioning the Target Blank Node are in the Collection then can't compress
// If there are no Triples in the Collection then this is a single use Blank Node so can always compress
if (c.Triples.Count > 0 && c.Triples.Count == context.Graph.GetTriples(kvp.Key).Count())
{
// TODO: This doesn't work because it can conflict
// In this case we can remove a single Triple from the Collection and hope this allows us to compress
// context.Collections[kvp.Key].Triples.RemoveAt(0);
context.Collections.Remove(kvp.Key);
}
}
else
{
// For implicit collections if the number of Triples in the Collection is exactly ((t*3) - 1) those in the Graph then
// can't compress i.e. the collection is not linked to anything else
// Or if the number of mentions compared to the expected mentions differs by more than 1 then
// can't compress i.e. the collection is linked to more than one thing
int mentions = context.Graph.GetTriples(kvp.Key).Count();
int expectedMentions = ((c.Triples.Count * 3) - 1);
if (expectedMentions == mentions || mentions - expectedMentions != 1)
{
context.Collections.Remove(kvp.Key);
}
}
}
if (context.Collections.Count == 0)
{
return;
}
// 2 - Look for cyclic collection dependencies
cs = context.Collections.OrderByDescending(kvp => kvp.Value.Triples.Count).ToList();
// First build up a dependencies table
Dictionary<INode, HashSet<INode>> dependencies = new Dictionary<INode, HashSet<INode>>();
foreach (KeyValuePair<INode, OutputRdfCollection> kvp in cs)
{
OutputRdfCollection c = kvp.Value;
// Empty Blank Node Collections cannot be cyclic i.e. []
if (c.Triples.Count == 0)
{
continue;
}
// Otherwise check each Object of the Triples for other Blank Nodes
HashSet<INode> ds = new HashSet<INode>(new FastNodeComparer());
foreach (Triple t in c.Triples)
{
// Only care about Blank Nodes which aren't the collection root but are the root for another collection
if (t.Object.NodeType == NodeType.Blank && !t.Object.Equals(kvp.Key) && context.Collections.ContainsKey(t.Object))
{
ds.Add(t.Object);
}
}
if (ds.Count > 0)
{
dependencies.Add(kvp.Key, ds);
}
}
// Now go back through that table looking for cycles
foreach (INode n in dependencies.Keys)
{
HashSet<INode> ds = dependencies[n];
if (ds.Count == 0)
{
continue;
}
foreach (INode d in ds.ToList())
{
if (dependencies.ContainsKey(d))
{
foreach (INode dd in dependencies[d])
{
ds.Add(dd);
}
}
}
//We can tell if there is a cycle since ds will now contain n
if (ds.Contains(n))
{
context.Collections.Remove(n);
}
}
if (context.Collections.Count == 0)
{
return;
}
// Finally fill out the TriplesDone for each Collection
foreach (KeyValuePair<INode, OutputRdfCollection> kvp in context.Collections)
{
OutputRdfCollection c = kvp.Value;
if (c.IsExplicit)
{
foreach (Triple t in c.Triples)
{
context.TriplesDone.Add(t);
}
}
else
{
INode temp = kvp.Key;
for (int i = 0; i < c.Triples.Count; i++)
{
context.TriplesDone.Add(c.Triples[i]);
if (i < c.Triples.Count - 1)
{
context.TriplesDone.Add(new Triple(c.Triples[i].Subject, rest, c.Triples[i + 1].Subject));
}
else
{
context.TriplesDone.Add(new Triple(c.Triples[i].Subject, rest, nil));
}
}
}
}
// As a final sanity check look for any Explicit Collection Key which is used more than once
cs = context.Collections.ToList();
foreach (KeyValuePair<INode, OutputRdfCollection> kvp in cs)
{
OutputRdfCollection c = kvp.Value;
if (c.IsExplicit)
{
int mentions = context.Graph.GetTriples(kvp.Key).Count(t => !context.TriplesDone.Contains(t));
if (mentions - 1 > c.Triples.Count)
{
context.Collections.Remove(kvp.Key);
}
}
}
}
/// <summary>
/// Helper method which finds Collections expressed in the Graph which can be compressed into concise collection syntax constructs in some RDF syntaxes
/// </summary>
/// <param name="context">Writer Context</param>
public static void FindCollections(ICollectionCompressingWriterContext context)
{
FindCollections(context, CollectionSearchMode.All);
}
/// <summary>
/// Encodes values for use in XML
/// </summary>
/// <param name="value">Value to encode</param>
/// <returns>
/// The value with any ampersands escaped to &
/// </returns>
public static string EncodeForXml(string value)
{
while (Regex.IsMatch(value, _uriEncodeForXmlPattern))
{
value = Regex.Replace(value, _uriEncodeForXmlPattern, "&$1");
}
if (value.EndsWith("&"))
{
value += "amp;";
}
return value.Replace("<", "<")
.Replace(">", ">")
.Replace("'", "'")
.Replace("\"", """);
}
/// <summary>
/// Get a list of all triples in the specified graph, sorted by subject and then predicate.
/// </summary>
/// <param name="graph">The graph whose triples are to be returned</param>
/// <returns>A list of the triples in <paramref name="graph"/> sorted by their subject and then predicate.</returns>
public static List<Triple> GetTriplesSortedBySubjectPredicate(IGraph graph)
{
var ts = graph.Triples.ToList();
SortTriplesBySubjectPredicate(ts);
return ts;
}
/// <summary>
/// Sort the provided list of triples by subject and then predicate. The list is modified in-place
/// </summary>
/// <param name="ts">The list of triples to be sorted</param>
public static void SortTriplesBySubjectPredicate(List<Triple> ts)
{
var capacity = ts.Count;
var sortHelperDictionary = new Dictionary<INode, Dictionary<INode, List<Triple>>>(capacity);
// Fill dictionary
foreach (var triple in ts)
{
if (!sortHelperDictionary.ContainsKey(triple.Subject))
{
sortHelperDictionary.Add(triple.Subject, new Dictionary<INode, List<Triple>>());
}
if (!sortHelperDictionary[triple.Subject].ContainsKey(triple.Predicate))
{
sortHelperDictionary[triple.Subject].Add(triple.Predicate, new List<Triple>());
}
sortHelperDictionary[triple.Subject][triple.Predicate].Add(triple);
}
ts.Clear();
var keys = sortHelperDictionary.Keys.ToArray();
Array.Sort(keys, new FastNodeComparer());
foreach (var subjectKey in keys)
{
var predicateKeys = sortHelperDictionary[subjectKey].Keys.ToArray();
Array.Sort(predicateKeys, new FastNodeComparer());
foreach (var predicateKey in predicateKeys)
{
ts.AddRange(sortHelperDictionary[subjectKey][predicateKey]);
}
}
}
}
} | 41.514877 | 195 | 0.544047 | [
"MIT"
] | TaviTruman/dotnetrdf | Libraries/dotNetRDF/Writing/WriterUtilities.cs | 32,091 | C# |
using MediatR;
namespace Plannoy.Application.CommonInterfaces
{
public interface ICommandHandler<TCommand> : IRequestHandler<TCommand, bool> where TCommand : class, ICommand
{
}
} | 24.125 | 113 | 0.756477 | [
"MIT"
] | douglasramos/plannoy | src/Application/CommonInterfaces/ICommandHandler.cs | 195 | C# |
// IPixelOperation.cs
//
// Copyright (C) BEditor
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
namespace BEditor.Drawing.PixelOperation
{
/// <summary>
/// Represents a pixels operation.
/// </summary>
public interface IPixelOperation
{
/// <summary>
/// Operate on a single pixel.
/// </summary>
/// <param name="pos">The index of the pixel to operate on.</param>
public void Invoke(int pos);
}
} | 25.857143 | 75 | 0.622468 | [
"MIT"
] | b-editor/BEditor | src/libraries/BEditor.Drawing/PixelOperation/IPixelOperation.cs | 545 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if NETFX_CORE
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
namespace HelixToolkit.UWP
#else
using System.Windows;
using System.Windows.Controls;
namespace HelixToolkit.Wpf.SharpDX
#endif
{
namespace Controls
{
public class HelixItemsControl : ItemsControl
{
public HelixItemsControl()
{
#if NETFX_CORE
ManipulationMode = Windows.UI.Xaml.Input.ManipulationModes.None;
#else
Focusable = false;
Visibility = Visibility.Collapsed;
#endif
IsHitTestVisible = false;
this.DefaultStyleKey = typeof(HelixItemsControl);
}
protected override Size ArrangeOverride(Size finalSize)
{
return new Size();
}
protected override Size MeasureOverride(Size availableSize)
{
return new Size();
}
}
}
}
| 23.543478 | 80 | 0.602955 | [
"MIT"
] | B3zaleel/helix-toolkit | Source/HelixToolkit.SharpDX.SharedModel/Controls/HelixItemsControl.cs | 1,085 | C# |
/////////////////////////////////////////
// //
// "lol why do u have so many unused //
// references that's dum." //
// -JT //
/////////////////////////////////////////
using System; //
using System.Collections.Generic; //
using System.Linq; // <------------ @_@ [ofug]
using System.Text; //
using System.Threading.Tasks; //
//-------------------------------------//
using ld36Game.Managers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace ld36Game.GameStates
{
class PlayingState : BaseGameState
{
EntityManager eManager;
LevelManager levelManager;
AssetManager aManager;
TowerManager tManager;
KeyboardState oldState;
public PlayingState(StateManager p) : base(p)
{
eManager = parent.game.eManager;
levelManager = parent.game.levelManager;
aManager = parent.game.aManager;
tManager = parent.game.tManager;
levelManager.loadLevel("LudumDareLevel.dat");
eManager.prepLevel();
}
public override void draw(SpriteBatch spriteBatch)
{
MouseState ms = Mouse.GetState();
Color tileColor = Color.White;
//if (ms.LeftButton == ButtonState.Pressed) tileColor = Color.LightPink;
for (int j = 0; j < tManager.getTowerTypeCount(); ++j)
{
Vector2 pos = new Vector2(700.0f, 100.0f + j * 100.0f);
if(eManager.isPaused()) drawTexture(spriteBatch, "character-bits", pos, 0.0f, Vector2.Zero, CharacterSpriteManager.getBody(0), 4.0f, Color.White);
else drawTexture(spriteBatch, "character-bits", pos, 0.0f, Vector2.Zero, CharacterSpriteManager.getBody(4), 4.0f, Color.White);
}
for (int i = 0; i < MapManager.getTileCount(); ++i)//this should switch to the level loader???
{
int xPos = (i % 20) * 32;
int yPos = (i / 20) * 32;
int[] testMap = levelManager.getMap();
if (ms.X >= xPos && ms.X < xPos + 32 && ms.Y >= yPos && ms.Y < yPos + 32 && ms.LeftButton == ButtonState.Pressed)
{
if (testMap[i] >= 3 && testMap[i] <= 11) tileColor = Color.LightPink;
else tileColor = Color.LightBlue;
parent.game.setMouseColor(tileColor);
}
else tileColor = Color.White;
//draw all the grass
int j = i / 20;
if ((i + j) % 2 == 0) spriteBatch.Draw(aManager.getTexture("map-tiles"), new Vector2(xPos, yPos), MapManager.getTile(0), tileColor, 0.0f, new Vector2(), 2.0f, SpriteEffects.None, 0.0f);
else spriteBatch.Draw(aManager.getTexture("map-tiles"), new Vector2(xPos, yPos), MapManager.getTile(1), tileColor, 0.0f, new Vector2(), 2.0f, SpriteEffects.None, 0.0f);
//draw roads from the map above
if (testMap[i] > 1) //not a grass tile
{
spriteBatch.Draw(aManager.getTexture("map-tiles"), new Vector2(xPos, yPos), MapManager.getTile(testMap[i]), tileColor, 0.0f, new Vector2(), 2.0f, SpriteEffects.None, 0.0f);
}
}
if (tManager.getSelectedTowerType() >= 0)
{
drawTexture(spriteBatch, "character-bits", new Vector2(ms.X-16, ms.Y-16), 0.0f, Vector2.Zero, CharacterSpriteManager.getBody(0), 2.0f, parent.game.getMouseColor());
}
for (int i = 0; i < tManager.getTowerCount(); ++i)
{
Tower t = tManager.getTower(i);
drawTexture(spriteBatch, "character-bits", t.position, 0.0f, new Vector2(0.0f, 8.0f), CharacterSpriteManager.getBody(0), 2.0f, Color.White);
}
for (int i = 0; i < tManager.getBulletCount(); ++i)
{
Bullet t = tManager.getBullet(i);
drawTexture(spriteBatch, "character-bits", t.position, 0.0f, new Vector2(8.0f, 8.0f), CharacterSpriteManager.getBody(0), 2.0f, Color.White);
}
for (int i = eManager.getCount()-1; i >= 0; --i)
{
Entity e = eManager.getEntity(i);
if (e != null)
{
float adjustedAngle = e.rotationAngle + e.rotationOffset;
if (e.spriteIndexes[0] >= 0) drawTexture(spriteBatch, e.spriteId, e.position, adjustedAngle, e.center, CharacterSpriteManager.getBody(e.spriteIndexes[0]), 2.0f, Color.White);
if (e.spriteIndexes[2] >= 0) drawTexture(spriteBatch, e.spriteId, e.position, adjustedAngle, e.center, CharacterSpriteManager.getPants(e.spriteIndexes[2]), 2.0f, Color.White);
if (e.spriteIndexes[1] >= 0) drawTexture(spriteBatch, e.spriteId, e.position, adjustedAngle, e.center, CharacterSpriteManager.getShirt(e.spriteIndexes[1]), 2.0f, Color.White);
if (e.spriteIndexes[3] >= 0) drawTexture(spriteBatch, e.spriteId, e.position, adjustedAngle, e.center, CharacterSpriteManager.getHeadpiece(e.spriteIndexes[3]), 2.0f, Color.White);
if (e.spriteIndexes[4] >= 0) drawTexture(spriteBatch, e.spriteId, e.position, adjustedAngle, e.center, CharacterSpriteManager.getWeapon(e.spriteIndexes[4]), 2.0f, Color.White);
if (e.spriteIndexes[5] >= 0) drawTexture(spriteBatch, e.spriteId, e.position, adjustedAngle, e.center, CharacterSpriteManager.getShield(e.spriteIndexes[5]), 2.0f, Color.White);
}
}
}
private void drawTexture(SpriteBatch spriteBatch, string id, Vector2 position, float adjustedAngle, Vector2 center, Rectangle rect, float scale, Color color)
{
spriteBatch.Draw(aManager.getTexture(id), position, rect, color, adjustedAngle, center, scale, SpriteEffects.None, 0.0f);
}
public override void update(GameTime gameTime)
{
KeyboardState kState = Keyboard.GetState();
if (kState.IsKeyDown(Keys.Escape)) parent.game.Exit();
if (kState.IsKeyDown(Keys.P) && oldState.IsKeyUp(Keys.P)) eManager.togglePaused();
eManager.update(gameTime, parent.game.levelManager);
tManager.update(gameTime);
if(parent.game.getPlayerStats().lives <= 0)
{
//game over.
parent.setEndGameState(false);
}
if(eManager.getRemainingEnemyCount() <= 0)
{
parent.setEndGameState(true);
}
oldState = kState;
}
}
}
| 48.330986 | 201 | 0.557774 | [
"MIT"
] | yacklebeam/ludumdare36 | ld36Game/ld36Game/GameStates/PlayingState.cs | 6,865 | C# |
using System;
namespace Eventos1
{
class Program
{
public static void NotificarCambioNombre(string msg)
{
//imprimos mensaje aviso.
Console.WriteLine("¡El nombre del empleado a cambiado!");
Console.WriteLine(msg);
}
public static void Main(string[] args)
{
Empleado MiEmpleado = new Empleado("Ramiro");
MiEmpleado.NombreCambiado +=NotificarCambioNombre; //suscribiendo
Console.Write("Nombre empleado: ");
MiEmpleado.setNombre(Console.ReadLine());
Console.Write("Pulsa cualquier tecla para continuar . . . ");
Console.ReadKey(true);
}
}
}
| 27.307692 | 77 | 0.58169 | [
"MIT"
] | cmontellanob/programacionIII | Eventos1/Eventos1/Program.cs | 713 | C# |
using System.Text.Json.Serialization;
namespace DotNetBungieAPI.Generated.Models.Destiny.Milestones;
/// <summary>
/// Part of our dynamic, localized Milestone content is arbitrary categories of items. These are built in our content management system, and thus aren't the same as programmatically generated rewards.
/// </summary>
public sealed class DestinyMilestoneContentItemCategory
{
[JsonPropertyName("title")]
public string Title { get; init; }
[JsonPropertyName("itemHashes")]
public List<uint> ItemHashes { get; init; } // DestinyInventoryItemDefinition
}
| 34.647059 | 204 | 0.762309 | [
"MIT"
] | EndGameGl/.NetBungieAPI | DotNetBungieAPI.Generated/Models/Destiny/Milestones/DestinyMilestoneContentItemCategory.cs | 589 | C# |
// ITrigger.cs in bukkitgui2/bukkitgui2
// Created 2014/08/10
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
//
// ©Bertware, visit http://bertware.net
namespace Net.Bertware.Bukkitgui2.AddOn.Tasker.Trigger
{
public interface ITrigger
{
event TaskerEventArgs TaskerTriggerFired;
/// <summary>
/// Name of the trigger
/// </summary>
string Name { get; }
/// <summary>
/// Description of the trigger
/// </summary>
string Description { get; }
/// <summary>
/// Description of the trigger parameters
/// </summary>
string ParameterDescription { get; }
/// <summary>
/// Validate parameter input
/// </summary>
/// <param name="inputText">The input to validate</param>
/// <returns>Returns True if valid</returns>
bool ValidateInput(string inputText);
/// <summary>
/// Load a trigger by name and parameter
/// </summary>
/// <param name="parameters"></param>
void Load(string parameters);
/// <summary>
/// The saved parameters for an instance of this trigger
/// </summary>
string Parameters { get; set; }
/// <summary>
/// If this trigger instance is enabled
/// </summary>
bool Enabled { get; }
/// <summary>
/// Enable this trigger
/// </summary>
void Enable();
/// <summary>
/// Disable this trigger
/// </summary>
void Disable();
}
} | 23.84375 | 87 | 0.629096 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Bertware/bukkitgui2 | bukkitgui2/AddOn/Tasker/Trigger/ITrigger.cs | 1,529 | C# |
using System;
using XFExpandableListView.Abstractions;
using XFExpandableListView.Models;
namespace XFExpandableListViewSample.Models
{
public class FruitGroup : ExpandableGroup<Fruit>, IExpandableGroup
{
public string Title { get; set; }
public string ShortName { get; set; }
public FruitGroup(string title, string shortName, bool expanded = true) : base(Guid.NewGuid())
{
Title = title;
ShortName = shortName;
IsExpanded = expanded;
}
public override IExpandableGroup NewInstance()
{
return new FruitGroup(Title, ShortName, IsExpanded) { Id = Id };
}
}
}
| 27.4 | 102 | 0.633577 | [
"Apache-2.0"
] | Jouna77/XFExpandableListView | src/Sample/XFExpandableListViewSample/Models/Fruits/FruitGroup.cs | 687 | C# |
namespace GF.UCenter.SDK.AppClient
{
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Common.Portable.Models.AppClient;
using Common.Portable.Models.Ip;
using Common.SDK;
/// <summary>
/// Provide a UCenter client class.
/// </summary>
public class UCenterClient
{
private readonly string host;
private readonly UCenterHttpClient httpClient;
/// <summary>
/// Initializes a new instance of the <see cref="UCenterClient" /> class.
/// </summary>
/// <param name="host">Indicating the host address.</param>
public UCenterClient(string host)
{
this.httpClient = new UCenterHttpClient();
this.host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host;
}
/// <summary>
/// Register account.
/// </summary>
/// <param name="info">Indicating the account information.</param>
/// <returns>Async response.</returns>
public async Task<AccountRegisterResponse> AccountRegisterAsync(AccountRegisterInfo info)
{
var url = this.GenerateApiEndpoint("account", "register");
var response = await this.httpClient.SendAsyncWithException<AccountRegisterInfo, AccountRegisterResponse>(
HttpMethod.Post,
url,
info);
return response;
}
/// <summary>
/// Login account.
/// </summary>
/// <param name="info">Indicating the account information.</param>
/// <returns>Async response.</returns>
public async Task<AccountLoginResponse> AccountLoginAsync(AccountLoginInfo info)
{
var url = this.GenerateApiEndpoint("account", "login");
var response = await this.httpClient.SendAsyncWithException<AccountLoginInfo, AccountLoginResponse>(
HttpMethod.Post,
url,
info);
return response;
}
/// <summary>
/// Login guest account.
/// </summary>
/// <returns>Async response.</returns>
public async Task<AccountGuestLoginResponse> AccountGuestLoginAsync()
{
var url = this.GenerateApiEndpoint("account", "guest");
var response = await this.httpClient.SendAsyncWithException<AccountLoginInfo, AccountGuestLoginResponse>(
HttpMethod.Post,
url,
null);
return response;
}
/// <summary>
/// Convert account.
/// </summary>
/// <param name="info">Indicating the account information.</param>
/// <returns>Async response.</returns>
public async Task<AccountConvertResponse> AccountConvertAsync(AccountConvertInfo info)
{
var url = this.GenerateApiEndpoint("account", "convert");
var response = await this.httpClient.SendAsyncWithException<AccountConvertInfo, AccountConvertResponse>(
HttpMethod.Post,
url,
info);
return response;
}
/// <summary>
/// Reset account password.
/// </summary>
/// <param name="info">Indicating the account information.</param>
/// <returns>Async response.</returns>
public async Task<AccountResetPasswordResponse> AccountResetPasswordAsync(AccountResetPasswordInfo info)
{
var url = this.GenerateApiEndpoint("account", "resetpassword");
return await this.httpClient.SendAsyncWithException<AccountResetPasswordInfo, AccountResetPasswordResponse>(
HttpMethod.Post,
url,
info);
}
/// <summary>
/// Upload account profile image.
/// </summary>
/// <param name="accountId">Indicating the account id.</param>
/// <param name="imagePath">Indicating the image file path.</param>
/// <returns>Async response.</returns>
public async Task<AccountUploadProfileImageResponse> AccountUploadProfileImagesync(
string accountId,
string imagePath)
{
const int BufferSize = 1024 * 1024;
using (var stream = new FileStream(
imagePath,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
BufferSize,
true))
{
return await this.AccountUploadProfileImagesync(accountId, stream);
}
}
/// <summary>
/// Register account.
/// </summary>
/// <param name="accountId">Indicating the account id.</param>
/// <param name="imageStream">Indicating the image stream.</param>
/// <returns>Async response.</returns>
public async Task<AccountUploadProfileImageResponse> AccountUploadProfileImagesync(
string accountId,
Stream imageStream)
{
var url = this.GenerateApiEndpoint("account", $"upload/{accountId}");
var content = new StreamContent(imageStream);
content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return await this.httpClient.SendAsyncWithException<HttpContent, AccountUploadProfileImageResponse>(
HttpMethod.Post,
url,
content);
}
/// <summary>
/// Get client IP information.
/// </summary>
/// <returns>Async response.</returns>
public async Task<IPInfoResponse> GetClientIpInfoAsync()
{
var url = this.GenerateApiEndpoint("appclient", "ip");
var response = await this.httpClient.SendAsyncWithException<string, IPInfoResponse>(
HttpMethod.Post,
url,
null);
return response;
}
/// <summary>
/// Get application configuration.
/// </summary>
/// <param name="appId">Indicating the application id.</param>
/// <returns>Async response.</returns>
public async Task<AppConfigurationResponse> GetAppConfigurationAsync(string appId)
{
var url = this.GenerateApiEndpoint("appclient", $"conf?appId={appId}");
var response = await this.httpClient.SendAsyncWithException<string, AppConfigurationResponse>(
HttpMethod.Post,
url,
null);
return response;
}
private string GenerateApiEndpoint(string controller, string route, string queryString = null)
{
var url = $"{this.host}/api/{controller}/{route}";
if (!string.IsNullOrEmpty(queryString))
{
url = $"{url}/?{queryString}";
}
return url;
}
}
} | 36.578947 | 120 | 0.574964 | [
"MIT"
] | lichunlincn/GF.UCenter | GF.UCenter.SDK.AppClient/UCenterClient.cs | 6,952 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Northwind.Entity.Base;
using Northwind.Entity.Dto;
using Northwind.Entity.IBase;
using Northwind.Entity.Models;
using Northwind.Interface;
using Northwind.WebApi.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Northwind.WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ApiBaseController<ICustomerService, Customer, DtoCustomer>
{
private readonly ICustomerService customerService;
public CustomerController(ICustomerService customerService) : base(customerService)
{
this.customerService = customerService;
}
[HttpGet("GetByStringId")]
public IResponse<DtoCustomer> FindCustomer(string customerId)
{
try
{
var response = customerService.GetByStringId(customerId);
return response;
}
catch (Exception ex)
{
return new Response<DtoCustomer>
{
Message = $"Error: {ex.Message}",
StatusCode = StatusCodes.Status500InternalServerError,
Data = null
};
}
}
}
}
| 29.020833 | 96 | 0.63173 | [
"MIT"
] | 142-Bupa-Acibadem-FullStack-Bootcamp/week-5-assignment-1-corskaya | Northwind.WebApi/Controllers/CustomerController.cs | 1,395 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Xml;
namespace ILR
{
public class LearnerContact : ChildEntity, IDataErrorInfo
{
#region Accessors
public override bool IsComplete
{
get
{
return this.ContType != null && this.LocType != null && (this.LocType!=1 || (this.PostAdd!=null && this.PostAdd.IsComplete));
}
}
#endregion
#region ILR Properties
public int? LocType { get { string LocType = XMLHelper.GetChildValue("LocType", Node, NSMgr); return (LocType != null ? int.Parse(LocType) : (int?)null); } set { XMLHelper.SetChildValue("LocType", value, Node, NSMgr); } }
public int? ContType { get { string ContType = XMLHelper.GetChildValue("ContType", Node, NSMgr); return (ContType != null ? int.Parse(ContType) : (int?)null); } set { XMLHelper.SetChildValue("ContType", value, Node, NSMgr); } }
public string PostCode { get { return XMLHelper.GetChildValue("PostCode", Node, NSMgr); } set { XMLHelper.SetChildValue("PostCode", value, Node, NSMgr); } }
public string TelNumber { get { return XMLHelper.GetChildValue("TelNumber", Node, NSMgr); } set { XMLHelper.SetChildValue("TelNumber", value, Node, NSMgr); } }
public string Email { get { return XMLHelper.GetChildValue("Email", Node, NSMgr); } set { XMLHelper.SetChildValue("Email", value, Node, NSMgr); } }
#endregion
#region ILR Child Entites
public PostAdd PostAdd;
#endregion
#region Child Entity Creation
public PostAdd CreatePostAdd()
{
XmlNode newNode = Node.OwnerDocument.CreateElement("PostAdd", NSMgr.LookupNamespace("ia"));
PostAdd = new PostAdd(newNode, NSMgr);
Node.AppendChild(newNode);
return PostAdd;
}
#endregion
#region Constructors
internal LearnerContact(XmlNode Node, XmlNamespaceManager NSMgr)
{
this.Node = Node;
this.NSMgr = NSMgr;
if (LocType == 1 && ContType == 2)
{
XmlNode postAddNode = Node.SelectSingleNode("./ia:PostAdd", NSMgr);
if(postAddNode!=null)
PostAdd=new PostAdd(postAddNode, NSMgr);
}
}
internal LearnerContact(LearnerContact MigrationLearnerContact, XmlNode Node, XmlNamespaceManager NSMgr)
{
this.Node = Node;
this.NSMgr = NSMgr;
this.LocType = MigrationLearnerContact.LocType;
this.ContType = MigrationLearnerContact.ContType;
this.Email = MigrationLearnerContact.Email;
this.TelNumber = MigrationLearnerContact.TelNumber;
this.PostCode = MigrationLearnerContact.PostCode;
if (MigrationLearnerContact.PostAdd != null)
{
XmlNode newNode = Node.OwnerDocument.CreateElement("PostAdd", NSMgr.LookupNamespace("ia"));
this.PostAdd = new PostAdd(MigrationLearnerContact.PostAdd, newNode, NSMgr);
Node.AppendChild(newNode);
}
}
#endregion
#region Methods
public void Delete(PostAdd postAdd)
{
Node.RemoveChild(postAdd.Node);
this.PostAdd = null;
}
#endregion
#region IDataErrorInfo Members
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "LocType")
{
if (LocType != null && LocType.ToString().Length > 3)
{
result = "LocType exceeds maximum length (3).";
//LocType = (int?)int.Parse(LocType.ToString().Substring(0, 3));
}
}
if (columnName == "ContType")
{
if (ContType != null && ContType.ToString().Length > 2)
{
result = "ContType exceeds maximum length (2).";
//ContType = (int?)int.Parse(ContType.ToString().Substring(0, 2));
}
}
return result;
}
}
#endregion
}
}
| 34.991803 | 235 | 0.587491 | [
"MIT"
] | SkillsFundingAgency/ILR-Learner-Entry | ILR Learner Entry 1516/ILR/LearnerContact.cs | 4,271 | C# |
namespace Yorozu.ComponentTween
{
public enum EaseType
{
Linear,
InSine,
OutSine,
InOutSine,
InQuad,
OutQuad,
InOutQuad,
InCubic,
OutCubic,
InOutCubic,
InQuart,
OutQuart,
InOutQuart,
InQuint,
OutQuint,
InOutQuint,
InExpo,
OutExpo,
InOutExpo,
InCirc,
OutCirc,
InOutCirc,
InElastic,
OutElastic,
InOutElastic,
InBack,
OutBack,
InOutBack,
InBounce,
OutBounce,
InOutBounce,
Custom,
}
}
| 11.487179 | 31 | 0.676339 | [
"MIT"
] | yayorozu/UnityComponentTween | Script/Ease/EaseType.cs | 448 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the swf-2012-01-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.SimpleWorkflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleWorkflow.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ActivityTaskStatus Object
/// </summary>
public class ActivityTaskStatusUnmarshaller : IUnmarshaller<ActivityTaskStatus, XmlUnmarshallerContext>, IUnmarshaller<ActivityTaskStatus, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
ActivityTaskStatus IUnmarshaller<ActivityTaskStatus, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ActivityTaskStatus Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
ActivityTaskStatus unmarshalledObject = new ActivityTaskStatus();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("cancelRequested", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.CancelRequested = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static ActivityTaskStatusUnmarshaller _instance = new ActivityTaskStatusUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ActivityTaskStatusUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.228261 | 167 | 0.647825 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/SimpleWorkflow/Generated/Model/Internal/MarshallTransformations/ActivityTaskStatusUnmarshaller.cs | 3,149 | C# |
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace AspNetCoreHero.Boilerplate.Web.ViewModels.Authorization
{
public class LogoutViewModel
{
[BindNever]
public string RequestId { get; set; }
}
} | 20.727273 | 65 | 0.70614 | [
"MIT"
] | dbriman/openiddict | AspNetCoreHero.Boilerplate.Web/ViewModels/Authorization/LogoutViewModel.cs | 230 | 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("Uno.Domain")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Uno.Domain")]
[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("a2a9724d-dfe1-4d3b-afd6-a58e4e4beb85")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.743001 | [
"MIT"
] | bedasa/UnoCustomer | Uno/Uno.Domain/Properties/AssemblyInfo.cs | 1,396 | C# |
namespace MassTransit.GrpcTransport
{
using System.Collections.Generic;
using Fabric;
public interface IGrpcHostNode :
IGrpcNode
{
TopologyHandle AddTopology(Contracts.Topology topology, TopologyHandle handle = default);
IEnumerable<Contracts.Topology> GetTopology();
}
}
| 21.266667 | 97 | 0.708464 | [
"ECL-2.0",
"Apache-2.0"
] | sinch/MassTransit | src/Transports/MassTransit.GrpcTransport/GrpcTransport/IGrpcHostNode.cs | 319 | C# |
namespace TestApp.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class _4 : DbMigration
{
public override void Up()
{
AddColumn("dbo.Categories", "Coef", c => c.Double(nullable: false));
}
public override void Down()
{
DropColumn("dbo.Categories", "Coef");
}
}
}
| 21.105263 | 80 | 0.53616 | [
"MIT"
] | Legendar11/AdaptiveDifficultyTest | TestApp/Migrations/201803201040167_4.cs | 401 | C# |
// ZipDirEntry.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2006-2011 Dino Chiesa .
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-July-11 12:03:03>
//
// ------------------------------------------------------------------
//
// This module defines members of the ZipEntry class for reading the
// Zip file central directory.
//
// Created: Tue, 27 Mar 2007 15:30
//
// ------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace Ionic.Zip
{
partial class ZipEntry
{
/// <summary>
/// True if the referenced entry is a directory.
/// </summary>
internal bool AttributesIndicateDirectory
{
get { return ((_InternalFileAttrs == 0) && ((_ExternalFileAttrs & 0x0010) == 0x0010)); }
}
internal void ResetDirEntry()
{
// __FileDataPosition is the position of the file data for an entry.
// It is _RelativeOffsetOfLocalHeader + size of local header.
// We cannot know the __FileDataPosition until we read the local
// header.
// The local header is not necessarily the same length as the record
// in the central directory.
// Set to -1, to indicate we need to read this later.
this.__FileDataPosition = -1;
// set _LengthOfHeader to 0, to indicate we need to read later.
this._LengthOfHeader = 0;
// reset the copy counter because we've got a good entry now
CopyHelper.Reset();
}
/// <summary>
/// Provides a human-readable string with information about the ZipEntry.
/// </summary>
public string Info
{
get
{
var builder = new System.Text.StringBuilder();
builder
.Append(string.Format(" ZipEntry: {0}\n", this.FileName))
.Append(string.Format(" Version Made By: {0}\n", this._VersionMadeBy))
.Append(string.Format(" Needed to extract: {0}\n", this.VersionNeeded));
if (this._IsDirectory)
builder.Append(" Entry type: directory\n");
else
{
builder.Append(string.Format(" File type: {0}\n", this._IsText? "text":"binary"))
.Append(string.Format(" Compression: {0}\n", this.CompressionMethod))
.Append(string.Format(" Compressed: 0x{0:X}\n", this.CompressedSize))
.Append(string.Format(" Uncompressed: 0x{0:X}\n", this.UncompressedSize))
.Append(string.Format(" CRC32: 0x{0:X8}\n", this._Crc32));
}
builder.Append(string.Format(" Disk Number: {0}\n", this._diskNumber));
if (this._RelativeOffsetOfLocalHeader > 0xFFFFFFFF)
builder
.Append(string.Format(" Relative Offset: 0x{0:X16}\n", this._RelativeOffsetOfLocalHeader));
else
builder
.Append(string.Format(" Relative Offset: 0x{0:X8}\n", this._RelativeOffsetOfLocalHeader));
builder
.Append(string.Format(" Bit Field: 0x{0:X4}\n", this._BitField))
.Append(string.Format(" Encrypted?: {0}\n", this._sourceIsEncrypted))
.Append(string.Format(" Timeblob: 0x{0:X8}\n", this._TimeBlob))
.Append(string.Format(" Time: {0}\n", Ionic.Zip.SharedUtilities.PackedToDateTime(this._TimeBlob)));
builder.Append(string.Format(" Is Zip64?: {0}\n", this._InputUsesZip64));
if (!string.IsNullOrEmpty(this._Comment))
{
builder.Append(string.Format(" Comment: {0}\n", this._Comment));
}
builder.Append("\n");
return builder.ToString();
}
}
// workitem 10330
private class CopyHelper
{
private static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex(" \\(copy (\\d+)\\)$");
private static int callCount = 0;
internal static void Reset()
{
callCount = 0;
}
internal static string AppendCopyToFileName(string f)
{
callCount++;
if (callCount > 25)
throw new OverflowException("overflow while creating filename");
int n = 1;
int r = f.LastIndexOf(".");
if (r == -1)
{
// there is no extension
System.Text.RegularExpressions.Match m = re.Match(f);
if (m.Success)
{
n = Int32.Parse(m.Groups[1].Value) + 1;
string copy = String.Format(" (copy {0})", n);
f = f.Substring(0, m.Index) + copy;
}
else
{
string copy = String.Format(" (copy {0})", n);
f = f + copy;
}
}
else
{
//System.Console.WriteLine("HasExtension");
System.Text.RegularExpressions.Match m = re.Match(f.Substring(0, r));
if (m.Success)
{
n = Int32.Parse(m.Groups[1].Value) + 1;
string copy = String.Format(" (copy {0})", n);
f = f.Substring(0, m.Index) + copy + f.Substring(r);
}
else
{
string copy = String.Format(" (copy {0})", n);
f = f.Substring(0, r) + copy + f.Substring(r);
}
//System.Console.WriteLine("returning f({0})", f);
}
return f;
}
}
/// <summary>
/// Reads one entry from the zip directory structure in the zip file.
/// </summary>
///
/// <param name="zf">
/// The zipfile for which a directory entry will be read. From this param, the
/// method gets the ReadStream and the expected text encoding
/// (ProvisionalAlternateEncoding) which is used if the entry is not marked
/// UTF-8.
/// </param>
///
/// <param name="previouslySeen">
/// a list of previously seen entry names; used to prevent duplicates.
/// </param>
///
/// <returns>the entry read from the archive.</returns>
internal static ZipEntry ReadDirEntry(ZipFile zf,
Dictionary<String,Object> previouslySeen)
{
System.IO.Stream s = zf.ReadStream;
System.Text.Encoding expectedEncoding = (zf.AlternateEncodingUsage == ZipOption.Always)
? zf.AlternateEncoding
: ZipFile.DefaultEncoding;
while (true)
{
int signature = Ionic.Zip.SharedUtilities.ReadSignature(s);
// return null if this is not a local file header signature
if (IsNotValidZipDirEntrySig(signature))
{
s.Seek(-4, System.IO.SeekOrigin.Current);
// workitem 10178
Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(s);
// Getting "not a ZipDirEntry signature" here is not always wrong or an
// error. This can happen when walking through a zipfile. After the
// last ZipDirEntry, we expect to read an
// EndOfCentralDirectorySignature. When we get this is how we know
// we've reached the end of the central directory.
if (signature != ZipConstants.EndOfCentralDirectorySignature &&
signature != ZipConstants.Zip64EndOfCentralDirectoryRecordSignature &&
signature != ZipConstants.ZipEntrySignature // workitem 8299
)
{
throw new BadReadException(String.Format(" Bad signature (0x{0:X8}) at position 0x{1:X8}", signature, s.Position));
}
return null;
}
int bytesRead = 42 + 4;
byte[] block = new byte[42];
int n = s.Read(block, 0, block.Length);
if (n != block.Length) return null;
int i = 0;
ZipEntry zde = new ZipEntry();
zde.AlternateEncoding = expectedEncoding;
zde._Source = ZipEntrySource.ZipFile;
zde._container = new ZipContainer(zf);
unchecked
{
zde._VersionMadeBy = (short)(block[i++] + block[i++] * 256);
zde._VersionNeeded = (short)(block[i++] + block[i++] * 256);
zde._BitField = (short)(block[i++] + block[i++] * 256);
zde._CompressionMethod = (Int16)(block[i++] + block[i++] * 256);
zde._TimeBlob = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
zde._LastModified = Ionic.Zip.SharedUtilities.PackedToDateTime(zde._TimeBlob);
zde._timestamp |= ZipEntryTimestamp.DOS;
zde._Crc32 = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
zde._CompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
zde._UncompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
}
// preserve
zde._CompressionMethod_FromZipFile = zde._CompressionMethod;
zde._filenameLength = (short)(block[i++] + block[i++] * 256);
zde._extraFieldLength = (short)(block[i++] + block[i++] * 256);
zde._commentLength = (short)(block[i++] + block[i++] * 256);
zde._diskNumber = (UInt32)(block[i++] + block[i++] * 256);
zde._InternalFileAttrs = (short)(block[i++] + block[i++] * 256);
zde._ExternalFileAttrs = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
zde._RelativeOffsetOfLocalHeader = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
// workitem 7801
zde.IsText = ((zde._InternalFileAttrs & 0x01) == 0x01);
block = new byte[zde._filenameLength];
n = s.Read(block, 0, block.Length);
bytesRead += n;
if ((zde._BitField & 0x0800) == 0x0800)
{
// UTF-8 is in use
zde._FileNameInArchive = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
}
else
{
zde._FileNameInArchive = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
}
// workitem 10330
// insure unique entry names
while (!zf.IgnoreDuplicateFiles && previouslySeen.ContainsKey(zde._FileNameInArchive))
{
zde._FileNameInArchive = CopyHelper.AppendCopyToFileName(zde._FileNameInArchive);
zde._metadataChanged = true;
}
if (zde.AttributesIndicateDirectory)
zde.MarkAsDirectory(); // may append a slash to filename if nec.
// workitem 6898
else if (zde._FileNameInArchive.EndsWith("/")) zde.MarkAsDirectory();
zde._CompressedFileDataSize = zde._CompressedSize;
if ((zde._BitField & 0x01) == 0x01)
{
// this may change after processing the Extra field
zde._Encryption_FromZipFile = zde._Encryption =
EncryptionAlgorithm.PkzipWeak;
zde._sourceIsEncrypted = true;
}
if (zde._extraFieldLength > 0)
{
zde._InputUsesZip64 = (zde._CompressedSize == 0xFFFFFFFF ||
zde._UncompressedSize == 0xFFFFFFFF ||
zde._RelativeOffsetOfLocalHeader == 0xFFFFFFFF);
// Console.WriteLine(" Input uses Z64?: {0}", zde._InputUsesZip64);
bytesRead += zde.ProcessExtraField(s, zde._extraFieldLength);
zde._CompressedFileDataSize = zde._CompressedSize;
}
// we've processed the extra field, so we know the encryption method is set now.
if (zde._Encryption == EncryptionAlgorithm.PkzipWeak)
{
// the "encryption header" of 12 bytes precedes the file data
zde._CompressedFileDataSize -= 12;
}
#if AESCRYPTO
else if (zde.Encryption == EncryptionAlgorithm.WinZipAes128 ||
zde.Encryption == EncryptionAlgorithm.WinZipAes256)
{
zde._CompressedFileDataSize = zde.CompressedSize -
(ZipEntry.GetLengthOfCryptoHeaderBytes(zde.Encryption) + 10);
zde._LengthOfTrailer = 10;
}
#endif
// tally the trailing descriptor
if ((zde._BitField & 0x0008) == 0x0008)
{
// sig, CRC, Comp and Uncomp sizes
if (zde._InputUsesZip64)
zde._LengthOfTrailer += 24;
else
zde._LengthOfTrailer += 16;
}
// workitem 12744
zde.AlternateEncoding = ((zde._BitField & 0x0800) == 0x0800)
? System.Text.Encoding.UTF8
:expectedEncoding;
zde.AlternateEncodingUsage = ZipOption.Always;
if (zde._commentLength > 0)
{
block = new byte[zde._commentLength];
n = s.Read(block, 0, block.Length);
bytesRead += n;
if ((zde._BitField & 0x0800) == 0x0800)
{
// UTF-8 is in use
zde._Comment = Ionic.Zip.SharedUtilities.Utf8StringFromBuffer(block);
}
else
{
zde._Comment = Ionic.Zip.SharedUtilities.StringFromBuffer(block, expectedEncoding);
}
}
//zde._LengthOfDirEntry = bytesRead;
if (zf.IgnoreDuplicateFiles && previouslySeen.ContainsKey(zde._FileNameInArchive))
{
continue;
}
return zde;
}
}
/// <summary>
/// Returns true if the passed-in value is a valid signature for a ZipDirEntry.
/// </summary>
/// <param name="signature">the candidate 4-byte signature value.</param>
/// <returns>true, if the signature is valid according to the PKWare spec.</returns>
internal static bool IsNotValidZipDirEntrySig(int signature)
{
return (signature != ZipConstants.ZipDirEntrySignature);
}
private Int16 _VersionMadeBy;
private Int16 _InternalFileAttrs;
private Int32 _ExternalFileAttrs;
//private Int32 _LengthOfDirEntry;
private Int16 _filenameLength;
private Int16 _extraFieldLength;
private Int16 _commentLength;
}
}
| 42.282116 | 145 | 0.486358 | [
"Apache-2.0"
] | Acidburn0zzz/DotNetZip.Semverd | src/Zip.Shared/ZipDirEntry.cs | 16,786 | 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.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.DependencyInjection;
using Xunit.Abstractions;
namespace Microsoft.Extensions.Logging.Testing
{
public class LoggedTestBase : ILoggedTest
{
private ExceptionDispatchInfo _initializationException;
private IDisposable _testLog;
// Obsolete but keeping for back compat
public LoggedTestBase(ITestOutputHelper output = null)
{
TestOutputHelper = output;
}
// Internal for testing
internal string ResolvedTestClassName { get; set; }
internal RetryContext RetryContext { get; set; }
public string ResolvedLogOutputDirectory { get; set; }
public string ResolvedTestMethodName { get; set; }
public ILogger Logger { get; set; }
public ILoggerFactory LoggerFactory { get; set; }
public ITestOutputHelper TestOutputHelper { get; set; }
public void AddTestLogging(IServiceCollection services) => services.AddSingleton(LoggerFactory);
// For back compat
public IDisposable StartLog(out ILoggerFactory loggerFactory, [CallerMemberName] string testName = null) => StartLog(out loggerFactory, LogLevel.Debug, testName);
// For back compat
public IDisposable StartLog(out ILoggerFactory loggerFactory, LogLevel minLogLevel, [CallerMemberName] string testName = null)
{
return AssemblyTestLog.ForAssembly(GetType().GetTypeInfo().Assembly).StartTestLog(TestOutputHelper, GetType().FullName, out loggerFactory, minLogLevel, testName);
}
public virtual void Initialize(MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper)
{
try
{
TestOutputHelper = testOutputHelper;
var classType = GetType();
var logLevelAttribute = methodInfo.GetCustomAttribute<LogLevelAttribute>()
?? methodInfo.DeclaringType.GetCustomAttribute<LogLevelAttribute>()
?? methodInfo.DeclaringType.Assembly.GetCustomAttribute<LogLevelAttribute>();
var testName = testMethodArguments.Aggregate(methodInfo.Name, (a, b) => $"{a}-{(b ?? "null")}");
var useShortClassName = methodInfo.DeclaringType.GetCustomAttribute<ShortClassNameAttribute>()
?? methodInfo.DeclaringType.Assembly.GetCustomAttribute<ShortClassNameAttribute>();
// internal for testing
ResolvedTestClassName = useShortClassName == null ? classType.FullName : classType.Name;
_testLog = AssemblyTestLog
.ForAssembly(classType.GetTypeInfo().Assembly)
.StartTestLog(
TestOutputHelper,
ResolvedTestClassName,
out var loggerFactory,
logLevelAttribute?.LogLevel ?? LogLevel.Debug,
out var resolvedTestName,
out var logOutputDirectory,
testName);
ResolvedLogOutputDirectory = logOutputDirectory;
ResolvedTestMethodName = resolvedTestName;
LoggerFactory = loggerFactory;
Logger = loggerFactory.CreateLogger(classType);
}
catch (Exception e)
{
_initializationException = ExceptionDispatchInfo.Capture(e);
}
}
public virtual void Dispose()
{
if(_testLog == null)
{
// It seems like sometimes the MSBuild goop that adds the test framework can end up in a bad state and not actually add it
// Not sure yet why that happens but the exception isn't clear so I'm adding this error so we can detect it better.
// -anurse
throw new InvalidOperationException("LoggedTest base class was used but nothing initialized it! The test framework may not be enabled. Try cleaning your 'obj' directory.");
}
_initializationException?.Throw();
_testLog.Dispose();
}
}
}
| 42.261682 | 188 | 0.629589 | [
"Apache-2.0"
] | JensYvanDeCraecker/Extensions | src/Logging/Logging.Testing/src/LoggedTest/LoggedTestBase.cs | 4,522 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LumiSoft.Net.STUN.Client
{
/// <summary>
/// Specifies UDP network type.
/// </summary>
public enum STUN_NetType
{
/// <summary>
/// UDP is always blocked.
/// </summary>
UdpBlocked,
/// <summary>
/// No NAT, public IP, no firewall.
/// </summary>
OpenInternet,
/// <summary>
/// No NAT, public IP, but symmetric UDP firewall.
/// </summary>
SymmetricUdpFirewall,
/// <summary>
/// A full cone NAT is one where all requests from the same internal IP address and port are
/// mapped to the same external IP address and port. Furthermore, any external host can send
/// a packet to the internal host, by sending a packet to the mapped external address.
/// </summary>
FullCone,
/// <summary>
/// A restricted cone NAT is one where all requests from the same internal IP address and
/// port are mapped to the same external IP address and port. Unlike a full cone NAT, an external
/// host (with IP address X) can send a packet to the internal host only if the internal host
/// had previously sent a packet to IP address X.
/// </summary>
RestrictedCone,
/// <summary>
/// A port restricted cone NAT is like a restricted cone NAT, but the restriction
/// includes port numbers. Specifically, an external host can send a packet, with source IP
/// address X and source port P, to the internal host only if the internal host had previously
/// sent a packet to IP address X and port P.
/// </summary>
PortRestrictedCone,
/// <summary>
/// A symmetric NAT is one where all requests from the same internal IP address and port,
/// to a specific destination IP address and port, are mapped to the same external IP address and
/// port. If the same host sends a packet with the same source address and port, but to
/// a different destination, a different mapping is used. Furthermore, only the external host that
/// receives a packet can send a UDP packet back to the internal host.
/// </summary>
Symmetric
}
}
| 39.05 | 106 | 0.618011 | [
"MIT"
] | garakutanokiseki/Join.NET | LumiSoftNet/Net/STUN/Client/STUN_NetType.cs | 2,343 | C# |
using System;
using System.Collections.Generic;
namespace WeShare.Web.Data
{
public partial class User
{
public User()
{
CanalUser = new HashSet<CanalUser>();
ComunidadeVideo = new HashSet<ComunidadeVideo>();
InscritosCanal = new HashSet<InscritosCanal>();
InscritosComunidade = new HashSet<InscritosComunidade>();
UserClaim = new HashSet<UserClaim>();
UserLogin = new HashSet<UserLogin>();
UserRole = new HashSet<UserRole>();
UserToken = new HashSet<UserToken>();
Video = new HashSet<Video>();
VideoComments = new HashSet<VideoComments>();
VideoRatings = new HashSet<VideoRatings>();
}
public string Id { get; set; }
public string UserName { get; set; }
public string NormalizedUserName { get; set; }
public string Email { get; set; }
public string NormalizedEmail { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string ConcurrencyStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTimeOffset? LockoutEnd { get; set; }
public bool LockoutEnabled { get; set; }
public int? AccessFailedCount { get; set; }
public ICollection<CanalUser> CanalUser { get; set; }
public ICollection<ComunidadeVideo> ComunidadeVideo { get; set; }
public ICollection<InscritosCanal> InscritosCanal { get; set; }
public ICollection<InscritosComunidade> InscritosComunidade { get; set; }
public ICollection<UserClaim> UserClaim { get; set; }
public ICollection<UserLogin> UserLogin { get; set; }
public ICollection<UserRole> UserRole { get; set; }
public ICollection<UserToken> UserToken { get; set; }
public ICollection<Video> Video { get; set; }
public ICollection<VideoComments> VideoComments { get; set; }
public ICollection<VideoRatings> VideoRatings { get; set; }
}
}
| 43 | 81 | 0.627907 | [
"MIT"
] | xEvilCorp/We.Share | Data/User.cs | 2,238 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Shopers.API.Classes;
using Shopers.API.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shopers.API.Controllers
{
[ApiVersion("1.0")]
[Route("v{v:apiVersion}/products")]
[ApiController]
public class ProductsV1_0Controller : ControllerBase
{
private readonly ShopContext _context;
public ProductsV1_0Controller(ShopContext context)
{
_context = context;
_context.Database.EnsureCreated();
}
[HttpGet]
public async Task<IActionResult> GetAllProducts([FromQuery] ProductQueryParameters queryParameters)
{
IQueryable<Product> products = _context.Products;
if (queryParameters.MinPrice != null && queryParameters.MaxPrice != null)
{
products = products.Where(p => p.Price >= queryParameters.MinPrice.Value
&& p.Price <= queryParameters.MaxPrice.Value);
}
if (!string.IsNullOrEmpty(queryParameters.Sku)) {
products = products.Where(p => p.Sku == queryParameters.Sku);
}
if(!string.IsNullOrEmpty(queryParameters.Name))
{
products = products.Where(p => p.Name.ToLower().Contains(queryParameters.Name.ToLower()));
}
products = products
.Skip(queryParameters.Size * (queryParameters.Page - 1))
.Take(queryParameters.Size);
return Ok(await products.ToArrayAsync());
}
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
[HttpPost]
public async Task<ActionResult<Product>> PostProduct([FromBody]Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction("GetProduct", new
{
id = product.Id
}, product);
}
[HttpPut("{id}")]
public async Task<IActionResult> PutProduct([FromRoute]int id, [FromBody] Product product)
{
if(id != product.Id)
{
return BadRequest();
}
_context.Entry(product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (_context.Products.Find(id) == null)
{
return NotFound();
}
throw;
}
return NoContent();
}
[HttpDelete("{id}")]
public async Task<ActionResult<Product>> DeleteProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if( product == null)
{
return NotFound();
}
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return product;
}
}
}
| 29.353448 | 107 | 0.544787 | [
"MIT"
] | aravind666/aspdotnet_versioning | Shopers.API/Controllers/ProductsV1_0Controller.cs | 3,407 | C# |
namespace Machete.X12Schema.V5010.Maps
{
using X12;
using X12.Configuration;
public class I410Map :
X12LayoutMap<I410, X12Entity>
{
public I410Map()
{
Id = "I410";
Name = "410 Rail Carrier Freight Details and Invoice";
Segment(x => x.InterchangeControlHeader, 0);
Layout(x => x.Transaction, 1);
Segment(x => x.InterchangeControlTrailer, 2);
}
}
} | 23.65 | 66 | 0.541226 | [
"Apache-2.0"
] | ahives/Machete | src/Machete.X12Schema/V5010/Layouts/Maps/I410Map.cs | 473 | C# |
using System;
using System.Linq;
class Altitude
{
static void Main()
{
string[] inputCommand = Console.ReadLine().Split(' ').ToArray();
double altitude = double.Parse(inputCommand[0]);
for (int i = 1; i < inputCommand.Length - 1; i += 2)
{
if (inputCommand[i].Equals("up"))
{
altitude += double.Parse(inputCommand[i + 1]);
}
else if (inputCommand[i].Equals("down"))
{
altitude -= double.Parse(inputCommand[i + 1]);
}
if (altitude <= 0)
{
break;
}
}
if (altitude > 0)
{
Console.WriteLine($"got through safely. current altitude: {altitude}m");
}
else
{
Console.WriteLine($"crashed");
}
}
} | 22.973684 | 84 | 0.451317 | [
"MIT"
] | Peter-Georgiev/Programming.Fundamentals | ArraysAndMethods-Exercises/17.Altitude/Altitude.cs | 875 | C# |
using System;
namespace WebApplication1.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | 20.272727 | 71 | 0.64574 | [
"MIT"
] | Bhaskers-Blu-Org2/MLFlow.NET | samples/web/WebApplication1/Models/ErrorViewModel.cs | 223 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
namespace DotVVM.Framework.Configuration
{
static class FreezableList
{
public static void Freeze<T>([AllowNull] ref IList<T> list)
{
if (list is FreezableList<T> freezable)
freezable.Freeze();
else if (list is object && !list.IsReadOnly)
list = new FreezableList<T>(list, frozen: true);
}
}
sealed class FreezableList<T> : IList<T>, IReadOnlyList<T>
{
private readonly List<T> list;
private bool isFrozen;
private void ThrowIfFrozen()
{
if (isFrozen)
throw FreezableUtils.Error("list");
}
public void Freeze()
{
this.isFrozen = true;
}
public FreezableList(bool frozen = false)
{
list = new List<T>();
isFrozen = frozen;
}
public FreezableList(IEnumerable<T> items, bool frozen = false)
{
list = items.ToList();
isFrozen = frozen;
}
public T this[int index]
{
get => list[index];
set { ThrowIfFrozen(); list[index] = value; }
}
public int Count => list.Count;
public bool IsReadOnly => isFrozen;
public void Add(T item)
{
ThrowIfFrozen();
list.Add(item);
}
public void AddRange(IEnumerable<T> items)
{
ThrowIfFrozen();
list.AddRange(items);
}
public void Clear()
{
ThrowIfFrozen();
list.Clear();
}
public bool Contains(T item) => list.Contains(item);
public void CopyTo(T[] array, int arrayIndex) => list.CopyTo(array, arrayIndex);
public IEnumerator<T> GetEnumerator() => list.GetEnumerator();
public int IndexOf(T item) => list.IndexOf(item);
public void Insert(int index, T item)
{
ThrowIfFrozen();
list.Insert(index, item);
}
public bool Remove(T item)
{
ThrowIfFrozen();
return list.Remove(item);
}
public void RemoveAt(int index)
{
ThrowIfFrozen();
list.RemoveAt(index);
}
IEnumerator IEnumerable.GetEnumerator() => list.GetEnumerator();
public void CopyTo(Array array, int index) => ((ICollection)list).CopyTo(array, index);
}
}
| 27.457447 | 95 | 0.534289 | [
"Apache-2.0"
] | AlexanderSemenyak/dotvvm | src/Framework/Framework/Configuration/FreezableList.cs | 2,581 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerStats : MonoBehaviour
{
public HUDManager hud;
public GameManager manager;
private Animator anim;
private PlayerMovement movement;
void Awake()
{
anim = gameObject.transform.Find("Avatar").gameObject.GetComponent<Animator>();
movement = gameObject.GetComponent<PlayerMovement>();
}
private void OnTriggerEnter(Collider other)
{
/* if (other.gameObject.tag == "Enemy")
{
HUDManager.livesLeft -= 1;
hud.UpdateUI();
if (HUDManager.livesLeft <= 0)
{
anim.SetTrigger("Die");
movement.enabled = false;
}
} else*/ if (other.gameObject.tag == "Collectible")
{
GameObject parent = other.transform.parent.gameObject;
AudioSource audio = parent.GetComponent<AudioSource>();
audio.Play();
Debug.Log("Found");
HUDManager.collectiblesFound++;
HUDManager.score += 100;
hud.UpdateUI();
if (HUDManager.collectiblesFound >= HUDManager.totalCollectibles)
{
manager.CompleteLevel();
}
other.gameObject.SetActive(false);
parent.GetComponent<Light>().enabled = false;
StartCoroutine(DestroyCollectible(parent));
StopCoroutine(DestroyCollectible(parent));
}
}
IEnumerator DestroyCollectible(GameObject obj)
{
yield return new WaitForSeconds(3);
Destroy(obj);
}
public void AttackPlayer()
{
HUDManager.livesLeft -= 1;
hud.UpdateUI();
if (HUDManager.livesLeft <= 0)
{
anim.SetTrigger("Die");
movement.enabled = false;
StartCoroutine(DeathWait());
StopCoroutine(DeathWait());
}
}
IEnumerator DeathWait()
{
yield return new WaitForSeconds(4);
manager.GameOver();
}
}
| 27.25974 | 87 | 0.572177 | [
"MIT"
] | ronyaguilar09/Ghost-Labyrinth | Ghost Labyrinth/Assets/Scripts/Player/PlayerStats.cs | 2,101 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// Debugger type proxy expansion.
/// </summary>
/// <remarks>
/// May include <see cref="System.Collections.IEnumerable"/> and
/// <see cref="System.Collections.Generic.IEnumerable{T}"/> as special cases.
/// (The proxy is not declared by an attribute, but is known to debugger.)
/// </remarks>
internal sealed class DebuggerTypeProxyExpansion : Expansion
{
internal static Expansion CreateExpansion(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext,
string name,
TypeAndCustomInfo typeDeclaringMemberAndInfoOpt,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
bool childShouldParenthesize,
string fullName,
string childFullNamePrefix,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultFlags flags,
string editableValue)
{
Debug.Assert((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) == 0);
// Note: The native EE uses the proxy type, even for
// null instances, so statics on the proxy type are
// displayed. That case is not supported currently.
if (!value.IsNull)
{
var proxyType = value.Type.GetProxyType();
if (proxyType != null)
{
if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ShowValueRaw) != 0)
{
var rawView = CreateRawView(resultProvider, inspectionContext, declaredTypeAndInfo, value);
Debug.Assert(rawView != null);
return rawView;
}
DkmClrValue proxyValue;
try
{
proxyValue = value.InstantiateProxyType(inspectionContext, proxyType);
}
catch
{
proxyValue = null;
}
if (proxyValue != null)
{
return new DebuggerTypeProxyExpansion(
inspectionContext,
proxyValue,
name,
typeDeclaringMemberAndInfoOpt,
declaredTypeAndInfo,
value,
childShouldParenthesize,
fullName,
childFullNamePrefix,
formatSpecifiers,
flags,
editableValue,
resultProvider);
}
}
}
return null;
}
private readonly EvalResult _proxyItem;
private readonly string _name;
private readonly TypeAndCustomInfo _typeDeclaringMemberAndInfoOpt;
private readonly TypeAndCustomInfo _declaredTypeAndInfo;
private readonly DkmClrValue _value;
private readonly bool _childShouldParenthesize;
private readonly string _fullName;
private readonly string _childFullNamePrefix;
private readonly ReadOnlyCollection<string> _formatSpecifiers;
private readonly DkmEvaluationResultFlags _flags;
private readonly string _editableValue;
private DebuggerTypeProxyExpansion(
DkmInspectionContext inspectionContext,
DkmClrValue proxyValue,
string name,
TypeAndCustomInfo typeDeclaringMemberAndInfoOpt,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
bool childShouldParenthesize,
string fullName,
string childFullNamePrefix,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultFlags flags,
string editableValue,
ResultProvider resultProvider)
{
Debug.Assert(proxyValue != null);
var proxyType = proxyValue.Type;
var proxyTypeAndInfo = new TypeAndCustomInfo(proxyType);
var proxyMembers = MemberExpansion.CreateExpansion(
inspectionContext,
proxyTypeAndInfo,
proxyValue,
ExpansionFlags.IncludeBaseMembers,
TypeHelpers.IsPublic,
resultProvider);
if (proxyMembers != null)
{
string proxyMemberFullNamePrefix = null;
if (childFullNamePrefix != null)
{
proxyMemberFullNamePrefix = resultProvider.FullNameProvider.GetClrObjectCreationExpression(inspectionContext, proxyTypeAndInfo.ClrType, proxyTypeAndInfo.Info, childFullNamePrefix);
}
_proxyItem = new EvalResult(
ExpansionKind.Default,
name: string.Empty,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: proxyTypeAndInfo,
useDebuggerDisplay: false,
value: proxyValue,
displayValue: null,
expansion: proxyMembers,
childShouldParenthesize: false,
fullName: null,
childFullNamePrefixOpt: proxyMemberFullNamePrefix,
formatSpecifiers: Formatter.NoFormatSpecifiers,
category: default(DkmEvaluationResultCategory),
flags: default(DkmEvaluationResultFlags),
editableValue: null,
inspectionContext: inspectionContext);
}
_name = name;
_typeDeclaringMemberAndInfoOpt = typeDeclaringMemberAndInfoOpt;
_declaredTypeAndInfo = declaredTypeAndInfo;
_value = value;
_childShouldParenthesize = childShouldParenthesize;
_fullName = fullName;
_childFullNamePrefix = childFullNamePrefix;
_formatSpecifiers = formatSpecifiers;
_flags = flags;
_editableValue = editableValue;
}
internal override void GetRows(
ResultProvider resultProvider,
ArrayBuilder<EvalResult> rows,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
DkmClrValue value,
int startIndex,
int count,
bool visitAll,
ref int index)
{
if (_proxyItem != null)
{
_proxyItem.Expansion.GetRows(resultProvider, rows, inspectionContext, _proxyItem.ToDataItem(), _proxyItem.Value, startIndex, count, visitAll, ref index);
}
if (InRange(startIndex, count, index))
{
rows.Add(this.CreateRawViewRow(resultProvider, inspectionContext));
}
index++;
}
private EvalResult CreateRawViewRow(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext)
{
return new EvalResult(
ExpansionKind.RawView,
_name,
_typeDeclaringMemberAndInfoOpt,
_declaredTypeAndInfo,
useDebuggerDisplay: false,
value: _value,
displayValue: null,
expansion: CreateRawView(resultProvider, inspectionContext, _declaredTypeAndInfo, _value),
childShouldParenthesize: _childShouldParenthesize,
fullName: _fullName,
childFullNamePrefixOpt: _childFullNamePrefix,
formatSpecifiers: Formatter.AddFormatSpecifier(_formatSpecifiers, "raw"),
category: DkmEvaluationResultCategory.Data,
flags: _flags | DkmEvaluationResultFlags.ReadOnly,
editableValue: _editableValue,
inspectionContext: inspectionContext);
}
private static Expansion CreateRawView(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value)
{
return resultProvider.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, ExpansionFlags.IncludeBaseMembers);
}
}
}
| 41.449074 | 200 | 0.57746 | [
"Apache-2.0"
] | AArnott/roslyn | src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/DebuggerTypeProxyExpansion.cs | 8,953 | C# |
using System.Collections.Generic;
using Bytes2you.Validation;
using MAutoSS.Data.Repositories.Contracts;
using MAutoSS.DataModels;
using MAutoSS.Services.Contracts;
namespace MAutoSS.Services
{
public class CarFeaturesService : ICarFeaturesService
{
private readonly IGenericRepository<CarFeature> carFeaturesRepo;
public CarFeaturesService(
IGenericRepository<CarFeature> carFeaturesRepo)
{
Guard.WhenArgument(carFeaturesRepo, "carFeaturesRepo").IsNull().Throw();
this.carFeaturesRepo = carFeaturesRepo;
}
public IEnumerable<CarFeature> GetAllCarFeatures()
{
return this.carFeaturesRepo.GetAll();
}
}
}
| 25.034483 | 84 | 0.695592 | [
"MIT"
] | transactionCompleteDB/MAutoSS | MAutoSS/MAutoSS.Services/CarFeaturesService.cs | 728 | C# |
using System;
using System.Windows.Markup;
using mathview.Expressions;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using mathview.Parsers.LaTeX;
namespace mathview.View
{
public class MathView : UserControl
{
#region Source Property
/// <summary>
/// The Source.
/// </summary>
public static DependencyProperty SourceProperty =
DependencyProperty.Register("Source",
typeof(ExpressionBase),
typeof(MathView),
new PropertyMetadata(null));
/// <summary>
/// The backing property for <see cref="MathView.SourceProperty"/>
/// </summary>
[Category("Common")]
public ExpressionBase Source
{
get { return (ExpressionBase)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
#endregion
#region ItalicLetters Property
/// <summary>
/// Controls the usage of italic letters.
/// </summary>
public static DependencyProperty ItalicLettersProperty =
DependencyProperty.Register("ItalicLetters",
typeof(bool),
typeof(MathView),
new PropertyMetadata(true));
/// <summary>
/// The backing property for <see cref="MathView.ItalicLettersProperty"/>
/// </summary>
[Category("Common")]
public bool ItalicLetters
{
get { return (bool)GetValue(ItalicLettersProperty); }
set { SetValue(ItalicLettersProperty, value); }
}
#endregion
/// <summary>
/// Creates a new <see cref="MathView"/> instance.
/// </summary>
public MathView()
{
DataContext = this;
Width = 60;
Height = 60;
string text = String.Format("z_n^2");
var parser = new LaTeXStringParser();
var expr = parser.Parse(text);
Source = expr;
//Background = Brushes.Red;
ContentPresenter cp = new ContentPresenter();
Content = cp;
InitializeComponent();
}
}
}
| 25.182927 | 78 | 0.610169 | [
"Unlicense"
] | yanzixiang/YZX.RTA | YZX.RTA/mathview/wpf/bak/mathview.xaml.cs | 2,067 | C# |
// Copyright (c) Giovanni Lafratta. All rights reserved.
// Licensed under the MIT license.
// See the LICENSE file in the project root for more information.
using Novacta.Analytics.Infrastructure;
using Novacta.Analytics.Tests.TestableItems.Matrices;
using Novacta.Analytics.Tests.Tools;
using System;
namespace Novacta.Analytics.Tests.TestableItems.Covariance
{
/// <summary>
/// Represents a covariance operation whose data operand
/// has not enough items to enable adjusting for bias.
/// </summary>
class OnRowsUnadjustableCovariance : AlongDimensionCovariance<ArgumentException>
{
protected OnRowsUnadjustableCovariance() :
base(
expected: new ArgumentException(
message: (string)Reflector.ExecuteStaticMember(
typeof(ImplementationServices),
"GetResourceString",
new string[] { "STR_EXCEPT_STA_VARIANCE_ADJUST_FOR_BIAS_UNDEFINED" }),
paramName: null),
data: TestableDoubleMatrix20.Get(),
adjustForBias: true,
dataOperation: DataOperation.OnRows
)
{
}
/// <summary>
/// Gets an instance of the <see cref="OnRowsUnadjustableCovariance"/> class.
/// </summary>
/// <returns>An instance of the
/// <see cref="OnRowsUnadjustableCovariance"/> class.</returns>
public static OnRowsUnadjustableCovariance Get()
{
return new OnRowsUnadjustableCovariance();
}
}
}
| 36.568182 | 98 | 0.620261 | [
"MIT"
] | Novacta/analytics | tests/Novacta.Analytics.Tests/TestableItems/Covariance/OnRowsUnadjustableCovariance.cs | 1,611 | C# |
using System.Threading.Tasks;
using Splitnab.Model;
namespace Splitnab
{
/// <summary>
/// Interface to get the required information from YNAB for Splitnab
/// </summary>
public interface IGetYnabInfoOperation
{
/// <summary>
/// Invoke the operation to fetch the necessary YNAB info.
/// </summary>
/// <param name="appSettings">The appsettings.json object</param>
/// <returns>The required YNAB info as <see cref="YnabInfo"/>, otherwise null.</returns>
public Task<YnabInfo?> Invoke(AppSettings appSettings);
}
}
| 31 | 96 | 0.648557 | [
"MIT"
] | chriskopher/splitnab | src/Splitnab/IGetYnabInfoOperation.cs | 591 | C# |
using Armut.Iterable.Client;
using Armut.Iterable.Client.Contracts;
using Armut.Iterable.Client.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
namespace Sample.Client.DependencyInjection
{
public class DependencyFactory
{
public static readonly DependencyFactory Instance = new DependencyFactory();
private ServiceProvider _serviceProvider;
private DependencyFactory() { }
public void RegisterDependencies()
{
var serviceCollection = new ServiceCollection();
HttpClient iterableHttpClient = new HttpClient
{
BaseAddress = new Uri("https://api.iterable.com/")
};
iterableHttpClient.DefaultRequestHeaders.Add("Api-Key", "your_api_key");
serviceCollection
.AddSingleton<IRestClient, RestClient>()
.AddTransient<IUserClient, UserClient>()
.AddTransient<IListClient,ListClient>()
//.AddSingleton(iterableHttpClient)
.AddSingleton(clientFactory =>
{
return (Func<string, HttpClient>)(key =>
{
switch (key)
{
case "IterableClient":
return iterableHttpClient;
default:
return null;
}
});
});
_serviceProvider = serviceCollection.BuildServiceProvider();
}
public T Resolve<T>()
{
return _serviceProvider.GetService<T>();
}
}
} | 31.454545 | 84 | 0.536416 | [
"MIT"
] | akselarzuman/iterable-client-dotnet | sample/Sample.Client/DependencyFactory.cs | 1,732 | C# |
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
namespace Microsoft.Toolkit.Uwp.UI.Controls
{
/// <summary>
/// The ImageEx control extends the default Image platform control improving the performance and responsiveness of your Apps.
/// Source images are downloaded asynchronously showing a load indicator while in progress.
/// Once downloaded, the source image is stored in the App local cache to preserve resources and load time next time the image needs to be displayed.
/// </summary>
public partial class ImageEx
{
/// <summary>
/// Identifies the <see cref="PlaceholderSource"/> dependency property.
/// </summary>
public static readonly DependencyProperty PlaceholderSourceProperty = DependencyProperty.Register(
nameof(PlaceholderSource),
typeof(ImageSource),
typeof(ImageEx),
new PropertyMetadata(default(ImageSource)));
/// <summary>
/// Identifies the <see cref="PlaceholderStretch"/> dependency property.
/// </summary>
public static readonly DependencyProperty PlaceholderStretchProperty = DependencyProperty.Register(
nameof(PlaceholderStretch),
typeof(Stretch),
typeof(ImageEx),
new PropertyMetadata(default(Stretch)));
/// <summary>
/// Gets or sets the placeholder source.
/// </summary>
/// <value>
/// The placeholder source.
/// </value>
public ImageSource PlaceholderSource
{
get { return (ImageSource)GetValue(PlaceholderSourceProperty); }
set { SetValue(PlaceholderSourceProperty, value); }
}
/// <summary>
/// Gets or sets the placeholder stretch.
/// </summary>
/// <value>
/// The placeholder stretch.
/// </value>
public Stretch PlaceholderStretch
{
get { return (Stretch)GetValue(PlaceholderStretchProperty); }
set { SetValue(PlaceholderStretchProperty, value); }
}
}
}
| 41.279412 | 153 | 0.620591 | [
"MIT"
] | azurechamp/UWPCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Controls/ImageEx/ImageEx.Placeholder.cs | 2,813 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using cadastrocidades.Repository.Data.Persistencia;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace CadastroCidades.Api
{
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
using (var context = scope.ServiceProvider.GetService<AppDbContext>())
{
context.Database.EnsureCreated();
}
host.Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| 28.764706 | 82 | 0.658487 | [
"MIT"
] | Rafael-Prado/GrifonBrasil | CadastroCidades.Api/CadastroCidades.Api/Program.cs | 978 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Trainsys
{
class Program
{
static void Main(string[] args)
{
dbdata dbgps = new dbdata();
dbgps.gpsdata(0, 0);
dbgps.gpsdata(69, 69);
}
}
}
| 15.75 | 40 | 0.549206 | [
"BSD-3-Clause"
] | jpnevrones/GPS-GSM-based-Real-time-Train-Tracking-System | Trainsys/Program.cs | 317 | C# |
using System;
using System.Linq;
using System.ComponentModel.Composition;
using System.Waf.Applications;
using System.Windows;
using System.Windows.Controls;
using Waf.InformationManager.EmailClient.Modules.Applications.Views;
using Waf.InformationManager.EmailClient.Modules.Applications.ViewModels;
using System.Windows.Threading;
namespace Waf.InformationManager.EmailClient.Modules.Presentation.Views
{
[Export(typeof(IEmailListView)), PartCreationPolicy(CreationPolicy.NonShared)]
public partial class EmailListView : IEmailListView
{
private readonly Lazy<EmailListViewModel> viewModel;
public EmailListView()
{
InitializeComponent();
viewModel = new Lazy<EmailListViewModel>(() => this.GetViewModel<EmailListViewModel>()!);
Loaded += LoadedHandler;
}
private EmailListViewModel ViewModel => viewModel.Value;
public void FocusItem()
{
if (ViewModel.SelectedEmail == null)
{
emailsBox.Focus();
return;
}
Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() =>
{
// It is necessary to delay this code because data binding updates the values asynchronously.
emailsBox.ScrollIntoView(ViewModel.SelectedEmail);
var selectedListBoxItem = (ListBoxItem)emailsBox.ItemContainerGenerator.ContainerFromItem(ViewModel.SelectedEmail);
selectedListBoxItem?.Focus();
}));
}
private void LoadedHandler(object sender, RoutedEventArgs e)
{
ViewModel.SelectedEmail = ViewModel.Emails.FirstOrDefault();
emailsBox.Focus();
if (ViewModel.SelectedEmail != null)
{
FocusItem();
}
}
}
}
| 35.777778 | 132 | 0.624224 | [
"MIT"
] | DotNetUz/waf | src/System.Waf/Samples/InformationManager/EmailClient.Modules.Presentation/Views/EmailListView.xaml.cs | 1,934 | 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;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Extensions.Internal;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query.Expressions.Internal;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors;
using Microsoft.Extensions.DependencyInjection;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.Expressions;
namespace Microsoft.EntityFrameworkCore.Query.Internal
{
/// <summary>
/// <para>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped"/>. This means that each
/// <see cref="DbContext"/> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
public class ExpressionPrinter : ExpressionVisitorBase, IExpressionPrinter
{
private readonly IndentedStringBuilder _stringBuilder;
private readonly Dictionary<ParameterExpression, string> _parametersInScope;
private readonly List<ParameterExpression> _namelessParameters;
private readonly Dictionary<ExpressionType, string> _binaryOperandMap = new Dictionary<ExpressionType, string>
{
{ ExpressionType.Assign, " = " },
{ ExpressionType.Equal, " == " },
{ ExpressionType.NotEqual, " != " },
{ ExpressionType.GreaterThan, " > " },
{ ExpressionType.GreaterThanOrEqual, " >= " },
{ ExpressionType.LessThan, " < " },
{ ExpressionType.LessThanOrEqual, " <= " },
{ ExpressionType.OrElse, " || " },
{ ExpressionType.AndAlso, " && " },
{ ExpressionType.Coalesce, " ?? " },
{ ExpressionType.Add, " + " },
{ ExpressionType.Subtract, " - " },
{ ExpressionType.Multiply, " * " },
{ ExpressionType.Divide, " / " },
{ ExpressionType.Modulo, " % " },
{ ExpressionType.And, " & " },
{ ExpressionType.Or, " | " },
{ ExpressionType.ExclusiveOr, " ^ " }
};
private bool _highlightNonreducibleNodes;
private bool _reduceBeforePrinting;
private const string HighlightLeft = " ---> ";
private const string HighlightRight = " <--- ";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public ExpressionPrinter()
: this(new List<ConstantPrinterBase>())
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected List<ConstantPrinterBase> ConstantPrinters = new List<ConstantPrinterBase>();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected ExpressionPrinter(List<ConstantPrinterBase> additionalConstantPrinters)
{
_stringBuilder = new IndentedStringBuilder();
_parametersInScope = new Dictionary<ParameterExpression, string>();
_namelessParameters = new List<ParameterExpression>();
ConstantPrinters.AddRange(additionalConstantPrinters);
ConstantPrinters.AddRange(
new List<ConstantPrinterBase>
{
new EntityQueryableConstantPrinter(),
new MetadataPropertyPrinter(),
new DefaultConstantPrinter()
});
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual IndentedStringBuilder StringBuilder => _stringBuilder;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool RemoveFormatting { get; set; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual int? CharacterLimit { get; set; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool PrintConnections { get; set; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool GenerateUniqueQsreIds { get; set; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual List<IQuerySource> VisitedQuerySources { get; } = new List<IQuerySource>();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual void VisitList<T>(
IReadOnlyList<T> items,
Action<ExpressionPrinter> joinAction = null)
where T : Expression
{
joinAction ??= (p => p.StringBuilder.Append(", "));
for (var i = 0; i < items.Count; i++)
{
if (i > 0)
{
joinAction(this);
}
Visit(items[i]);
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual void Append([NotNull] string message) => _stringBuilder.Append(message);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual void AppendLine([NotNull] string message = "")
{
if (RemoveFormatting)
{
_stringBuilder.Append(string.IsNullOrEmpty(message) ? " " : message);
}
_stringBuilder.AppendLine(message);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual string Print(
Expression expression,
bool removeFormatting = false,
int? characterLimit = null,
bool printConnections = true)
{
return PrintInternal(
expression,
removeFormatting,
characterLimit,
highlightNonreducibleNodes: false,
reduceBeforePrinting: false,
generateUniqueQsreIds: false,
printConnections: printConnections);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual string PrintDebug(
Expression expression,
bool highlightNonreducibleNodes = true,
bool reduceBeforePrinting = true,
bool generateUniqueQsreIds = true,
bool printConnections = true)
{
return PrintInternal(
expression,
removeFormatting: false,
characterLimit: null,
highlightNonreducibleNodes: highlightNonreducibleNodes,
reduceBeforePrinting: reduceBeforePrinting,
generateUniqueQsreIds: generateUniqueQsreIds,
printConnections: printConnections);
}
private string PrintInternal(
Expression expression,
bool removeFormatting,
int? characterLimit,
bool highlightNonreducibleNodes,
bool reduceBeforePrinting,
bool generateUniqueQsreIds,
bool printConnections)
{
_stringBuilder.Clear();
_parametersInScope.Clear();
_namelessParameters.Clear();
RemoveFormatting = removeFormatting;
CharacterLimit = characterLimit;
GenerateUniqueQsreIds = generateUniqueQsreIds;
PrintConnections = printConnections;
_highlightNonreducibleNodes = highlightNonreducibleNodes;
_reduceBeforePrinting = reduceBeforePrinting;
Visit(expression);
var queryPlan = PostProcess(_stringBuilder.ToString());
if (characterLimit != null
&& characterLimit.Value > 0)
{
queryPlan = queryPlan.Length > characterLimit
? queryPlan.Substring(0, characterLimit.Value) + "..."
: queryPlan;
}
return queryPlan;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual string GenerateBinaryOperator(ExpressionType expressionType)
{
return _binaryOperandMap[expressionType];
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override Expression Visit(Expression expression)
{
if (expression == null)
{
return null;
}
if (CharacterLimit != null
&& _stringBuilder.Length > CharacterLimit.Value)
{
return expression;
}
switch (expression.NodeType)
{
case ExpressionType.AndAlso:
case ExpressionType.ArrayIndex:
case ExpressionType.Assign:
case ExpressionType.Equal:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.NotEqual:
case ExpressionType.OrElse:
case ExpressionType.Coalesce:
case ExpressionType.Add:
case ExpressionType.Subtract:
case ExpressionType.Multiply:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.Or:
case ExpressionType.ExclusiveOr:
VisitBinary((BinaryExpression)expression);
break;
case ExpressionType.Block:
VisitBlock((BlockExpression)expression);
break;
case ExpressionType.Conditional:
VisitConditional((ConditionalExpression)expression);
break;
case ExpressionType.Constant:
VisitConstant((ConstantExpression)expression);
break;
case ExpressionType.Lambda:
base.Visit(expression);
break;
case ExpressionType.Goto:
VisitGoto((GotoExpression)expression);
break;
case ExpressionType.Label:
VisitLabel((LabelExpression)expression);
break;
case ExpressionType.MemberAccess:
VisitMember((MemberExpression)expression);
break;
case ExpressionType.MemberInit:
VisitMemberInit((MemberInitExpression)expression);
break;
case ExpressionType.Call:
VisitMethodCall((MethodCallExpression)expression);
break;
case ExpressionType.New:
VisitNew((NewExpression)expression);
break;
case ExpressionType.NewArrayInit:
VisitNewArray((NewArrayExpression)expression);
break;
case ExpressionType.Parameter:
VisitParameter((ParameterExpression)expression);
break;
case ExpressionType.Convert:
case ExpressionType.Throw:
case ExpressionType.Not:
case ExpressionType.TypeAs:
case ExpressionType.Quote:
VisitUnary((UnaryExpression)expression);
break;
case ExpressionType.Default:
VisitDefault((DefaultExpression)expression);
break;
case ExpressionType.Try:
VisitTry((TryExpression)expression);
break;
case ExpressionType.Index:
VisitIndex((IndexExpression)expression);
break;
case ExpressionType.TypeIs:
VisitTypeBinary((TypeBinaryExpression)expression);
break;
case ExpressionType.Extension:
VisitExtension(expression);
break;
default:
UnhandledExpressionType(expression);
break;
}
return expression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
Visit(binaryExpression.Left);
if (binaryExpression.NodeType == ExpressionType.ArrayIndex)
{
_stringBuilder.Append("[");
Visit(binaryExpression.Right);
_stringBuilder.Append("]");
}
else
{
if (!_binaryOperandMap.TryGetValue(binaryExpression.NodeType, out var operand))
{
UnhandledExpressionType(binaryExpression);
}
else
{
_stringBuilder.Append(operand);
}
Visit(binaryExpression.Right);
}
return binaryExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitBlock(BlockExpression blockExpression)
{
AppendLine();
if (PrintConnections)
{
_stringBuilder.SuspendCurrentNode();
}
AppendLine("{");
_stringBuilder.IncrementIndent();
foreach (var variable in blockExpression.Variables)
{
if (!_parametersInScope.ContainsKey(variable))
{
_parametersInScope.Add(variable, variable.Name);
}
}
var expressions = blockExpression.Result != null
? blockExpression.Expressions.Except(new[] { blockExpression.Result })
: blockExpression.Expressions;
foreach (var expression in expressions)
{
Visit(expression);
AppendLine();
}
if (blockExpression.Result != null)
{
Append("return ");
Visit(blockExpression.Result);
AppendLine();
}
_stringBuilder.DecrementIndent();
Append("}");
if (PrintConnections)
{
_stringBuilder.ReconnectCurrentNode();
}
return blockExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitConditional(ConditionalExpression conditionalExpression)
{
Visit(conditionalExpression.Test);
_stringBuilder.Append(" ? ");
Visit(conditionalExpression.IfTrue);
_stringBuilder.Append(" : ");
Visit(conditionalExpression.IfFalse);
return conditionalExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitConstant(ConstantExpression constantExpression)
{
if (PrintConnections)
{
_stringBuilder.SuspendCurrentNode();
}
if (constantExpression.Value is IPrintable printable)
{
printable.Print(this);
}
else
{
foreach (var constantPrinter in ConstantPrinters)
{
if (constantPrinter.TryPrintConstant(constantExpression, _stringBuilder, RemoveFormatting))
{
break;
}
}
}
if (PrintConnections)
{
_stringBuilder.ReconnectCurrentNode();
}
return constantExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitGoto(GotoExpression gotoExpression)
{
AppendLine("return (" + gotoExpression.Target.Type.ShortDisplayName() + ")" + gotoExpression.Target + " {");
_stringBuilder.IncrementIndent();
Visit(gotoExpression.Value);
_stringBuilder.DecrementIndent();
_stringBuilder.Append("}");
return gotoExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitLabel(LabelExpression labelExpression)
{
_stringBuilder.Append(labelExpression.Target.ToString());
return labelExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitLambda<T>(Expression<T> lambdaExpression)
{
_stringBuilder.Append("(");
foreach (var parameter in lambdaExpression.Parameters)
{
var parameterName = parameter.Name ?? parameter.ToString();
if (!_parametersInScope.ContainsKey(parameter))
{
_parametersInScope.Add(parameter, parameterName);
}
_stringBuilder.Append(parameter.Type.ShortDisplayName() + " " + parameterName);
if (parameter != lambdaExpression.Parameters.Last())
{
_stringBuilder.Append(" | ");
}
}
_stringBuilder.Append(") => ");
Visit(lambdaExpression.Body);
foreach (var parameter in lambdaExpression.Parameters)
{
// however we don't remove nameless parameters so that they are unique globally, not just within the scope
_parametersInScope.Remove(parameter);
}
return lambdaExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitMember(MemberExpression memberExpression)
{
if (memberExpression.Expression != null)
{
if (memberExpression.Expression.NodeType == ExpressionType.Convert)
{
_stringBuilder.Append("(");
Visit(memberExpression.Expression);
_stringBuilder.Append(")");
}
else
{
Visit(memberExpression.Expression);
}
}
else
{
// ReSharper disable once PossibleNullReferenceException
_stringBuilder.Append(memberExpression.Member.DeclaringType.Name);
}
_stringBuilder.Append("." + memberExpression.Member.Name);
return memberExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitMemberInit(MemberInitExpression memberInitExpression)
{
_stringBuilder.Append("new " + memberInitExpression.Type.ShortDisplayName());
var appendAction = memberInitExpression.Bindings.Count > 1 ? (Action<string>)AppendLine : Append;
appendAction("{ ");
_stringBuilder.IncrementIndent();
for (var i = 0; i < memberInitExpression.Bindings.Count; i++)
{
if (memberInitExpression.Bindings[i] is MemberAssignment assignment)
{
_stringBuilder.Append(assignment.Member.Name + " = ");
Visit(assignment.Expression);
appendAction(i == memberInitExpression.Bindings.Count - 1 ? " " : ", ");
}
else
{
////throw new NotSupportedException(CoreStrings.InvalidMemberInitBinding);
AppendLine(CoreStrings.InvalidMemberInitBinding);
}
}
_stringBuilder.DecrementIndent();
AppendLine("}");
return memberInitExpression;
}
private static readonly List<string> _simpleMethods = new List<string>
{
"get_Item",
"TryReadValue",
"ReferenceEquals"
};
private static readonly List<string> _nonConnectableMethods = new List<string>
{
"GetValueFromEntity",
"StartTracking",
"SetRelationshipSnapshotValue",
"SetRelationshipIsLoaded",
"Add"
};
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
if (!methodCallExpression.Method.IsEFPropertyMethod())
{
_stringBuilder.Append(methodCallExpression.Method.ReturnType.ShortDisplayName() + " ");
}
if (methodCallExpression.Object != null)
{
if (methodCallExpression.Object is BinaryExpression)
{
_stringBuilder.Append("(");
Visit(methodCallExpression.Object);
_stringBuilder.Append(")");
}
else
{
Visit(methodCallExpression.Object);
}
_stringBuilder.Append(".");
}
_stringBuilder.Append(methodCallExpression.Method.Name + "(");
var isSimpleMethodOrProperty = _simpleMethods.Contains(methodCallExpression.Method.Name)
|| methodCallExpression.Arguments.Count < 2
|| methodCallExpression.Method.IsEFPropertyMethod();
var appendAction = isSimpleMethodOrProperty ? (Action<string>)Append : AppendLine;
if (methodCallExpression.Arguments.Count > 0)
{
appendAction("");
var argumentNames
= !isSimpleMethodOrProperty
? methodCallExpression.Method.GetParameters().Select(p => p.Name).ToList()
: new List<string>();
if (!isSimpleMethodOrProperty)
{
var shouldPrintConnections = PrintConnections && !_nonConnectableMethods.Contains(methodCallExpression.Method.Name);
_stringBuilder.IncrementIndent(shouldPrintConnections);
}
for (var i = 0; i < methodCallExpression.Arguments.Count; i++)
{
var argument = methodCallExpression.Arguments[i];
if (!isSimpleMethodOrProperty)
{
_stringBuilder.Append(argumentNames[i] + ": ");
}
if (i == methodCallExpression.Arguments.Count - 1
&& !isSimpleMethodOrProperty)
{
_stringBuilder.DisconnectCurrentNode();
}
Visit(argument);
if (i < methodCallExpression.Arguments.Count - 1)
{
appendAction(", ");
}
}
if (!isSimpleMethodOrProperty)
{
_stringBuilder.DecrementIndent();
}
}
Append(")");
return methodCallExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitNew(NewExpression newExpression)
{
_stringBuilder.Append("new ");
var isComplex = newExpression.Arguments.Count > 1;
var appendAction = isComplex ? (Action<string>)AppendLine : Append;
var isAnonymousType = newExpression.Type.IsAnonymousType();
if (!isAnonymousType)
{
_stringBuilder.Append(newExpression.Type.ShortDisplayName());
appendAction("(");
}
else
{
appendAction("{ ");
}
if (isComplex)
{
_stringBuilder.IncrementIndent();
}
for (var i = 0; i < newExpression.Arguments.Count; i++)
{
if (newExpression.Members != null)
{
Append(newExpression.Members[i].Name + " = ");
}
Visit(newExpression.Arguments[i]);
appendAction(i == newExpression.Arguments.Count - 1 ? "" : ", ");
}
if (isComplex)
{
_stringBuilder.DecrementIndent();
}
if (!isAnonymousType)
{
_stringBuilder.Append(")");
}
else
{
_stringBuilder.Append(" }");
}
return newExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitNewArray(NewArrayExpression newArrayExpression)
{
var isComplex = newArrayExpression.Expressions.Count > 1;
var appendAction = isComplex ? (Action<string>)AppendLine : Append;
appendAction("new " + newArrayExpression.Type.GetElementType().ShortDisplayName() + "[]");
if (PrintConnections)
{
_stringBuilder.SuspendCurrentNode();
}
appendAction("{ ");
if (isComplex)
{
_stringBuilder.IncrementIndent();
}
VisitArguments(newArrayExpression.Expressions, appendAction, lastSeparator: " ");
if (isComplex)
{
_stringBuilder.DecrementIndent();
}
Append("}");
if (PrintConnections)
{
_stringBuilder.ReconnectCurrentNode();
}
return newArrayExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitParameter(ParameterExpression parameterExpression)
{
if (_parametersInScope.ContainsKey(parameterExpression))
{
var parameterName = _parametersInScope[parameterExpression];
if (parameterName == null)
{
if (!_namelessParameters.Contains(parameterExpression))
{
_namelessParameters.Add(parameterExpression);
}
_stringBuilder.Append("namelessParameter{" + _namelessParameters.IndexOf(parameterExpression) + "}");
}
else if (parameterName.Contains("."))
{
_stringBuilder.Append("[" + parameterName + "]");
}
else
{
_stringBuilder.Append(parameterName);
}
}
else
{
_stringBuilder.Append("Unhandled parameter: " + parameterExpression);
}
return parameterExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitUnary(UnaryExpression unaryExpression)
{
// ReSharper disable once SwitchStatementMissingSomeCases
switch (unaryExpression.NodeType)
{
case ExpressionType.Convert:
_stringBuilder.Append("(" + unaryExpression.Type.ShortDisplayName() + ")");
if (unaryExpression.Operand is BinaryExpression)
{
_stringBuilder.Append("(");
Visit(unaryExpression.Operand);
_stringBuilder.Append(")");
}
else
{
Visit(unaryExpression.Operand);
}
break;
case ExpressionType.Throw:
_stringBuilder.Append("throw ");
Visit(unaryExpression.Operand);
break;
case ExpressionType.Not:
_stringBuilder.Append("!(");
Visit(unaryExpression.Operand);
_stringBuilder.Append(")");
break;
case ExpressionType.TypeAs:
_stringBuilder.Append("(");
Visit(unaryExpression.Operand);
_stringBuilder.Append(" as " + unaryExpression.Type.ShortDisplayName() + ")");
break;
case ExpressionType.Quote:
Visit(unaryExpression.Operand);
break;
default:
UnhandledExpressionType(unaryExpression);
break;
}
return unaryExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitDefault(DefaultExpression defaultExpression)
{
_stringBuilder.Append("default(" + defaultExpression.Type.ShortDisplayName() + ")");
return defaultExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitTry(TryExpression tryExpression)
{
_stringBuilder.Append("try { ");
Visit(tryExpression.Body);
_stringBuilder.Append(" } ");
foreach (var handler in tryExpression.Handlers)
{
_stringBuilder.Append("catch (" + handler.Test.Name + ") { ... } ");
}
return tryExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitIndex(IndexExpression indexExpression)
{
Visit(indexExpression.Object);
_stringBuilder.Append("[");
VisitArguments(indexExpression.Arguments, s => _stringBuilder.Append(s));
_stringBuilder.Append("]");
return indexExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitTypeBinary(TypeBinaryExpression typeBinaryExpression)
{
_stringBuilder.Append("(");
Visit(typeBinaryExpression.Expression);
_stringBuilder.Append(" is " + typeBinaryExpression.TypeOperand.ShortDisplayName() + ")");
return typeBinaryExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitExtension(Expression extensionExpression)
{
if (_highlightNonreducibleNodes && !extensionExpression.CanReduce)
{
StringBuilder.Append(HighlightLeft);
}
if (_reduceBeforePrinting && extensionExpression.CanReduce)
{
var reduced = extensionExpression.Reduce();
Visit(reduced);
return extensionExpression;
}
if (extensionExpression is IPrintable printable)
{
printable.Print(this);
}
else
{
switch (extensionExpression)
{
case QuerySourceReferenceExpression qsre:
if (GenerateUniqueQsreIds)
{
var index = VisitedQuerySources.IndexOf(qsre.ReferencedQuerySource);
if (index == -1)
{
StringBuilder.Append("[" + HighlightLeft + qsre.ReferencedQuerySource.ItemName + "{" + index + "}" + HighlightRight + "]");
}
else
{
StringBuilder.Append("[" + qsre.ReferencedQuerySource.ItemName + "{" + index + "}]");
}
}
else
{
StringBuilder.Append(qsre);
}
break;
case SubQueryExpression subqueryExpression:
VisitSubqueryExpression(subqueryExpression);
break;
default:
UnhandledExpressionType(extensionExpression);
break;
}
}
if (_highlightNonreducibleNodes && !extensionExpression.CanReduce)
{
StringBuilder.Append(HighlightRight);
}
return extensionExpression;
}
private void VisitSubqueryExpression(SubQueryExpression subqueryExpression)
{
_stringBuilder.Append(subqueryExpression.QueryModel.Print());
}
private void VisitArguments(IList<Expression> arguments, Action<string> appendAction, string lastSeparator = "", bool areConnected = false)
{
for (var i = 0; i < arguments.Count; i++)
{
if (areConnected && i == arguments.Count - 1)
{
Append("");
_stringBuilder.DisconnectCurrentNode();
}
Visit(arguments[i]);
appendAction(i == arguments.Count - 1 ? lastSeparator : ", ");
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual string PostProcess([NotNull] string queryPlan)
{
var processedPlan = queryPlan
.Replace("Microsoft.EntityFrameworkCore.Query.", "")
.Replace("Microsoft.EntityFrameworkCore.", "")
.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
return processedPlan;
}
private void UnhandledExpressionType(Expression expression)
=> AppendLine(expression.ToString());
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected abstract class ConstantPrinterBase
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public abstract bool TryPrintConstant(
[NotNull] ConstantExpression constantExpression,
[NotNull] IndentedStringBuilder stringBuilder,
bool removeFormatting);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual Action<IndentedStringBuilder, string> Append => (sb, s) => sb.Append(s);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual Action<IndentedStringBuilder, string> AppendLine => (sb, s) => sb.AppendLine(s);
}
private class EntityQueryableConstantPrinter : ConstantPrinterBase
{
public override bool TryPrintConstant(
ConstantExpression constantExpression,
IndentedStringBuilder stringBuilder,
bool removeFormatting)
{
if (constantExpression.IsEntityQueryable())
{
stringBuilder.Append($"DbSet<{constantExpression.Type.GetTypeInfo().GenericTypeArguments.First().ShortDisplayName()}>");
return true;
}
return false;
}
}
private class MetadataPropertyPrinter : ConstantPrinterBase
{
public override bool TryPrintConstant(
ConstantExpression constantExpression,
IndentedStringBuilder stringBuilder,
bool removeFormatting)
{
if (constantExpression.Value is PropertyBase property)
{
stringBuilder.Append(property.DeclaringType.ClrType.Name + "." + property.Name);
return true;
}
return false;
}
}
private class DefaultConstantPrinter : ConstantPrinterBase
{
public override bool TryPrintConstant(
ConstantExpression constantExpression,
IndentedStringBuilder stringBuilder,
bool removeFormatting)
{
Print(constantExpression.Value, stringBuilder, removeFormatting);
return true;
}
private void Print(
object value,
IndentedStringBuilder stringBuilder,
bool removeFormatting)
{
if (value is IEnumerable enumerable
&& !(value is string))
{
var appendAction = value is byte[] || removeFormatting ? Append : AppendLine;
appendAction(stringBuilder, value.GetType().ShortDisplayName() + " ");
appendAction(stringBuilder, "{ ");
stringBuilder.IncrementIndent();
foreach (var item in enumerable)
{
Print(item, stringBuilder, removeFormatting);
appendAction(stringBuilder, ", ");
}
stringBuilder.DecrementIndent();
stringBuilder.Append("}");
return;
}
var stringValue = value == null
? "null"
: value.ToString() != value.GetType().ToString()
? value.ToString()
: value.GetType().ShortDisplayName();
if (value != null
&& value is string)
{
stringValue = $@"""{stringValue}""";
}
stringBuilder.Append(stringValue);
}
}
}
}
| 43.275096 | 155 | 0.57754 | [
"Apache-2.0"
] | Wrank/EntityFrameworkCore | src/EFCore/Query/Internal/ExpressionPrinter.cs | 56,474 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.DotNet.Interactive.Telemetry
{
public class ApplicationInsightsEntryFormat
{
public ApplicationInsightsEntryFormat(
string eventName = null,
IDictionary<string, string> properties = null,
IDictionary<string, double> measurements = null)
{
EventName = eventName;
Properties = properties;
Measurements = measurements;
}
public string EventName { get; }
public IDictionary<string, string> Properties { get; }
public IDictionary<string, double> Measurements { get; }
public ApplicationInsightsEntryFormat WithAppliedToPropertiesValue(Func<string, string> func, Func<string, bool> filter)
{
var appliedProperties = Properties
.ToDictionary(p => p.Key, p => filter(p.Key)? func(p.Value) : p.Value);
return new ApplicationInsightsEntryFormat(EventName, appliedProperties, Measurements);
}
}
}
| 36.705882 | 128 | 0.668269 | [
"MIT"
] | AngelusGi/interactive | src/Microsoft.DotNet.Interactive.Telemetry/ApplicationInsightsEntryFormat.cs | 1,250 | C# |
using OpenQA.Selenium;
using SeleniumDotNetTemplate.Shared;
namespace SeleniumDotNetTemplate.HCC.Pages
{
public abstract class HCCBasePage : BasePage
{
#region elements
private static readonly By Logo = By.XPath("//a[@class='title']/b[text()='Home Cost Calculators']");
#endregion
protected HCCBasePage(IWebDriver driver) : base(driver)
{ }
public HCCHomePage ClickLogo()
{
Driver.WaitForElement(Logo).Click();
return new HCCHomePage(Driver);
}
}
}
| 23.125 | 108 | 0.627027 | [
"MIT"
] | jordnkr/SeleniumDotNetTemplate | HCC/Pages/HCCBasePage.cs | 557 | C# |
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
/* ------------------------------------------------------------------------- */
using Cube.FileSystem;
using Cube.Mixin.String;
using iTextSharp.text.exceptions;
using iTextSharp.text.pdf;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
namespace Cube.Pdf.Itext
{
/* --------------------------------------------------------------------- */
///
/// ReaderFactory
///
/// <summary>
/// Provices functionality to create a PdfReader instance.
/// </summary>
///
/* --------------------------------------------------------------------- */
internal static class ReaderFactory
{
#region Methods
/* ----------------------------------------------------------------- */
///
/// FromPdf
///
/// <summary>
/// Creates a new instance of the PdfReader class.
/// </summary>
///
/// <param name="src">Path of the PDF file.</param>
///
/// <returns>PdfReader object.</returns>
///
/* ----------------------------------------------------------------- */
public static PdfReader FromPdf(string src) => new PdfReader(src);
/* ----------------------------------------------------------------- */
///
/// FromPdf
///
/// <summary>
/// Creates a new instance of the PdfReader class.
/// </summary>
///
/// <param name="src">Path of the PDF file.</param>
/// <param name="password">Password string or query.</param>
/// <param name="options">Open options.</param>
///
/// <returns>PdfReader object.</returns>
///
/* ----------------------------------------------------------------- */
public static PdfReader FromPdf(string src,
QueryMessage<IQuery<string>, string> password,
OpenOption options
) {
while (true)
{
try
{
var bytes = password.Value.HasValue() ? Encoding.UTF8.GetBytes(password.Value) : null;
var dest = new PdfReader(src, bytes, options.SaveMemory);
if (dest.IsOpenedWithFullPermissions || !options.FullAccess) return dest;
dest.Dispose();
throw new BadPasswordException("FullAccess");
}
catch (BadPasswordException)
{
var msg = password.Source.Request(src);
if (!msg.Cancel) password.Value = msg.Value;
else throw new OperationCanceledException();
}
}
}
/* ----------------------------------------------------------------- */
///
/// FromImage
///
/// <summary>
/// Creates a new instance of the PdfReader class from the
/// specified image.
/// </summary>
///
/// <param name="src">Path of the image.</param>
/// <param name="io">I/O handler.</param>
///
/// <returns>PdfReader object.</returns>
///
/* ----------------------------------------------------------------- */
public static PdfReader FromImage(string src, IO io)
{
using (var ms = new System.IO.MemoryStream())
using (var ss = io.OpenRead(src))
using (var image = Image.FromStream(ss))
{
var doc = new iTextSharp.text.Document();
var writer = PdfWriter.GetInstance(doc, ms);
doc.Open();
var guid = image.FrameDimensionsList[0];
var dim = new FrameDimension(guid);
for (var i = 0; i < image.GetFrameCount(dim); ++i)
{
_ = image.SelectActiveFrame(dim, i);
var scale = PdfFile.Point / image.HorizontalResolution;
var w = image.Width * scale;
var h = image.Height * scale;
_ = doc.SetPageSize(new iTextSharp.text.Rectangle(w, h));
_ = doc.NewPage();
_ = doc.Add(image.GetItextImage());
}
doc.Close();
writer.Close();
return new PdfReader(ms.ToArray());
}
}
#endregion
#region Implementations
/* ----------------------------------------------------------------- */
///
/// Request
///
/// <summary>
/// Requests the password of the specified PDF file.
/// </summary>
///
/// <param name="query">Query object.</param>
/// <param name="src">Path of the PDF file.</param>
///
/// <returns>Query result.</returns>
///
/* ----------------------------------------------------------------- */
private static QueryMessage<string, string> Request(this IQuery<string> query, string src)
{
try
{
var dest = Query.NewMessage(src);
query.Request(dest);
if (dest.Cancel || dest.Value.HasValue()) return dest;
throw new ArgumentException("Password is empty.");
}
catch (Exception e) { throw new EncryptionException("Input password may be incorrect.", e); }
}
#endregion
}
} | 35.862857 | 106 | 0.445188 | [
"Apache-2.0"
] | WPG/Cube.Pdf | Libraries/Itext/Sources/Details/ReaderFactory.cs | 6,278 | C# |
using System;
using UnityEngine;
namespace UniRx.Examples
{
public class Sample04_ConvertFromUnityCallback : MonoBehaviour
{
// This is about log but more reliable log sample => Sample11_Logger
private class LogCallback
{
public string Condition;
public string StackTrace;
public UnityEngine.LogType LogType;
}
static class LogHelper
{
// If static register callback, use Subject for event branching.
#if (UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
static Subject<LogCallback> subject;
public static IObservable<LogCallback> LogCallbackAsObservable()
{
if (subject == null)
{
subject = new Subject<LogCallback>();
// Publish to Subject in callback
UnityEngine.Application.RegisterLogCallback((condition, stackTrace, type) =>
{
subject.OnNext(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = type });
});
}
return subject.AsObservable();
}
#else
// If standard evetns, you can use Observable.FromEvent.
public static IObservable<LogCallback> LogCallbackAsObservable()
{
return Observable.FromEvent<Application.LogCallback, LogCallback>(
h => (condition, stackTrace, type) => h(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = type }),
h => Application.logMessageReceived += h, h => Application.logMessageReceived -= h);
}
#endif
}
void Awake()
{
// method is separatable and composable
LogHelper.LogCallbackAsObservable()
.Where(x => x.LogType == LogType.Warning)
.Subscribe(x => Debug.Log(x));
LogHelper.LogCallbackAsObservable()
.Where(x => x.LogType == LogType.Error)
.Subscribe(x => Debug.Log(x));
}
}
} | 34.80303 | 145 | 0.538093 | [
"Apache-2.0"
] | lorenchorley/StrangeIoC-Updated | Assets/Examples/Scripts/Rx/UniRx/Sample04_ConvertFromUnityCallback.cs | 2,297 | C# |
using PipBenchmark.Runner.Execution;
using PipBenchmark.Utilities;
namespace PipBenchmark.Runner.Config
{
public class NumberOfThreadsParameter : Parameter
{
private BenchmarkProcess _process;
public NumberOfThreadsParameter(BenchmarkProcess process)
: base(
"General.Benchmarking.NumberOfThreads",
"Number of threads for concurrent benchmarking",
"1"
)
{
_process = process;
}
public override string Value
{
get { return Converter.IntegerToString(_process.NumberOfThreads); }
set { _process.NumberOfThreads = Converter.StringToInteger(value, 1); }
}
}
}
| 27.222222 | 83 | 0.612245 | [
"MIT"
] | pip-benchmark/pip-benchmark-dotnet | src/PipBenchmark.NetStandard16/Runner/Config/NumberOfThreadsParameter.cs | 737 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 06.12.2021.
using System;
using System.Data;
using System.Globalization;
using System.Threading;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Add.Complete.DateOnly.String{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.DateOnly;
using T_DATA2 =System.String;
using T_DATA1_U=System.DateOnly;
using T_DATA2_U=System.String;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param
public static class TestSet_504__param
{
private const string c_NameOf__TABLE="DUAL";
//-----------------------------------------------------------------------
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int64? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(2020,11,29);
T_DATA2 vv2="--cucu";
var recs=db.testTable.Where(r => (vv1+vv2)=="2020-11-29--cucu");
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
[Test]
public static void Test_C02__LeftToObjectToString()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(2020,11,29);
T_DATA2 vv2="--cucu";
var recs=db.testTable.Where(r => ((string)(object)vv1+vv2)=="2020-11-29--cucu");
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_C02__LeftToObjectToString
};//class TestSet_504__param
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Add.Complete.DateOnly.String
| 25.10625 | 126 | 0.528504 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Add/Complete/DateOnly/String/TestSet_504__param.cs | 4,019 | C# |
using P01_HospitalDatabase.Data;
using P01_HospitalDatabase.Data.Models;
using System;
namespace HospitalStartUp
{
public class Program
{
static void Main()
{
//Installed Microsoft.EntityFrameworkCore.Tools
var dbContext = new HospitalContext();
using (dbContext)
{
dbContext.Database.EnsureCreated();
}
}
}
}
| 21.2 | 59 | 0.582547 | [
"MIT"
] | ewgeni-dinew/04.Databases_Advanced-Entity_Framework | 06.Code First/P01,P02_HospitalDatabase/HospitalStartUp/StartUp.cs | 426 | C# |
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2013 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the camera's field of view.
/// </summary>
[RequireComponent(typeof(Camera))]
[AddComponentMenu("NGUI/Tween/Field of View")]
public class TweenFOV : UITweener
{
public float from;
public float to;
Camera mCam;
/// <summary>
/// Camera that's being tweened.
/// </summary>
public Camera cachedCamera { get { if (mCam == null) mCam = GetComponent<Camera>(); return mCam; } }
/// <summary>
/// Current field of view value.
/// </summary>
public float fov { get { return cachedCamera.fieldOfView; } set { cachedCamera.fieldOfView = value; } }
/// <summary>
/// Perform the tween.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
cachedCamera.fieldOfView = from * (1f - factor) + to * factor;
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenFOV Begin (GameObject go, float duration, float to)
{
TweenFOV comp = UITweener.Begin<TweenFOV>(go, duration);
comp.from = comp.fov;
comp.to = to;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
} | 22.389831 | 104 | 0.60863 | [
"MIT"
] | Camiloasc1/UnityPinball | Assets/NGUI/Scripts/Tweening/TweenFOV.cs | 1,323 | C# |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
namespace Leaf.xNet
{
internal delegate void ProgressDelegate(long bytes, long totalBytes, long totalBytesExpected);
// ReSharper disable once UnusedMember.Global
internal class ProgressStreamContent : System.Net.Http.StreamContent
{
// ReSharper disable once UnusedMember.Global
public ProgressStreamContent(Stream stream, CancellationToken token)
: this(new ProgressStream(stream, token))
{
}
// ReSharper disable once UnusedMember.Global
public ProgressStreamContent(Stream stream, int bufferSize)
: this(new ProgressStream(stream, CancellationToken.None), bufferSize)
{
}
private ProgressStreamContent(ProgressStream stream)
: base(stream) => Init(stream);
private ProgressStreamContent(ProgressStream stream, int bufferSize)
: base(stream, bufferSize) => Init(stream);
private void Init(ProgressStream stream)
{
stream.ReadCallback = ReadBytes;
Progress = delegate { };
}
private void Reset()
{
_totalBytes = 0L;
}
private long _totalBytes;
private long _totalBytesExpected = -1;
private void ReadBytes(long bytes)
{
if (_totalBytesExpected == -1)
_totalBytesExpected = Headers.ContentLength ?? -1;
if (_totalBytesExpected == -1 && TryComputeLength(out long computedLength))
_totalBytesExpected = computedLength == 0 ? -1 : computedLength;
// If less than zero still then change to -1
_totalBytesExpected = Math.Max(-1, _totalBytesExpected);
_totalBytes += bytes;
Progress(bytes, _totalBytes, _totalBytesExpected);
}
private ProgressDelegate _progress;
public ProgressDelegate Progress
{
get => _progress;
set => _progress = value ?? delegate { };
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Reset();
return base.SerializeToStreamAsync(stream, context);
}
protected override bool TryComputeLength(out long length)
{
var result = base.TryComputeLength(out length);
_totalBytesExpected = length;
return result;
}
private class ProgressStream : Stream
{
private readonly CancellationToken _token;
public ProgressStream(Stream stream, CancellationToken token)
{
ParentStream = stream;
_token = token;
ReadCallback = delegate { };
WriteCallback = delegate { };
}
public Action<long> ReadCallback { private get; set; }
private Action<long> WriteCallback { get;}
private Stream ParentStream { get; }
public override bool CanRead => ParentStream.CanRead;
public override bool CanSeek => ParentStream.CanSeek;
public override bool CanWrite => ParentStream.CanWrite;
public override bool CanTimeout => ParentStream.CanTimeout;
public override long Length => ParentStream.Length;
public override void Flush()
{
ParentStream.Flush();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return ParentStream.FlushAsync(cancellationToken);
}
public override long Position
{
get => ParentStream.Position;
set => ParentStream.Position = value;
}
public override int Read(byte[] buffer, int offset, int count)
{
_token.ThrowIfCancellationRequested();
var readCount = ParentStream.Read(buffer, offset, count);
ReadCallback(readCount);
return readCount;
}
public override long Seek(long offset, SeekOrigin origin)
{
_token.ThrowIfCancellationRequested();
return ParentStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
_token.ThrowIfCancellationRequested();
ParentStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
_token.ThrowIfCancellationRequested();
ParentStream.Write(buffer, offset, count);
WriteCallback(count);
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
_token.ThrowIfCancellationRequested();
var linked = CancellationTokenSource.CreateLinkedTokenSource(_token, cancellationToken);
var readCount = await ParentStream.ReadAsync(buffer, offset, count, linked.Token);
ReadCallback(readCount);
return readCount;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
_token.ThrowIfCancellationRequested();
var linked = CancellationTokenSource.CreateLinkedTokenSource(_token, cancellationToken);
var task = ParentStream.WriteAsync(buffer, offset, count, linked.Token);
WriteCallback(count);
return task;
}
#region Dispose
private bool _disposed;
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
ParentStream?.Dispose();
_disposed = true;
}
#endregion
}
}
}
| 31.676923 | 128 | 0.576493 | [
"MIT"
] | YungSamzy/SimpsLib | Web/~Internal/ProgressStreamContent.cs | 6,179 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.TrafficManager.Models
{
using Newtonsoft.Json;
using System.Reflection;
/// <summary>
/// Defines values for MonitorProtocol.
/// </summary>
public sealed class MonitorProtocolConverter : JsonConverter
{
/// <summary>
/// Returns if objectType can be converted to MonitorProtocol by the
/// converter.
/// </summary>
public override bool CanConvert(System.Type objectType)
{
return typeof(MonitorProtocol).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
/// <summary>
/// Overrides ReadJson and converts token to MonitorProtocol.
/// </summary>
public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == Newtonsoft.Json.JsonToken.Null)
{
return null;
}
return (MonitorProtocol)serializer.Deserialize<string>(reader);
}
/// <summary>
/// Overriding WriteJson for MonitorProtocol for serialization.
/// </summary>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
}
| 31.833333 | 131 | 0.644561 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/trafficmanager/Microsoft.Azure.Management.TrafficManager/src/Generated/Models/MonitorProtocolConverter.cs | 1,719 | C# |
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Mono.Cecil;
using NUnit.Framework;
using Xamarin.Android.Tasks;
using Xamarin.ProjectTools;
using Xamarin.Tools.Zip;
using Microsoft.Android.Build.Tasks;
namespace Xamarin.Android.Build.Tests
{
[TestFixture]
[NonParallelizable] // On MacOS, parallel /restore causes issues
[Category ("Node-2"), Category ("DotNetIgnore")] // These don't need to run under `dotnet test`
public class XASdkTests : BaseTest
{
/// <summary>
/// The full path to the project directory
/// </summary>
public string FullProjectDirectory { get; set; }
static readonly object [] DotNetBuildLibrarySource = new object [] {
new object [] {
/* isRelease */ false,
/* duplicateAar */ false,
},
new object [] {
/* isRelease */ false,
/* duplicateAar */ true,
},
new object [] {
/* isRelease */ true,
/* duplicateAar */ false,
},
};
[Test]
[Category ("SmokeTests")]
[TestCaseSource (nameof (DotNetBuildLibrarySource))]
public void DotNetBuildLibrary (bool isRelease, bool duplicateAar)
{
var path = Path.Combine ("temp", TestName);
var env_var = "MY_ENVIRONMENT_VAR";
var env_val = "MY_VALUE";
// Setup dependencies App A -> Lib B -> Lib C
var libC = new XASdkProject (outputType: "Library") {
ProjectName = "LibraryC",
IsRelease = isRelease,
Sources = {
new BuildItem.Source ("Bar.cs") {
TextContent = () => "public class Bar { }",
},
new AndroidItem.AndroidResource (() => "Resources\\drawable\\IMALLCAPS.png") {
BinaryContent = () => XamarinAndroidApplicationProject.icon_binary_mdpi,
},
}
};
libC.OtherBuildItems.Add (new AndroidItem.AndroidAsset ("Assets\\bar\\bar.txt") {
BinaryContent = () => Array.Empty<byte> (),
});
var activity = libC.Sources.FirstOrDefault (s => s.Include () == "MainActivity.cs");
if (activity != null)
libC.Sources.Remove (activity);
var libCBuilder = CreateDotNetBuilder (libC, Path.Combine (path, libC.ProjectName));
Assert.IsTrue (libCBuilder.Build (), $"{libC.ProjectName} should succeed");
var libB = new XASdkProject (outputType: "Library") {
ProjectName = "LibraryB",
IsRelease = isRelease,
Sources = {
new BuildItem.Source ("Foo.cs") {
TextContent = () =>
@"public class Foo : Bar
{
public Foo ()
{
int x = LibraryB.Resource.Drawable.IMALLCAPS;
}
}",
},
new AndroidItem.AndroidResource ("Resources\\layout\\test.axml") {
TextContent = () => {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ImageView xmlns:android=\"http://schemas.android.com/apk/res/android\" android:src=\"@drawable/IMALLCAPS\" />";
}
}
}
};
libB.OtherBuildItems.Add (new AndroidItem.AndroidAsset ("Assets\\foo\\foo.txt") {
BinaryContent = () => Array.Empty<byte> (),
});
libB.OtherBuildItems.Add (new AndroidItem.AndroidResource ("Resources\\layout\\MyLayout.axml") {
TextContent = () => "<?xml version=\"1.0\" encoding=\"utf-8\" ?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" />"
});
libB.OtherBuildItems.Add (new AndroidItem.AndroidResource ("Resources\\raw\\bar.txt") {
BinaryContent = () => Array.Empty<byte> (),
});
libB.OtherBuildItems.Add (new AndroidItem.AndroidEnvironment ("env.txt") {
TextContent = () => $"{env_var}={env_val}",
});
libB.OtherBuildItems.Add (new AndroidItem.AndroidEnvironment ("sub\\directory\\env.txt") {
TextContent = () => $"{env_var}={env_val}",
});
libB.OtherBuildItems.Add (new AndroidItem.AndroidLibrary ("sub\\directory\\foo.jar") {
BinaryContent = () => ResourceData.JavaSourceJarTestJar,
});
libB.OtherBuildItems.Add (new AndroidItem.AndroidLibrary ("sub\\directory\\arm64-v8a\\libfoo.so") {
BinaryContent = () => Array.Empty<byte> (),
});
libB.OtherBuildItems.Add (new AndroidItem.AndroidNativeLibrary (default (Func<string>)) {
Update = () => "libfoo.so",
MetadataValues = "Link=x86\\libfoo.so",
BinaryContent = () => Array.Empty<byte> (),
});
libB.AddReference (libC);
activity = libB.Sources.FirstOrDefault (s => s.Include () == "MainActivity.cs");
if (activity != null)
libB.Sources.Remove (activity);
var libBBuilder = CreateDotNetBuilder (libB, Path.Combine (path, libB.ProjectName));
Assert.IsTrue (libBBuilder.Build (), $"{libB.ProjectName} should succeed");
// Check .aar file for class library
var aarPath = Path.Combine (FullProjectDirectory, libB.OutputPath, $"{libB.ProjectName}.aar");
FileAssert.Exists (aarPath);
using (var aar = ZipHelper.OpenZip (aarPath)) {
aar.AssertContainsEntry (aarPath, "assets/foo/foo.txt");
aar.AssertContainsEntry (aarPath, "res/layout/mylayout.xml");
aar.AssertContainsEntry (aarPath, "res/raw/bar.txt");
aar.AssertContainsEntry (aarPath, ".net/__res_name_case_map.txt");
aar.AssertContainsEntry (aarPath, ".net/env/190E30B3D205731E.env");
aar.AssertContainsEntry (aarPath, ".net/env/2CBDAB7FEEA94B19.env");
aar.AssertContainsEntry (aarPath, "libs/A1AFA985571E728E.jar");
aar.AssertContainsEntry (aarPath, "jni/arm64-v8a/libfoo.so");
aar.AssertContainsEntry (aarPath, "jni/x86/libfoo.so");
}
// Check EmbeddedResource files do not exist
var assemblyPath = Path.Combine (FullProjectDirectory, libB.OutputPath, $"{libB.ProjectName}.dll");
FileAssert.Exists (assemblyPath);
using (var assembly = AssemblyDefinition.ReadAssembly (assemblyPath)) {
Assert.AreEqual (0, assembly.MainModule.Resources.Count);
}
var appA = new XASdkProject {
ProjectName = "AppA",
IsRelease = isRelease,
Sources = {
new BuildItem.Source ("Bar.cs") {
TextContent = () => "public class Bar : Foo { }",
}
}
};
appA.AddReference (libB);
if (duplicateAar) {
// Test a duplicate @(AndroidLibrary) item with the same path of LibraryB.aar
appA.OtherBuildItems.Add (new AndroidItem.AndroidLibrary (aarPath));
}
var appBuilder = CreateDotNetBuilder (appA, Path.Combine (path, appA.ProjectName));
Assert.IsTrue (appBuilder.Build (), $"{appA.ProjectName} should succeed");
// Check .apk for assets, res, and native libraries
var apkPath = Path.Combine (FullProjectDirectory, appA.OutputPath, $"{appA.PackageName}.apk");
FileAssert.Exists (apkPath);
using (var apk = ZipHelper.OpenZip (apkPath)) {
apk.AssertContainsEntry (apkPath, "assets/foo/foo.txt");
apk.AssertContainsEntry (apkPath, "assets/bar/bar.txt");
apk.AssertContainsEntry (aarPath, "res/layout/mylayout.xml");
apk.AssertContainsEntry (apkPath, "res/raw/bar.txt");
apk.AssertContainsEntry (apkPath, "lib/arm64-v8a/libfoo.so");
apk.AssertContainsEntry (apkPath, "lib/x86/libfoo.so");
}
// Check classes.dex contains foo.jar
var intermediate = Path.Combine (FullProjectDirectory, appA.IntermediateOutputPath);
var dexFile = Path.Combine (intermediate, "android", "bin", "classes.dex");
FileAssert.Exists (dexFile);
string className = "Lcom/xamarin/android/test/msbuildtest/JavaSourceJarTest;";
Assert.IsTrue (DexUtils.ContainsClass (className, dexFile, AndroidSdkPath), $"`{dexFile}` should include `{className}`!");
// Check environment variable
var environmentFiles = EnvironmentHelper.GatherEnvironmentFiles (intermediate, "x86", required: true);
var environmentVariables = EnvironmentHelper.ReadEnvironmentVariables (environmentFiles);
Assert.IsTrue (environmentVariables.TryGetValue (env_var, out string actual), $"Environment should contain {env_var}");
Assert.AreEqual (env_val, actual, $"{env_var} should be {env_val}");
// Check Resource.designer.cs
var resource_designer_cs = Path.Combine (intermediate, "Resource.designer.cs");
FileAssert.Exists (resource_designer_cs);
var resource_designer_text = File.ReadAllText (resource_designer_cs);
StringAssert.Contains ("public const int MyLayout", resource_designer_text);
StringAssert.Contains ("global::LibraryB.Resource.Drawable.IMALLCAPS = global::AppA.Resource.Drawable.IMALLCAPS", resource_designer_text);
}
[Test]
public void DotNetNew ([Values ("android", "androidlib", "android-bindinglib")] string template)
{
var dotnet = CreateDotNetBuilder ();
Assert.IsTrue (dotnet.New (template), $"`dotnet new {template}` should succeed");
File.WriteAllBytes (Path.Combine (dotnet.ProjectDirectory, "foo.jar"), ResourceData.JavaSourceJarTestJar);
Assert.IsTrue (dotnet.New ("android-activity"), "`dotnet new android-activity` should succeed");
Assert.IsTrue (dotnet.New ("android-layout", Path.Combine (dotnet.ProjectDirectory, "Resources", "layout")), "`dotnet new android-layout` should succeed");
Assert.IsTrue (dotnet.Build (), "`dotnet build` should succeed");
}
[Test]
public void DotNetPack ([Values ("net6.0-android", "net6.0-android30")] string targetFramework)
{
var proj = new XASdkProject (outputType: "Library") {
TargetFramework = targetFramework,
IsRelease = true,
Sources = {
new BuildItem.Source ("Foo.cs") {
TextContent = () => "public class Foo { }",
}
}
};
proj.OtherBuildItems.Add (new AndroidItem.AndroidResource ("Resources\\raw\\bar.txt") {
BinaryContent = () => Array.Empty<byte> (),
});
proj.OtherBuildItems.Add (new AndroidItem.AndroidLibrary ("sub\\directory\\foo.jar") {
BinaryContent = () => ResourceData.JavaSourceJarTestJar,
});
proj.OtherBuildItems.Add (new AndroidItem.AndroidLibrary ("sub\\directory\\arm64-v8a\\libfoo.so") {
BinaryContent = () => Array.Empty<byte> (),
});
proj.OtherBuildItems.Add (new AndroidItem.AndroidNativeLibrary (default (Func<string>)) {
Update = () => "libfoo.so",
MetadataValues = "Link=x86\\libfoo.so",
BinaryContent = () => Array.Empty<byte> (),
});
var dotnet = CreateDotNetBuilder (proj);
Assert.IsTrue (dotnet.Pack (), "`dotnet pack` should succeed");
var nupkgPath = Path.Combine (FullProjectDirectory, proj.OutputPath, "..", $"{proj.ProjectName}.1.0.0.nupkg");
FileAssert.Exists (nupkgPath);
using (var nupkg = ZipHelper.OpenZip (nupkgPath)) {
nupkg.AssertContainsEntry (nupkgPath, $"lib/net6.0-android30.0/{proj.ProjectName}.dll");
nupkg.AssertContainsEntry (nupkgPath, $"lib/net6.0-android30.0/{proj.ProjectName}.aar");
}
}
[Test]
public void DotNetLibraryAarChanges ()
{
var proj = new XASdkProject (outputType: "Library");
proj.Sources.Add (new AndroidItem.AndroidResource ("Resources\\raw\\foo.txt") {
TextContent = () => "foo",
});
proj.Sources.Add (new AndroidItem.AndroidResource ("Resources\\raw\\bar.txt") {
TextContent = () => "bar",
});
var dotnet = CreateDotNetBuilder (proj);
Assert.IsTrue (dotnet.Build (), "first build should succeed");
var aarPath = Path.Combine (FullProjectDirectory, proj.OutputPath, $"{proj.ProjectName}.aar");
FileAssert.Exists (aarPath);
using (var aar = ZipHelper.OpenZip (aarPath)) {
aar.AssertEntryContents (aarPath, "res/raw/foo.txt", contents: "foo");
aar.AssertEntryContents (aarPath, "res/raw/bar.txt", contents: "bar");
}
// Change res/raw/bar.txt contents
WaitFor (1000);
var bar_txt = Path.Combine (FullProjectDirectory, "Resources", "raw", "bar.txt");
File.WriteAllText (bar_txt, contents: "baz");
Assert.IsTrue (dotnet.Build (), "second build should succeed");
FileAssert.Exists (aarPath);
using (var aar = ZipHelper.OpenZip (aarPath)) {
aar.AssertEntryContents (aarPath, "res/raw/foo.txt", contents: "foo");
aar.AssertEntryContents (aarPath, "res/raw/bar.txt", contents: "baz");
}
// Delete res/raw/bar.txt
File.Delete (bar_txt);
Assert.IsTrue (dotnet.Build (), "third build should succeed");
FileAssert.Exists (aarPath);
using (var aar = ZipHelper.OpenZip (aarPath)) {
aar.AssertEntryContents (aarPath, "res/raw/foo.txt", contents: "foo");
aar.AssertDoesNotContainEntry (aarPath, "res/raw/bar.txt");
}
}
[Test]
[Category ("SmokeTests")]
public void DotNetBuildBinding ()
{
var proj = new XASdkProject (outputType: "Library");
// Both transform files should be applied
proj.Sources.Add (new AndroidItem.TransformFile ("Transforms.xml") {
TextContent = () =>
@"<metadata>
<attr path=""/api/package[@name='com.xamarin.android.test.msbuildtest']"" name=""managedName"">FooBar</attr>
</metadata>",
});
proj.Sources.Add (new AndroidItem.TransformFile ("Transforms\\Metadata.xml") {
TextContent = () =>
@"<metadata>
<attr path=""/api/package[@managedName='FooBar']"" name=""managedName"">MSBuildTest</attr>
</metadata>",
});
proj.Sources.Add (new AndroidItem.AndroidLibrary ("javaclasses.jar") {
BinaryContent = () => ResourceData.JavaSourceJarTestJar,
});
proj.OtherBuildItems.Add (new BuildItem ("JavaSourceJar", "javaclasses-sources.jar") {
BinaryContent = () => ResourceData.JavaSourceJarTestSourcesJar,
});
var dotnet = CreateDotNetBuilder (proj);
Assert.IsTrue (dotnet.Build (), "`dotnet build` should succeed");
var assemblyPath = Path.Combine (FullProjectDirectory, proj.OutputPath, "UnnamedProject.dll");
FileAssert.Exists (assemblyPath);
using (var assembly = AssemblyDefinition.ReadAssembly (assemblyPath)) {
var typeName = "MSBuildTest.JavaSourceJarTest";
var type = assembly.MainModule.GetType (typeName);
Assert.IsNotNull (type, $"{assemblyPath} should contain {typeName}");
}
}
static readonly object [] DotNetBuildSource = new object [] {
new object [] {
/* runtimeIdentifiers */ "android-arm",
/* isRelease */ false,
/* aot */ false,
},
new object [] {
/* runtimeIdentifiers */ "android-arm64",
/* isRelease */ false,
/* aot */ false,
},
new object [] {
/* runtimeIdentifiers */ "android-x86",
/* isRelease */ false,
/* aot */ false,
},
new object [] {
/* runtimeIdentifiers */ "android-x64",
/* isRelease */ false,
/* aot */ false,
},
new object [] {
/* runtimeIdentifiers */ "android-arm",
/* isRelease */ true,
/* aot */ false,
},
new object [] {
/* runtimeIdentifiers */ "android-arm",
/* isRelease */ true,
/* aot */ true,
},
new object [] {
/* runtimeIdentifiers */ "android-arm64",
/* isRelease */ true,
/* aot */ false,
},
new object [] {
/* runtimeIdentifiers */ "android-arm;android-arm64;android-x86;android-x64",
/* isRelease */ false,
/* aot */ false,
},
new object [] {
/* runtimeIdentifiers */ "android-arm;android-arm64;android-x86",
/* isRelease */ true,
/* aot */ false,
},
new object [] {
/* runtimeIdentifiers */ "android-arm;android-arm64;android-x86;android-x64",
/* isRelease */ true,
/* aot */ false,
},
new object [] {
/* runtimeIdentifiers */ "android-arm;android-arm64;android-x86;android-x64",
/* isRelease */ true,
/* aot */ true,
},
};
[Test]
[Category ("SmokeTests")]
[TestCaseSource (nameof (DotNetBuildSource))]
public void DotNetBuild (string runtimeIdentifiers, bool isRelease, bool aot)
{
var proj = new XASdkProject {
IsRelease = isRelease,
ExtraNuGetConfigSources = {
"https://pkgs.dev.azure.com/azure-public/vside/_packaging/xamarin-impl/nuget/v3/index.json"
},
PackageReferences = {
new Package { Id = "Xamarin.AndroidX.AppCompat", Version = "1.2.0.7-net6preview01" },
new Package { Id = "Microsoft.AspNetCore.Components.WebView", Version = "6.0.0-preview.5.21301.17" },
new Package { Id = "Microsoft.Extensions.FileProviders.Embedded", Version = "6.0.0-preview.6.21306.3" },
new Package { Id = "Microsoft.JSInterop", Version = "6.0.0-preview.6.21306.3" },
new Package { Id = "System.Text.Json", Version = "6.0.0-preview.7.21323.3" },
},
Sources = {
new BuildItem ("EmbeddedResource", "Foo.resx") {
TextContent = () => InlineData.ResxWithContents ("<data name=\"CancelButton\"><value>Cancel</value></data>")
},
new BuildItem ("EmbeddedResource", "Foo.es.resx") {
TextContent = () => InlineData.ResxWithContents ("<data name=\"CancelButton\"><value>Cancelar</value></data>")
},
new AndroidItem.TransformFile ("Transforms.xml") {
// Remove two methods that introduced warnings:
// Com.Balysv.Material.Drawable.Menu.MaterialMenuView.cs(214,30): warning CS0114: 'MaterialMenuView.OnRestoreInstanceState(IParcelable)' hides inherited member 'View.OnRestoreInstanceState(IParcelable?)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// Com.Balysv.Material.Drawable.Menu.MaterialMenuView.cs(244,56): warning CS0114: 'MaterialMenuView.OnSaveInstanceState()' hides inherited member 'View.OnSaveInstanceState()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
TextContent = () => "<metadata><remove-node path=\"/api/package[@name='com.balysv.material.drawable.menu']/class[@name='MaterialMenuView']/method[@name='onRestoreInstanceState']\" /><remove-node path=\"/api/package[@name='com.balysv.material.drawable.menu']/class[@name='MaterialMenuView']/method[@name='onSaveInstanceState']\" /></metadata>",
},
new AndroidItem.AndroidLibrary ("material-menu-1.1.0.aar") {
WebContent = "https://repo1.maven.org/maven2/com/balysv/material-menu/1.1.0/material-menu-1.1.0.aar"
},
}
};
proj.MainActivity = proj.DefaultMainActivity.Replace (": Activity", ": AndroidX.AppCompat.App.AppCompatActivity");
if (aot) {
proj.SetProperty ("RunAOTCompilation", "true");
}
proj.OtherBuildItems.Add (new AndroidItem.InputJar ("javaclasses.jar") {
BinaryContent = () => ResourceData.JavaSourceJarTestJar,
});
proj.OtherBuildItems.Add (new BuildItem ("JavaSourceJar", "javaclasses-sources.jar") {
BinaryContent = () => ResourceData.JavaSourceJarTestSourcesJar,
});
if (!runtimeIdentifiers.Contains (";")) {
proj.SetProperty (KnownProperties.RuntimeIdentifier, runtimeIdentifiers);
} else {
proj.SetProperty (KnownProperties.RuntimeIdentifiers, runtimeIdentifiers);
}
var dotnet = CreateDotNetBuilder (proj);
Assert.IsTrue (dotnet.Build (), "`dotnet build` should succeed");
dotnet.AssertHasNoWarnings ();
var outputPath = Path.Combine (FullProjectDirectory, proj.OutputPath);
var intermediateOutputPath = Path.Combine (FullProjectDirectory, proj.IntermediateOutputPath);
if (!runtimeIdentifiers.Contains (";")) {
outputPath = Path.Combine (outputPath, runtimeIdentifiers);
intermediateOutputPath = Path.Combine (intermediateOutputPath, runtimeIdentifiers);
}
var files = Directory.EnumerateFileSystemEntries (outputPath)
.Select (Path.GetFileName)
.OrderBy (f => f)
.ToArray ();
var expectedFiles = new[]{
$"{proj.PackageName}.apk",
$"{proj.PackageName}-Signed.apk",
"es",
$"{proj.ProjectName}.dll",
$"{proj.ProjectName}.pdb",
$"{proj.ProjectName}.runtimeconfig.json",
$"{proj.ProjectName}.xml",
};
CollectionAssert.AreEqual (expectedFiles, files, $"Expected: {string.Join (";", expectedFiles)}\n Found: {string.Join (";", files)}");
var assemblyPath = Path.Combine (outputPath, $"{proj.ProjectName}.dll");
FileAssert.Exists (assemblyPath);
using (var assembly = AssemblyDefinition.ReadAssembly (assemblyPath)) {
var typeName = "Com.Xamarin.Android.Test.Msbuildtest.JavaSourceJarTest";
Assert.IsNotNull (assembly.MainModule.GetType (typeName), $"{assemblyPath} should contain {typeName}");
typeName = "Com.Balysv.Material.Drawable.Menu.MaterialMenuView";
Assert.IsNotNull (assembly.MainModule.GetType (typeName), $"{assemblyPath} should contain {typeName}");
}
var rids = runtimeIdentifiers.Split (';');
if (isRelease) {
// Check for stripped native libraries
foreach (var rid in rids) {
FileAssert.Exists (Path.Combine (intermediateOutputPath, "native", rid, "libmono-android.release.so"));
FileAssert.Exists (Path.Combine (intermediateOutputPath, "native", rid, "libmonosgen-2.0.so"));
}
}
// Check AndroidManifest.xml
var manifestPath = Path.Combine (intermediateOutputPath, "android", "AndroidManifest.xml");
FileAssert.Exists (manifestPath);
var manifest = XDocument.Load (manifestPath);
XNamespace ns = "http://schemas.android.com/apk/res/android";
var uses_sdk = manifest.Root.Element ("uses-sdk");
Assert.AreEqual ("21", uses_sdk.Attribute (ns + "minSdkVersion").Value);
Assert.AreEqual ("30", uses_sdk.Attribute (ns + "targetSdkVersion").Value);
bool expectEmbeddedAssembies = !(CommercialBuildAvailable && !isRelease);
var apkPath = Path.Combine (outputPath, $"{proj.PackageName}.apk");
FileAssert.Exists (apkPath);
using (var apk = ZipHelper.OpenZip (apkPath)) {
apk.AssertContainsEntry (apkPath, $"assemblies/{proj.ProjectName}.dll", shouldContainEntry: expectEmbeddedAssembies);
apk.AssertContainsEntry (apkPath, $"assemblies/{proj.ProjectName}.pdb", shouldContainEntry: !CommercialBuildAvailable && !isRelease);
apk.AssertContainsEntry (apkPath, $"assemblies/System.Linq.dll", shouldContainEntry: expectEmbeddedAssembies);
apk.AssertContainsEntry (apkPath, $"assemblies/es/{proj.ProjectName}.resources.dll", shouldContainEntry: expectEmbeddedAssembies);
foreach (var abi in rids.Select (AndroidRidAbiHelper.RuntimeIdentifierToAbi)) {
apk.AssertContainsEntry (apkPath, $"lib/{abi}/libmonodroid.so");
apk.AssertContainsEntry (apkPath, $"lib/{abi}/libmonosgen-2.0.so");
if (rids.Length > 1) {
apk.AssertContainsEntry (apkPath, $"assemblies/{abi}/System.Private.CoreLib.dll", shouldContainEntry: expectEmbeddedAssembies);
} else {
apk.AssertContainsEntry (apkPath, "assemblies/System.Private.CoreLib.dll", shouldContainEntry: expectEmbeddedAssembies);
}
}
}
}
[Test]
public void SupportedOSPlatformVersion ([Values (21, 30)] int minSdkVersion)
{
var proj = new XASdkProject {
SupportedOSPlatformVersion = minSdkVersion.ToString (),
};
// Call AccessibilityTraversalAfter from API level 22
// https://developer.android.com/reference/android/view/View#getAccessibilityTraversalAfter()
proj.MainActivity = proj.DefaultMainActivity.Replace ("button.Click", "button.AccessibilityTraversalAfter.ToString ();\nbutton.Click");
var dotnet = CreateDotNetBuilder (proj);
Assert.IsTrue (dotnet.Build (), "`dotnet build` should succeed");
if (minSdkVersion < 22) {
StringAssertEx.Contains ("warning CA1416", dotnet.LastBuildOutput, "Should get warning about Android 22 API");
} else {
dotnet.AssertHasNoWarnings ();
}
var manifestPath = Path.Combine (FullProjectDirectory, proj.IntermediateOutputPath, "android", "AndroidManifest.xml");
FileAssert.Exists (manifestPath);
var manifest = XDocument.Load (manifestPath);
XNamespace ns = "http://schemas.android.com/apk/res/android";
Assert.AreEqual (minSdkVersion.ToString (), manifest.Root.Element ("uses-sdk").Attribute (ns + "minSdkVersion").Value);
}
[Test]
[Category ("SmokeTests")]
public void DotNetBuildXamarinForms ([Values (true, false)] bool useInterpreter)
{
var proj = new XamarinFormsXASdkProject ();
proj.SetProperty ("UseInterpreter", useInterpreter.ToString ());
var dotnet = CreateDotNetBuilder (proj);
Assert.IsTrue (dotnet.Build (), "`dotnet build` should succeed");
dotnet.AssertHasNoWarnings ();
}
[Test]
public void DotNetPublish ([Values (false, true)] bool isRelease)
{
const string runtimeIdentifier = "android-arm";
var proj = new XASdkProject {
IsRelease = isRelease
};
proj.SetProperty (KnownProperties.RuntimeIdentifier, runtimeIdentifier);
var dotnet = CreateDotNetBuilder (proj);
Assert.IsTrue (dotnet.Publish (), "first `dotnet publish` should succeed");
var publishDirectory = Path.Combine (FullProjectDirectory, proj.OutputPath, runtimeIdentifier, "publish");
var apk = Path.Combine (publishDirectory, $"{proj.PackageName}.apk");
var apkSigned = Path.Combine (publishDirectory, $"{proj.PackageName}-Signed.apk");
FileAssert.Exists (apk);
FileAssert.Exists (apkSigned);
Assert.IsTrue (dotnet.Publish (parameters: new [] { "AndroidPackageFormat=aab" }), $"second `dotnet publish` should succeed");
var aab = Path.Combine (publishDirectory, $"{proj.PackageName}.aab");
var aabSigned = Path.Combine (publishDirectory, $"{proj.PackageName}-Signed.aab");
FileAssert.DoesNotExist (apk);
FileAssert.DoesNotExist (apkSigned);
FileAssert.Exists (aab);
FileAssert.Exists (aabSigned);
}
[Test]
public void DefaultItems ()
{
void CreateEmptyFile (params string [] paths)
{
var path = Path.Combine (FullProjectDirectory, Path.Combine (paths));
Directory.CreateDirectory (Path.GetDirectoryName (path));
File.WriteAllText (path, contents: "");
}
var proj = new XASdkProject ();
var dotnet = CreateDotNetBuilder (proj);
// Build error -> no nested sub-directories in Resources
CreateEmptyFile ("Resources", "drawable", "foo", "bar.png");
CreateEmptyFile ("Resources", "raw", "foo", "bar.png");
// Build error -> no files/directories that start with .
CreateEmptyFile ("Resources", "raw", ".DS_Store");
CreateEmptyFile ("Assets", ".DS_Store");
CreateEmptyFile ("Assets", ".svn", "foo.txt");
// Files that should work
CreateEmptyFile ("Resources", "raw", "foo.txt");
CreateEmptyFile ("Assets", "foo", "bar.txt");
Assert.IsTrue (dotnet.Build (), "`dotnet build` should succeed");
var apkPath = Path.Combine (FullProjectDirectory, proj.OutputPath, $"{proj.PackageName}.apk");
FileAssert.Exists (apkPath);
using (var apk = ZipHelper.OpenZip (apkPath)) {
apk.AssertContainsEntry (apkPath, "res/raw/foo.txt");
apk.AssertContainsEntry (apkPath, "assets/foo/bar.txt");
}
}
[Test]
public void XamarinLegacySdk ()
{
var proj = new XASdkProject (outputType: "Library") {
Sdk = "Xamarin.Legacy.Sdk/0.1.0-alpha2",
Sources = {
new AndroidItem.AndroidLibrary ("javaclasses.jar") {
BinaryContent = () => ResourceData.JavaSourceJarTestJar,
}
}
};
using var b = new Builder ();
var dotnetTargetFramework = "net6.0-android30.0";
var legacyTargetFrameworkVersion = "11.0";
var legacyTargetFramework = $"monoandroid{legacyTargetFrameworkVersion}";
proj.SetProperty ("TargetFramework", value: "");
proj.SetProperty ("TargetFrameworks", value: $"{dotnetTargetFramework};{legacyTargetFramework}");
var dotnet = CreateDotNetBuilder (proj);
Assert.IsTrue (dotnet.Pack (), "`dotnet pack` should succeed");
var nupkgPath = Path.Combine (FullProjectDirectory, proj.OutputPath, $"{proj.ProjectName}.1.0.0.nupkg");
FileAssert.Exists (nupkgPath);
using var nupkg = ZipHelper.OpenZip (nupkgPath);
nupkg.AssertContainsEntry (nupkgPath, $"lib/{dotnetTargetFramework}/{proj.ProjectName}.dll");
nupkg.AssertContainsEntry (nupkgPath, $"lib/{legacyTargetFramework}/{proj.ProjectName}.dll");
}
[Test]
public void MauiTargetFramework ([Values ("net6.0-android", "net6.0-android30", "net6.0-android30.0")] string targetFramework)
{
var library = new XASdkProject (outputType: "Library") {
TargetFramework = targetFramework,
};
library.ExtraNuGetConfigSources.Add ("https://pkgs.dev.azure.com/azure-public/vside/_packaging/xamarin-impl/nuget/v3/index.json");
library.Sources.Clear ();
library.Sources.Add (new BuildItem.Source ("Foo.cs") {
TextContent = () =>
@"using Microsoft.Maui;
using Microsoft.Maui.Handlers;
public abstract class Foo<TVirtualView, TNativeView> : AbstractViewHandler<TVirtualView, TNativeView>
where TVirtualView : class, IView
#if ANDROID
where TNativeView : Android.Views.View
#else
where TNativeView : class
#endif
{
protected Foo (PropertyMapper mapper) : base(mapper)
{
#if ANDROID
var t = this.Context;
#endif
}
}",
});
library.PackageReferences.Add (new Package { Id = "Microsoft.Maui.Core", Version = "6.0.100-preview.3.269" });
var dotnet = CreateDotNetBuilder (library);
Assert.IsTrue (dotnet.Build (), $"{library.ProjectName} should succeed");
dotnet.AssertHasNoWarnings ();
}
[Test]
public void DotNetIncremental ()
{
// Setup dependencies App A -> Lib B
var path = Path.Combine ("temp", TestName);
var libB = new XASdkProject (outputType: "Library") {
ProjectName = "LibraryB"
};
libB.Sources.Clear ();
libB.Sources.Add (new BuildItem.Source ("Foo.cs") {
TextContent = () => "public class Foo { }",
});
// Will save the project, does not need to build it
CreateDotNetBuilder (libB, Path.Combine (path, libB.ProjectName));
var appA = new XASdkProject {
ProjectName = "AppA",
Sources = {
new BuildItem.Source ("Bar.cs") {
TextContent = () => "public class Bar : Foo { }",
}
}
};
appA.AddReference (libB);
var appBuilder = CreateDotNetBuilder (appA, Path.Combine (path, appA.ProjectName));
Assert.IsTrue (appBuilder.Build (), $"{appA.ProjectName} should succeed");
appBuilder.AssertTargetIsNotSkipped ("CoreCompile");
// Build again, no changes
Assert.IsTrue (appBuilder.Build (), $"{appA.ProjectName} should succeed");
appBuilder.AssertTargetIsSkipped ("CoreCompile");
}
[Test]
public void SignAndroidPackage ()
{
var proj = new XASdkProject ();
var builder = CreateDotNetBuilder (proj);
var parameters = new [] { "BuildingInsideVisualStudio=true" };
Assert.IsTrue (builder.Build ("SignAndroidPackage", parameters), $"{proj.ProjectName} should succeed");
}
DotNetCLI CreateDotNetBuilder (string relativeProjectDir = null)
{
if (string.IsNullOrEmpty (relativeProjectDir)) {
relativeProjectDir = Path.Combine ("temp", TestName);
}
TestOutputDirectories [TestContext.CurrentContext.Test.ID] =
FullProjectDirectory = Path.Combine (Root, relativeProjectDir);
new XASdkProject ().CopyNuGetConfig (relativeProjectDir);
return new DotNetCLI (Path.Combine (FullProjectDirectory, $"{TestName}.csproj"));
}
DotNetCLI CreateDotNetBuilder (XASdkProject project, string relativeProjectDir = null)
{
if (string.IsNullOrEmpty (relativeProjectDir)) {
relativeProjectDir = Path.Combine ("temp", TestName);
}
TestOutputDirectories [TestContext.CurrentContext.Test.ID] =
FullProjectDirectory = Path.Combine (Root, relativeProjectDir);
var files = project.Save ();
project.Populate (relativeProjectDir, files);
project.CopyNuGetConfig (relativeProjectDir);
return new DotNetCLI (project, Path.Combine (FullProjectDirectory, project.ProjectFilePath));
}
}
}
| 42.033784 | 349 | 0.684906 | [
"MIT"
] | azyobuzin/xamarin-android | src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/XASdkTests.cs | 31,105 | C# |
//
// Photo.cs
//
// Author:
// Scott Peterson <lunchtimemama@gmail.com>
//
// Copyright (c) 2009 Scott Peterson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Mono.Upnp.Internal;
using Mono.Upnp.Xml;
namespace Mono.Upnp.Dcp.MediaServer1.ContentDirectory1.AV
{
public class Photo : ImageItem
{
protected Photo ()
{
Albums = new List<string> ();
}
public Photo (string id, string parentId, PhotoOptions options)
: base (id, parentId, options)
{
Albums = Helper.MakeReadOnlyCopy (options.Albums);
}
protected void CopyToOptions (PhotoOptions options)
{
base.CopyToOptions (options);
options.Albums = new List<string> (Albums);
}
public new PhotoOptions GetOptions ()
{
var options = new PhotoOptions ();
CopyToOptions (options);
return options;
}
[XmlArrayItem ("album", Schemas.UpnpSchema)]
public virtual IList<string> Albums { get; private set; }
protected override void Deserialize (XmlDeserializationContext context)
{
base.Deserialize (context);
Albums = new ReadOnlyCollection<string> (Albums);
}
protected override void DeserializeElement (XmlDeserializationContext context)
{
context.AutoDeserializeElement (this);
}
protected override void SerializeMembers (XmlSerializationContext context)
{
AutoSerializeMembers (this, context);
}
}
}
| 32.738095 | 86 | 0.664364 | [
"MIT"
] | Silvenga/Mono.Upnp | src/Mono.Upnp.Dcp/Mono.Upnp.Dcp.MediaServer1/Mono.Upnp.Dcp.MediaServer1/Mono.Upnp.Dcp.MediaServer1.ContentDirectory1.AV/Photo.cs | 2,750 | C# |
using IdentityServer4.Events;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using OpenPerpetuum.Core.Foundation.Processing;
using OpenPerpetuum.Core.SharedIdentity.Extensions;
using OpenPerpetuum.IdentityServer.Configuration;
using OpenPerpetuum.IdentityServer.InputModel.Consent;
using OpenPerpetuum.IdentityServer.ViewModel.Account;
using OpenPerpetuum.IdentityServer.ViewModel.Consent;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace OpenPerpetuum.IdentityServer.Controllers
{
[SecurityHeaders, Authorize]
public class ConsentController : ApiControllerBase
{
private readonly IIdentityServerInteractionService interaction;
private readonly IClientStore clientStore;
private readonly IResourceStore resourceStore;
private readonly IEventService events;
private readonly ILogger<ConsentController> logger;
public ConsentController(IIdentityServerInteractionService interaction, IClientStore clientStore, IResourceStore resourceStore, IEventService events, ILogger<ConsentController> logger, ICoreContext coreContext) : base(coreContext)
{
this.interaction = interaction;
this.clientStore = clientStore;
this.resourceStore = resourceStore;
this.events = events;
this.logger = logger;
}
[HttpGet]
public async Task<IActionResult> Index(string returnUrl)
{
var vm = await BuildViewModelAsync(returnUrl);
if (vm != null)
return View("Index", vm);
return View("Error");
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ConsentInputModel model)
{
var result = await ProcessConsentAsync(model);
if (result.IsRedirect)
{
if (await clientStore.IsPkceClientAsync(result.ClientId))
return View("Redirect", new RedirectViewModel { RedirectUrl = result.RedirectUri });
return Redirect(result.RedirectUri);
}
if (result.HasValidationError)
ModelState.AddModelError(string.Empty, result.ValidationError);
if (result.ShowView)
return View("Index", result.ViewModel);
return View("Error");
}
private async Task<ProcessConsentResult> ProcessConsentAsync(ConsentInputModel model)
{
var result = new ProcessConsentResult();
var request = await interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (request == null)
return result;
ConsentResponse grantedConsent = null;
if (model?.Button == "no")
{
grantedConsent = ConsentResponse.Denied;
await events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested));
}
else if (model?.Button == "yes")
{
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (!ConsentOptions.EnableOfflineAccess)
scopes = scopes.Where(s => s != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess);
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesConsented = scopes.ToArray()
};
await events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent));
}
else
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
else
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
if (grantedConsent == null)
result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model);
else
{
await interaction.GrantConsentAsync(request, grantedConsent);
result.RedirectUri = model.ReturnUrl;
result.ClientId = request.ClientId;
}
return result;
}
private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null)
{
var request = await interaction.GetAuthorizationContextAsync(returnUrl);
if (request != null)
{
var client = await clientStore.FindEnabledClientByIdAsync(request.ClientId);
if (client != null)
{
var resources = await resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested);
if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any()))
return CreateConsentViewModel(model, returnUrl, request, client, resources);
else
logger.LogError($"No scopes matching { request.ScopesRequested.Aggregate((x, y) => $"{x}, {y}") }");
}
}
else
logger.LogError($"No consent request matching: { returnUrl }");
return null;
}
private ConsentViewModel CreateConsentViewModel(ConsentInputModel model, string returnUrl, AuthorizationRequest request, Client client, Resources resources)
{
var vm = new ConsentViewModel
{
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
ReturnUrl = returnUrl,
ClientName = client.ClientName ?? client.ClientId,
ClientUrl = client.ClientUri,
ClientLogoUrl = client.LogoUri,
AllowRememberConsent = client.AllowRememberConsent
};
vm.IdentityScopes = resources.IdentityResources.Select(ir => CreateScopeViewModel(ir, vm.ScopesConsented.Contains(ir.Name) || model == null)).ToArray();
vm.ResourceScopes = resources.ApiResources.SelectMany(ar => ar.Scopes).Select(s => CreateScopeViewModel(s, vm.ScopesConsented.Contains(s.Name) || model == null)).ToArray();
if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
{
vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] {
GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
});
}
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
DisplayName = identity.DisplayName,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(Scope scope, bool check)
{
return new ScopeViewModel
{
Name = scope.Name,
DisplayName = scope.DisplayName,
Description = scope.Description,
Emphasize = scope.Emphasize,
Required = scope.Required,
Checked = check || scope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}
| 32.957143 | 232 | 0.749747 | [
"Apache-2.0"
] | OpenPerpetuum/APIv2 | src/OpenPerpetuum.IdentityServer/Controllers/ConsentController.cs | 6,923 | C# |
using System.Reflection;
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("awesomeapp.spaf")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("awesomeapp.spaf")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("E826A054-84E9-447E-8AEA-C9F09E1E2CCB")]
// 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.942857 | 84 | 0.741746 | [
"MIT"
] | markjackmilian/spaf101 | spaf101/awesomeapp.spaf/Properties/AssemblyInfo.cs | 1,366 | C# |
// <copyright file="GuildMember.Generated.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
//------------------------------------------------------------------------------
// <auto-generated>
// This source code was auto-generated by a roslyn code generator.
// </auto-generated>
//------------------------------------------------------------------------------
// ReSharper disable All
namespace MUnique.OpenMU.Persistence.BasicModel;
using MUnique.OpenMU.Persistence.Json;
/// <summary>
/// A plain implementation of <see cref="GuildMember"/>.
/// </summary>
public partial class GuildMember : MUnique.OpenMU.DataModel.Entities.GuildMember, IIdentifiable, IConvertibleTo<GuildMember>
{
/// <inheritdoc />
public GuildMember()
{
}
/// <inheritdoc />
public GuildMember(System.Guid id)
: base(id)
{
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
var baseObject = obj as IIdentifiable;
if (baseObject != null)
{
return baseObject.Id == this.Id;
}
return base.Equals(obj);
}
/// <inheritdoc/>
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
/// <inheritdoc/>
public GuildMember Convert() => this;
}
| 24.350877 | 124 | 0.560519 | [
"MIT"
] | ADMTec/OpenMU | src/Persistence/BasicModel/GuildMember.Generated.cs | 1,388 | C# |
namespace ContactsSync
{
public static class GraphConstants
{
// Defines the permission scopes used by the app
public readonly static string[] Scopes =
{
"User.Read",
"MailboxSettings.Read",
"Calendars.ReadWrite",
"Contacts.ReadWrite"
};
}
}
| 22.333333 | 56 | 0.549254 | [
"Apache-2.0"
] | Corliss-Dukes/ContactsSync | ContactsSync/ContactsSync/Graph/GraphConstants.cs | 337 | C# |
using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using TextMining.Core;
using TextMining.Service;
namespace OpinionMining
{
using OpinionMining.DirectIndirectSpeechExtensions;
/*
separator1 ::=
<
<U> - </U>
>
*/
internal static class separator1
{
private static readonly string[] U_WORDS = new[] { "-", "–" };
public static bool uConditionFunction( string utext )
{
return (U_WORDS.Any( _ => utext.EndsWith( _ ) ));
}
public static bool IsCondition( XElement u )
{
return (u.IsElementU() && uConditionFunction( u.GetRawCDataTextFromElementU().TrimWhiteSpaces() ));
}
}
/*
separator2 ::=
<
<U> - || , </U>
>
*/
internal static class separator2
{
private static readonly string[] U_WORDS = new[] { ",", "-", "–" };
public static bool uConditionFunction( string utext )
{
return (U_WORDS.Any( _ => utext.EndsWith( _ ) ));
}
public static bool IsCondition( XElement u )
{
return (u.IsElementU() && uConditionFunction( u.GetRawCDataTextFromElementU().TrimWhiteSpaces() ));
}
}
} | 24.519231 | 111 | 0.564706 | [
"MIT"
] | elzin/SentimentAnalysisService | Sources/TextMining/OpinionMining/Implementation/OpinionMining.WcfService/OpinionMining/separators.cs | 1,281 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClaLibFwork
{
public class Class1
{
}
}
| 14.769231 | 34 | 0.6875 | [
"MIT"
] | byrne8783/controlled | someComparisons/ClaLibFwork/Class1.cs | 194 | C# |
/* *********************************************************************
* This Source Code Form is copyright of 51Degrees Mobile Experts Limited.
* Copyright © 2017 51Degrees Mobile Experts Limited, 5 Charlotte Close,
* Caversham, Reading, Berkshire, United Kingdom RG4 7BY
*
* This Source Code Form is the subject of the following patents and patent
* applications, owned by 51Degrees Mobile Experts Limited of 5 Charlotte
* Close, Caversham, Reading, Berkshire, United Kingdom RG4 7BY:
* European Patent No. 2871816;
* European Patent Application No. 17184134.9;
* United States Patent Nos. 9,332,086 and 9,350,823; and
* United States Patent Application No. 15/686,066.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0.
*
* If a copy of the MPL was not distributed with this file, You can obtain
* one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is “Incompatible With Secondary Licenses”, as
* defined by the Mozilla Public License, v. 2.0.
* ********************************************************************* */
using System;
using System.Text;
namespace FiftyOne.Foundation.Mobile.Detection.Entities
{
/// <summary>
/// A node index contains the characters and related child nodes of the
/// node should any of the characters match at the position.
/// </summary>
internal class NodeIndex : NodeIndexBase, IComparable<NodeIndex>
{
#region Fields
/// <summary>
/// True if the value is an index to a sub string. False
/// if the value is 1 to 4 consecutive characters.
/// </summary>
internal readonly bool IsString;
/// <summary>
/// The value of the node index. Interpretation
/// depends on IsSubString.
/// </summary>
/// <remarks>
/// If IsSubString is true the 4 bytes represent an offset
/// in the strings data structure to 5 or more characters.
/// If IsSubString is false the 4 bytes are character
/// values themselves where 0 values are ignored.
/// </remarks>
private readonly byte[] _value;
#endregion
#region Properties
/// <summary>
/// Returns the characters related to this node index.
/// </summary>
internal byte[] Characters
{
get
{
if (_characters == null)
{
lock (this)
{
if (_characters == null)
{
_characters = GetCharacters();
}
}
}
return _characters;
}
}
private byte[] _characters;
#endregion
#region Constructors
/// <summary>
/// Constructs a new instance of <see cref="NodeIndex"/>.
/// </summary>
/// <param name="dataSet">
/// The data set the node is contained within.
/// </param>
/// <param name="index">
/// The index of this object in the Node.
/// </param>
/// <param name="isString">
/// True if the value is an integer offset to a string, or false
/// if the value is an array of characters to be used by the node.
/// </param>
/// <param name="value">
/// Array of bytes representing an integer offset to a string, or
/// the array of characters to be used by the node.
/// </param>
/// <param name="relatedNodeOffset">
/// The offset in the list of nodes to the node the index relates to.
/// </param>
internal NodeIndex(
DataSet dataSet,
int index,
bool isString,
byte[] value,
int relatedNodeOffset)
: base(dataSet, index, relatedNodeOffset)
{
IsString = isString;
_value = value;
}
#endregion
#region Methods
/// <summary>
/// Called after the entire data set has been loaded to ensure
/// any further initialisation steps that require other items in
/// the data set can be completed.
/// </summary>
internal override void Init()
{
base.Init();
if (_characters == null)
{
_characters = GetCharacters();
}
}
/// <summary>
/// Returns the characters the node index relates to.
/// </summary>
/// <returns></returns>
private byte[] GetCharacters()
{
if (IsString)
{
// Returns the characters based on the sub string referenced.
return DataSet.Strings[BitConverter.ToInt32(_value, 0)].Value;
}
else
{
// Return the byte array.
return _value;
}
}
/// <summary>
/// Compares a byte array of characters at the position provided
/// to the array of characters for this node.
/// </summary>
/// <param name="other">Array of characters to compare</param>
/// <param name="startIndex">
/// The index in the other array to the required characters
/// </param>
/// <returns>
/// The relative position of the node in relation to the other array
/// </returns>
/// <para>
/// Used to determine if a target User-Agent contains the node.
/// </para>
internal int CompareTo(byte[] other, int startIndex)
{
for (int i = Characters.Length - 1, o = startIndex + Characters.Length - 1; i >= 0; i--, o--)
{
var difference = Characters[i].CompareTo(other[o]);
if (difference != 0)
return difference;
}
return 0;
}
#endregion
#region Public Methods
/// <summary>
/// Compares this node index to another.
/// </summary>
/// <param name="other">
/// The node index to compare.
/// </param>
/// <returns>
/// Indication of relative value based on ComponentId field.
/// </returns>
public int CompareTo(NodeIndex other)
{
return CompareTo(other.Characters, 0);
}
/// <summary>
/// Converts the node index into a string.
/// </summary>
/// <returns>
/// A string representation of the node characters.
/// </returns>
public override string ToString()
{
return String.Format(
"{0}[{1}]",
Encoding.ASCII.GetString(Characters),
RelatedNodeOffset);
}
#endregion
}
}
| 33.429907 | 106 | 0.506011 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | 51Degrees/.NET-Device-Detection | FoundationV3/Mobile/Detection/Entities/NodeIndex.cs | 7,161 | C# |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
namespace FeedBuilder
{
partial class frmMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
this.lstFiles = new System.Windows.Forms.ListView();
this.colFilename = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colVersion = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colDate = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colHash = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.imgFiles = new System.Windows.Forms.ImageList(this.components);
this.fbdOutputFolder = new System.Windows.Forms.FolderBrowserDialog();
this.sfdFeedXML = new System.Windows.Forms.SaveFileDialog();
this.tsMain = new System.Windows.Forms.ToolStrip();
this.btnNew = new System.Windows.Forms.ToolStripButton();
this.btnOpen = new System.Windows.Forms.ToolStripButton();
this.btnSave = new System.Windows.Forms.ToolStripButton();
this.btnSaveAs = new System.Windows.Forms.ToolStripButton();
this.tsSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnRefresh = new System.Windows.Forms.ToolStripButton();
this.btnOpenOutputs = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnBuild = new System.Windows.Forms.ToolStripButton();
this.ToolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.panFiles = new System.Windows.Forms.Panel();
this.grpSettings = new System.Windows.Forms.GroupBox();
this.chkCleanUp = new System.Windows.Forms.CheckBox();
this.chkCopyFiles = new System.Windows.Forms.CheckBox();
this.lblIgnore = new System.Windows.Forms.Label();
this.lblMisc = new System.Windows.Forms.Label();
this.lblCompare = new System.Windows.Forms.Label();
this.chkHash = new System.Windows.Forms.CheckBox();
this.chkDate = new System.Windows.Forms.CheckBox();
this.chkSize = new System.Windows.Forms.CheckBox();
this.chkVersion = new System.Windows.Forms.CheckBox();
this.txtBaseURL = new FeedBuilder.HelpfulTextBox(this.components);
this.lblBaseURL = new System.Windows.Forms.Label();
this.chkIgnoreVsHost = new System.Windows.Forms.CheckBox();
this.chkIgnoreSymbols = new System.Windows.Forms.CheckBox();
this.cmdFeedXML = new System.Windows.Forms.Button();
this.txtFeedXML = new FeedBuilder.HelpfulTextBox(this.components);
this.lblFeedXML = new System.Windows.Forms.Label();
this.cmdOutputFolder = new System.Windows.Forms.Button();
this.txtOutputFolder = new FeedBuilder.HelpfulTextBox(this.components);
this.lblOutputFolder = new System.Windows.Forms.Label();
this.txtAddExtension = new FeedBuilder.HelpfulTextBox(this.components);
this.lblAddExtension = new System.Windows.Forms.Label();
this.tsMain.SuspendLayout();
this.ToolStripContainer1.ContentPanel.SuspendLayout();
this.ToolStripContainer1.TopToolStripPanel.SuspendLayout();
this.ToolStripContainer1.SuspendLayout();
this.panFiles.SuspendLayout();
this.grpSettings.SuspendLayout();
this.SuspendLayout();
//
// lstFiles
//
this.lstFiles.CheckBoxes = true;
this.lstFiles.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colFilename,
this.colVersion,
this.colSize,
this.colDate,
this.colHash});
this.lstFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstFiles.Location = new System.Drawing.Point(0, 12);
this.lstFiles.Margin = new System.Windows.Forms.Padding(0);
this.lstFiles.Name = "lstFiles";
this.lstFiles.Size = new System.Drawing.Size(810, 230);
this.lstFiles.SmallImageList = this.imgFiles;
this.lstFiles.TabIndex = 0;
this.lstFiles.UseCompatibleStateImageBehavior = false;
this.lstFiles.View = System.Windows.Forms.View.Details;
//
// colFilename
//
this.colFilename.Text = "Filename";
this.colFilename.Width = 200;
//
// colVersion
//
this.colVersion.Text = "Version";
this.colVersion.Width = 80;
//
// colSize
//
this.colSize.Text = "Size";
this.colSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.colSize.Width = 80;
//
// colDate
//
this.colDate.Text = "Date";
this.colDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.colDate.Width = 120;
//
// colHash
//
this.colHash.Text = "Hash";
this.colHash.Width = 300;
//
// imgFiles
//
this.imgFiles.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgFiles.ImageStream")));
this.imgFiles.TransparentColor = System.Drawing.Color.Transparent;
this.imgFiles.Images.SetKeyName(0, "file_extension_other.png");
this.imgFiles.Images.SetKeyName(1, "file_extension_bmp.png");
this.imgFiles.Images.SetKeyName(2, "file_extension_dll.png");
this.imgFiles.Images.SetKeyName(3, "file_extension_doc.png");
this.imgFiles.Images.SetKeyName(4, "file_extension_exe.png");
this.imgFiles.Images.SetKeyName(5, "file_extension_htm.png");
this.imgFiles.Images.SetKeyName(6, "file_extension_jpg.png");
this.imgFiles.Images.SetKeyName(7, "file_extension_pdf.png");
this.imgFiles.Images.SetKeyName(8, "file_extension_png.png");
this.imgFiles.Images.SetKeyName(9, "file_extension_txt.png");
this.imgFiles.Images.SetKeyName(10, "file_extension_wav.png");
this.imgFiles.Images.SetKeyName(11, "file_extension_wmv.png");
this.imgFiles.Images.SetKeyName(12, "file_extension_zip.png");
//
// fbdOutputFolder
//
this.fbdOutputFolder.Description = "Select your projects output folder:";
//
// sfdFeedXML
//
this.sfdFeedXML.DefaultExt = "xml";
this.sfdFeedXML.Filter = "XML Files (*.xml)|*.xml|All Files (*.*)|*.*";
this.sfdFeedXML.Title = "Select the location to save your NauXML file:";
//
// tsMain
//
this.tsMain.Dock = System.Windows.Forms.DockStyle.None;
this.tsMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnNew,
this.btnOpen,
this.btnSave,
this.btnSaveAs,
this.tsSeparator1,
this.btnRefresh,
this.btnOpenOutputs,
this.toolStripSeparator1,
this.btnBuild});
this.tsMain.Location = new System.Drawing.Point(0, 0);
this.tsMain.Name = "tsMain";
this.tsMain.Size = new System.Drawing.Size(834, 25);
this.tsMain.Stretch = true;
this.tsMain.TabIndex = 2;
this.tsMain.Text = "Commands";
//
// btnNew
//
this.btnNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnNew.Image = ((System.Drawing.Image)(resources.GetObject("btnNew.Image")));
this.btnNew.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnNew.Name = "btnNew";
this.btnNew.Size = new System.Drawing.Size(23, 22);
this.btnNew.Text = "&New";
this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
//
// btnOpen
//
this.btnOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnOpen.Image = ((System.Drawing.Image)(resources.GetObject("btnOpen.Image")));
this.btnOpen.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnOpen.Name = "btnOpen";
this.btnOpen.Size = new System.Drawing.Size(23, 22);
this.btnOpen.Text = "&Open";
this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click);
//
// btnSave
//
this.btnSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image")));
this.btnSave.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(23, 22);
this.btnSave.Text = "&Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// btnSaveAs
//
this.btnSaveAs.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnSaveAs.Image = ((System.Drawing.Image)(resources.GetObject("btnSaveAs.Image")));
this.btnSaveAs.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSaveAs.Name = "btnSaveAs";
this.btnSaveAs.Size = new System.Drawing.Size(60, 22);
this.btnSaveAs.Text = "Save As...";
this.btnSaveAs.Click += new System.EventHandler(this.btnSaveAs_Click);
//
// tsSeparator1
//
this.tsSeparator1.Name = "tsSeparator1";
this.tsSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnRefresh
//
this.btnRefresh.Image = ((System.Drawing.Image)(resources.GetObject("btnRefresh.Image")));
this.btnRefresh.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(92, 22);
this.btnRefresh.Text = "Refresh Files";
this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
//
// btnOpenOutputs
//
this.btnOpenOutputs.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.btnOpenOutputs.Image = ((System.Drawing.Image)(resources.GetObject("btnOpenOutputs.Image")));
this.btnOpenOutputs.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnOpenOutputs.Name = "btnOpenOutputs";
this.btnOpenOutputs.Size = new System.Drawing.Size(133, 22);
this.btnOpenOutputs.Text = "Open Output Folder";
this.btnOpenOutputs.Click += new System.EventHandler(this.btnOpenOutputs_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnBuild
//
this.btnBuild.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.btnBuild.Image = ((System.Drawing.Image)(resources.GetObject("btnBuild.Image")));
this.btnBuild.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnBuild.Name = "btnBuild";
this.btnBuild.Size = new System.Drawing.Size(54, 22);
this.btnBuild.Text = "Build";
this.btnBuild.Click += new System.EventHandler(this.cmdBuild_Click);
//
// ToolStripContainer1
//
//
// ToolStripContainer1.ContentPanel
//
this.ToolStripContainer1.ContentPanel.Controls.Add(this.panFiles);
this.ToolStripContainer1.ContentPanel.Controls.Add(this.grpSettings);
this.ToolStripContainer1.ContentPanel.Padding = new System.Windows.Forms.Padding(12, 8, 12, 12);
this.ToolStripContainer1.ContentPanel.Size = new System.Drawing.Size(834, 467);
this.ToolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.ToolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.ToolStripContainer1.Name = "ToolStripContainer1";
this.ToolStripContainer1.Size = new System.Drawing.Size(834, 492);
this.ToolStripContainer1.TabIndex = 3;
this.ToolStripContainer1.Text = "ToolStripContainer1";
//
// ToolStripContainer1.TopToolStripPanel
//
this.ToolStripContainer1.TopToolStripPanel.Controls.Add(this.tsMain);
//
// panFiles
//
this.panFiles.Controls.Add(this.lstFiles);
this.panFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.panFiles.Location = new System.Drawing.Point(12, 213);
this.panFiles.Name = "panFiles";
this.panFiles.Padding = new System.Windows.Forms.Padding(0, 12, 0, 0);
this.panFiles.Size = new System.Drawing.Size(810, 242);
this.panFiles.TabIndex = 2;
//
// grpSettings
//
this.grpSettings.Controls.Add(this.lblAddExtension);
this.grpSettings.Controls.Add(this.txtAddExtension);
this.grpSettings.Controls.Add(this.chkCleanUp);
this.grpSettings.Controls.Add(this.chkCopyFiles);
this.grpSettings.Controls.Add(this.lblIgnore);
this.grpSettings.Controls.Add(this.lblMisc);
this.grpSettings.Controls.Add(this.lblCompare);
this.grpSettings.Controls.Add(this.chkHash);
this.grpSettings.Controls.Add(this.chkDate);
this.grpSettings.Controls.Add(this.chkSize);
this.grpSettings.Controls.Add(this.chkVersion);
this.grpSettings.Controls.Add(this.txtBaseURL);
this.grpSettings.Controls.Add(this.lblBaseURL);
this.grpSettings.Controls.Add(this.chkIgnoreVsHost);
this.grpSettings.Controls.Add(this.chkIgnoreSymbols);
this.grpSettings.Controls.Add(this.cmdFeedXML);
this.grpSettings.Controls.Add(this.txtFeedXML);
this.grpSettings.Controls.Add(this.lblFeedXML);
this.grpSettings.Controls.Add(this.cmdOutputFolder);
this.grpSettings.Controls.Add(this.txtOutputFolder);
this.grpSettings.Controls.Add(this.lblOutputFolder);
this.grpSettings.Dock = System.Windows.Forms.DockStyle.Top;
this.grpSettings.Location = new System.Drawing.Point(12, 8);
this.grpSettings.Name = "grpSettings";
this.grpSettings.Padding = new System.Windows.Forms.Padding(12, 8, 12, 8);
this.grpSettings.Size = new System.Drawing.Size(810, 205);
this.grpSettings.TabIndex = 1;
this.grpSettings.TabStop = false;
this.grpSettings.Text = "Settings:";
//
// chkCleanUp
//
this.chkCleanUp.AutoSize = true;
this.chkCleanUp.Checked = true;
this.chkCleanUp.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkCleanUp.Location = new System.Drawing.Point(293, 145);
this.chkCleanUp.Name = "chkCleanUp";
this.chkCleanUp.Size = new System.Drawing.Size(134, 17);
this.chkCleanUp.TabIndex = 17;
this.chkCleanUp.Text = "Clean Unselected Files";
this.chkCleanUp.UseVisualStyleBackColor = true;
//
// chkCopyFiles
//
this.chkCopyFiles.AutoSize = true;
this.chkCopyFiles.Checked = true;
this.chkCopyFiles.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkCopyFiles.Location = new System.Drawing.Point(146, 145);
this.chkCopyFiles.Name = "chkCopyFiles";
this.chkCopyFiles.Size = new System.Drawing.Size(141, 17);
this.chkCopyFiles.TabIndex = 16;
this.chkCopyFiles.Text = "Copy Files with NauXML";
this.chkCopyFiles.UseVisualStyleBackColor = true;
this.chkCopyFiles.CheckedChanged += new System.EventHandler(this.chkCopyFiles_CheckedChanged);
//
// lblIgnore
//
this.lblIgnore.AutoSize = true;
this.lblIgnore.Location = new System.Drawing.Point(15, 174);
this.lblIgnore.Name = "lblIgnore";
this.lblIgnore.Size = new System.Drawing.Size(40, 13);
this.lblIgnore.TabIndex = 15;
this.lblIgnore.Text = "Ignore:";
//
// lblMisc
//
this.lblMisc.AutoSize = true;
this.lblMisc.Location = new System.Drawing.Point(15, 146);
this.lblMisc.Name = "lblMisc";
this.lblMisc.Size = new System.Drawing.Size(32, 13);
this.lblMisc.TabIndex = 15;
this.lblMisc.Text = "Misc:";
//
// lblCompare
//
this.lblCompare.AutoSize = true;
this.lblCompare.Location = new System.Drawing.Point(15, 118);
this.lblCompare.Name = "lblCompare";
this.lblCompare.Size = new System.Drawing.Size(52, 13);
this.lblCompare.TabIndex = 14;
this.lblCompare.Text = "Compare:";
//
// chkHash
//
this.chkHash.AutoSize = true;
this.chkHash.Checked = true;
this.chkHash.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkHash.Location = new System.Drawing.Point(320, 117);
this.chkHash.Name = "chkHash";
this.chkHash.Size = new System.Drawing.Size(51, 17);
this.chkHash.TabIndex = 13;
this.chkHash.Text = "Hash";
this.chkHash.UseVisualStyleBackColor = true;
//
// chkDate
//
this.chkDate.AutoSize = true;
this.chkDate.Location = new System.Drawing.Point(265, 117);
this.chkDate.Name = "chkDate";
this.chkDate.Size = new System.Drawing.Size(49, 17);
this.chkDate.TabIndex = 12;
this.chkDate.Text = "Date";
this.chkDate.UseVisualStyleBackColor = true;
//
// chkSize
//
this.chkSize.AutoSize = true;
this.chkSize.Location = new System.Drawing.Point(213, 117);
this.chkSize.Name = "chkSize";
this.chkSize.Size = new System.Drawing.Size(46, 17);
this.chkSize.TabIndex = 11;
this.chkSize.Text = "Size";
this.chkSize.UseVisualStyleBackColor = true;
//
// chkVersion
//
this.chkVersion.AutoSize = true;
this.chkVersion.Checked = true;
this.chkVersion.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkVersion.Location = new System.Drawing.Point(146, 117);
this.chkVersion.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.chkVersion.Name = "chkVersion";
this.chkVersion.Size = new System.Drawing.Size(61, 17);
this.chkVersion.TabIndex = 10;
this.chkVersion.Text = "Version";
this.chkVersion.UseVisualStyleBackColor = true;
//
// txtBaseURL
//
this.txtBaseURL.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtBaseURL.HelpfulText = "Where you will upload the feed and update files for distribution to clients";
this.txtBaseURL.Location = new System.Drawing.Point(146, 86);
this.txtBaseURL.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtBaseURL.Name = "txtBaseURL";
this.txtBaseURL.Size = new System.Drawing.Size(617, 20);
this.txtBaseURL.TabIndex = 9;
//
// lblBaseURL
//
this.lblBaseURL.AutoSize = true;
this.lblBaseURL.Location = new System.Drawing.Point(15, 89);
this.lblBaseURL.Name = "lblBaseURL";
this.lblBaseURL.Size = new System.Drawing.Size(59, 13);
this.lblBaseURL.TabIndex = 8;
this.lblBaseURL.Text = "Base URL:";
//
// chkIgnoreVsHost
//
this.chkIgnoreVsHost.AutoSize = true;
this.chkIgnoreVsHost.Checked = true;
this.chkIgnoreVsHost.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkIgnoreVsHost.Location = new System.Drawing.Point(293, 173);
this.chkIgnoreVsHost.Name = "chkIgnoreVsHost";
this.chkIgnoreVsHost.Size = new System.Drawing.Size(103, 17);
this.chkIgnoreVsHost.TabIndex = 7;
this.chkIgnoreVsHost.Text = "VS Hosting Files";
this.chkIgnoreVsHost.UseVisualStyleBackColor = true;
//
// chkIgnoreSymbols
//
this.chkIgnoreSymbols.AutoSize = true;
this.chkIgnoreSymbols.Checked = true;
this.chkIgnoreSymbols.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkIgnoreSymbols.Location = new System.Drawing.Point(146, 173);
this.chkIgnoreSymbols.Name = "chkIgnoreSymbols";
this.chkIgnoreSymbols.Size = new System.Drawing.Size(100, 17);
this.chkIgnoreSymbols.TabIndex = 7;
this.chkIgnoreSymbols.Text = "Debug Symbols";
this.chkIgnoreSymbols.UseVisualStyleBackColor = true;
this.chkIgnoreSymbols.CheckedChanged += new System.EventHandler(this.chkIgnoreSymbols_CheckedChanged);
//
// cmdFeedXML
//
this.cmdFeedXML.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdFeedXML.Location = new System.Drawing.Point(769, 53);
this.cmdFeedXML.Name = "cmdFeedXML";
this.cmdFeedXML.Size = new System.Drawing.Size(26, 23);
this.cmdFeedXML.TabIndex = 5;
this.cmdFeedXML.Text = "...";
this.cmdFeedXML.UseVisualStyleBackColor = true;
this.cmdFeedXML.Click += new System.EventHandler(this.cmdFeedXML_Click);
//
// txtFeedXML
//
this.txtFeedXML.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtFeedXML.BackColor = System.Drawing.Color.White;
this.txtFeedXML.HelpfulText = "The file your application downloads to determine if there are updates";
this.txtFeedXML.Location = new System.Drawing.Point(146, 55);
this.txtFeedXML.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtFeedXML.Name = "txtFeedXML";
this.txtFeedXML.Size = new System.Drawing.Size(617, 20);
this.txtFeedXML.TabIndex = 4;
//
// lblFeedXML
//
this.lblFeedXML.AutoSize = true;
this.lblFeedXML.Location = new System.Drawing.Point(15, 58);
this.lblFeedXML.Name = "lblFeedXML";
this.lblFeedXML.Size = new System.Drawing.Size(98, 13);
this.lblFeedXML.TabIndex = 3;
this.lblFeedXML.Text = "Feed NauXML File:";
//
// cmdOutputFolder
//
this.cmdOutputFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdOutputFolder.Location = new System.Drawing.Point(769, 22);
this.cmdOutputFolder.Name = "cmdOutputFolder";
this.cmdOutputFolder.Size = new System.Drawing.Size(26, 23);
this.cmdOutputFolder.TabIndex = 2;
this.cmdOutputFolder.Text = "...";
this.cmdOutputFolder.UseVisualStyleBackColor = true;
this.cmdOutputFolder.Click += new System.EventHandler(this.cmdOutputFolder_Click);
//
// txtOutputFolder
//
this.txtOutputFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtOutputFolder.BackColor = System.Drawing.Color.White;
this.txtOutputFolder.HelpfulText = "The folder that contains the files you want to distribute";
this.txtOutputFolder.Location = new System.Drawing.Point(146, 24);
this.txtOutputFolder.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtOutputFolder.Name = "txtOutputFolder";
this.txtOutputFolder.Size = new System.Drawing.Size(617, 20);
this.txtOutputFolder.TabIndex = 1;
//
// lblOutputFolder
//
this.lblOutputFolder.AutoSize = true;
this.lblOutputFolder.Location = new System.Drawing.Point(15, 27);
this.lblOutputFolder.Name = "lblOutputFolder";
this.lblOutputFolder.Size = new System.Drawing.Size(110, 13);
this.lblOutputFolder.TabIndex = 0;
this.lblOutputFolder.Text = "Project Output Folder:";
//
// txtAddExtension
//
this.txtAddExtension.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtAddExtension.HelpfulText = "Add extension to each file";
this.txtAddExtension.Location = new System.Drawing.Point(516, 142);
this.txtAddExtension.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtAddExtension.Name = "txtAddExtension";
this.txtAddExtension.Size = new System.Drawing.Size(98, 20);
this.txtAddExtension.TabIndex = 18;
//
// lblAddExtension
//
this.lblAddExtension.AutoSize = true;
this.lblAddExtension.Location = new System.Drawing.Point(433, 146);
this.lblAddExtension.Name = "lblAddExtension";
this.lblAddExtension.Size = new System.Drawing.Size(77, 13);
this.lblAddExtension.TabIndex = 19;
this.lblAddExtension.Text = "Add extension:";
//
// frmMain
//
this.AllowDrop = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(834, 492);
this.Controls.Add(this.ToolStripContainer1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(850, 530);
this.Name = "frmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Feed Builder";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmMain_FormClosing);
this.Load += new System.EventHandler(this.frmMain_Load);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.frmMain_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.frmMain_DragEnter);
this.tsMain.ResumeLayout(false);
this.tsMain.PerformLayout();
this.ToolStripContainer1.ContentPanel.ResumeLayout(false);
this.ToolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.ToolStripContainer1.TopToolStripPanel.PerformLayout();
this.ToolStripContainer1.ResumeLayout(false);
this.ToolStripContainer1.PerformLayout();
this.panFiles.ResumeLayout(false);
this.grpSettings.ResumeLayout(false);
this.grpSettings.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FolderBrowserDialog fbdOutputFolder;
private System.Windows.Forms.SaveFileDialog sfdFeedXML;
private System.Windows.Forms.ImageList imgFiles;
private System.Windows.Forms.ListView lstFiles;
private System.Windows.Forms.ColumnHeader colFilename;
private System.Windows.Forms.ColumnHeader colVersion;
private System.Windows.Forms.ColumnHeader colSize;
private System.Windows.Forms.ColumnHeader colDate;
private System.Windows.Forms.ColumnHeader colHash;
private System.Windows.Forms.ToolStrip tsMain;
private System.Windows.Forms.ToolStripButton btnNew;
private System.Windows.Forms.ToolStripButton btnOpen;
private System.Windows.Forms.ToolStripButton btnSave;
private System.Windows.Forms.ToolStripButton btnRefresh;
private System.Windows.Forms.ToolStripContainer ToolStripContainer1;
private System.Windows.Forms.GroupBox grpSettings;
private System.Windows.Forms.CheckBox chkCleanUp;
private System.Windows.Forms.CheckBox chkCopyFiles;
private System.Windows.Forms.Label lblIgnore;
private System.Windows.Forms.Label lblMisc;
private System.Windows.Forms.Label lblCompare;
private System.Windows.Forms.CheckBox chkHash;
private System.Windows.Forms.CheckBox chkDate;
private System.Windows.Forms.CheckBox chkSize;
private System.Windows.Forms.CheckBox chkVersion;
private HelpfulTextBox txtBaseURL;
private System.Windows.Forms.Label lblBaseURL;
private System.Windows.Forms.CheckBox chkIgnoreVsHost;
private System.Windows.Forms.CheckBox chkIgnoreSymbols;
private System.Windows.Forms.Button cmdFeedXML;
private HelpfulTextBox txtFeedXML;
private System.Windows.Forms.Label lblFeedXML;
private System.Windows.Forms.Button cmdOutputFolder;
private HelpfulTextBox txtOutputFolder;
private System.Windows.Forms.Label lblOutputFolder;
private System.Windows.Forms.ToolStripButton btnSaveAs;
private System.Windows.Forms.ToolStripButton btnBuild;
private System.Windows.Forms.ToolStripSeparator tsSeparator1;
private ToolStripButton btnOpenOutputs;
private Panel panFiles;
private ToolStripSeparator toolStripSeparator1;
private Label lblAddExtension;
private HelpfulTextBox txtAddExtension;
}
}
| 51.458861 | 163 | 0.625023 | [
"MIT"
] | Apprentice-doa/result_and_transcript_system | desktop_src/result_and_transcript_system/eUpdater/NAppUpdate-0.5.1.0/NAppUpdate-0.5.1.0/FeedBuilder/frmMain.Designer.cs | 32,522 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.