content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TimekeeperDAL.EF { [Table("TimeTaskAllocations")] public partial class TimeTaskAllocation { public double Amount { get; set; } public double PerOffset { get; set; } public bool Limited { get; set; } public double InstanceMinimum { get; set; } [Required] public string Method { get; set; } [Key] [Column(Order = 1)] public int TimeTask_Id { get; set; } [Key] [Column(Order = 2)] public int Resource_Id { get; set; } public int? PerId { get; set; } [Required] [ForeignKey("TimeTask_Id")] public virtual TimeTask TimeTask { get; set; } [Required] [ForeignKey("Resource_Id")] public virtual Resource Resource { get; set; } [ForeignKey("PerId")] public virtual Resource Per { get; set; } } }
23.571429
54
0.589899
[ "MIT" ]
NuCode1497/TimekeeperWPF
TimekeeperDAL/EF/TimeTaskAllocation.cs
992
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Wyam.Common; using Wyam.Common.Documents; using Wyam.Common.Modules; using Wyam.Common.Execution; using Wyam.Common.Tracing; using Wyam.Common.Util; using YamlDotNet.Dynamic; using YamlDotNet.RepresentationModel; namespace Wyam.Yaml { /// <summary> /// Parses YAML content for each input document and stores the result in it's metadata. /// </summary> /// <remarks> /// Parses the content for each input document and then stores a dynamic object /// representing the first YAML document in metadata with the specified key. If no key is specified, /// then the dynamic object is not added. You can also flatten the YAML to add top-level pairs directly /// to the document metadata. /// </remarks> /// <category>Metadata</category> public class Yaml : IModule { private readonly bool _flatten; private readonly string _key; /// <summary> /// The content of the input document is parsed as YAML. All root-level scalars are added to the input document's /// metadata. Any more complex YAML structures are ignored. This is best for simple key-value YAML documents. /// </summary> public Yaml() { _flatten = true; } /// <summary> /// The content of the input document is parsed as YAML. A dynamic object representing the first YAML /// document is set as the value for the given metadata key. See YamlDotNet.Dynamic for more details /// about the dynamic YAML object. If flatten is true, all root-level scalars are also added /// to the input document's metadata. /// </summary> /// <param name="key">The metadata key in which to set the dynamic YAML object.</param> /// <param name="flatten">If set to <c>true</c>, all root-level scalars are also added to the input document's metadata.</param> public Yaml(string key, bool flatten = false) { _key = key; _flatten = flatten; } /// <inheritdoc /> public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context) { return inputs .AsParallel() .SelectMany(context, input => { List<Dictionary<string, object>> documentMetadata = new List<Dictionary<string, object>>(); using (TextReader contentReader = new StringReader(input.Content)) { YamlStream yamlStream = new YamlStream(); yamlStream.Load(contentReader); foreach (YamlDocument document in yamlStream.Documents) { // If this is a sequence, get a document for each item YamlSequenceNode rootSequence = document.RootNode as YamlSequenceNode; if (rootSequence != null) { documentMetadata.AddRange(rootSequence.Children.Select(x => GetDocumentMetadata(x, context))); } else { // Otherwise, just get a single set of metadata documentMetadata.Add(GetDocumentMetadata(document.RootNode, context)); } } } return documentMetadata.Select(metadata => context.GetDocument(input, metadata)); }) .Where(x => x != null); } private Dictionary<string, object> GetDocumentMetadata(YamlNode node, IExecutionContext context) { Dictionary<string, object> metadata = new Dictionary<string, object>(); // Get the dynamic representation if (!string.IsNullOrEmpty(_key)) { metadata[_key] = new DynamicYaml(node); } // Also get the flat metadata if requested if (_flatten) { YamlMappingNode mappingNode = node as YamlMappingNode; if (mappingNode == null) { throw new InvalidOperationException("Cannot flatten YAML content that doesn't have a mapping node at the root (or within a root sequence)."); } // Map scalar-to-scalar children foreach (KeyValuePair<YamlNode, YamlNode> child in mappingNode.Children.Where(y => y.Key is YamlScalarNode && y.Value is YamlScalarNode)) { metadata[((YamlScalarNode)child.Key).Value] = ((YamlScalarNode)child.Value).Value; } // Map simple sequences foreach (KeyValuePair<YamlNode, YamlNode> child in mappingNode.Children.Where(y => y.Key is YamlScalarNode && y.Value is YamlSequenceNode && ((YamlSequenceNode)y.Value).All(z => z is YamlScalarNode))) { metadata[((YamlScalarNode)child.Key).Value] = ((YamlSequenceNode)child.Value).Select(a => ((YamlScalarNode)a).Value).ToArray(); } // Map object sequences foreach (KeyValuePair<YamlNode, YamlNode> child in mappingNode.Children.Where(y => y.Key is YamlScalarNode && y.Value is YamlSequenceNode && ((YamlSequenceNode)y.Value).All(z => z is YamlMappingNode))) { metadata[((YamlScalarNode)child.Key).Value] = ((YamlSequenceNode)child.Value).Select(a => context.GetDocument(GetDocumentMetadata(a, context))).ToArray(); } // Note: No support for mixed sequences of YamlMappingNode and YamlScalarNode together } return metadata; } } }
44.837037
174
0.5736
[ "MIT" ]
ardalis/Wyam
src/extensions/Wyam.Yaml/Yaml.cs
6,055
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("ActiveDirectory.PasswordChangePolicy")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ActiveDirectory.PasswordChangePolicy")] [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("533b128c-c449-4756-8fdf-9b4dd8e7426b")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.861111
85
0.74007
[ "MIT" ]
Adam-Auth0/rules
redirect-rules/active-directory-pwd-reset-policy/src/ActiveDirectory.PasswordChangePolicy/Properties/AssemblyInfo.cs
1,438
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace Api1 { public class Section1 { public class Configuration : IConfigureOptions<Section1> { private readonly IConfiguration configuration; public Configuration(IConfiguration configuration) { this.configuration = configuration; } public void Configure(Section1 options) { configuration.GetSection(nameof(Section1)).Bind(options); } } public class SomeDataSection { public int SomeData { get; set; } } public string Property1 { get; set; } public string Property2 { get; set; } public SomeDataSection[] Property3 { get; set; } } }
24.424242
66
0.658809
[ "Apache-2.0" ]
maciejw/configuration-tracker
Api1/Section1.cs
806
C#
using Accord.Imaging.Filters; using Macaw.Filtering; namespace Macaw.Editing.Rotation { public class mRotateNearistNeighbor : mFilter { RotateNearestNeighbor Effect = null; public mRotateNearistNeighbor(double Angle, bool Fit,System.Drawing.Color CornerColor) { BitmapType = mFilter.BitmapTypes.Rgb24bpp; Effect = new RotateNearestNeighbor(Angle,Fit); Effect.FillColor = CornerColor; filter = Effect; } } }
22.521739
94
0.638996
[ "MIT" ]
cdriesler/Aviary
Macaw/Editing/Rotation/mRotateNearistNeighbor.cs
520
C#
//------------------------------------------------------------------------------ // <auto-generated> // Generated by the MSBuild WriteCodeFragment class. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("web.Views")] [assembly: Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute("2.1")] [assembly: Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute("MVC-2.1")] [assembly: Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute("MVC-2.1", "Microsoft.AspNetCore.Mvc.Razor.Extensions")]
50.428571
138
0.623229
[ "MIT" ]
shahiddev/docker-compose-example
web/obj/Debug/netcoreapp2.1/web.RazorAssemblyInfo.cs
706
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BalkanAir.Web { public partial class ViewNews { /// <summary> /// InvalidNewsPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel InvalidNewsPanel; /// <summary> /// ViewNewsFormView control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.FormView ViewNewsFormView; /// <summary> /// CommentsListView control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ListView CommentsListView; /// <summary> /// NewsIdHiddenField control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HiddenField NewsIdHiddenField; } }
34.269231
84
0.526936
[ "MIT" ]
itplamen/Balkan-Air
Balkan Air/Web/BalkanAir.Web/ViewNews.aspx.designer.cs
1,784
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using R5T.T0033.D002.I001; namespace R5T.T0033.Construction { class Program { static async Task Main() { var interpretableString = "Hello world from %TEST1% on %TEST2%!!!"; var interpreter = new StringSubstitutionInterpreter(); var substitutions = new Dictionary<string, string> { { "TEST1", "Program" }, { "TEST2", DateTime.Now.ToString() } }; var interprettedString = await interpreter.Interpret(interpretableString, substitutions); Console.WriteLine($"Interprettable string:\n\n{interpretableString}\n\nInterpretted to:\n\n{interprettedString}"); } } }
26.466667
126
0.61461
[ "MIT" ]
SafetyCone/R5T.T0033
source/R5T.T0033.Construction/Code/Program.cs
796
C#
using ARKBreedingStats.species; using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using ARKBreedingStats.Library; namespace ARKBreedingStats { internal static class CreatureColored { private const string Extension = ".png"; private static readonly string ImgFolder = FileService.GetPath(FileService.ImageFolderName); private static string ImgCacheFolderPath = GetImgCacheFolderPath(); private const int TemplateSize = 256; /// <summary> /// Returns the name of the image file used for the species. E.g. parts like Aberrant or Brute are removed, they share the same graphics. /// </summary> internal static string SpeciesImageName(string speciesName, bool replacePolar = true) { if (string.IsNullOrEmpty(speciesName)) return string.Empty; return replacePolar ? speciesName.Replace("Aberrant ", string.Empty).Replace("Brute ", string.Empty) .Replace("Polar Bear", "Dire Bear").Replace("Polar ", string.Empty) : speciesName.Replace("Aberrant ", string.Empty).Replace("Brute ", string.Empty); } /// <summary> /// Returns the image file path to the image with the according colorization. /// </summary> private static string ColoredCreatureCacheFilePath(string speciesName, int[] colorIds, bool listView = false) => Path.Combine(ImgCacheFolderPath, speciesName.Substring(0, Math.Min(speciesName.Length, 5)) + "_" + (speciesName + string.Join(".", colorIds.Select(i => i.ToString()))).GetHashCode().ToString("X8") + (listView ? "_lv" : string.Empty) + Extension); /// <summary> /// Checks if an according species image exists in the cache folder, if not it tries to creates one. Returns false if there's no image. /// </summary> internal static (bool imageExists, string imagePath, string speciesListName) SpeciesImageExists(Species species, int[] colorIds) { string speciesImageName = SpeciesImageName(species?.name); string speciesNameForList = SpeciesImageName(species?.name, false); string cacheFileName = ColoredCreatureCacheFilePath(speciesImageName, colorIds, true); if (File.Exists(cacheFileName)) return (true, cacheFileName, speciesNameForList); string speciesBackgroundFilePath = Path.Combine(ImgFolder, speciesImageName + Extension); string speciesColorMaskFilePath = Path.Combine(ImgFolder, speciesImageName + "_m" + Extension); if (CreateAndSaveCacheSpeciesFile(colorIds, species?.EnabledColorRegions, speciesBackgroundFilePath, speciesColorMaskFilePath, cacheFileName, 64)) return (true, cacheFileName, speciesNameForList); return (false, null, null); } /// <summary> /// Returns a bitmap image that represents the given colors. If a species color file is available, that is used, else a pic-chart like representation. /// </summary> /// <param name="colorIds"></param> /// <param name="species"></param> /// <param name="enabledColorRegions"></param> /// <param name="size"></param> /// <param name="pieSize"></param> /// <param name="onlyColors">Only return a pie-chart like color representation.</param> /// <param name="onlyImage">Only return an image of the colored creature. If that's not possible, return null.</param> /// <param name="creatureSex">If given, it's tried for find a sex-specific image.</param> /// <returns></returns> public static Bitmap GetColoredCreature(int[] colorIds, Species species, bool[] enabledColorRegions, int size = 128, int pieSize = 64, bool onlyColors = false, bool onlyImage = false, Sex creatureSex = Sex.Unknown) { if (colorIds == null) return null; string speciesName = SpeciesImageName(species?.name); // check if there are sex specific images if (creatureSex != Sex.Unknown) { string speciesNameWithSex; switch (creatureSex) { case Sex.Female: speciesNameWithSex = speciesName + "F"; if (File.Exists(Path.Combine(ImgFolder, speciesNameWithSex + Extension))) speciesName = speciesNameWithSex; break; case Sex.Male: speciesNameWithSex = speciesName + "M"; if (File.Exists(Path.Combine(ImgFolder, speciesNameWithSex + Extension))) speciesName = speciesNameWithSex; break; } } string speciesBackgroundFilePath = Path.Combine(ImgFolder, speciesName + Extension); string speciesColorMaskFilePath = Path.Combine(ImgFolder, speciesName + "_m" + Extension); string cacheFilePath = ColoredCreatureCacheFilePath(speciesName, colorIds); bool cacheFileExists = File.Exists(cacheFilePath); if (!onlyColors && !cacheFileExists) { cacheFileExists = CreateAndSaveCacheSpeciesFile(colorIds, enabledColorRegions, speciesBackgroundFilePath, speciesColorMaskFilePath, cacheFilePath); } if (onlyImage && !cacheFileExists) return null; // creating the species file failed if (cacheFileExists && size == TemplateSize) { try { return new Bitmap(cacheFilePath); } catch { // cached file corrupted, recreate if (CreateAndSaveCacheSpeciesFile(colorIds, enabledColorRegions, speciesBackgroundFilePath, speciesColorMaskFilePath, cacheFilePath)) { try { return new Bitmap(cacheFilePath); } catch { // file is still invalid after recreation, ignore file } } } return null; } Bitmap bm = new Bitmap(size, size); using (Graphics graph = Graphics.FromImage(bm)) { graph.SmoothingMode = SmoothingMode.AntiAlias; if (cacheFileExists) { graph.CompositingMode = CompositingMode.SourceCopy; graph.CompositingQuality = CompositingQuality.HighQuality; graph.InterpolationMode = InterpolationMode.HighQualityBicubic; graph.SmoothingMode = SmoothingMode.HighQuality; graph.PixelOffsetMode = PixelOffsetMode.HighQuality; try { using (var cachedImgBmp = new Bitmap(cacheFilePath)) graph.DrawImage(cachedImgBmp, 0, 0, size, size); } catch { // cached file invalid, recreate if (CreateAndSaveCacheSpeciesFile(colorIds, enabledColorRegions, speciesBackgroundFilePath, speciesColorMaskFilePath, cacheFilePath)) { try { using (var cachedImgBmp = new Bitmap(cacheFilePath)) graph.DrawImage(cachedImgBmp, 0, 0, size, size); } catch { // file is still invalid after recreation, ignore file bm.Dispose(); return null; } } } } else { // draw pieChart int pieAngle = enabledColorRegions?.Count(c => c) ?? Species.ColorRegionCount; pieAngle = 360 / (pieAngle > 0 ? pieAngle : 1); int pieNr = 0; for (int c = 0; c < Species.ColorRegionCount; c++) { if (enabledColorRegions?[c] ?? true) { if (colorIds[c] > 0) { using (var b = new SolidBrush(CreatureColors.CreatureColor(colorIds[c]))) { graph.FillPie(b, (size - pieSize) / 2, (size - pieSize) / 2, pieSize, pieSize, pieNr * pieAngle + 270, pieAngle); } } pieNr++; } } using (var pen = new Pen(Color.Gray)) graph.DrawEllipse(pen, (size - pieSize) / 2, (size - pieSize) / 2, pieSize, pieSize); } } return bm; } /// <summary> /// Creates a colored species image and saves it as cache file. Returns true when created successful. /// </summary> /// <returns></returns> private static bool CreateAndSaveCacheSpeciesFile(int[] colorIds, bool[] enabledColorRegions, string speciesBackgroundFilePath, string speciesColorMaskFilePath, string cacheFilePath, int outputSize = 256) { if (string.IsNullOrEmpty(cacheFilePath) || !File.Exists(speciesBackgroundFilePath)) return false; using (Bitmap bmpBackground = new Bitmap(speciesBackgroundFilePath)) using (Bitmap bmpColoredCreature = new Bitmap(bmpBackground.Width, bmpBackground.Height, PixelFormat.Format32bppArgb)) using (Graphics graph = Graphics.FromImage(bmpColoredCreature)) { bool imageFine = true; graph.SmoothingMode = SmoothingMode.AntiAlias; //// ellipse shadow const int scx = TemplateSize / 2; const int scy = (int)(scx * 1.6); const double perspectiveFactor = 0.3; const int yStart = scy - (int)(perspectiveFactor * .7 * scx); const int yEnd = (int)(2 * perspectiveFactor * scx); GraphicsPath pathShadow = new GraphicsPath(); pathShadow.AddEllipse(0, yStart, TemplateSize, yEnd); var colorBlend = new ColorBlend { Colors = new[] { Color.FromArgb(0), Color.FromArgb(40, 0, 0, 0), Color.FromArgb(80, 0, 0, 0) }, Positions = new[] { 0, 0.6f, 1 } }; PathGradientBrush pthGrBrush = new PathGradientBrush(pathShadow) { InterpolationColors = colorBlend }; graph.FillEllipse(pthGrBrush, 0, yStart, TemplateSize, yEnd); // shadow done // shaded base image graph.DrawImage(bmpBackground, 0, 0, TemplateSize, TemplateSize); // if species has color regions, apply colors if (File.Exists(speciesColorMaskFilePath)) { var rgb = new byte[Species.ColorRegionCount][]; var useColorRegions = new bool[Species.ColorRegionCount]; for (int c = 0; c < Species.ColorRegionCount; c++) { useColorRegions[c] = enabledColorRegions[c] && colorIds[c] != 0; if (useColorRegions[c]) { Color cl = CreatureColors.CreatureColor(colorIds[c]); rgb[c] = new[] { cl.R, cl.G, cl.B }; } } imageFine = ApplyColorsUnsafe(rgb, useColorRegions, speciesColorMaskFilePath, TemplateSize, bmpBackground, bmpColoredCreature); } if (imageFine) { string cacheFolder = Path.GetDirectoryName(cacheFilePath); if (string.IsNullOrEmpty(cacheFolder)) return false; if (!Directory.Exists(cacheFolder)) Directory.CreateDirectory(cacheFolder); if (outputSize == TemplateSize) return SaveBitmapToFile(bmpColoredCreature, cacheFilePath); using (var resized = new Bitmap(outputSize, outputSize)) using (var g = Graphics.FromImage(resized)) { g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(bmpColoredCreature, 0, 0, outputSize, outputSize); return SaveBitmapToFile(resized, cacheFilePath); } } } return false; } private static bool SaveBitmapToFile(Bitmap bmp, string filePath) { try { bmp.Save(filePath); return true; } catch { // something went wrong when trying to save the cached creature image. // could be related to have no write access if the portable version is placed in a protected folder like program files. return false; } } /// <summary> /// Applies the colors to the base image. /// </summary> private static bool ApplyColorsUnsafe(byte[][] rgb, bool[] enabledColorRegions, string speciesColorMaskFilePath, int templateSize, Bitmap bmpBackground, Bitmap bmpColoredCreature) { var imageFine = false; using (Bitmap bmpMask = new Bitmap(templateSize, templateSize)) { // get mask in correct size using (var g = Graphics.FromImage(bmpMask)) using (var bmpMaskOriginal = new Bitmap(speciesColorMaskFilePath)) { g.InterpolationMode = InterpolationMode.Bicubic; g.SmoothingMode = SmoothingMode.AntiAlias; g.DrawImage(bmpMaskOriginal, 0, 0, templateSize, templateSize); } BitmapData bmpDataBackground = bmpBackground.LockBits( new Rectangle(0, 0, bmpBackground.Width, bmpBackground.Height), ImageLockMode.ReadOnly, bmpBackground.PixelFormat); BitmapData bmpDataMask = bmpMask.LockBits( new Rectangle(0, 0, bmpMask.Width, bmpMask.Height), ImageLockMode.ReadOnly, bmpMask.PixelFormat); BitmapData bmpDataColoredCreature = bmpColoredCreature.LockBits( new Rectangle(0, 0, bmpColoredCreature.Width, bmpColoredCreature.Height), ImageLockMode.WriteOnly, bmpColoredCreature.PixelFormat); int bgBytes = bmpBackground.PixelFormat == PixelFormat.Format32bppArgb ? 4 : 3; int msBytes = bmpDataMask.PixelFormat == PixelFormat.Format32bppArgb ? 4 : 3; int ccBytes = bmpColoredCreature.PixelFormat == PixelFormat.Format32bppArgb ? 4 : 3; float o = 0; try { unsafe { byte* scan0Bg = (byte*)bmpDataBackground.Scan0.ToPointer(); byte* scan0Ms = (byte*)bmpDataMask.Scan0.ToPointer(); byte* scan0Cc = (byte*)bmpDataColoredCreature.Scan0.ToPointer(); for (int i = 0; i < bmpDataBackground.Width; i++) { for (int j = 0; j < bmpDataBackground.Height; j++) { byte* dBg = scan0Bg + j * bmpDataBackground.Stride + i * bgBytes; // continue if the pixel is transparent if (dBg[3] == 0) continue; byte* dMs = scan0Ms + j * bmpDataMask.Stride + i * msBytes; byte* dCc = scan0Cc + j * bmpDataColoredCreature.Stride + i * ccBytes; int r = dMs[2]; int g = dMs[1]; int b = dMs[0]; byte finalR = dBg[2]; byte finalG = dBg[1]; byte finalB = dBg[0]; for (int m = 0; m < Species.ColorRegionCount; m++) { if (!enabledColorRegions[m]) continue; switch (m) { case 0: o = Math.Max(0, r - g - b) / 255f; break; case 1: o = Math.Max(0, g - r - b) / 255f; break; case 2: o = Math.Max(0, b - r - g) / 255f; break; case 3: o = Math.Min(g, b) / 255f; break; case 4: o = Math.Min(r, g) / 255f; break; case 5: o = Math.Min(r, b) / 255f; break; } if (o == 0) continue; // using "grain merge", e.g. see https://docs.gimp.org/en/gimp-concepts-layer-modes.html int rMix = finalR + rgb[m][0] - 128; if (rMix < 0) rMix = 0; else if (rMix > 255) rMix = 255; int gMix = finalG + rgb[m][1] - 128; if (gMix < 0) gMix = 0; else if (gMix > 255) gMix = 255; int bMix = finalB + rgb[m][2] - 128; if (bMix < 0) bMix = 0; else if (bMix > 255) bMix = 255; finalR = (byte)(o * rMix + (1 - o) * finalR); finalG = (byte)(o * gMix + (1 - o) * finalG); finalB = (byte)(o * bMix + (1 - o) * finalB); } // set final color dCc[0] = finalB; dCc[1] = finalG; dCc[2] = finalR; dCc[3] = dBg[3]; // same alpha as base image } } imageFine = true; } } catch { // error during drawing, maybe mask is smaller than image } bmpBackground.UnlockBits(bmpDataBackground); bmpMask.UnlockBits(bmpDataMask); bmpColoredCreature.UnlockBits(bmpDataColoredCreature); } return imageFine; } public static string RegionColorInfo(Species species, int[] colorIds) { if (species == null || colorIds == null) return null; var creatureRegionColors = new StringBuilder("Colors:"); var cs = species.colors; for (int r = 0; r < Species.ColorRegionCount; r++) { if (!string.IsNullOrEmpty(cs[r]?.name)) { creatureRegionColors.Append($"\n{cs[r].name} ({r}): {CreatureColors.CreatureColorName(colorIds[r])} ({colorIds[r]})"); } } return creatureRegionColors.ToString(); } /// <summary> /// Deletes all cached species color images with a specific pattern that weren't used for some time. /// </summary> internal static void CleanupCache() { if (!Directory.Exists(ImgCacheFolderPath)) return; DirectoryInfo directory = new DirectoryInfo(ImgCacheFolderPath); var oldCacheFiles = directory.GetFiles().Where(f => f.LastAccessTime < DateTime.Now.AddDays(-7)).ToArray(); foreach (FileInfo f in oldCacheFiles) { FileService.TryDeleteFile(f); } } /// <summary> /// If the setting ImgCacheUseLocalAppData is true, the image cache files are saved in the %localAppData% folder instead of the app folder. /// This is always true if the app is installed. /// Call this method after the setting was changed. /// The reason to use the appData folder is that this folder is used to save files, the portable version can be shared and be write protected. /// </summary> internal static void UpdateImgCacheLocation() { ImgCacheFolderPath = GetImgCacheFolderPath(); } private static string GetImgCacheFolderPath() => FileService.GetPath(FileService.ImageFolderName, FileService.CacheFolderName, useAppData: Updater.IsProgramInstalled || Properties.Settings.Default.ImgCacheUseLocalAppData); } }
48.247357
261
0.488585
[ "MIT" ]
AriesPlaysNation/ARKStatsExtractor
ARKBreedingStats/CreatureColored.cs
22,823
C#
/** * $File: JCS_OneJump.cs $ * $Date: $ * $Revision: $ * $Creator: Jen-Chieh Shen $ * $Notice: See LICENSE.txt for modification and distribution information * Copyright (c) 2016 by Shen, Jen-Chieh $ */ using UnityEngine; namespace JCSUnity { /// <summary> /// Effect makes the item jumps and spreads. /// </summary> [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(BoxCollider))] public class JCS_OneJump : MonoBehaviour { /* Variables */ private bool mEffect = false; #if (UNITY_EDITOR) [Header("** Helper Variables (JCS_OneJump) **")] [Tooltip("Name of the collider that blocks the jump.")] [SerializeField] private string mColliderName = null; #endif [Header("** Runtime Variables (JCS_OneJump) **")] [Tooltip("How many force to apply on jump?")] [SerializeField] private float mJumpForce = 10.0f; [Tooltip("How fast this item moves?")] [SerializeField] private float mMoveForce = 10.0f; [Tooltip("Item gravity.")] [SerializeField] private float mItemGravity = 2.0f; private Vector3 mVelocity = Vector3.zero; private BoxCollider mBoxCollider = null; private Rigidbody mRigidbody = null; private RaycastHit mRaycastHit; private Collider mFixCollider = null; // trigger once then disable to save performance. private bool mHitTheWall = false; [Tooltip(@"Do the item bounce back from the wall after hit the wall or just stop there.")] [SerializeField] private bool mBounceBackfromWall = true; /* Setter & Getter */ public bool Effect { get { return this.mEffect; } set { this.mEffect = value; } } public Vector3 GetVelocity() { return this.mVelocity; } public Rigidbody GetRigidbody() { return this.mRigidbody; } public Collider GetFixCollider() { return this.mFixCollider; } public bool BounceBackfromWall { get { return this.mBounceBackfromWall; } set { this.mBounceBackfromWall = value; } } /* Functions */ private void Awake() { mBoxCollider = this.GetComponent<BoxCollider>(); mRigidbody = this.GetComponent<Rigidbody>(); } private void Start() { JCS_PlayerManager pm = JCS_PlayerManager.instance; JCS_2DGameManager gm2d = JCS_2DGameManager.instance; if (pm != null) pm.IgnorePhysicsToAllPlayer(mBoxCollider); if (gm2d != null) gm2d.IgnoreAllPlatformTrigger(mBoxCollider); } private void FixedUpdate() { if (!mEffect) return; this.transform.position += mVelocity * Time.deltaTime; mVelocity.y += -JCS_GameConstant.GRAVITY * Time.deltaTime * mItemGravity; } private void OnTriggerEnter(Collider other) { if (!mHitTheWall) { JCS_ItemWall jcsiw = other.GetComponent<JCS_ItemWall>(); if (jcsiw != null) { // no longer moving along x-axis. { // bounce it back! if (mBounceBackfromWall) mVelocity.x = -mVelocity.x; else mVelocity.x = 0; } mHitTheWall = true; } } /* Only check when the item start dropping. */ TriggerDropping(other); } /// <summary> /// Apply force in order to do hop effect. /// </summary> /// <param name="depth"> include depth? </param> public void DoForce(bool depth = false) { DoForce(mMoveForce, mJumpForce, depth); } /// <summary> /// Apply force in order to do hop effect. /// </summary> /// <param name="moveForce"> force to move in x axis </param> /// <param name="jumpForce"> force to move in y axis </param> /// /// <param name="depth"> include depth? </param> public void DoForce(float moveForce, float jumpForce, bool depth = false) { mVelocity.y = jumpForce; mVelocity.x = moveForce; this.mMoveForce = moveForce; this.mJumpForce = jumpForce; mEffect = true; // including depth! if (depth) { float tempMoveForce = moveForce / 2.0f; // override x mVelocity.x = JCS_Random.Range(-tempMoveForce, tempMoveForce); // apply depth mVelocity.z = JCS_Random.Range(-tempMoveForce, tempMoveForce); } } /// <summary> /// Only check when the item start dropping. /// </summary> /// <param name="other"> collider detected. </param> private void TriggerDropping(Collider other) { if (mVelocity.y > 0) return; // meet ignore object JCS_ItemIgnore jcsii = other.GetComponent<JCS_ItemIgnore>(); if (jcsii != null) return; JCS_Item otherItem = this.GetComponent<JCS_Item>(); // if itself is a item, we check other is a item or not. if (otherItem != null) { otherItem = other.GetComponent<JCS_Item>(); // if both are item then we dont bother each other action. if (otherItem != null) return; } #if (UNITY_EDITOR) // if is debug mode print this out. // in order to know what does item touched and // stop this movement. if (JCS_GameSettings.instance.DEBUG_MODE) JCS_Debug.PrintName(other.transform); mColliderName = other.name; #endif mVelocity.y = 0; mEffect = false; mFixCollider = other; // TODO(jenchieh): not all the object we get set are // box collider only. BoxCollider beSetBox = other.GetComponent<BoxCollider>(); // set this ontop of the other box(ground) if (beSetBox != null) JCS_Physics.SetOnTopOfBoxWithSlope(mBoxCollider, beSetBox); // enable the physic once on the ground JCS_PlayerManager.instance.IgnorePhysicsToAllPlayer(this.mBoxCollider, false); } } }
31.894737
125
0.542754
[ "BSD-3-Clause" ]
MapleStoryUnity/MapleStoryUnity
Assets/JCSUnity/Scripts/Effects/Item/JCS_OneJump.cs
6,668
C#
#nullable disable using Microsoft.Maps.ElevationAdjustmentService.HDPhoto; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace WWT.Providers { [RequestEndpoint("/wwtweb/BingDemTile2.aspx")] public class BingDemTile2Provider : RequestProvider { private readonly IVirtualEarthDownloader _veDownloader; public BingDemTile2Provider(IVirtualEarthDownloader veDownload) { _veDownloader = veDownload; } public override string ContentType => ContentTypes.OctetStream; public override async Task RunAsync(IWwtContext context, CancellationToken token) { string query = context.Request.Params["Q"]; string[] values = query.Split(','); int level = Convert.ToInt32(values[0]); int tileX = Convert.ToInt32(values[1]); int tileY = Convert.ToInt32(values[2]); const int demSize = 33 * 33; using var stream = await _veDownloader.DownloadVeTileAsync(VirtualEarthTile.Ecn, level, tileX, tileY, token); DemTile tile = DemCodec.Decompress(stream); if (tile != null) { float[] DemData = new float[demSize]; int yh = 0; for (int yl = 0; yl < 33; yl++) { int xh = 0; for (int xl = 0; xl < 33; xl++) { int indexI = xl + (32 - yl) * 33; DemData[indexI] = (float)tile.AltitudeInMeters(yh, xh); xh += 8; } yh += 8; } var data = new byte[DemData.Length * 4]; using var ms = new MemoryStream(data); var bw = new BinaryWriter(ms); foreach (float sample in DemData) { bw.Write(sample); } bw.Flush(); await context.Response.OutputStream.WriteAsync(data, 0, data.Length, token); } context.Response.End(); } } }
30.985714
121
0.521899
[ "MIT" ]
pkgw/wwt-website
src/WWT.Providers/Providers/Bingdemtile2provider.cs
2,169
C#
namespace Ren.CMS.Persistence.Mapping { using System; using System.Collections.Generic; using System.Linq; using System.Text; using NHibernate.Mapping.ByCode; using NHibernate.Mapping.ByCode.Conformist; using Ren.CMS.Persistence.Domain; [Ren.CMS.Persistence.Base.PersistenceMapping] public class ContentClickCounterMap : ClassMapping<ContentClickCounter> { #region Constructors public ContentClickCounterMap() { Table(Ren.CMS.CORE.Config.RenConfig.DB.Prefix.Replace("dbo.", "") +"Content_ClickCounter"); Schema("dbo"); Lazy(true); Id(x => x.Id, map => map.Generator(Generators.Identity)); Property(x => x.Ip); Property(x => x.Cid, map => map.NotNullable(true)); } #endregion Constructors } }
28.4
103
0.630282
[ "MIT" ]
nfMalde/Ren.CMS.NET
Ren.CMS.Net/Source/Ren.CMS.Net-Libraries/Ren.CMS.Persistence/Mapping/ContentClickCounterMap.cs
852
C#
namespace AlphaControls { partial class PicShiftPanel { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { //showImageList = null; if (foodModelList != null) { foodModelList.Clear(); foodModelList = null; } this.picShiftControl.DoubleClick -= new System.EventHandler(this.picShiftControl_DoubleClick); this.picShiftControl.Dispose(); this.panel.Dispose(); this.btnNext.Click -= new System.EventHandler(this.btnNext_Click); this.btnNext.Dispose(); this.btnLast.Click -= new System.EventHandler(this.btnLast_Click); this.btnLast.Dispose(); this.btnBuy.Click -= new System.EventHandler(this.btnBuy_Click); this.btnBuy.Dispose(); this.lbCount.Dispose(); this.gestureRecognizer.Scroll -= new System.EventHandler<Microsoft.WindowsMobile.Gestures.GestureScrollEventArgs>(this.gestureRecognizer_Scroll); //this.gestureRecognizer.Dispose(); PictureShiftPanelEvent.OnPictureSelectChange -= new PictureShiftPanelEvent.PicturnTurnDelegate(PictureTurnEvent_OnPictureSelectChange); if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 组件设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.panel = new System.Windows.Forms.Panel(); this.picShiftControl = new AlphaControls.PicShiftControl(); this.btnNext = new System.Windows.Forms.Button(); this.btnLast = new System.Windows.Forms.Button(); this.lbCount = new System.Windows.Forms.Label(); this.gestureRecognizer = new Microsoft.WindowsMobile.Gestures.GestureRecognizer(); this.btnBuy = new System.Windows.Forms.Button(); this.lbID = new System.Windows.Forms.Label(); this.lbName = new System.Windows.Forms.Label(); this.lbPrice = new System.Windows.Forms.Label(); this.panel.SuspendLayout(); this.SuspendLayout(); // // panel // this.panel.Controls.Add(this.picShiftControl); this.panel.Location = new System.Drawing.Point(0, 0); this.panel.Name = "panel"; this.panel.Size = new System.Drawing.Size(180, 160); // // picShiftControl // this.picShiftControl.Location = new System.Drawing.Point(5, 5); this.picShiftControl.Name = "picShiftControl"; this.picShiftControl.Size = new System.Drawing.Size(170, 150); this.picShiftControl.TabIndex = 0; this.picShiftControl.Text = "picShiftControl"; this.picShiftControl.DoubleClick += new System.EventHandler(this.picShiftControl_DoubleClick); // // btnNext // this.btnNext.Location = new System.Drawing.Point(185, 5); this.btnNext.Name = "btnNext"; this.btnNext.Size = new System.Drawing.Size(50, 20); this.btnNext.TabIndex = 1; this.btnNext.Text = "下一个"; this.btnNext.Click += new System.EventHandler(this.btnNext_Click); // // btnLast // this.btnLast.Location = new System.Drawing.Point(185, 30); this.btnLast.Name = "btnLast"; this.btnLast.Size = new System.Drawing.Size(50, 20); this.btnLast.TabIndex = 2; this.btnLast.Text = "上一个"; this.btnLast.Click += new System.EventHandler(this.btnLast_Click); // // lbCount // this.lbCount.Location = new System.Drawing.Point(184, 55); this.lbCount.Name = "lbCount"; this.lbCount.Size = new System.Drawing.Size(50, 15); this.lbCount.Text = "?/?"; this.lbCount.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // gestureRecognizer // this.gestureRecognizer.TargetControl = this.picShiftControl; this.gestureRecognizer.Scroll += new System.EventHandler<Microsoft.WindowsMobile.Gestures.GestureScrollEventArgs>(this.gestureRecognizer_Scroll); // // btnBuy // this.btnBuy.Location = new System.Drawing.Point(185, 125); this.btnBuy.Name = "btnBuy"; this.btnBuy.Size = new System.Drawing.Size(50, 30); this.btnBuy.TabIndex = 4; this.btnBuy.Text = "下单"; this.btnBuy.Click += new System.EventHandler(this.btnBuy_Click); // // lbID // this.lbID.Font = new System.Drawing.Font("Tahoma", 7F, System.Drawing.FontStyle.Regular); this.lbID.Location = new System.Drawing.Point(185, 75); this.lbID.Name = "lbID"; this.lbID.Size = new System.Drawing.Size(50, 15); this.lbID.Text = "ID:"; // // lbName // this.lbName.Font = new System.Drawing.Font("Tahoma", 7F, System.Drawing.FontStyle.Regular); this.lbName.Location = new System.Drawing.Point(185, 90); this.lbName.Name = "lbName"; this.lbName.Size = new System.Drawing.Size(50, 15); this.lbName.Text = "Name:"; // // lbPrice // this.lbPrice.Font = new System.Drawing.Font("Tahoma", 7F, System.Drawing.FontStyle.Regular); this.lbPrice.Location = new System.Drawing.Point(185, 105); this.lbPrice.Name = "lbPrice"; this.lbPrice.Size = new System.Drawing.Size(50, 15); this.lbPrice.Text = "Price:"; // // PicShiftPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.lbPrice); this.Controls.Add(this.lbName); this.Controls.Add(this.lbID); this.Controls.Add(this.btnBuy); this.Controls.Add(this.lbCount); this.Controls.Add(this.btnLast); this.Controls.Add(this.btnNext); this.Controls.Add(this.panel); this.Name = "PicShiftPanel"; this.Size = new System.Drawing.Size(240, 160); this.panel.ResumeLayout(false); this.ResumeLayout(false); } #endregion private PicShiftControl picShiftControl; private System.Windows.Forms.Panel panel; private System.Windows.Forms.Button btnNext; private System.Windows.Forms.Button btnLast; private System.Windows.Forms.Label lbCount; private Microsoft.WindowsMobile.Gestures.GestureRecognizer gestureRecognizer; private System.Windows.Forms.Button btnBuy; private System.Windows.Forms.Label lbID; private System.Windows.Forms.Label lbName; private System.Windows.Forms.Label lbPrice; } }
41.765957
158
0.557692
[ "MIT" ]
CZHSoft/LT_EPOSApp
AlphaButton/OtherControl/PictureShiftPanel.Designer.cs
8,020
C#
namespace MercuryBOT { partial class CommentsGather { /// <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() { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CommentsGather)); this.combox_GatherProfileOrGroup = new MetroFramework.Controls.MetroComboBox(); this.metroLabel1 = new MetroFramework.Controls.MetroLabel(); this.btn_doTask = new MetroFramework.Controls.MetroButton(); this.metroLabel3 = new MetroFramework.Controls.MetroLabel(); this.chck_containsWords = new MetroFramework.Controls.MetroCheckBox(); this.txtBox_filterWords = new MetroFramework.Controls.MetroTextBox(); this.GridCommentsData = new MetroFramework.Controls.MetroGrid(); this.ColumnID = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.content = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.autor = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.time = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.metroLabel2 = new MetroFramework.Controls.MetroLabel(); this.panel1 = new System.Windows.Forms.Panel(); this.lbl_totalCommentsInGrid = new MetroFramework.Controls.MetroLabel(); this.MongoToolTip = new MetroFramework.Components.MetroToolTip(); this.metroCheckBox1 = new MetroFramework.Controls.MetroCheckBox(); this.txtBox_Comments2GetCount = new MetroFramework.Controls.MetroTextBox(); this.metroLabel4 = new MetroFramework.Controls.MetroLabel(); this.ProgressSpinner_LoadComments = new MetroFramework.Controls.MetroProgressSpinner(); this.CollectComments = new System.ComponentModel.BackgroundWorker(); this.CommentsList_ScrollBar = new MetroFramework.Controls.MetroScrollBar(); this.combox_ProfileURLorGroupID = new MetroFramework.Controls.MetroComboBox(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); ((System.ComponentModel.ISupportInitialize)(this.GridCommentsData)).BeginInit(); this.SuspendLayout(); // // combox_GatherProfileOrGroup // this.combox_GatherProfileOrGroup.ForeColor = System.Drawing.Color.White; this.combox_GatherProfileOrGroup.FormattingEnabled = true; this.combox_GatherProfileOrGroup.ItemHeight = 23; this.combox_GatherProfileOrGroup.Items.AddRange(new object[] { "My Profile", "My Group"}); this.combox_GatherProfileOrGroup.Location = new System.Drawing.Point(197, 569); this.combox_GatherProfileOrGroup.Name = "combox_GatherProfileOrGroup"; this.combox_GatherProfileOrGroup.Size = new System.Drawing.Size(232, 29); this.combox_GatherProfileOrGroup.TabIndex = 2; this.combox_GatherProfileOrGroup.Theme = MetroFramework.MetroThemeStyle.Dark; this.combox_GatherProfileOrGroup.UseCustomForeColor = true; this.combox_GatherProfileOrGroup.UseSelectable = true; this.combox_GatherProfileOrGroup.UseStyleColors = true; this.combox_GatherProfileOrGroup.SelectedIndexChanged += new System.EventHandler(this.Combox_profileOrClan_SelectedIndexChanged); // // metroLabel1 // this.metroLabel1.AutoSize = true; this.metroLabel1.ForeColor = System.Drawing.Color.White; this.metroLabel1.Location = new System.Drawing.Point(87, 574); this.metroLabel1.Name = "metroLabel1"; this.metroLabel1.Size = new System.Drawing.Size(110, 19); this.metroLabel1.Style = MetroFramework.MetroColorStyle.Purple; this.metroLabel1.TabIndex = 3; this.metroLabel1.Text = "Where to gather:"; this.metroLabel1.Theme = MetroFramework.MetroThemeStyle.Dark; this.metroLabel1.UseCustomBackColor = true; this.metroLabel1.UseCustomForeColor = true; this.metroLabel1.UseStyleColors = true; // // btn_doTask // this.btn_doTask.DisplayFocus = true; this.btn_doTask.ForeColor = System.Drawing.Color.White; this.btn_doTask.Location = new System.Drawing.Point(848, 575); this.btn_doTask.Name = "btn_doTask"; this.btn_doTask.Size = new System.Drawing.Size(154, 97); this.btn_doTask.Style = MetroFramework.MetroColorStyle.Purple; this.btn_doTask.TabIndex = 5; this.btn_doTask.Text = "GATHER COMMENTS!"; this.btn_doTask.Theme = MetroFramework.MetroThemeStyle.Dark; this.btn_doTask.UseCustomForeColor = true; this.btn_doTask.UseSelectable = true; this.btn_doTask.UseStyleColors = true; this.btn_doTask.Click += new System.EventHandler(this.Btn_doTask_Click); // // metroLabel3 // this.metroLabel3.AutoSize = true; this.metroLabel3.ForeColor = System.Drawing.Color.White; this.metroLabel3.Location = new System.Drawing.Point(468, 569); this.metroLabel3.Name = "metroLabel3"; this.metroLabel3.Size = new System.Drawing.Size(96, 19); this.metroLabel3.Style = MetroFramework.MetroColorStyle.Purple; this.metroLabel3.TabIndex = 6; this.metroLabel3.Text = "Delete options:"; this.metroLabel3.Theme = MetroFramework.MetroThemeStyle.Dark; this.metroLabel3.UseCustomBackColor = true; this.metroLabel3.UseCustomForeColor = true; this.metroLabel3.UseStyleColors = true; // // chck_containsWords // this.chck_containsWords.AutoSize = true; this.chck_containsWords.Location = new System.Drawing.Point(509, 618); this.chck_containsWords.Name = "chck_containsWords"; this.chck_containsWords.Size = new System.Drawing.Size(108, 15); this.chck_containsWords.TabIndex = 8; this.chck_containsWords.Text = "Contains words:"; this.MongoToolTip.SetToolTip(this.chck_containsWords, "This will delete your comments based on words"); this.chck_containsWords.UseCustomBackColor = true; this.chck_containsWords.UseSelectable = true; this.chck_containsWords.UseStyleColors = true; // // txtBox_filterWords // this.txtBox_filterWords.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(25)))), ((int)(((byte)(25)))), ((int)(((byte)(25))))); // // // this.txtBox_filterWords.CustomButton.Image = null; this.txtBox_filterWords.CustomButton.Location = new System.Drawing.Point(127, 1); this.txtBox_filterWords.CustomButton.Name = ""; this.txtBox_filterWords.CustomButton.Size = new System.Drawing.Size(39, 39); this.txtBox_filterWords.CustomButton.Style = MetroFramework.MetroColorStyle.Blue; this.txtBox_filterWords.CustomButton.TabIndex = 1; this.txtBox_filterWords.CustomButton.Theme = MetroFramework.MetroThemeStyle.Light; this.txtBox_filterWords.CustomButton.UseSelectable = true; this.txtBox_filterWords.CustomButton.Visible = false; this.txtBox_filterWords.ForeColor = System.Drawing.Color.White; this.txtBox_filterWords.Lines = new string[0]; this.txtBox_filterWords.Location = new System.Drawing.Point(619, 617); this.txtBox_filterWords.MaxLength = 32767; this.txtBox_filterWords.Multiline = true; this.txtBox_filterWords.Name = "txtBox_filterWords"; this.txtBox_filterWords.PasswordChar = '\0'; this.txtBox_filterWords.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtBox_filterWords.SelectedText = ""; this.txtBox_filterWords.SelectionLength = 0; this.txtBox_filterWords.SelectionStart = 0; this.txtBox_filterWords.ShortcutsEnabled = true; this.txtBox_filterWords.Size = new System.Drawing.Size(167, 41); this.txtBox_filterWords.TabIndex = 9; this.txtBox_filterWords.Theme = MetroFramework.MetroThemeStyle.Dark; this.MongoToolTip.SetToolTip(this.txtBox_filterWords, "Use comma to separate all words"); this.txtBox_filterWords.UseCustomBackColor = true; this.txtBox_filterWords.UseCustomForeColor = true; this.txtBox_filterWords.UseSelectable = true; this.txtBox_filterWords.UseStyleColors = true; this.txtBox_filterWords.WaterMark = "FREE,CASE,GIVEAWAY"; this.txtBox_filterWords.WaterMarkColor = System.Drawing.Color.FromArgb(((int)(((byte)(109)))), ((int)(((byte)(109)))), ((int)(((byte)(109))))); this.txtBox_filterWords.WaterMarkFont = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); // // GridCommentsData // this.GridCommentsData.AllowUserToAddRows = false; this.GridCommentsData.AllowUserToDeleteRows = false; this.GridCommentsData.AllowUserToOrderColumns = true; this.GridCommentsData.AllowUserToResizeColumns = false; this.GridCommentsData.AllowUserToResizeRows = false; this.GridCommentsData.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(17)))), ((int)(((byte)(17)))), ((int)(((byte)(17))))); this.GridCommentsData.BorderStyle = System.Windows.Forms.BorderStyle.None; this.GridCommentsData.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.GridCommentsData.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(174)))), ((int)(((byte)(219))))); dataGridViewCellStyle1.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); dataGridViewCellStyle1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(17)))), ((int)(((byte)(17)))), ((int)(((byte)(17))))); dataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(198)))), ((int)(((byte)(247))))); dataGridViewCellStyle1.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(17)))), ((int)(((byte)(17)))), ((int)(((byte)(17))))); dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.GridCommentsData.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; this.GridCommentsData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.GridCommentsData.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnID, this.content, this.autor, this.time}); dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(17)))), ((int)(((byte)(17)))), ((int)(((byte)(17))))); dataGridViewCellStyle2.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); dataGridViewCellStyle2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(109)))), ((int)(((byte)(109)))), ((int)(((byte)(109))))); dataGridViewCellStyle2.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(198)))), ((int)(((byte)(247))))); dataGridViewCellStyle2.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(17)))), ((int)(((byte)(17)))), ((int)(((byte)(17))))); dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.GridCommentsData.DefaultCellStyle = dataGridViewCellStyle2; this.GridCommentsData.EnableHeadersVisualStyles = false; this.GridCommentsData.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.GridCommentsData.GridColor = System.Drawing.Color.FromArgb(((int)(((byte)(17)))), ((int)(((byte)(17)))), ((int)(((byte)(17))))); this.GridCommentsData.Location = new System.Drawing.Point(-41, 65); this.GridCommentsData.MultiSelect = false; this.GridCommentsData.Name = "GridCommentsData"; this.GridCommentsData.ReadOnly = true; this.GridCommentsData.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(174)))), ((int)(((byte)(219))))); dataGridViewCellStyle3.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); dataGridViewCellStyle3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(17)))), ((int)(((byte)(17)))), ((int)(((byte)(17))))); dataGridViewCellStyle3.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(198)))), ((int)(((byte)(247))))); dataGridViewCellStyle3.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(17)))), ((int)(((byte)(17)))), ((int)(((byte)(17))))); dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.GridCommentsData.RowHeadersDefaultCellStyle = dataGridViewCellStyle3; this.GridCommentsData.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; this.GridCommentsData.ScrollBars = System.Windows.Forms.ScrollBars.None; this.GridCommentsData.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.GridCommentsData.Size = new System.Drawing.Size(1054, 478); this.GridCommentsData.TabIndex = 13; this.GridCommentsData.Theme = MetroFramework.MetroThemeStyle.Dark; this.GridCommentsData.UseCustomBackColor = true; this.GridCommentsData.UseCustomForeColor = true; this.GridCommentsData.UseStyleColors = true; // // ColumnID // this.ColumnID.HeaderText = "COMMENT ID"; this.ColumnID.Name = "ColumnID"; this.ColumnID.ReadOnly = true; this.ColumnID.Width = 130; // // content // this.content.HeaderText = "CONTENT"; this.content.Name = "content"; this.content.ReadOnly = true; this.content.Width = 625; // // autor // this.autor.HeaderText = "AUTHOR"; this.autor.Name = "autor"; this.autor.ReadOnly = true; this.autor.Width = 130; // // time // this.time.HeaderText = "TIME"; this.time.Name = "time"; this.time.ReadOnly = true; this.time.Width = 130; // // metroLabel2 // this.metroLabel2.AutoSize = true; this.metroLabel2.ForeColor = System.Drawing.Color.White; this.metroLabel2.Location = new System.Drawing.Point(105, 613); this.metroLabel2.Name = "metroLabel2"; this.metroLabel2.Size = new System.Drawing.Size(92, 19); this.metroLabel2.Style = MetroFramework.MetroColorStyle.Purple; this.metroLabel2.TabIndex = 15; this.metroLabel2.Text = "Profile/Group:"; this.metroLabel2.Theme = MetroFramework.MetroThemeStyle.Dark; this.metroLabel2.UseCustomBackColor = true; this.metroLabel2.UseCustomForeColor = true; this.metroLabel2.UseStyleColors = true; // // panel1 // this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(25)))), ((int)(((byte)(25)))), ((int)(((byte)(25))))); this.panel1.Location = new System.Drawing.Point(-1, 544); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(1016, 10); this.panel1.TabIndex = 16; // // lbl_totalCommentsInGrid // this.lbl_totalCommentsInGrid.FontSize = MetroFramework.MetroLabelSize.Small; this.lbl_totalCommentsInGrid.ForeColor = System.Drawing.Color.White; this.lbl_totalCommentsInGrid.Location = new System.Drawing.Point(726, 46); this.lbl_totalCommentsInGrid.Name = "lbl_totalCommentsInGrid"; this.lbl_totalCommentsInGrid.Size = new System.Drawing.Size(286, 19); this.lbl_totalCommentsInGrid.TabIndex = 17; this.lbl_totalCommentsInGrid.Text = "Total Deleted: ..."; this.lbl_totalCommentsInGrid.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.lbl_totalCommentsInGrid.UseCustomBackColor = true; this.lbl_totalCommentsInGrid.UseCustomForeColor = true; this.lbl_totalCommentsInGrid.UseStyleColors = true; // // MongoToolTip // this.MongoToolTip.Style = MetroFramework.MetroColorStyle.Blue; this.MongoToolTip.StyleManager = null; this.MongoToolTip.Theme = MetroFramework.MetroThemeStyle.Light; // // metroCheckBox1 // this.metroCheckBox1.AutoSize = true; this.metroCheckBox1.Location = new System.Drawing.Point(509, 595); this.metroCheckBox1.Name = "metroCheckBox1"; this.metroCheckBox1.Size = new System.Drawing.Size(66, 15); this.metroCheckBox1.TabIndex = 26; this.metroCheckBox1.Text = "Any link"; this.MongoToolTip.SetToolTip(this.metroCheckBox1, "This will delete your comments based on words"); this.metroCheckBox1.UseCustomBackColor = true; this.metroCheckBox1.UseSelectable = true; this.metroCheckBox1.UseStyleColors = true; // // txtBox_Comments2GetCount // // // // this.txtBox_Comments2GetCount.CustomButton.Image = null; this.txtBox_Comments2GetCount.CustomButton.Location = new System.Drawing.Point(210, 1); this.txtBox_Comments2GetCount.CustomButton.Name = ""; this.txtBox_Comments2GetCount.CustomButton.Size = new System.Drawing.Size(21, 21); this.txtBox_Comments2GetCount.CustomButton.Style = MetroFramework.MetroColorStyle.Blue; this.txtBox_Comments2GetCount.CustomButton.TabIndex = 1; this.txtBox_Comments2GetCount.CustomButton.Theme = MetroFramework.MetroThemeStyle.Light; this.txtBox_Comments2GetCount.CustomButton.UseSelectable = true; this.txtBox_Comments2GetCount.CustomButton.Visible = false; this.txtBox_Comments2GetCount.ForeColor = System.Drawing.Color.White; this.txtBox_Comments2GetCount.Lines = new string[] { "5000"}; this.txtBox_Comments2GetCount.Location = new System.Drawing.Point(197, 649); this.txtBox_Comments2GetCount.MaxLength = 4; this.txtBox_Comments2GetCount.Name = "txtBox_Comments2GetCount"; this.txtBox_Comments2GetCount.PasswordChar = '\0'; this.txtBox_Comments2GetCount.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtBox_Comments2GetCount.SelectedText = ""; this.txtBox_Comments2GetCount.SelectionLength = 0; this.txtBox_Comments2GetCount.SelectionStart = 0; this.txtBox_Comments2GetCount.ShortcutsEnabled = true; this.txtBox_Comments2GetCount.Size = new System.Drawing.Size(232, 23); this.txtBox_Comments2GetCount.TabIndex = 18; this.txtBox_Comments2GetCount.Text = "5000"; this.txtBox_Comments2GetCount.Theme = MetroFramework.MetroThemeStyle.Dark; this.txtBox_Comments2GetCount.UseCustomBackColor = true; this.txtBox_Comments2GetCount.UseCustomForeColor = true; this.txtBox_Comments2GetCount.UseSelectable = true; this.txtBox_Comments2GetCount.UseStyleColors = true; this.txtBox_Comments2GetCount.WaterMark = "Max: 5000 per Task! (for now)"; this.txtBox_Comments2GetCount.WaterMarkColor = System.Drawing.Color.FromArgb(((int)(((byte)(109)))), ((int)(((byte)(109)))), ((int)(((byte)(109))))); this.txtBox_Comments2GetCount.WaterMarkFont = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Pixel); // // metroLabel4 // this.metroLabel4.AutoSize = true; this.metroLabel4.ForeColor = System.Drawing.Color.White; this.metroLabel4.Location = new System.Drawing.Point(19, 646); this.metroLabel4.Name = "metroLabel4"; this.metroLabel4.Size = new System.Drawing.Size(178, 19); this.metroLabel4.Style = MetroFramework.MetroColorStyle.Purple; this.metroLabel4.TabIndex = 19; this.metroLabel4.Text = "How much comments to get:"; this.metroLabel4.Theme = MetroFramework.MetroThemeStyle.Dark; this.metroLabel4.UseCustomBackColor = true; this.metroLabel4.UseCustomForeColor = true; this.metroLabel4.UseStyleColors = true; // // ProgressSpinner_LoadComments // this.ProgressSpinner_LoadComments.Location = new System.Drawing.Point(327, 23); this.ProgressSpinner_LoadComments.Maximum = 100; this.ProgressSpinner_LoadComments.Name = "ProgressSpinner_LoadComments"; this.ProgressSpinner_LoadComments.Size = new System.Drawing.Size(29, 30); this.ProgressSpinner_LoadComments.TabIndex = 20; this.ProgressSpinner_LoadComments.Theme = MetroFramework.MetroThemeStyle.Dark; this.ProgressSpinner_LoadComments.UseCustomBackColor = true; this.ProgressSpinner_LoadComments.UseCustomForeColor = true; this.ProgressSpinner_LoadComments.UseSelectable = true; this.ProgressSpinner_LoadComments.UseStyleColors = true; // // CollectComments // this.CollectComments.DoWork += new System.ComponentModel.DoWorkEventHandler(this.CollectComments_DoWork); // // CommentsList_ScrollBar // this.CommentsList_ScrollBar.LargeChange = 10; this.CommentsList_ScrollBar.Location = new System.Drawing.Point(997, 80); this.CommentsList_ScrollBar.Maximum = 100; this.CommentsList_ScrollBar.Minimum = 0; this.CommentsList_ScrollBar.MouseWheelBarPartitions = 10; this.CommentsList_ScrollBar.Name = "CommentsList_ScrollBar"; this.CommentsList_ScrollBar.Orientation = MetroFramework.Controls.MetroScrollOrientation.Vertical; this.CommentsList_ScrollBar.ScrollbarSize = 15; this.CommentsList_ScrollBar.Size = new System.Drawing.Size(15, 463); this.CommentsList_ScrollBar.Style = MetroFramework.MetroColorStyle.Purple; this.CommentsList_ScrollBar.TabIndex = 22; this.CommentsList_ScrollBar.Theme = MetroFramework.MetroThemeStyle.Dark; this.CommentsList_ScrollBar.UseBarColor = true; this.CommentsList_ScrollBar.UseSelectable = true; this.CommentsList_ScrollBar.Scroll += new System.Windows.Forms.ScrollEventHandler(this.CommentsList_ScrollBar_Scroll); // // combox_ProfileURLorGroupID // this.combox_ProfileURLorGroupID.ForeColor = System.Drawing.Color.White; this.combox_ProfileURLorGroupID.FormattingEnabled = true; this.combox_ProfileURLorGroupID.ItemHeight = 23; this.combox_ProfileURLorGroupID.Location = new System.Drawing.Point(197, 609); this.combox_ProfileURLorGroupID.Name = "combox_ProfileURLorGroupID"; this.combox_ProfileURLorGroupID.Size = new System.Drawing.Size(232, 29); this.combox_ProfileURLorGroupID.TabIndex = 24; this.combox_ProfileURLorGroupID.Theme = MetroFramework.MetroThemeStyle.Dark; this.combox_ProfileURLorGroupID.UseCustomForeColor = true; this.combox_ProfileURLorGroupID.UseSelectable = true; this.combox_ProfileURLorGroupID.UseStyleColors = true; this.combox_ProfileURLorGroupID.SelectedIndexChanged += new System.EventHandler(this.combox_ProfileURLorGroupID_SelectedIndexChanged); // // richTextBox1 // this.richTextBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(17)))), ((int)(((byte)(17)))), ((int)(((byte)(17))))); this.richTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.richTextBox1.Cursor = System.Windows.Forms.Cursors.Arrow; this.richTextBox1.DetectUrls = false; this.richTextBox1.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.richTextBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.richTextBox1.Location = new System.Drawing.Point(470, 593); this.richTextBox1.MaxLength = 50; this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.ReadOnly = true; this.richTextBox1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.richTextBox1.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None; this.richTextBox1.Size = new System.Drawing.Size(42, 14); this.richTextBox1.TabIndex = 25; this.richTextBox1.Text = "└───"; // // CommentsGather // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.ClientSize = new System.Drawing.Size(1012, 681); this.Controls.Add(this.metroCheckBox1); this.Controls.Add(this.chck_containsWords); this.Controls.Add(this.richTextBox1); this.Controls.Add(this.combox_ProfileURLorGroupID); this.Controls.Add(this.CommentsList_ScrollBar); this.Controls.Add(this.ProgressSpinner_LoadComments); this.Controls.Add(this.txtBox_Comments2GetCount); this.Controls.Add(this.metroLabel4); this.Controls.Add(this.lbl_totalCommentsInGrid); this.Controls.Add(this.GridCommentsData); this.Controls.Add(this.txtBox_filterWords); this.Controls.Add(this.metroLabel3); this.Controls.Add(this.btn_doTask); this.Controls.Add(this.combox_GatherProfileOrGroup); this.Controls.Add(this.metroLabel2); this.Controls.Add(this.metroLabel1); this.Controls.Add(this.panel1); this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "CommentsGather"; this.Resizable = false; this.ShadowType = MetroFramework.Forms.MetroFormShadowType.DropShadow; this.Style = MetroFramework.MetroColorStyle.Default; this.Text = "Mercury - Comments Gather"; this.Theme = MetroFramework.MetroThemeStyle.Dark; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.CommentsGather_FormClosed); this.Load += new System.EventHandler(this.CommentsGather_Load); ((System.ComponentModel.ISupportInitialize)(this.GridCommentsData)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private MetroFramework.Controls.MetroComboBox combox_GatherProfileOrGroup; private MetroFramework.Controls.MetroLabel metroLabel1; private MetroFramework.Controls.MetroButton btn_doTask; private MetroFramework.Controls.MetroLabel metroLabel3; private MetroFramework.Controls.MetroCheckBox chck_containsWords; private MetroFramework.Controls.MetroTextBox txtBox_filterWords; private MetroFramework.Controls.MetroGrid GridCommentsData; private MetroFramework.Controls.MetroLabel metroLabel2; private System.Windows.Forms.Panel panel1; private MetroFramework.Controls.MetroLabel lbl_totalCommentsInGrid; private MetroFramework.Components.MetroToolTip MongoToolTip; private MetroFramework.Controls.MetroTextBox txtBox_Comments2GetCount; private MetroFramework.Controls.MetroLabel metroLabel4; private MetroFramework.Controls.MetroProgressSpinner ProgressSpinner_LoadComments; private System.ComponentModel.BackgroundWorker CollectComments; private MetroFramework.Controls.MetroScrollBar CommentsList_ScrollBar; private MetroFramework.Controls.MetroComboBox combox_ProfileURLorGroupID; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnID; private System.Windows.Forms.DataGridViewTextBoxColumn content; private System.Windows.Forms.DataGridViewTextBoxColumn autor; private System.Windows.Forms.DataGridViewTextBoxColumn time; private MetroFramework.Controls.MetroLabel lbl_cDeletedLive; private System.Windows.Forms.RichTextBox richTextBox1; private MetroFramework.Controls.MetroCheckBox metroCheckBox1; } }
63.316832
173
0.659703
[ "MIT" ]
Chad90b/Mercury
MercuryBOT/Comments/CommentsGather.Designer.cs
31,985
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Automation.Common; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Automation.Models; using System.Collections; using System.Management.Automation; using System.Security.Permissions; using AutomationAccount = Microsoft.Azure.Commands.Automation.Model.AutomationAccount; namespace Microsoft.Azure.Commands.Automation.Cmdlet { /// <summary> /// Creates azure automation accounts based on automation account name and location. /// </summary> [Cmdlet(VerbsCommon.New, "AzureRmAutomationAccount")] [OutputType(typeof(AutomationAccount))] public class NewAzureAutomationAccount : ResourceManager.Common.AzureRMCmdlet { /// <summary> /// The automation client. /// </summary> private IAutomationClient automationClient; /// <summary> /// Gets or sets the automation client base. /// </summary> public IAutomationClient AutomationClient { get { return this.automationClient = this.automationClient ?? new AutomationClient(DefaultProfile.DefaultContext); } set { this.automationClient = value; } } /// <summary> /// Gets or sets the automation account name. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")] [ResourceGroupCompleter()] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } /// <summary> /// Gets or sets the automation account name. /// </summary> [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The automation account name.")] [Alias("AutomationAccountName")] [ValidateNotNullOrEmpty] public string Name { get; set; } /// <summary> /// Gets or sets the location. /// </summary> [Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The geo region of the automation account")] [LocationCompleter("Microsoft.Automation/automationAccounts")] public string Location { get; set; } /// <summary> /// Gets or sets the plan. /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The plan of the automation account")] [ValidateSet(SkuNameEnum.Free, SkuNameEnum.Basic, IgnoreCase = true)] public string Plan { get; set; } /// <summary> /// Gets or sets the module tags. /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The automation account tags.")] [Alias("Tag")] public IDictionary Tags { get; set; } /// <summary> /// Execute this cmdlet. /// </summary> [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] public override void ExecuteCmdlet() { var account = this.AutomationClient.CreateAutomationAccount(this.ResourceGroupName, this.Name, this.Location, this.Plan, this.Tags); this.WriteObject(account); } } }
41.851485
150
0.614857
[ "MIT" ]
AzureDataBox/azure-powershell
src/ResourceManager/Automation/Commands.Automation/Cmdlet/NewAzureAutomationAccount.cs
4,129
C#
// <copyright file="SqlActivitySourceHelper.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Diagnostics; namespace OpenTelemetry.Instrumentation.SqlClient.Implementation { /// <summary> /// Helper class to hold common properties used by both SqlClientDiagnosticListener on .NET Core /// and SqlEventSourceListener on .NET Framework. /// </summary> internal class SqlActivitySourceHelper { public const string ActivitySourceName = "OpenTelemetry.SqlClient"; public const string ActivityName = ActivitySourceName + ".Execute"; public const string MicrosoftSqlServerDatabaseSystemName = "mssql"; private static readonly Version Version = typeof(SqlActivitySourceHelper).Assembly.GetName().Version; #pragma warning disable SA1202 // Elements should be ordered by access <- In this case, Version MUST come before ActivitySource otherwise null ref exception is thrown. internal static readonly ActivitySource ActivitySource = new ActivitySource(ActivitySourceName, Version.ToString()); #pragma warning restore SA1202 // Elements should be ordered by access } }
46.184211
167
0.757835
[ "Apache-2.0" ]
HankiDesign/opentelemetry-dotnet
src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlActivitySourceHelper.cs
1,755
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("InfinityEngine")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("InfinityEngine")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("33c839d6-e6cf-415b-9281-c3972c99481c")] // 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")] [assembly: InternalsVisibleTo("Assembly-CSharp-Editor")]
39.378378
84
0.748799
[ "MIT" ]
mciissee/InfinityEngine
Infinity Engine/Properties/AssemblyInfo.cs
1,460
C#
using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; namespace CSharpGL { public partial class TransformFeedbackObject { private bool disposedValue = false; /// <summary> /// /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// /// </summary> ~TransformFeedbackObject() { this.Dispose(false); } private void Dispose(bool disposing) { if (this.disposedValue == false) { if (disposing) { // Dispose managed resources. } // Dispose unmanaged resources. IntPtr context = GL.Instance.GetCurrentContext(); if (context != IntPtr.Zero) { glDeleteTransformFeedbacks(1, this.ids); } this.ids[0] = 0; } this.disposedValue = true; } } }
21.903846
65
0.462687
[ "MIT" ]
AugusZhan/CSharpGL
CSharpGL/GLObjects/TransformFeedbackObject/TransformFeedbackObject.IDisposable.cs
1,141
C#
using Assets.Script; using System.Collections; using System.Collections.Generic; using UnityEngine; public class GetItemUIEvent : MonoBehaviour { Animator anim;//UI上的动画组件 PlayerPos playerPos; public GameObject story3;//剧情 public GameObject story6; public GameObject story10; // Use this for initialization void Start () { anim = GetComponent<Animator>(); playerPos = PlayerPos.GetInstance(); } // Update is called once per frame void Update () { } public void OpenThisUI() { anim.SetBool("IsOpen", !anim.GetBool("IsOpen"));//打开/关闭UI //剧情的触发,根据剧情编号触发对应的剧情 if (playerPos.storyIndex == 3) { story3.SetActive(true); playerPos.storyIndex = 4; } if (playerPos.storyIndex == 6) { story6.SetActive(true); playerPos.storyIndex = 7; } if (playerPos.storyIndex == 10) { story10.SetActive(true); playerPos.storyIndex = 11; } } }
23
65
0.581285
[ "Apache-2.0" ]
laterrain/WitchSpring2
Assets/Script/GetItemUIEvent.cs
1,122
C#
using System.Linq; using static Crypto.CJJJKRS.Scheme<Simulation.Protocol.SSE.Word, Simulation.Protocol.SSE.Index>; namespace Simulation.Protocol.SSE.CJJJKRS { internal class PublishDatabaseMessage : AbsMessage<(Database db, int b, int B)> { public PublishDatabaseMessage((Database db, int b, int B) content) : base(content) { } public override int GetSize() => _content.db.Size; } public class TokensMessage : AbsMessage<Token[]> { public TokensMessage(Token[] content) : base(content) { } public override int GetSize() => _content.Sum(t => t.Size); } public class ResultMessage : AbsMessage<Index[]> { public ResultMessage(Index[] content) : base(content) { } public override int GetSize() => 0; // result is inherent and no false positives } }
28.666667
96
0.724806
[ "MIT" ]
dbogatov/ore-benchmark
src/simulator/Protocol/Protocols/SSE/CJJJKRS/Messages.cs
774
C#
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * MoveTowards.cs * Script for moving a GameObject towards another GameObject. Also rotates the * game object towards the target. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ using UnityEngine; using System.Collections; public class MoveTowards : MonoBehaviour { /* GameObject for the target to move towards. */ public GameObject target; /* Float value for the speed at which to move and rotate. */ public float speed = 10.0f, rotSpeed = 90.0f; /* Get the rigidbody of this game object. */ void Start() { target = GameObject.FindGameObjectWithTag("Player"); } /* Moves this object towards the target every frame. */ void Update() { /* If the target has been set and still exists in the game. */ if(target != null) { /* Vector from this game object to the target. */ Vector3 targetDir = target.transform.position - this.transform.position; /* Turn this object to face the target. */ Quaternion rotationAngle = Quaternion.LookRotation(targetDir); transform.rotation = Quaternion.Slerp(this.transform.rotation, rotationAngle, Time.deltaTime * rotSpeed); if(targetDir.magnitude > 25) { /* Translate this object towards the target object. */ Vector3 towardsVector = Vector3.MoveTowards(this.transform.position, target.transform.position, Time.deltaTime * speed); towardsVector.y = 0; Debug.DrawRay(transform.position, towardsVector, Color.red); this.transform.position = towardsVector; } } } }
34.28
83
0.598016
[ "MIT" ]
Pandinosaurus/unity-examples
TankGame/Assets/Scripts/MoveTowards.cs
1,714
C#
using System; using FluentAssertions; using Moq; using SimpleMvcSitemap.Routing; using Xunit; namespace SimpleMvcSitemap.Tests { public class UrlValidatorTests : TestBase { private readonly IUrlValidator urlValidator; private readonly Mock<IBaseUrlProvider> baseUrlProvider; public UrlValidatorTests() { IReflectionHelper reflectionHelper = new FakeReflectionHelper(); urlValidator = new UrlValidator(reflectionHelper); baseUrlProvider = MockFor<IBaseUrlProvider>(); } private class SampleType1 { [Url] public string Url { get; set; } } [Fact] public void ValidateUrls_ItemIsNull_ThrowsException() { Action act = () => urlValidator.ValidateUrls(null, baseUrlProvider.Object); act.ShouldThrow<ArgumentNullException>(); } [Fact] public void ValidateUrls_BaseUrlProviderIsNull_ThrowsException() { Action act = () => urlValidator.ValidateUrls(new SampleType1(), null); act.ShouldThrow<ArgumentNullException>(); } [Fact] public void ValidateUrls_UrlIsRelativeUrl_ConvertsToAbsoluteUrl() { SampleType1 item = new SampleType1 { Url = "/sitemap" }; SetBaseUrl(); urlValidator.ValidateUrls(item, baseUrlProvider.Object); item.Url.Should().Be("http://example.org/sitemap"); } [Fact] public void ValidateUrl_RelativeUrlDeosNotStartWithSlash_BaseUrlEndsWithSlash() { SampleType1 item = new SampleType1 { Url = "sitemap" }; SetBaseUrl(); urlValidator.ValidateUrls(item, baseUrlProvider.Object); item.Url.Should().Be("http://example.org/sitemap"); } [Theory] [InlineData("sitemap")] [InlineData("/sitemap")] public void ValidateUrl_BaseUrlInNotDomainRoot(string relativeUrl) { SampleType1 item = new SampleType1 { Url = relativeUrl }; SetBaseUrl("http://example.org/app/"); urlValidator.ValidateUrls(item, baseUrlProvider.Object); item.Url.Should().Be("http://example.org/app/sitemap"); } [Fact] public void ValidateUrls_AbsoluteUrl_DoesntChangeUrl() { SampleType1 item = new SampleType1 { Url = "http://example.org/sitemap" }; urlValidator.ValidateUrls(item, baseUrlProvider.Object); item.Url.Should().Be("http://example.org/sitemap"); } [Fact] public void ValidateUrls_MalformedUrl_DoesntThrowException() { string malformedUrl = ":abc"; SampleType1 item = new SampleType1 { Url = malformedUrl }; urlValidator.ValidateUrls(item, baseUrlProvider.Object); item.Url.Should().Be(malformedUrl); } private class SampleType2 { public SampleType1 SampleType1 { get; set; } } [Fact] public void ValidateUrls_RelativeUrlInNestedObject_ConvertsToAbsoluteUrl() { SampleType2 item = new SampleType2 { SampleType1 = new SampleType1 { Url = "/sitemap2" } }; SetBaseUrl(); urlValidator.ValidateUrls(item, baseUrlProvider.Object); item.SampleType1.Url.Should().Be("http://example.org/sitemap2"); } [Fact] public void ValidateUrls_NestedObjectIsNull_DoesNotThrowException() { SampleType2 item = new SampleType2(); Action action = () => { urlValidator.ValidateUrls(item, baseUrlProvider.Object); }; action.ShouldNotThrow(); } private class SampleType3 { public SampleType1[] Items { get; set; } } [Fact] public void ValidateUrls_RelativeUrlInList_ConvertsToAbsoluteUrl() { var relativeUrl1 = "/sitemap/1"; var relativeUrl2 = "/sitemap/2"; SampleType3 item = new SampleType3 { Items = new[] { new SampleType1 { Url = relativeUrl1 }, new SampleType1 { Url = relativeUrl2 } } }; SetBaseUrl(); urlValidator.ValidateUrls(item, baseUrlProvider.Object); item.Items[0].Url.Should().Be("http://example.org/sitemap/1"); item.Items[1].Url.Should().Be("http://example.org/sitemap/2"); } [Fact] public void ValidateUrls_EnumerablePropertyIsNull_DoesNotThrowException() { SampleType3 item = new SampleType3(); Action action = () => { urlValidator.ValidateUrls(item, baseUrlProvider.Object); }; action.ShouldNotThrow(); } [Fact] public void ValidateUrls_CallingConsecutivelyWithTheSameType_GetsPropertyModelOnce() { SampleType1 item = new SampleType1 { Url = "/sitemap" }; SetBaseUrl(); Action action = () => { urlValidator.ValidateUrls(item, baseUrlProvider.Object); }; action.ShouldNotThrow(); } private void SetBaseUrl(string baseUrl = "http://example.org/") { baseUrlProvider.Setup(provider => provider.BaseUrl).Returns(new Uri(baseUrl)); } } }
30.563218
148
0.600226
[ "MIT" ]
MahmutYaman/SimpleMvcSitemap
test/SimpleMvcSitemap.Tests/UrlValidatorTests.cs
5,320
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using WebAPiJWT.Areas.HelpPage.ModelDescriptions; using WebAPiJWT.Areas.HelpPage.Models; namespace WebAPiJWT.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
52.435897
197
0.611002
[ "Apache-2.0" ]
avinash84r/webApI
WebAPiJWT/Areas/HelpPage/HelpPageConfigurationExtensions.cs
24,540
C#
using HighriseApi.Models; using HighriseApi.Models.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HighriseApi.Interfaces { public interface IDealCategoryRequest { /// <summary> /// Gets a deal category by category ID. /// </summary> /// <returns>An instance of a <see cref="DealCategory"/> object</returns> DealCategory Get(int id); /// <summary> /// Gets an IEnumerable collection of <see cref="DealCategory"/> objects. /// </summary> /// <returns>An IEnumerable collection of <see cref="DealCategory"/> objects</returns>. IEnumerable<DealCategory> Get(); /// <summary> /// Creates a new deal category /// </summary> /// <param name="category">A <see cref="DealCategory"/> object</param> /// <returns>A <see cref="DealCategory"/> object, populated with new Highrise ID and CreatedAt/UpdatedAt values</returns> DealCategory Create(DealCategory category); /// <summary> /// Updates a deal category /// </summary> /// <param name="category">A <see cref="DealCategory"/> object</param> /// <returns>True if successfully updated, otherwise false</returns> bool Update(DealCategory category); /// <summary> /// Deletes a deal category /// </summary> /// <param name="id">The ID of the deal category to delete</param> /// <returns>True if successfully deleted, otherwise false</returns> bool Delete(int id); } }
34.891304
129
0.615576
[ "MIT" ]
bancker/highrise-api
src/HighriseApi/Interfaces/IDealCategoryRequest.cs
1,607
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using Coffee.Models; using Coffee.Types; using Coffee; namespace Coffee.ViewModels { public class CoffeeLogViewModel : ViewModelBase { private Administration Admin; private string title = "Coffee Log"; public string Title { get => title; } private User user; public User User { get => user; } private List<ItemLog> itemLog; public List<ItemLog> ItemLog { get => itemLog; } public CoffeeLogViewModel(Administration admin) { Admin = admin; user = admin.Login("daniel.nehrig", "test123"); itemLog = admin.GetItemLogFromUser(user); } } }
21.181818
53
0.666667
[ "MIT" ]
danielnehrig/BIF22A
src/kaffeekasse/src/ViewModels/CoffeeLogViewModel.cs
699
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using KeyHub.Model; using System.Data.Entity; using System.Linq; namespace KeyHub.Data.Extensions { public static class DomainLicenseExtensions { public static bool AnyEquals(this DbSet<DomainLicense> domainLicenseSet, DomainLicense domainLicense) { return domainLicenseSet.Any(x => x.DomainName == domainLicense.DomainName && x.LicenseId == domainLicense.LicenseId); } public static IQueryable<DomainLicense> AutomaticallyCreated(this IQueryable<DomainLicense> domainLicenses) { return domainLicenses.Where(x => x.AutomaticallyCreated); } public static IQueryable<DomainLicense> Expired(this IQueryable<DomainLicense> domainLicenses) { return domainLicenses.Where(x => x.DomainLicenseExpires < DateTime.Now); } } }
33.785714
130
0.689218
[ "Apache-2.0" ]
imazen/keyhub
src/KeyHub.Data/Extensions/DomainLicenseExtensions.cs
948
C#
namespace LearningSystem.Services { using LearningSystem.Data.Models; using Models; using System.Collections.Generic; using System.Threading.Tasks; public interface ITrainerService { Task<IEnumerable<CourseListingServiceModel>> Courses(string trainerId); Task<bool> IsTrainer(string userId, int courseId); Task<IEnumerable<StudentInCourseServiceModel>> StudentsInCourseAsync(int courseId); Task<bool> GradeStudentAsync(int courseId, string studentId, Grade grade); } }
28.105263
91
0.734082
[ "MIT" ]
l3kov9/CSharpMVCFrameworks
LearningSystem/LearningSystem.Services/ITrainerService.cs
536
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/services/ad_group_audience_view_service.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Holder for reflection information generated from google/ads/googleads/v9/services/ad_group_audience_view_service.proto</summary> public static partial class AdGroupAudienceViewServiceReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v9/services/ad_group_audience_view_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AdGroupAudienceViewServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkVnb29nbGUvYWRzL2dvb2dsZWFkcy92OS9zZXJ2aWNlcy9hZF9ncm91cF9h", "dWRpZW5jZV92aWV3X3NlcnZpY2UucHJvdG8SIGdvb2dsZS5hZHMuZ29vZ2xl", "YWRzLnY5LnNlcnZpY2VzGj5nb29nbGUvYWRzL2dvb2dsZWFkcy92OS9yZXNv", "dXJjZXMvYWRfZ3JvdXBfYXVkaWVuY2Vfdmlldy5wcm90bxocZ29vZ2xlL2Fw", "aS9hbm5vdGF0aW9ucy5wcm90bxoXZ29vZ2xlL2FwaS9jbGllbnQucHJvdG8a", "H2dvb2dsZS9hcGkvZmllbGRfYmVoYXZpb3IucHJvdG8aGWdvb2dsZS9hcGkv", "cmVzb3VyY2UucHJvdG8ibAodR2V0QWRHcm91cEF1ZGllbmNlVmlld1JlcXVl", "c3QSSwoNcmVzb3VyY2VfbmFtZRgBIAEoCUI04EEC+kEuCixnb29nbGVhZHMu", "Z29vZ2xlYXBpcy5jb20vQWRHcm91cEF1ZGllbmNlVmlldzLHAgoaQWRHcm91", "cEF1ZGllbmNlVmlld1NlcnZpY2US4QEKFkdldEFkR3JvdXBBdWRpZW5jZVZp", "ZXcSPy5nb29nbGUuYWRzLmdvb2dsZWFkcy52OS5zZXJ2aWNlcy5HZXRBZEdy", "b3VwQXVkaWVuY2VWaWV3UmVxdWVzdBo2Lmdvb2dsZS5hZHMuZ29vZ2xlYWRz", "LnY5LnJlc291cmNlcy5BZEdyb3VwQXVkaWVuY2VWaWV3Ik6C0+STAjgSNi92", "OS97cmVzb3VyY2VfbmFtZT1jdXN0b21lcnMvKi9hZEdyb3VwQXVkaWVuY2VW", "aWV3cy8qfdpBDXJlc291cmNlX25hbWUaRcpBGGdvb2dsZWFkcy5nb29nbGVh", "cGlzLmNvbdJBJ2h0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvYWR3", "b3Jkc0KGAgokY29tLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY5LnNlcnZpY2Vz", "Qh9BZEdyb3VwQXVkaWVuY2VWaWV3U2VydmljZVByb3RvUAFaSGdvb2dsZS5n", "b2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvYWRzL2dvb2dsZWFkcy92", "OS9zZXJ2aWNlcztzZXJ2aWNlc6ICA0dBQaoCIEdvb2dsZS5BZHMuR29vZ2xl", "QWRzLlY5LlNlcnZpY2VzygIgR29vZ2xlXEFkc1xHb29nbGVBZHNcVjlcU2Vy", "dmljZXPqAiRHb29nbGU6OkFkczo6R29vZ2xlQWRzOjpWOTo6U2VydmljZXNi", "BnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V9.Resources.AdGroupAudienceViewReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.ClientReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V9.Services.GetAdGroupAudienceViewRequest), global::Google.Ads.GoogleAds.V9.Services.GetAdGroupAudienceViewRequest.Parser, new[]{ "ResourceName" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// Request message for [AdGroupAudienceViewService.GetAdGroupAudienceView][google.ads.googleads.v9.services.AdGroupAudienceViewService.GetAdGroupAudienceView]. /// </summary> public sealed partial class GetAdGroupAudienceViewRequest : pb::IMessage<GetAdGroupAudienceViewRequest> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<GetAdGroupAudienceViewRequest> _parser = new pb::MessageParser<GetAdGroupAudienceViewRequest>(() => new GetAdGroupAudienceViewRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<GetAdGroupAudienceViewRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V9.Services.AdGroupAudienceViewServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GetAdGroupAudienceViewRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GetAdGroupAudienceViewRequest(GetAdGroupAudienceViewRequest other) : this() { resourceName_ = other.resourceName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public GetAdGroupAudienceViewRequest Clone() { return new GetAdGroupAudienceViewRequest(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// Required. The resource name of the ad group audience view to fetch. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as GetAdGroupAudienceViewRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(GetAdGroupAudienceViewRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(GetAdGroupAudienceViewRequest other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { ResourceName = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
41.942308
330
0.717102
[ "Apache-2.0" ]
friedenberg/google-ads-dotnet
src/V9/Services/AdGroupAudienceViewService.g.cs
10,905
C#
using System; using AspectCore.Extensions.Autofac; using Autofac; using KCommon.Core.Abstract.Components; namespace KCommon.Core.Autofac { public class AutofacObjectContainer : IObjectContainer { /// <summary>Represents the iner autofac container builder. /// </summary> public ContainerBuilder ContainerBuilder { get; } /// <summary>Represents the inner autofac container. /// </summary> public IContainer Container { get; set; } /// <summary>Default constructor. /// </summary> public AutofacObjectContainer() : this(new ContainerBuilder()) { } /// <summary>Parameterized constructor. /// </summary> public AutofacObjectContainer(ContainerBuilder containerBuilder) { ContainerBuilder = containerBuilder; // 注册动态代理器 // 方便实现后续的面向切面编程实现. // 目前所有IOC都统一使用AspectCore的动态代理器. ContainerBuilder.RegisterDynamicProxy(); } /// <summary>Parameterized constructor. /// </summary> public AutofacObjectContainer(IContainer container) { Container = container; } /// <summary>Build the container. /// </summary> public void Build() { Container = ContainerBuilder.Build(); } /// <summary>Register a implementation type. /// </summary> /// <param name="implementationType">The implementation type.</param> /// <param name="serviceName">The service name.</param> /// <param name="life">The life cycle of the implementer type.</param> public void RegisterType(Type implementationType, string serviceName = null, LifeStyle life = LifeStyle.Singleton) { if (implementationType.IsGenericType) { var registrationBuilder = ContainerBuilder.RegisterGeneric(implementationType); if (serviceName != null) { registrationBuilder.Named(serviceName, implementationType); } switch (life) { case LifeStyle.Scoped: registrationBuilder.InstancePerLifetimeScope(); break; case LifeStyle.Singleton: registrationBuilder.SingleInstance(); break; } } else { var registrationBuilder = ContainerBuilder.RegisterType(implementationType); if (serviceName != null) { registrationBuilder.Named(serviceName, implementationType); } switch (life) { case LifeStyle.Scoped: registrationBuilder.InstancePerLifetimeScope(); break; case LifeStyle.Singleton: registrationBuilder.SingleInstance(); break; } } } /// <summary>Register a implementer type as a service implementation. /// </summary> /// <param name="serviceType">The service type.</param> /// <param name="implementationType">The implementation type.</param> /// <param name="serviceName">The service name.</param> /// <param name="life">The life cycle of the implementer type.</param> public void RegisterType(Type serviceType, Type implementationType, string serviceName = null, LifeStyle life = LifeStyle.Singleton) { if (implementationType.IsGenericType) { var registrationBuilder = ContainerBuilder.RegisterGeneric(implementationType).As(serviceType); if (serviceName != null) { registrationBuilder.Named(serviceName, implementationType); } switch (life) { case LifeStyle.Scoped: registrationBuilder.InstancePerLifetimeScope(); break; case LifeStyle.Singleton: registrationBuilder.SingleInstance(); break; } } else { var registrationBuilder = ContainerBuilder.RegisterType(implementationType).As(serviceType); if (serviceName != null) { registrationBuilder.Named(serviceName, serviceType); } switch (life) { case LifeStyle.Scoped: registrationBuilder.InstancePerLifetimeScope(); break; case LifeStyle.Singleton: registrationBuilder.SingleInstance(); break; } } } /// <summary>Register a implementer type as a service implementation. /// </summary> /// <typeparam name="TService">The service type.</typeparam> /// <typeparam name="TImplementer">The implementer type.</typeparam> /// <param name="serviceName">The service name.</param> /// <param name="life">The life cycle of the implementer type.</param> public void Register<TService, TImplementer>(string serviceName = null, LifeStyle life = LifeStyle.Singleton) where TService : class where TImplementer : class, TService { var registrationBuilder = ContainerBuilder.RegisterType<TImplementer>().As<TService>(); if (serviceName != null) { registrationBuilder.Named<TService>(serviceName); } switch (life) { case LifeStyle.Scoped: registrationBuilder.InstancePerLifetimeScope(); break; case LifeStyle.Singleton: registrationBuilder.SingleInstance(); break; } } /// <summary>Register a implementer type instance as a service implementation. /// </summary> /// <typeparam name="TService">The service type.</typeparam> /// <typeparam name="TImplementer">The implementer type.</typeparam> /// <param name="instance">The implementer type instance.</param> /// <param name="serviceName">The service name.</param> public void RegisterInstance<TService, TImplementer>(TImplementer instance, string serviceName = null) where TService : class where TImplementer : class, TService { var registrationBuilder = ContainerBuilder.RegisterInstance(instance).As<TService>().SingleInstance(); if (serviceName != null) { registrationBuilder.Named<TService>(serviceName); } } /// <summary>Resolve a service. /// </summary> /// <typeparam name="TService">The service type.</typeparam> /// <returns>The component instance that provides the service.</returns> public TService Resolve<TService>() where TService : class { return Container.Resolve<TService>(); } /// <summary>Resolve a service. /// </summary> /// <param name="serviceType">The service type.</param> /// <returns>The component instance that provides the service.</returns> public object Resolve(Type serviceType) { return Container.Resolve(serviceType); } /// <summary>Try to retrieve a service from the container. /// </summary> /// <typeparam name="TService">The service type to resolve.</typeparam> /// <param name="instance">The resulting component instance providing the service, or default(TService).</param> /// <returns>True if a component providing the service is available.</returns> public bool TryResolve<TService>(out TService instance) where TService : class { return Container.TryResolve(out instance); } /// <summary>Try to retrieve a service from the container. /// </summary> /// <param name="serviceType">The service type to resolve.</param> /// <param name="instance">The resulting component instance providing the service, or null.</param> /// <returns>True if a component providing the service is available.</returns> public bool TryResolve(Type serviceType, out object instance) { return Container.TryResolve(serviceType, out instance); } /// <summary>Resolve a service. /// </summary> /// <typeparam name="TService">The service type.</typeparam> /// <param name="serviceName">The service name.</param> /// <returns>The component instance that provides the service.</returns> public TService ResolveNamed<TService>(string serviceName) where TService : class { return Container.ResolveNamed<TService>(serviceName); } /// <summary>Resolve a service. /// </summary> /// <param name="serviceName">The service name.</param> /// <param name="serviceType">The service type.</param> /// <returns>The component instance that provides the service.</returns> public object ResolveNamed(string serviceName, Type serviceType) { return Container.ResolveNamed(serviceName, serviceType); } /// <summary>Try to retrieve a service from the container. /// </summary> /// <param name="serviceName">The name of the service to resolve.</param> /// <param name="serviceType">The type of the service to resolve.</param> /// <param name="instance">The resulting component instance providing the service, or null.</param> /// <returns>True if a component providing the service is available.</returns> public bool TryResolveNamed(string serviceName, Type serviceType, out object instance) { return Container.TryResolveNamed(serviceName, serviceType, out instance); } } }
43.638655
140
0.568169
[ "MIT" ]
Xiangrui2019/kcommon
src/Impls/KCommon.Core.Autofac/AutofacObjectContainer.cs
10,462
C#
/* * convertapi * * Convert API lets you effortlessly convert file formats and types. * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = Cloudmersive.APIClient.NET.DocumentAndDataConvert.Client.SwaggerDateConverter; namespace Cloudmersive.APIClient.NET.DocumentAndDataConvert.Model { /// <summary> /// A worksheet (tab) in an Excel (XLSX) spreadsheet /// </summary> [DataContract] public partial class XlsxWorksheet : IEquatable<XlsxWorksheet>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="XlsxWorksheet" /> class. /// </summary> /// <param name="path">The Path of the location of this object; leave blank for new worksheets.</param> /// <param name="worksheetName">User-facing name of the worksheet tab.</param> public XlsxWorksheet(string path = default(string), string worksheetName = default(string)) { this.Path = path; this.WorksheetName = worksheetName; } /// <summary> /// The Path of the location of this object; leave blank for new worksheets /// </summary> /// <value>The Path of the location of this object; leave blank for new worksheets</value> [DataMember(Name="Path", EmitDefaultValue=false)] public string Path { get; set; } /// <summary> /// User-facing name of the worksheet tab /// </summary> /// <value>User-facing name of the worksheet tab</value> [DataMember(Name="WorksheetName", EmitDefaultValue=false)] public string WorksheetName { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class XlsxWorksheet {\n"); sb.Append(" Path: ").Append(Path).Append("\n"); sb.Append(" WorksheetName: ").Append(WorksheetName).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as XlsxWorksheet); } /// <summary> /// Returns true if XlsxWorksheet instances are equal /// </summary> /// <param name="input">Instance of XlsxWorksheet to be compared</param> /// <returns>Boolean</returns> public bool Equals(XlsxWorksheet input) { if (input == null) return false; return ( this.Path == input.Path || (this.Path != null && this.Path.Equals(input.Path)) ) && ( this.WorksheetName == input.WorksheetName || (this.WorksheetName != null && this.WorksheetName.Equals(input.WorksheetName)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Path != null) hashCode = hashCode * 59 + this.Path.GetHashCode(); if (this.WorksheetName != null) hashCode = hashCode * 59 + this.WorksheetName.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
34.874126
140
0.579306
[ "Apache-2.0" ]
Cloudmersive/Cloudmersive.APIClient.NET.DocumentAndDataConvert
client/src/Cloudmersive.APIClient.NET.DocumentAndDataConvert/Model/XlsxWorksheet.cs
4,987
C#
/* * The MIT License * * Copyright 2019 Palmtree Software. * * 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. */ namespace Palmtree.Math.Test.Plugin.Sint { class ComponentTestPlugin_op_Equality_X_UI : ComponentTestPluginBase_2_1 { public ComponentTestPlugin_op_Equality_X_UI() : base("sint", "op_equality_x_ui", "test_data_equality_x_ui.xml") { } protected override IDataItem TestFunc(IDataItem p1, IDataItem p2) { var u = p1.ToBigInt().Value; var v = p2.ToUInt32().Value; var w = u == v; return (new UInt32DataItem(w ? 1U : 0U)); } public override int Order => 101; } } /* * END OF FILE */
34.568627
80
0.694838
[ "MIT" ]
rougemeilland/Palmtree.Math
Palmtree.Math.Test/Plugin/Sint/ComponentTestPlugin_op_Equality_X_UI.cs
1,765
C#
// <copyright file="CollectionOfFactorsShould.cs" company="Okta, Inc"> // Copyright (c) 2014 - present Okta, Inc. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. // </copyright> using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.Logging.Abstractions; using Okta.Sdk.Internal; using Okta.Sdk.UnitTests.Internal; using Xunit; namespace Okta.Sdk.UnitTests { public class CollectionOfFactorsShould { private static readonly List<IFactor> AllFactors = new List<IFactor>() { TestResourceCreator.NewFactor( factorType: FactorType.Question, provider: "OTKA", profile: new SecurityQuestionFactorProfile { Question = "disliked_food" }), TestResourceCreator.NewFactor( factorType: FactorType.Sms, provider: "OTKA", profile: new SmsFactorProfile() { PhoneNumber = "+15556667899" }), }; [Fact] public async Task RetrieveQuestionFactor() { var mockRequestExecutor = new MockedCollectionRequestExecutor<IFactor>(pageSize: 2, items: AllFactors); var dataStore = new DefaultDataStore( mockRequestExecutor, new DefaultSerializer(), new ResourceFactory(null, null), NullLogger.Instance); var collection = new CollectionClient<Factor>( dataStore, new HttpRequest { Uri = "http://mock-collection.dev" }, new RequestContext()); var retrievedItems = await collection.ToArray(); var securityQuestionFactor = retrievedItems.OfType<SecurityQuestionFactor>().FirstOrDefault(); securityQuestionFactor.Should().NotBeNull(); } [Fact] public async Task RetrieveQuestionFactorAsInterface() { var mockRequestExecutor = new MockedCollectionRequestExecutor<IFactor>(pageSize: 2, items: AllFactors); var dataStore = new DefaultDataStore( mockRequestExecutor, new DefaultSerializer(), new ResourceFactory(null, null), NullLogger.Instance); var collection = new CollectionClient<Factor>( dataStore, new HttpRequest { Uri = "http://mock-collection.dev" }, new RequestContext()); var retrievedItems = await collection.ToArray(); var securityQuestionFactor = retrievedItems.OfType<ISecurityQuestionFactor>().FirstOrDefault(); securityQuestionFactor.Should().NotBeNull(); } } }
38.39726
115
0.627542
[ "Apache-2.0" ]
cwoolum/okta-sdk-dotnet
src/Okta.Sdk.UnitTests/CollectionOfFactorsShould.cs
2,805
C#
using System; namespace BnSVN_Discord_Bot { class Program { private static Bot botInstance; static void Main(string[] args) { Console.CancelKeyPress += Console_CancelKeyPress; botInstance = new Bot(); botInstance.Run(args); // Friendly Blocking exit ??? ConsoleKeyInfo keyinfo = Console.ReadKey(false); while (keyinfo.Key != ConsoleKey.Escape) keyinfo = Console.ReadKey(false); botInstance.Stop(5000); } private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { botInstance.Stop(5000); Environment.Exit(0); } } }
24.633333
91
0.572395
[ "MIT" ]
Leayal/BnSVN-Discord-Bot
BnSVN-Discord-Bot/Program.cs
741
C#
using IdentityModel.OidcClient; namespace HelseId.Clients.WPF.EmbeddedBrowser.EventArgs { public class LoginEventArgs: System.EventArgs { public string IdentityToken { get; set; } public string AccessToken { get; set; } public bool IsError { get; set; } public string Error { get; set; } public LoginResult Response { get; set; } } }
27.714286
55
0.657216
[ "MIT" ]
HelseID/HelseID.Samples-old
HelseId.Clients.WPF.EmbeddedBrowser/EventArgs/LoginEventArgs.cs
390
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPattern.Composite { /// <summary> /// 叶子节点 /// </summary> public class Leaf : Component { public Leaf(string name) : base(name) { } ///// <summary> ///// 由于叶子节点没有子节点,所以Add和Remove方法对它来说没有意义,但它继承自Component,这样做可以消除叶节点和枝节点对象在抽象层次的区别,它们具备完全一致的接口。 ///// </summary> ///// <param name="component"></param> //public override void Add(Component component) //{ // Console.WriteLine("Can not add a component to a leaf."); //} ///// <summary> ///// 实现它没有意义,只是提供了一个一致的调用接口 ///// </summary> ///// <param name="component"></param> //public override void Remove(Component component) //{ // Console.WriteLine("Can not remove a component to a leaf."); //} public override void Display(int level) { Console.WriteLine(new string('-', level) + name); } } }
26.047619
101
0.555759
[ "MIT" ]
SnailDev/SnailDev.DesignPattern
src/DesignPattern/DesignPattern/Composite/Leaf.cs
1,286
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Vue.DataLayer { using System; using System.Collections.Generic; using Vue.Core; public partial class Shipper: CoreEntity { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Shipper() { this.Orders = new HashSet<Order>(); } public int ShipperID { get; set; } public string CompanyName { get; set; } public string Phone { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Order> Orders { get; set; } } }
35.5625
128
0.575571
[ "MIT" ]
Pasinli/Tryingforvue
Vue.DataLayer/Shipper.cs
1,138
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the schemas-2019-12-02.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.Schemas.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Schemas.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ListSchemaVersions operation /// </summary> public class ListSchemaVersionsResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { ListSchemaVersionsResponse response = new ListSchemaVersionsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("NextToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextToken = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SchemaVersions", targetDepth)) { var unmarshaller = new ListUnmarshaller<SchemaVersionSummary, SchemaVersionSummaryUnmarshaller>(SchemaVersionSummaryUnmarshaller.Instance); response.SchemaVersions = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException")) { return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException")) { return ForbiddenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException")) { return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedException")) { return UnauthorizedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonSchemasException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static ListSchemaVersionsResponseUnmarshaller _instance = new ListSchemaVersionsResponseUnmarshaller(); internal static ListSchemaVersionsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListSchemaVersionsResponseUnmarshaller Instance { get { return _instance; } } } }
41.661765
190
0.637487
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Schemas/Generated/Model/Internal/MarshallTransformations/ListSchemaVersionsResponseUnmarshaller.cs
5,666
C#
using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using GNF.Domain.Entities; namespace GNF.DapperUow.Repositories { /// <summary> /// Represents that the implemented classes are repositories. /// </summary> /// <typeparam name="TEntity">The type of the aggregate root on which the repository operations /// should be performed.</typeparam> public interface IRepository<TEntity> where TEntity : IEntity { /// <summary> /// DB事务对象 /// </summary> IDbConnection DbConnection { get; } /// <summary> /// 设置DB事务对象,设置后ConnectionString会为空 /// </summary> /// <param name="dbConnection"></param> IRepository<TEntity> SetDbConnection(IDbConnection dbConnection); bool Insert(TEntity entity); Task<bool> InsertAsync(TEntity entity); bool Update(TEntity entity); Task<bool> UpdateAsync(TEntity entity); bool Remove(TEntity condition); Task<bool> RemoveAsync(TEntity condition); TEntity Get(string sql,object parameterObject = null); Task<TEntity> GetAsync(string sql, object parameterObject = null); TEntity Get(dynamic id); Task<TEntity> GetAsync(dynamic id); ///// <summary> ///// 指定Id,获取一个实体对象;如果要求附带UPDLOCK更新锁,就能防止脏读数据 ///// </summary> ///// <param name="id"></param> ///// <param name="isUpdateLock"></param> ///// <returns></returns> //TEntity GetById(dynamic id,bool isUpdateLock); IList<TEntity> GetList(string sql, object parameterObject = null); Task<IList<TEntity>> GetListAsync(string sql, object parameterObject = null); IList<TEntity> GetAll(); Task<IList<TEntity>> GetAllAsync(); Paging<TEntity> Paging(string whereSql, string orderBy,object parameterObjects, int pageIndex, int pageSize); Task<Paging<TEntity>> PagingAsync(string whereSql, string orderBy, object parameterObjects, int pageIndex, int pageSize); } }
30.382353
129
0.642788
[ "Apache-2.0" ]
rjf1979/GNF
GNF.DapperUow/Repositories/IRepository.cs
2,162
C#
using WinBM.Recipe; using WinBM.PowerShell.Lib.TestWinBMYaml; string targetPath = "Test.yml"; var list = new List<string>(); list.Add(targetPath); TestYaml test = new TestYaml(); test.CheckFiles(list); Console.ReadLine();
12.65
42
0.664032
[ "MIT" ]
tgiqfe/TestWinBMYaml
TestWinBMYaml/Program.cs
255
C#
using System; using System.IO; using System.Linq; using System.Web; using System.Web.Caching; using System.Xml; using Umbraco.Core; using System.Collections.Generic; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using RazorDataTypeModelStaticMappingItem = umbraco.MacroEngines.RazorDataTypeModelStaticMappingItem; namespace umbraco { /// <summary> /// The UmbracoSettings Class contains general settings information for the entire Umbraco instance based on information from the /config/umbracoSettings.config file /// </summary> [Obsolete("Use UmbracoConfiguration.Current.UmbracoSettings instead, it offers all settings in strongly typed formats. This class will be removed in future versions.")] public class UmbracoSettings { [Obsolete("This hasn't been used since 4.1!")] public const string TEMP_FRIENDLY_XML_CHILD_CONTAINER_NODENAME = ""; // "children"; /// <summary> /// Gets the umbraco settings document. /// </summary> /// <value>The _umbraco settings.</value> public static XmlDocument _umbracoSettings { get { var us = (XmlDocument)HttpRuntime.Cache["umbracoSettingsFile"] ?? EnsureSettingsDocument(); return us; } } /// <summary> /// Gets a value indicating whether the media library will create new directories in the /media directory. /// </summary> /// <value> /// <c>true</c> if new directories are allowed otherwise, <c>false</c>. /// </value> public static bool UploadAllowDirectories { get { return UmbracoConfig.For.UmbracoSettings().Content.UploadAllowDirectories; } } /// <summary> /// Gets a value indicating whether logging is enabled in umbracoSettings.config (/settings/logging/enableLogging). /// </summary> /// <value><c>true</c> if logging is enabled; otherwise, <c>false</c>.</value> public static bool EnableLogging { get { return UmbracoConfig.For.UmbracoSettings().Logging.EnableLogging; } } /// <summary> /// Gets a value indicating whether logging happens async. /// </summary> /// <value><c>true</c> if async logging is enabled; otherwise, <c>false</c>.</value> public static bool EnableAsyncLogging { get { return UmbracoConfig.For.UmbracoSettings().Logging.EnableAsyncLogging; } } /// <summary> /// Gets the assembly of an external logger that can be used to store log items in 3rd party systems /// </summary> public static string ExternalLoggerAssembly { get { return UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerAssembly; } } /// <summary> /// Gets the type of an external logger that can be used to store log items in 3rd party systems /// </summary> public static string ExternalLoggerType { get { return UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerType; } } /// <summary> /// Long Audit Trail to external log too /// </summary> public static bool ExternalLoggerLogAuditTrail { get { return UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerEnableAuditTrail; } } /// <summary> /// Keep user alive as long as they have their browser open? Default is true /// </summary> public static bool KeepUserLoggedIn { get { return UmbracoConfig.For.UmbracoSettings().Security.KeepUserLoggedIn; } } /// <summary> /// Show disabled users in the tree in the Users section in the backoffice /// </summary> public static bool HideDisabledUsersInBackoffice { get { return UmbracoConfig.For.UmbracoSettings().Security.HideDisabledUsersInBackoffice; } } /// <summary> /// Gets a value indicating whether the logs will be auto cleaned /// </summary> /// <value><c>true</c> if logs are to be automatically cleaned; otherwise, <c>false</c></value> public static bool AutoCleanLogs { get { return UmbracoConfig.For.UmbracoSettings().Logging.AutoCleanLogs; } } /// <summary> /// Gets the value indicating the log cleaning frequency (in miliseconds) /// </summary> public static int CleaningMiliseconds { get { return UmbracoConfig.For.UmbracoSettings().Logging.CleaningMiliseconds; } } public static int MaxLogAge { get { return UmbracoConfig.For.UmbracoSettings().Logging.MaxLogAge; } } /// <summary> /// Gets the disabled log types. /// </summary> /// <value>The disabled log types.</value> public static XmlNode DisabledLogTypes { get { return GetKeyAsNode("/settings/logging/disabledLogTypes"); } } /// <summary> /// Gets the package server url. /// </summary> /// <value>The package server url.</value> public static string PackageServer { get { return "packages.umbraco.org"; } } /// <summary> /// Gets a value indicating whether umbraco will use domain prefixes. /// </summary> /// <value><c>true</c> if umbraco will use domain prefixes; otherwise, <c>false</c>.</value> public static bool UseDomainPrefixes { get { return UmbracoConfig.For.UmbracoSettings().RequestHandler.UseDomainPrefixes; } } /// <summary> /// This will add a trailing slash (/) to urls when in directory url mode /// NOTICE: This will always return false if Directory Urls in not active /// </summary> public static bool AddTrailingSlash { get { return UmbracoConfig.For.UmbracoSettings().RequestHandler.AddTrailingSlash; } } /// <summary> /// Gets a value indicating whether umbraco will use ASP.NET MasterPages for rendering instead of its propriatary templating system. /// </summary> /// <value><c>true</c> if umbraco will use ASP.NET MasterPages; otherwise, <c>false</c>.</value> public static bool UseAspNetMasterPages { get { return UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages; } } /// <summary> /// Gets a value indicating whether umbraco will attempt to load any skins to override default template files /// </summary> /// <value><c>true</c> if umbraco will override templates with skins if present and configured <c>false</c>.</value> public static bool EnableTemplateFolders { get { return UmbracoConfig.For.UmbracoSettings().Templates.EnableTemplateFolders; } } /// <summary> /// razor DynamicNode typecasting detects XML and returns DynamicXml - Root elements that won't convert to DynamicXml /// </summary> public static List<string> NotDynamicXmlDocumentElements { get { return UmbracoConfig.For.UmbracoSettings().Scripting.NotDynamicXmlDocumentElements.Select(x => x.Element).ToList(); } } public static List<RazorDataTypeModelStaticMappingItem> RazorDataTypeModelStaticMapping { get { var mapping = UmbracoConfig.For.UmbracoSettings().Scripting.DataTypeModelStaticMappings; //now we need to map to the old object until we can clean all this nonsense up return mapping.Select(x => new RazorDataTypeModelStaticMappingItem() { DataTypeGuid = x.DataTypeGuid, NodeTypeAlias = x.NodeTypeAlias, PropertyTypeAlias = x.PropertyTypeAlias, Raw = string.Empty, TypeName = x.MappingName }).ToList(); } } /// <summary> /// Gets a value indicating whether umbraco will clone XML cache on publish. /// </summary> /// <value> /// <c>true</c> if umbraco will clone XML cache on publish; otherwise, <c>false</c>. /// </value> public static bool CloneXmlCacheOnPublish { get { return UmbracoConfig.For.UmbracoSettings().Content.CloneXmlContent; } } /// <summary> /// Gets a value indicating whether rich text editor content should be parsed by tidy. /// </summary> /// <value><c>true</c> if content is parsed; otherwise, <c>false</c>.</value> public static bool TidyEditorContent { get { return UmbracoConfig.For.UmbracoSettings().Content.TidyEditorContent; } } /// <summary> /// Gets the encoding type for the tidyied content. /// </summary> /// <value>The encoding type as string.</value> public static string TidyCharEncoding { get { return UmbracoConfig.For.UmbracoSettings().Content.TidyCharEncoding; } } /// <summary> /// Gets the property context help option, this can either be 'text', 'icon' or 'none' /// </summary> /// <value>The property context help option.</value> public static string PropertyContextHelpOption { get { return UmbracoConfig.For.UmbracoSettings().Content.PropertyContextHelpOption; } } public static string DefaultBackofficeProvider { get { return UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider; } } /// <summary> /// Whether to force safe aliases (no spaces, no special characters) at businesslogic level on contenttypes and propertytypes /// </summary> public static bool ForceSafeAliases { get { return UmbracoConfig.For.UmbracoSettings().Content.ForceSafeAliases; } } /// <summary> /// File types that will not be allowed to be uploaded via the content/media upload control /// </summary> public static IEnumerable<string> DisallowedUploadFiles { get { return UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles; } } /// <summary> /// Gets the allowed image file types. /// </summary> /// <value>The allowed image file types.</value> public static string ImageFileTypes { get { return string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes.Select(x => x.ToLowerInvariant())); } } /// <summary> /// Gets the allowed script file types. /// </summary> /// <value>The allowed script file types.</value> public static string ScriptFileTypes { get { return string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ScriptFileTypes); } } /// <summary> /// Gets the duration in seconds to cache queries to umbraco library member and media methods /// Default is 1800 seconds (30 minutes) /// </summary> public static int UmbracoLibraryCacheDuration { get { return UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration; } } /// <summary> /// Gets the path to the scripts folder used by the script editor. /// </summary> /// <value>The script folder path.</value> public static string ScriptFolderPath { get { return UmbracoConfig.For.UmbracoSettings().Content.ScriptFolderPath; } } /// <summary> /// Enabled or disable the script/code editor /// </summary> public static bool ScriptDisableEditor { get { return UmbracoConfig.For.UmbracoSettings().Content.ScriptEditorDisable; } } /// <summary> /// Gets a value indicating whether umbraco will ensure unique node naming. /// This will ensure that nodes cannot have the same url, but will add extra characters to a url. /// ex: existingnodename.aspx would become existingnodename(1).aspx if a node with the same name is found /// </summary> /// <value><c>true</c> if umbraco ensures unique node naming; otherwise, <c>false</c>.</value> public static bool EnsureUniqueNaming { get { return UmbracoConfig.For.UmbracoSettings().Content.EnsureUniqueNaming; } } /// <summary> /// Gets the notification email sender. /// </summary> /// <value>The notification email sender.</value> public static string NotificationEmailSender { get { return UmbracoConfig.For.UmbracoSettings().Content.NotificationEmailAddress; } } /// <summary> /// Gets a value indicating whether notification-emails are HTML. /// </summary> /// <value> /// <c>true</c> if html notification-emails are disabled; otherwise, <c>false</c>. /// </value> public static bool NotificationDisableHtmlEmail { get { return UmbracoConfig.For.UmbracoSettings().Content.DisableHtmlEmail; } } /// <summary> /// Gets the allowed attributes on images. /// </summary> /// <value>The allowed attributes on images.</value> public static string ImageAllowedAttributes { get { return string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageTagAllowedAttributes); } } public static XmlNode ImageAutoFillImageProperties { get { return GetKeyAsNode("/settings/content/imaging/autoFillImageProperties"); } } /// <summary> /// Gets the scheduled tasks as XML /// </summary> /// <value>The scheduled tasks.</value> public static XmlNode ScheduledTasks { get { return GetKeyAsNode("/settings/scheduledTasks"); } } /// <summary> /// Gets a list of characters that will be replaced when generating urls /// </summary> /// <value>The URL replacement characters.</value> public static XmlNode UrlReplaceCharacters { get { return GetKeyAsNode("/settings/requestHandler/urlReplacing"); } } /// <summary> /// Whether to replace double dashes from url (ie my--story----from--dash.aspx caused by multiple url replacement chars /// </summary> public static bool RemoveDoubleDashesFromUrlReplacing { get { return UmbracoConfig.For.UmbracoSettings().RequestHandler.RemoveDoubleDashes; } } /// <summary> /// Gets a value indicating whether umbraco will use distributed calls. /// This enables umbraco to share cache and content across multiple servers. /// Used for load-balancing high-traffic sites. /// </summary> /// <value><c>true</c> if umbraco uses distributed calls; otherwise, <c>false</c>.</value> public static bool UseDistributedCalls { get { return UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled; } } /// <summary> /// Gets the ID of the user with access rights to perform the distributed calls. /// </summary> /// <value>The distributed call user.</value> public static int DistributedCallUser { get { return UmbracoConfig.For.UmbracoSettings().DistributedCall.UserId; } } /// <summary> /// Gets the html injected into a (x)html page if Umbraco is running in preview mode /// </summary> public static string PreviewBadge { get { return UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge; } } /// <summary> /// Gets IP or hostnames of the distribution servers. /// These servers will receive a call everytime content is created/deleted/removed /// and update their content cache accordingly, ensuring a consistent cache on all servers /// </summary> /// <value>The distribution servers.</value> public static XmlNode DistributionServers { get { try { return GetKeyAsNode("/settings/distributedCall/servers"); } catch { return null; } } } /// <summary> /// Gets HelpPage configurations. /// A help page configuration specify language, user type, application, application url and /// the target help page url. /// </summary> public static XmlNode HelpPages { get { try { return GetKeyAsNode("/settings/help"); } catch { return null; } } } /// <summary> /// Gets all repositories registered, and returns them as XmlNodes, containing name, alias and webservice url. /// These repositories are used by the build-in package installer and uninstaller to install new packages and check for updates. /// All repositories should have a unique alias. /// All packages installed from a repository gets the repository alias included in the install information /// </summary> /// <value>The repository servers.</value> public static XmlNode Repositories { get { try { return GetKeyAsNode("/settings/repositories"); } catch { return null; } } } /// <summary> /// Gets a value indicating whether umbraco will use the viewstate mover module. /// The viewstate mover will move all asp.net viewstate information to the bottom of the aspx page /// to ensure that search engines will index text instead of javascript viewstate information. /// </summary> /// <value> /// <c>true</c> if umbraco will use the viewstate mover module; otherwise, <c>false</c>. /// </value> public static bool UseViewstateMoverModule { get { return UmbracoConfig.For.UmbracoSettings().ViewStateMoverModule.Enable; } } /// <summary> /// Tells us whether the Xml Content cache is disabled or not /// Default is enabled /// </summary> public static bool isXmlContentCacheDisabled { get { return UmbracoConfig.For.UmbracoSettings().Content.XmlCacheEnabled == false; } } /// <summary> /// Check if there's changes to the umbraco.config xml file cache on disk on each request /// Makes it possible to updates environments by syncing the umbraco.config file across instances /// Relates to http://umbraco.codeplex.com/workitem/30722 /// </summary> public static bool XmlContentCheckForDiskChanges { get { return UmbracoConfig.For.UmbracoSettings().Content.XmlContentCheckForDiskChanges; } } /// <summary> /// If this is enabled, all Umbraco objects will generate data in the preview table (cmsPreviewXml). /// If disabled, only documents will generate data. /// This feature is useful if anyone would like to see how data looked at a given time /// </summary> public static bool EnableGlobalPreviewStorage { get { return UmbracoConfig.For.UmbracoSettings().Content.GlobalPreviewStorageEnabled; } } /// <summary> /// Whether to use the new 4.1 schema or the old legacy schema /// </summary> /// <value> /// <c>true</c> if yes, use the old node/data model; otherwise, <c>false</c>. /// </value> public static bool UseLegacyXmlSchema { get { return UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema; } } public static IEnumerable<string> AppCodeFileExtensionsList { get { return UmbracoConfig.For.UmbracoSettings().Developer.AppCodeFileExtensions.Select(x => x.Extension); } } [Obsolete("Use AppCodeFileExtensionsList instead")] public static XmlNode AppCodeFileExtensions { get { XmlNode value = GetKeyAsNode("/settings/developer/appCodeFileExtensions"); if (value != null) { return value; } // default is .cs and .vb value = _umbracoSettings.CreateElement("appCodeFileExtensions"); value.AppendChild(XmlHelper.AddTextNode(_umbracoSettings, "ext", "cs")); value.AppendChild(XmlHelper.AddTextNode(_umbracoSettings, "ext", "vb")); return value; } } /// <summary> /// Tells us whether the Xml to always update disk cache, when changes are made to content /// Default is enabled /// </summary> public static bool continouslyUpdateXmlDiskCache { get { return UmbracoConfig.For.UmbracoSettings().Content.ContinouslyUpdateXmlDiskCache; } } /// <summary> /// Tells us whether to use a splash page while umbraco is initializing content. /// If not, requests are queued while umbraco loads content. For very large sites (+10k nodes) it might be usefull to /// have a splash page /// Default is disabled /// </summary> public static bool EnableSplashWhileLoading { get { return UmbracoConfig.For.UmbracoSettings().Content.EnableSplashWhileLoading; } } public static bool ResolveUrlsFromTextString { get { return UmbracoConfig.For.UmbracoSettings().Content.ResolveUrlsFromTextString; } } /// <summary> /// This configuration setting defines how to handle macro errors: /// - Inline - Show error within macro as text (default and current Umbraco 'normal' behavior) /// - Silent - Suppress error and hide macro /// - Throw - Throw an exception and invoke the global error handler (if one is defined, if not you'll get a YSOD) /// </summary> /// <value>MacroErrorBehaviour enum defining how to handle macro errors.</value> public static MacroErrorBehaviour MacroErrorBehaviour { get { return UmbracoConfig.For.UmbracoSettings().Content.MacroErrorBehaviour; } } /// <summary> /// This configuration setting defines how to show icons in the document type editor. /// - ShowDuplicates - Show duplicates in files and sprites. (default and current Umbraco 'normal' behaviour) /// - HideSpriteDuplicates - Show files on disk and hide duplicates from the sprite /// - HideFileDuplicates - Show files in the sprite and hide duplicates on disk /// </summary> /// <value>MacroErrorBehaviour enum defining how to show icons in the document type editor.</value> [Obsolete("This is no longer used and will be removed from the core in future versions")] public static IconPickerBehaviour IconPickerBehaviour { get { return IconPickerBehaviour.ShowDuplicates; } } /// <summary> /// Gets the default document type property used when adding new properties through the back-office /// </summary> /// <value>Configured text for the default document type property</value> /// <remarks>If undefined, 'Textstring' is the default</remarks> public static string DefaultDocumentTypeProperty { get { return UmbracoConfig.For.UmbracoSettings().Content.DefaultDocumentTypeProperty; } } private static string _path; /// <summary> /// Gets the settings file path /// </summary> internal static string SettingsFilePath { get { return _path ?? (_path = GlobalSettings.FullpathToRoot + Path.DirectorySeparatorChar + "config" + Path.DirectorySeparatorChar); } } internal const string Filename = "umbracoSettings.config"; internal static XmlDocument EnsureSettingsDocument() { var settingsFile = HttpRuntime.Cache["umbracoSettingsFile"]; // Check for language file in cache if (settingsFile == null) { var temp = new XmlDocument(); var settingsReader = new XmlTextReader(SettingsFilePath + Filename); try { temp.Load(settingsReader); HttpRuntime.Cache.Insert("umbracoSettingsFile", temp, new CacheDependency(SettingsFilePath + Filename)); } catch (XmlException e) { throw new XmlException("Your umbracoSettings.config file fails to pass as valid XML. Refer to the InnerException for more information", e); } catch (Exception e) { LogHelper.Error<UmbracoSettings>("Error reading umbracoSettings file: " + e.ToString(), e); } settingsReader.Close(); return temp; } else return (XmlDocument)settingsFile; } internal static void Save() { _umbracoSettings.Save(SettingsFilePath + Filename); } /// <summary> /// Selects a xml node in the umbraco settings config file. /// </summary> /// <param name="key">The xpath query to the specific node.</param> /// <returns>If found, it returns the specific configuration xml node.</returns> internal static XmlNode GetKeyAsNode(string key) { if (key == null) throw new ArgumentException("Key cannot be null"); EnsureSettingsDocument(); if (_umbracoSettings == null || _umbracoSettings.DocumentElement == null) return null; return _umbracoSettings.DocumentElement.SelectSingleNode(key); } /// <summary> /// Gets the value of configuration xml node with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> internal static string GetKey(string key) { EnsureSettingsDocument(); string attrName = null; var pos = key.IndexOf('@'); if (pos > 0) { attrName = key.Substring(pos + 1); key = key.Substring(0, pos - 1); } var node = _umbracoSettings.DocumentElement.SelectSingleNode(key); if (node == null) return string.Empty; if (pos < 0) { if (node.FirstChild == null || node.FirstChild.Value == null) return string.Empty; return node.FirstChild.Value; } else { var attr = node.Attributes[attrName]; if (attr == null) return string.Empty; return attr.Value; } } } }
40.051966
173
0.578778
[ "MIT" ]
ConnectionMaster/Umbraco-CMS
src/umbraco.businesslogic/UmbracoSettings.cs
28,517
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.CommandLine; using Microsoft.EntityFrameworkCore.Tools.Properties; namespace Microsoft.EntityFrameworkCore.Tools.Commands { internal partial class DbContextListCommand : ProjectCommandBase { private CommandOption? _json; public override void Configure(CommandLineApplication command) { command.Description = Resources.DbContextListDescription; _json = Json.ConfigureOption(command); base.Configure(command); } } }
28.826087
71
0.720965
[ "MIT" ]
Applesauce314/efcore
src/ef/Commands/DbContextListCommand.Configure.cs
663
C#
namespace ImageProcessor.Mobile { public class ProcessedImage { public ProcessedImage() { } public string Id { get; set; } public string Name { get; set; } public string OriginalImageUrl { get; set; } public string TextBoxImageUrl { get; set; } public string TextRecognizedImageUrl { get; set; } public string TextRecognizedThumbnailUrl { get; set; } public string OcrData { get; set; } } }
25.875
56
0.705314
[ "MIT", "Unlicense" ]
michael-watson/ImageProcessor
ImageProcessor.Mobile/ImageProcessor.Mobile/Models/ProcessedImage.cs
416
C#
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2012 Tasharen Entertainment //---------------------------------------------- using UnityEngine; using System.Collections.Generic; /// <summary> /// Symbols are a sequence of characters such as ":)" that get replaced with a sprite, such as the smiley face. /// </summary> [System.Serializable] public class BMSymbol { public string sequence; public string spriteName; UIAtlas.Sprite mSprite = null; bool mIsValid = false; int mLength = 0; int mOffsetX = 0; // (outer - inner) in pixels int mOffsetY = 0; // (outer - inner) in pixels int mWidth = 0; // Symbol's width in pixels (sprite.outer.width) int mHeight = 0; // Symbol's height in pixels (sprite.outer.height) int mAdvance = 0; // Symbol's inner width in pixels (sprite.inner.width) Rect mUV; public int length { get { if (mLength == 0) mLength = sequence.Length; return mLength; } } public int offsetX { get { return mOffsetX; } } public int offsetY { get { return mOffsetY; } } public int width { get { return mWidth; } } public int height { get { return mHeight; } } public int advance { get { return mAdvance; } } public Rect uvRect { get { return mUV; } } /// <summary> /// Mark this symbol as dirty, clearing the sprite reference. /// </summary> public void MarkAsDirty () { mIsValid = false; } /// <summary> /// Validate this symbol, given the specified atlas. /// </summary> public bool Validate (UIAtlas atlas) { if (atlas == null) return false; #if UNITY_EDITOR if (!Application.isPlaying || !mIsValid) #else if (!mIsValid) #endif { if (string.IsNullOrEmpty(spriteName)) return false; mSprite = (atlas != null) ? atlas.GetSprite(spriteName) : null; if (mSprite != null) { Texture tex = atlas.texture; if (tex == null) { mSprite = null; } else { Rect outer = mSprite.outer; mUV = outer; if (atlas.coordinates == UIAtlas.Coordinates.Pixels) { mUV = NGUIMath.ConvertToTexCoords(mUV, tex.width, tex.height); } else { outer = NGUIMath.ConvertToPixels(outer, tex.width, tex.height, true); } mOffsetX = Mathf.RoundToInt(mSprite.paddingLeft * outer.width); mOffsetY = Mathf.RoundToInt(mSprite.paddingTop * outer.width); mWidth = Mathf.RoundToInt(outer.width); mHeight = Mathf.RoundToInt(outer.height); mAdvance = Mathf.RoundToInt(outer.width + (mSprite.paddingRight + mSprite.paddingLeft) * outer.width); mIsValid = true; } } } return (mSprite != null); } }
27.484211
111
0.632325
[ "MIT" ]
kidshenlong/warpspeed
Project Files/Assets/NGUI/Scripts/Internal/BMSymbol.cs
2,612
C#
using System; using System.Windows.Input; namespace GBAC; /// <summary> /// A base RelayCommand to use for RelayCommands /// </summary> public abstract class BaseRelayCommand : ICommand { #region Constructors /// <summary> /// Default constructor /// </summary> protected BaseRelayCommand() { _canExecute = true; } /// <summary> /// Default constructor /// </summary> /// <param name="canExecute">Determines if the command can be executed</param> protected BaseRelayCommand(bool canExecute) { _canExecute = canExecute; } #endregion #region Private Fields /// <summary> /// Determines if the command can execute /// </summary> private bool _canExecute; #endregion #region Public Properties /// <summary> /// True if the command can execute, false if not /// </summary> public virtual bool CanExecuteCommand { get => _canExecute; set => SetCanExecute(value); } #endregion #region Public Methods /// <summary> /// Changes the state determining if the command can execute /// </summary> /// <param name="value">True if the command can execute</param> public virtual void SetCanExecute(bool value) { _canExecute = value; CanExecuteChanged?.Invoke(this, EventArgs.Empty); } /// <summary> /// Get a boolean determining if the command can execute /// </summary> /// <param name="parameter">Optional parameter to pass in</param> /// <returns></returns> public virtual bool CanExecute(object? parameter = null) => _canExecute; /// <summary> /// Execute the command /// </summary> /// <param name="parameter">Optional parameters to pass in</param> public abstract void Execute(object? parameter = null); #endregion #region Events /// <summary> /// Fires when the state determining if the command can execute has changed /// </summary> public event EventHandler? CanExecuteChanged; #endregion }
23.258427
82
0.630435
[ "MIT" ]
RayCarrot/GBAC
src/MVVM/BaseRelayCommand.cs
2,072
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IssueManagementSystem.DomainModel.Issue; namespace IssueManagementSystem.DomainService.Issue { /// <summary> /// 課題マネージャー /// </summary> public class IssueManager : IIssueManager { #region プロパティ /// <summary> /// 課題Repository /// </summary> private IIssueRepository IssueRepository { get; } #endregion #region メソッド #region コンストラクタ /// <summary> /// コンストラクタ /// </summary> /// <param name="issueRepository">課題Repository</param> public IssueManager(IIssueRepository issueRepository) { IssueRepository = issueRepository; } #endregion /// <summary> /// 課題を作成する。 /// </summary> /// <param name="issue">作成する課題</param> public void Create(DomainModel.Issue.Issue issue) { IssueRepository.Add(issue); } /// <summary> /// 課題を修正する。 /// </summary> /// <param name="issue">修正する課題</param> public void Edit(DomainModel.Issue.Issue issue) { IssueRepository.Modify(issue); } /// <summary> /// 課題を削除する。 /// </summary> /// <param name="issueId">削除する課題ID</param> public void Delete(int issueId) { IssueRepository.Remove(issueId); } #endregion } }
23.9375
62
0.54765
[ "MIT" ]
nodashin/DDD-OnionArchitecture-Traning
IssueManagementSystem/IssueManagementSystem.DomainService/Issue/IssueManager.cs
1,688
C#
using System.Linq; using System.Text; namespace XmlTools.CodeGenerator { public static class ComplexTypeAttributeCheckGenerator { public static void GenerateAttributesCheckingCode(XmlTypeWithAttributes xmlType, StringBuilder stringBuilder) { if (!xmlType.Attributes.Any()) { return; } stringBuilder.AppendLine($"foreach (var {CodeGeneratorConstants.ELEMENT_CHECK_METHOD_CHILD_ATTRIBUTE_VARIABLE_NAME} in {CodeGeneratorConstants.ELEMENT_CHECK_METHOD_ELEMENT_VARIABLE_NAME}.Attributes().ToList())"); using (new CodeGeneratorBlockWrapper(stringBuilder)) { for (var i = 0; i < xmlType.Attributes.Count; i++) { var attribute = xmlType.Attributes[i]; stringBuilder.AppendLine($"{(i == 0 ? "" : "else ")}if ({CodeGeneratorConstants.ELEMENT_CHECK_METHOD_CHILD_ATTRIBUTE_VARIABLE_NAME}.Name.LocalName.Equals(\"{attribute.Name}\", StringComparison.OrdinalIgnoreCase))"); using (new CodeGeneratorBlockWrapper(stringBuilder)) { var elementCheckMethodName = XmlCodeGeneratorMethodNameProvider.GetNameForAttributeCheckMethod(attribute.Type); stringBuilder.AppendLine($"{elementCheckMethodName}({CodeGeneratorConstants.ELEMENT_CHECK_METHOD_CHILD_ATTRIBUTE_VARIABLE_NAME});"); XmlElementNameCorrectorCodeGenerator.GenerateAttributeNameCorrector(attribute, stringBuilder, CodeGeneratorConstants.ELEMENT_CHECK_METHOD_CHILD_ATTRIBUTE_VARIABLE_NAME); } } } } } }
54.806452
235
0.663331
[ "MIT" ]
GeorgDangl/XmlTools
src/XmlTools/CodeGenerator/ComplexTypeAttributeCheckGenerator.cs
1,699
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.400) // Version 5.400.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.Diagnostics; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Navigator { /// <summary> /// View element that insets children by the border rounding value of a source. /// </summary> internal class ViewLayoutInsetOverlap : ViewComposite { #region Instance Fields private readonly ViewDrawCanvas _drawCanvas; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewLayoutInsetOverlap class. /// </summary> public ViewLayoutInsetOverlap(ViewDrawCanvas drawCanvas) { Debug.Assert(drawCanvas != null); // Remember source of the rounding values _drawCanvas = drawCanvas; // Default other state Orientation = VisualOrientation.Top; } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewLayoutInsetForRounding:" + Id; } #endregion #region Orientation /// <summary> /// Gets and sets the bar orientation. /// </summary> public VisualOrientation Orientation { [DebuggerStepThrough] get; set; } #endregion #region Rounding /// <summary> /// Gets the rounding value to apply on the edges. /// </summary> public int Rounding { get { // Get the rounding and width values for the border int rounding = _drawCanvas.PaletteBorder.GetBorderRounding(_drawCanvas.State); int width = _drawCanvas.PaletteBorder.GetBorderWidth(_drawCanvas.State); // We have to add half the width as that increases the rounding effect return rounding + (width / 2); } } #endregion #region BorderWidth /// <summary> /// Gets the rounding value to apply on the edges. /// </summary> public int BorderWidth => _drawCanvas.PaletteBorder.GetBorderWidth(_drawCanvas.State); #endregion #region Layout /// <summary> /// Discover the preferred size of the element. /// </summary> /// <param name="context">Layout context.</param> public override Size GetPreferredSize(ViewLayoutContext context) { Debug.Assert(context != null); // Get the preferred size requested by the children Size size = base.GetPreferredSize(context); // Apply the rounding in the appropriate orientation if ((Orientation == VisualOrientation.Top) || (Orientation == VisualOrientation.Bottom)) { size.Width += Rounding * 2; size.Height += BorderWidth; } else { size.Height += Rounding * 2; size.Width += BorderWidth; } return size; } /// <summary> /// Perform a layout of the elements. /// </summary> /// <param name="context">Layout context.</param> public override void Layout(ViewLayoutContext context) { Debug.Assert(context != null); // We take on all the available display area ClientRectangle = context.DisplayRectangle; // Find the rectangle available to each child by removing the rounding Rectangle childRect = ClientRectangle; // Find the amount of rounding to apply int rounding = Rounding; // Apply the rounding in the appropriate orientation if ((Orientation == VisualOrientation.Top) || (Orientation == VisualOrientation.Bottom)) { childRect.Width -= rounding * 2; childRect.X += rounding; } else { childRect.Height -= rounding * 2; childRect.Y += rounding; } // Inform each child to layout inside the reduced rectangle foreach (ViewBase child in this) { context.DisplayRectangle = childRect; child.Layout(context); } // Remember the set context to the size we were given context.DisplayRectangle = ClientRectangle; } #endregion } }
33.790123
157
0.560833
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.400
Source/Krypton Components/ComponentFactory.Krypton.Navigator/View Layout/ViewLayoutInsetOverlap.cs
5,477
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Xml; using System.Collections; namespace QXS.ChatBot { public class ReplacementBotRule : BotRule { protected Random rnd = new Random(); protected string[] _Replacements; protected Regex _Regex = new Regex("\\$(r|s)\\$([a-z0-9]+)\\$", RegexOptions.IgnoreCase); protected Dictionary<string, string> _setters = new Dictionary<string, string>(); public ReplacementBotRule(string Name, int Weight, Regex MessagePattern, string Replacement, Dictionary<string, string> setters) : this(Name, Weight, MessagePattern, Replacement) { this._setters = setters; } public ReplacementBotRule(string Name, int Weight, Regex MessagePattern, string[] Replacements, Dictionary<string, string> setters) : this(Name, Weight, MessagePattern, Replacements) { this._setters = setters; } public ReplacementBotRule(string Name, int Weight, Regex MessagePattern, string Replacement) : base(Name, Weight, MessagePattern) { this._Replacements = new string[] { Replacement }; this._Process = this.ReplaceMessage; } public ReplacementBotRule(string Name, int Weight, Regex MessagePattern, string[] Replacements) : base(Name, Weight, MessagePattern) { this._Replacements = Replacements; this._Process = this.ReplaceMessage; } public string ReplaceMessage(Match match, ChatSessionInterface session) { // set the setters foreach (string key in this._setters.Keys) { session.SessionStorage.Values[key] = this._Regex.Replace( this._setters[key], (Match m) => { switch (m.Groups[1].Value.ToLower()) { case "s": if (session.SessionStorage.Values.ContainsKey(m.Groups[2].Value)) { return session.SessionStorage.Values[m.Groups[2].Value]; } break; case "r": return match.Groups[m.Groups[2].Value].Value; } return ""; } ); } // send a anwer if (this._Replacements.Length == 0) { return ""; } string msg; if (this._Replacements.Length > 1) { msg = this._Replacements[rnd.Next(this._Replacements.Length)]; } else { msg = this._Replacements[0]; } return this._Regex.Replace( msg, (Match m) => { switch (m.Groups[1].Value.ToLower()) { case "s": if (session.SessionStorage.Values.ContainsKey(m.Groups[2].Value)) { return session.SessionStorage.Values[m.Groups[2].Value]; } break; case "r": return match.Groups[m.Groups[2].Value].Value; } return ""; } ); } new public static BotRule CreateRuleFromXml(ChatBotRuleGenerator generator, XmlNode node) { // get unique setters Dictionary<string, string> setters = new Dictionary<string, string>(); foreach (XmlNode subnode in node.SelectChatBotNodes("cb:Setters/cb:Set").Cast<XmlNode>().Where(n => n.Attributes["Key"] != null)) { setters[subnode.Attributes["Key"].Value] = subnode.InnerText; } return new ReplacementBotRule( generator.GetRuleName(node), generator.GetRuleWeight(node), new Regex(generator.GetRulePattern(node)), node.SelectChatBotNodes("cb:Messages/cb:Message").Cast<XmlNode>().Select(n => n.InnerText).ToArray(), setters ); } } }
36.975806
141
0.497056
[ "MIT" ]
dbnmur/Project_OLP_Rest
ChatBot/Rules/ReplacementBotRule.cs
4,587
C#
namespace Rabbit.WeiXin.MP.Messages.Events.CustomService { /// <summary> /// 接入会话通知消息。 /// </summary> public sealed class CloseSessionMessage : EventMessageBase { /// <summary> /// 客服账号。 /// </summary> public string Account { get; set; } /// <summary> /// 事件类型。 /// </summary> public override EventType EventType { get { return EventType.KF_Close_Session; } } } }
21.695652
62
0.503006
[ "Apache-2.0" ]
YouenZeng/WeiXinSDK
src/Rabbit.WeiXin/MP/Messages/Events/CustomService/CloseSessionMessage.cs
539
C#
using System; using System.Globalization; using System.Xml.Linq; namespace RCNet.Neural.Network.SM.Preprocessing.Neuron.Predictor { /// <summary> /// Configuration of the ActivationRescaledRange predictor computer. /// </summary> [Serializable] public class PredictorActivationRescaledRangeSettings : RCNetBaseSettings, IPredictorSettings { //Constants /// <summary> /// The name of the associated xsd type. /// </summary> public const string XsdTypeName = "PredictorActivationRescaledRangeType"; //Attribute properties /// <summary> /// Specifies the data window size. /// </summary> public int Window { get; } //Constructors /// <summary> /// Creates an initialized instance. /// </summary> /// <param name="window">Specifies the data window size.</param> public PredictorActivationRescaledRangeSettings(int window) { Window = window; Check(); return; } /// <summary> /// The copy constructor. /// </summary> /// <param name="source">The source instance.</param> public PredictorActivationRescaledRangeSettings(PredictorActivationRescaledRangeSettings source) : this(source.Window) { return; } /// <summary> /// Creates an initialized instance. /// </summary> /// <param name="elem">A xml element containing the configuration data.</param> public PredictorActivationRescaledRangeSettings(XElement elem) { //Validation XElement settingsElem = Validate(elem, XsdTypeName); //Parsing Window = int.Parse(settingsElem.Attribute("window").Value, CultureInfo.InvariantCulture); Check(); return; } //Properties /// <inheritdoc/> public PredictorsProvider.PredictorID ID { get { return PredictorsProvider.PredictorID.ActivationRescaledRange; } } /// <inheritdoc/> public int RequiredWndSizeOfActivations { get { return Window; } } /// <inheritdoc/> public int RequiredWndSizeOfFirings { get { return 0; } } /// <inheritdoc/> public bool NeedsContinuousActivationStat { get { return false; } } /// <inheritdoc/> public bool NeedsContinuousActivationDiffStat { get { return false; } } /// <inheritdoc/> public override bool ContainsOnlyDefaults { get { return false; } } //Methods /// <inheritdoc/> protected override void Check() { if (Window < 2 || Window > 1024) { throw new ArgumentException($"Invalid Window size {Window.ToString(CultureInfo.InvariantCulture)}. Window size must be GE2 and LE1024.", "Window"); } return; } /// <inheritdoc/> public override RCNetBaseSettings DeepClone() { return new PredictorActivationRescaledRangeSettings(this); } /// <inheritdoc/> public override XElement GetXml(string rootElemName, bool suppressDefaults) { XElement rootElem = new XElement(rootElemName, new XAttribute("window", Window.ToString(CultureInfo.InvariantCulture)) ); Validate(rootElem, XsdTypeName); return rootElem; } /// <inheritdoc/> public override XElement GetXml(bool suppressDefaults) { return GetXml(PredictorFactory.GetXmlName(ID), suppressDefaults); } }//PredictorActivationRescaledRangeSettings }//Namespace
32.521368
163
0.585808
[ "MIT" ]
okozelsk/NET
RCNet/Neural/Network/SM/Preprocessing/Neuron/Predictor/PredictorActivationRescaledRangeSettings.cs
3,807
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Trading.Model.RefData { public class Exchange { [Key] public int Id { get; set; } public int Code { get; set; } public string Name { get; set; } } }
17.722222
44
0.636364
[ "Apache-2.0" ]
ayxue/Stocks
src/StockSolution/Trading.Model/RefData/Exchange.cs
321
C#
using java.lang; using java.lang.reflect; public class ParameterAnnotation { public static bool test() { Class<?> c = typeof(ParameterAnnotation); Method m = c.getMethod("method", typeof(int)); return m.getParameterAnnotations()[0][0] != null; } public static void method([Deprecated] int arg) { } }
23
53
0.68323
[ "Apache-2.0" ]
monoman/cnatural-language
tests/resources/ObjectModelTest/sources/ParameterAnnotation.stab.cs
322
C#
using System; using System.Runtime.InteropServices; public static unsafe class Program { [DllImport("common.dll", CallingConvention = CallingConvention.Cdecl)] public static extern ushort FirstElementOfUshortArray(IntPtr ptr); public static void Main () { var arr = new ushort[5] { 1, 2, 3, 4, 5 }; GCHandle dataHandle = GCHandle.Alloc(arr, GCHandleType.Pinned); Console.WriteLine("Test: {0}", FirstElementOfUshortArray(dataHandle.AddrOfPinnedObject())); } }
39.076923
99
0.700787
[ "MIT" ]
RedpointGames/JSIL
Tests/EmscriptenTestCases/PassPtrToPinnedArray.cs
508
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Multiply_Vector128_Byte() { var test = new SimpleBinaryOpTest__Multiply_Vector128_Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__Multiply_Vector128_Byte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Multiply_Vector128_Byte testClass) { var result = AdvSimd.Multiply(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Multiply_Vector128_Byte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.Multiply( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Multiply_Vector128_Byte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__Multiply_Vector128_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Multiply( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Multiply( AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Multiply), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Multiply), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Multiply( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Multiply( AdvSimd.LoadVector128((Byte*)(pClsVar1)), AdvSimd.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = AdvSimd.Multiply(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Multiply(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Multiply_Vector128_Byte(); var result = AdvSimd.Multiply(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__Multiply_Vector128_Byte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = AdvSimd.Multiply( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Multiply(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.Multiply( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Multiply(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Multiply( AdvSimd.LoadVector128((Byte*)(&test._fld1)), AdvSimd.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Multiply(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Multiply)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
41.684906
184
0.580863
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Multiply.Vector128.Byte.cs
22,093
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.VisualStudio.Composition { using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.Composition.Reflection; using MefV1 = System.ComponentModel.Composition; public class AttributedPartDiscoveryV1 : PartDiscovery { private static readonly MethodInfo OnImportsSatisfiedMethodInfo = typeof(IPartImportsSatisfiedNotification).GetMethod("OnImportsSatisfied", BindingFlags.Public | BindingFlags.Instance); public AttributedPartDiscoveryV1(Resolver resolver) : base(resolver) { } protected override ComposablePartDefinition CreatePart(Type partType, bool typeExplicitlyRequested) { Requires.NotNull(partType, nameof(partType)); var partTypeInfo = partType.GetTypeInfo(); // We want to ignore abstract classes, but we want to consider static classes. // Static classes claim to be both abstract and sealed. So to ignore just abstract // ones, we check that they are not sealed. if (partTypeInfo.IsAbstract && !partTypeInfo.IsSealed) { return null; } BindingFlags everythingLocal = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; BindingFlags instanceLocal = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; // If the type is abstract only find local static exports var exportBindingFlags = everythingLocal; if (partTypeInfo.IsAbstract) { exportBindingFlags &= ~BindingFlags.Instance; } var declaredMethods = partType.GetMethods(exportBindingFlags); // methods can only export, not import var declaredProperties = partType.GetProperties(everythingLocal); var declaredFields = partType.GetFields(everythingLocal); var allLocalMembers = declaredMethods.Concat<MemberInfo>(declaredProperties).Concat(declaredFields); var exportingMembers = from member in allLocalMembers from export in member.GetAttributes<ExportAttribute>() select new KeyValuePair<MemberInfo, ExportAttribute>(member, export); var exportedTypes = from export in partTypeInfo.GetAttributes<ExportAttribute>() select new KeyValuePair<MemberInfo, ExportAttribute>(partTypeInfo, export); var inheritedExportedTypes = from baseTypeOrInterface in partType.GetInterfaces().Concat(partType.EnumTypeAndBaseTypes().Skip(1)) where baseTypeOrInterface != typeof(object) from export in baseTypeOrInterface.GetTypeInfo().GetAttributes<InheritedExportAttribute>() select new KeyValuePair<MemberInfo, ExportAttribute>(baseTypeOrInterface.GetTypeInfo(), export); var exportsByMember = (from export in exportingMembers.Concat(exportedTypes).Concat(inheritedExportedTypes) group export.Value by export.Key into exportsByType select exportsByType).Select(g => new KeyValuePair<MemberInfo, ExportAttribute[]>(g.Key, g.ToArray())).ToArray(); if (exportsByMember.Length == 0) { return null; } // Check for PartNotDiscoverable only after we've established it's an interesting part. // This optimizes for the fact that most types have no exports, in which case it's not a discoverable // part anyway. Checking for the PartNotDiscoverableAttribute first, which is rarely defined, // doesn't usually pay for itself in terms of short-circuiting. But it does add an extra // attribute to look for that we don't need to find for all the types that have no export attributes either. if (!typeExplicitlyRequested && partTypeInfo.IsAttributeDefined<PartNotDiscoverableAttribute>()) { return null; } foreach (var exportingMember in exportsByMember) { this.ThrowOnInvalidExportingMember(exportingMember.Key); } TypeRef partTypeRef = TypeRef.Get(partType, this.Resolver); Type partTypeAsGenericTypeDefinition = partTypeInfo.IsGenericType ? partType.GetGenericTypeDefinition() : null; // Collect information for all imports. var imports = ImmutableList.CreateBuilder<ImportDefinitionBinding>(); this.AddImportsFromMembers(declaredProperties, declaredFields, partTypeRef, imports); Type baseType = partTypeInfo.BaseType; while (baseType != null && baseType != typeof(object)) { this.AddImportsFromMembers(baseType.GetProperties(instanceLocal), baseType.GetFields(instanceLocal), partTypeRef, imports); baseType = baseType.GetTypeInfo().BaseType; } var partCreationPolicy = CreationPolicy.Any; var partCreationPolicyAttribute = partTypeInfo.GetFirstAttribute<PartCreationPolicyAttribute>(); if (partCreationPolicyAttribute != null) { partCreationPolicy = (CreationPolicy)partCreationPolicyAttribute.CreationPolicy; } var allExportsMetadata = ImmutableDictionary.CreateRange(PartCreationPolicyConstraint.GetExportMetadata(partCreationPolicy)); var inheritedExportContractNamesFromNonInterfaces = ImmutableHashSet.CreateBuilder<string>(); var exportDefinitions = ImmutableList.CreateBuilder<KeyValuePair<MemberInfo, ExportDefinition>>(); foreach (var export in exportsByMember) { var memberExportMetadata = allExportsMetadata.AddRange(GetExportMetadata(export.Key)); if (export.Key is MethodInfo) { var method = export.Key as MethodInfo; var exportAttributes = export.Value; if (exportAttributes.Any()) { foreach (var exportAttribute in exportAttributes) { Type exportedType = exportAttribute.ContractType ?? ReflectionHelpers.GetContractTypeForDelegate(method); string contractName = string.IsNullOrEmpty(exportAttribute.ContractName) ? GetContractName(exportedType) : exportAttribute.ContractName; var exportMetadata = memberExportMetadata .Add(CompositionConstants.ExportTypeIdentityMetadataName, ContractNameServices.GetTypeIdentity(exportedType)); var exportDefinition = new ExportDefinition(contractName, exportMetadata); exportDefinitions.Add(new KeyValuePair<MemberInfo, ExportDefinition>(export.Key, exportDefinition)); } } } else { MemberInfo exportingTypeOrPropertyOrField = export.Key; Verify.Operation(export.Key is TypeInfo || !partTypeInfo.IsGenericTypeDefinition, Strings.ExportsOnMembersNotAllowedWhenDeclaringTypeGeneric); Type exportSiteType = ReflectionHelpers.GetMemberType(exportingTypeOrPropertyOrField); foreach (var exportAttribute in export.Value) { Type exportedType = exportAttribute.ContractType ?? partTypeAsGenericTypeDefinition ?? exportSiteType; string contractName = string.IsNullOrEmpty(exportAttribute.ContractName) ? GetContractName(exportedType) : exportAttribute.ContractName; if (export.Key is TypeInfo && exportAttribute is InheritedExportAttribute) { if (inheritedExportContractNamesFromNonInterfaces.Contains(contractName)) { // We already have an export with this contract name on this type (from a more derived type) // using InheritedExportAttribute. continue; } if (!((TypeInfo)export.Key).IsInterface) { inheritedExportContractNamesFromNonInterfaces.Add(contractName); } } var exportMetadata = memberExportMetadata .Add(CompositionConstants.ExportTypeIdentityMetadataName, ContractNameServices.GetTypeIdentity(exportedType)); var exportDefinition = new ExportDefinition(contractName, exportMetadata); exportDefinitions.Add(new KeyValuePair<MemberInfo, ExportDefinition>(export.Key, exportDefinition)); } } } MethodInfo onImportsSatisfied = null; if (typeof(IPartImportsSatisfiedNotification).IsAssignableFrom(partType)) { onImportsSatisfied = OnImportsSatisfiedMethodInfo; } var importingConstructorParameters = ImmutableList.CreateBuilder<ImportDefinitionBinding>(); var importingCtor = GetImportingConstructor<ImportingConstructorAttribute>(partType, publicOnly: false); if (importingCtor != null) // some parts have exports merely for metadata -- they can't be instantiated { foreach (var parameter in importingCtor.GetParameters()) { var import = this.CreateImport(parameter); if (import.ImportDefinition.Cardinality == ImportCardinality.ZeroOrMore) { Verify.Operation(PartDiscovery.IsImportManyCollectionTypeCreateable(import), Strings.CollectionMustBePublicAndPublicCtorWhenUsingImportingCtor); } importingConstructorParameters.Add(import); } } var partMetadata = ImmutableDictionary.CreateBuilder<string, object>(); foreach (var partMetadataAttribute in partTypeInfo.GetAttributes<PartMetadataAttribute>()) { partMetadata[partMetadataAttribute.Name] = partMetadataAttribute.Value; } var exportsOnType = exportDefinitions.Where(kv => kv.Key is TypeInfo).Select(kv => kv.Value).ToArray(); var exportsOnMembers = (from kv in exportDefinitions where !(kv.Key is TypeInfo) group kv.Value by kv.Key into byMember select byMember).ToDictionary(g => MemberRef.Get(g.Key, this.Resolver), g => (IReadOnlyCollection<ExportDefinition>)g.ToArray()); var assemblyNamesForMetadataAttributes = ImmutableHashSet.CreateBuilder<AssemblyName>(ByValueEquality.AssemblyName); foreach (var export in exportsByMember) { GetAssemblyNamesFromMetadataAttributes<MetadataAttributeAttribute>(export.Key, assemblyNamesForMetadataAttributes); } return new ComposablePartDefinition( TypeRef.Get(partType, this.Resolver), partMetadata.ToImmutable(), exportsOnType, exportsOnMembers, imports.ToImmutable(), partCreationPolicy != CreationPolicy.NonShared ? string.Empty : null, MethodRef.Get(onImportsSatisfied, this.Resolver), MethodRef.Get(importingCtor, this.Resolver), importingCtor != null ? importingConstructorParameters.ToImmutable() : null, // some MEF parts are only for metadata partCreationPolicy, assemblyNamesForMetadataAttributes, partCreationPolicy != CreationPolicy.NonShared); } private void AddImportsFromMembers(PropertyInfo[] declaredProperties, FieldInfo[] declaredFields, TypeRef partTypeRef, IList<ImportDefinitionBinding> imports) { Requires.NotNull(declaredProperties, nameof(declaredProperties)); Requires.NotNull(declaredFields, nameof(declaredFields)); Requires.NotNull(partTypeRef, nameof(partTypeRef)); Requires.NotNull(imports, nameof(imports)); foreach (var member in declaredFields.Concat<MemberInfo>(declaredProperties)) { if (!member.IsStatic()) { try { if (this.TryCreateImportDefinition(ReflectionHelpers.GetMemberType(member), member, out ImportDefinition importDefinition)) { Type importingSiteType = ReflectionHelpers.GetMemberType(member); var importDefinitionBinding = new ImportDefinitionBinding( importDefinition, partTypeRef, MemberRef.Get(member, this.Resolver), TypeRef.Get(importingSiteType, this.Resolver), TypeRef.Get(GetImportingSiteTypeWithoutCollection(importDefinition, importingSiteType), this.Resolver)); imports.Add(importDefinitionBinding); } } catch (Exception ex) { throw new PartDiscoveryException( string.Format( CultureInfo.CurrentCulture, Strings.PartDiscoveryFailedAtMember, member.Name), ex); } } } } public override bool IsExportFactoryType(Type type) { if (type != null && type.GetTypeInfo().IsGenericType) { var typeDefinition = type.GetGenericTypeDefinition(); if (typeDefinition.Equals(typeof(ExportFactory<>)) || typeDefinition.IsEquivalentTo(typeof(ExportFactory<,>))) { return true; } } return false; } protected override IEnumerable<Type> GetTypes(Assembly assembly) { Requires.NotNull(assembly, nameof(assembly)); return assembly.GetTypes(); } private bool TryCreateImportDefinition(Type importingType, ICustomAttributeProvider member, out ImportDefinition importDefinition) { Requires.NotNull(importingType, nameof(importingType)); Requires.NotNull(member, nameof(member)); ImportAttribute importAttribute = member.GetFirstAttribute<ImportAttribute>(); ImportManyAttribute importManyAttribute = member.GetFirstAttribute<ImportManyAttribute>(); // Importing constructors get implied attributes on their parameters. if (importAttribute == null && importManyAttribute == null && member is ParameterInfo) { importAttribute = new ImportAttribute(); } if (importAttribute != null) { this.ThrowOnInvalidImportingMemberOrParameter(member, isImportMany: false); if (importAttribute.Source != ImportSource.Any) { throw new NotSupportedException(Strings.CustomImportSourceNotSupported); } var requiredCreationPolicy = importingType.IsExportFactoryTypeV1() ? CreationPolicy.NonShared : (CreationPolicy)importAttribute.RequiredCreationPolicy; Type contractType = importAttribute.ContractType ?? GetTypeIdentityFromImportingType(importingType, importMany: false); var constraints = PartCreationPolicyConstraint.GetRequiredCreationPolicyConstraints(requiredCreationPolicy) .Union(this.GetMetadataViewConstraints(importingType, importMany: false)) .Union(GetExportTypeIdentityConstraints(contractType)); importDefinition = new ImportDefinition( string.IsNullOrEmpty(importAttribute.ContractName) ? GetContractName(contractType) : importAttribute.ContractName, importAttribute.AllowDefault ? ImportCardinality.OneOrZero : ImportCardinality.ExactlyOne, GetImportMetadataForGenericTypeImport(contractType), constraints); return true; } else if (importManyAttribute != null) { this.ThrowOnInvalidImportingMemberOrParameter(member, isImportMany: true); if (importManyAttribute.Source != ImportSource.Any) { throw new NotSupportedException(Strings.CustomImportSourceNotSupported); } var requiredCreationPolicy = GetElementTypeFromMany(importingType).IsExportFactoryTypeV1() ? CreationPolicy.NonShared : (CreationPolicy)importManyAttribute.RequiredCreationPolicy; Type contractType = importManyAttribute.ContractType ?? GetTypeIdentityFromImportingType(importingType, importMany: true); var constraints = PartCreationPolicyConstraint.GetRequiredCreationPolicyConstraints(requiredCreationPolicy) .Union(this.GetMetadataViewConstraints(importingType, importMany: true)) .Union(GetExportTypeIdentityConstraints(contractType)); importDefinition = new ImportDefinition( string.IsNullOrEmpty(importManyAttribute.ContractName) ? GetContractName(contractType) : importManyAttribute.ContractName, ImportCardinality.ZeroOrMore, GetImportMetadataForGenericTypeImport(contractType), constraints); return true; } else { importDefinition = null; return false; } } private ImportDefinitionBinding CreateImport(ParameterInfo parameter) { Assumes.True(this.TryCreateImportDefinition(parameter.ParameterType, parameter, out ImportDefinition importDefinition)); return new ImportDefinitionBinding( importDefinition, TypeRef.Get(parameter.Member.DeclaringType, this.Resolver), ParameterRef.Get(parameter, this.Resolver), TypeRef.Get(parameter.ParameterType, this.Resolver), TypeRef.Get(GetImportingSiteTypeWithoutCollection(importDefinition, parameter.ParameterType), this.Resolver)); } private static IReadOnlyDictionary<string, object> GetExportMetadata(MemberInfo member) { Requires.NotNull(member, nameof(member)); var result = ImmutableDictionary.CreateBuilder<string, object>(); foreach (var attribute in member.GetAttributes<Attribute>()) { var exportMetadataAttribute = attribute as ExportMetadataAttribute; if (exportMetadataAttribute != null) { if (exportMetadataAttribute.IsMultiple) { result[exportMetadataAttribute.Name] = AddElement(result.GetValueOrDefault(exportMetadataAttribute.Name) as Array, exportMetadataAttribute.Value, null); } else { result.Add(exportMetadataAttribute.Name, exportMetadataAttribute.Value); } } else { Type attrType = attribute.GetType(); // Perf optimization, relies on short circuit evaluation, often a property attribute is an ExportAttribute if (attrType != typeof(ExportAttribute) && attrType.GetTypeInfo().IsAttributeDefined<MetadataAttributeAttribute>(true)) { var usage = attrType.GetTypeInfo().GetFirstAttribute<AttributeUsageAttribute>(true); var properties = attribute.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties.Where(p => p.DeclaringType != typeof(Attribute) && p.DeclaringType != typeof(ExportAttribute))) { if (usage != null && usage.AllowMultiple) { result[property.Name] = AddElement(result.GetValueOrDefault(property.Name) as Array, property.GetValue(attribute), ReflectionHelpers.GetMemberType(property)); } else { if (result.ContainsKey(property.Name)) { string memberName = member.MemberType.HasFlag(MemberTypes.TypeInfo) || member.MemberType.HasFlag(MemberTypes.NestedType) ? ((TypeInfo)member).FullName : $"{member.DeclaringType.FullName}.{member.Name}"; throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Strings.DiscoveredIdenticalPropertiesInMetadataAttributesForPart, memberName, property.Name)); } result.Add(property.Name, property.GetValue(attribute)); } } } } } return result.ToImmutable(); } } }
54.194245
204
0.60246
[ "MIT" ]
Bhaskers-Blu-Org2/vs-mef
src/Microsoft.VisualStudio.Composition/Configuration/AttributedPartDiscoveryV1.cs
22,601
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.BenefitsAdministration { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Add_Dependent_ResponseType : INotifyPropertyChanged { private Unique_IdentifierObjectType event_ReferenceField; private WorkerObjectType employee_ReferenceField; private DependentObjectType dependent_ReferenceField; private Exception_DataType[][] exceptions_Response_DataField; private string versionField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement(Order = 0)] public Unique_IdentifierObjectType Event_Reference { get { return this.event_ReferenceField; } set { this.event_ReferenceField = value; this.RaisePropertyChanged("Event_Reference"); } } [XmlElement(Order = 1)] public WorkerObjectType Employee_Reference { get { return this.employee_ReferenceField; } set { this.employee_ReferenceField = value; this.RaisePropertyChanged("Employee_Reference"); } } [XmlElement(Order = 2)] public DependentObjectType Dependent_Reference { get { return this.dependent_ReferenceField; } set { this.dependent_ReferenceField = value; this.RaisePropertyChanged("Dependent_Reference"); } } [XmlArray(Order = 3), XmlArrayItem("Exceptions_Data", typeof(Exception_DataType[]), IsNullable = false), XmlArrayItem("Exception_Data", typeof(Exception_DataType), IsNullable = false, NestingLevel = 1)] public Exception_DataType[][] Exceptions_Response_Data { get { return this.exceptions_Response_DataField; } set { this.exceptions_Response_DataField = value; this.RaisePropertyChanged("Exceptions_Response_Data"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string version { get { return this.versionField; } set { this.versionField = value; this.RaisePropertyChanged("version"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
23.238532
204
0.740229
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.BenefitsAdministration/Add_Dependent_ResponseType.cs
2,533
C#
using System; using System.Diagnostics; namespace SdlSharp.Graphics { /// <summary> /// A color. /// </summary> [DebuggerDisplay("({Red}, {Green}, {Blue}, {Alpha})")] public readonly struct Color : IEquatable<Color> { /// <summary> /// The opaque alpha value. /// </summary> public const byte AlphaOpaque = 255; /// <summary> /// The transparent alpha value. /// </summary> public const byte AlphaTransparent = 0; /// <summary> /// The red value. /// </summary> public byte Red { get; } /// <summary> /// The green value. /// </summary> public byte Green { get; } /// <summary> /// The blue value. /// </summary> public byte Blue { get; } /// <summary> /// The alpha value. /// </summary> public byte Alpha { get; } /// <summary> /// Constructs a color. /// </summary> /// <param name="red">The red value.</param> /// <param name="green">The green value.</param> /// <param name="blue">The blue value.</param> /// <param name="alpha">The alpha value.</param> public Color(byte red, byte green, byte blue, byte alpha = AlphaOpaque) { Red = red; Green = green; Blue = blue; Alpha = alpha; } /// <summary> /// Converts an RGB tuple to a color. /// </summary> /// <param name="tuple">The RGB value.</param> public static implicit operator Color((byte Red, byte Green, byte Blue) tuple) => new(tuple.Red, tuple.Green, tuple.Blue); /// <summary> /// Converts an RGBA tuple to a color. /// </summary> /// <param name="tuple">The RGBA value.</param> public static implicit operator Color((byte Red, byte Green, byte Blue, byte Alpha) tuple) => new(tuple.Red, tuple.Green, tuple.Blue, tuple.Alpha); /// <summary> /// Compares two colors. /// </summary> /// <param name="left">The left color.</param> /// <param name="right">The right color.</param> /// <returns>Whether the colors are equal.</returns> public static bool operator ==(Color left, Color right) => left.Equals(right); /// <summary> /// Compares two colors. /// </summary> /// <param name="left">The left color.</param> /// <param name="right">The right color.</param> /// <returns>Whether the colors are not equal.</returns> public static bool operator !=(Color left, Color right) => !left.Equals(right); /// <summary> /// Compares two colors. /// </summary> /// <param name="other">The other color to compare.</param> /// <returns>Whether the two colors are equal.</returns> public bool Equals(Color other) => Red == other.Red && Green == other.Green && Blue == other.Blue; /// <inheritdoc/> public override bool Equals(object? obj) => obj is Color other && Equals(other); /// <inheritdoc/> public override int GetHashCode() => HashCode.Combine(Red, Green, Blue); } }
32.909091
155
0.532535
[ "MIT" ]
panopticoncentral/sdl-sharp
src/SdlSharp/Graphics/Color.cs
3,260
C#
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.12 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ namespace OSGeo.OGR { using System; using System.Runtime.InteropServices; public class DataSource : IDisposable { private HandleRef swigCPtr; protected bool swigCMemOwn; protected object swigParentRef; protected static object ThisOwn_true() { return null; } protected object ThisOwn_false() { return this; } public DataSource(IntPtr cPtr, bool cMemoryOwn, object parent) { swigCMemOwn = cMemoryOwn; swigParentRef = parent; swigCPtr = new HandleRef(this, cPtr); } public static HandleRef getCPtr(DataSource obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } public static HandleRef getCPtrAndDisown(DataSource obj, object parent) { if (obj != null) { obj.swigCMemOwn = false; obj.swigParentRef = parent; return obj.swigCPtr; } else { return new HandleRef(null, IntPtr.Zero); } } public static HandleRef getCPtrAndSetReference(DataSource obj, object parent) { if (obj != null) { obj.swigParentRef = parent; return obj.swigCPtr; } else { return new HandleRef(null, IntPtr.Zero); } } ~DataSource() { Dispose(); } public virtual void Dispose() { lock(this) { if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) { swigCMemOwn = false; OgrPINVOKE.delete_DataSource(swigCPtr); } swigCPtr = new HandleRef(null, IntPtr.Zero); swigParentRef = null; GC.SuppressFinalize(this); } } public string name { get { string ret = OgrPINVOKE.DataSource_name_get(swigCPtr); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } } public int GetRefCount() { int ret = OgrPINVOKE.DataSource_GetRefCount(swigCPtr); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public int GetSummaryRefCount() { int ret = OgrPINVOKE.DataSource_GetSummaryRefCount(swigCPtr); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public int GetLayerCount() { int ret = OgrPINVOKE.DataSource_GetLayerCount(swigCPtr); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Driver GetDriver() { IntPtr cPtr = OgrPINVOKE.DataSource_GetDriver(swigCPtr); Driver ret = (cPtr == IntPtr.Zero) ? null : new Driver(cPtr, false, ThisOwn_false()); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public string GetName() { string ret = OgrPINVOKE.DataSource_GetName(swigCPtr); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public int DeleteLayer(int index) { int ret = OgrPINVOKE.DataSource_DeleteLayer(swigCPtr, index); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public int SyncToDisk() { int ret = OgrPINVOKE.DataSource_SyncToDisk(swigCPtr); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void FlushCache() { OgrPINVOKE.DataSource_FlushCache(swigCPtr); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); } public Layer CreateLayer(string name, OSGeo.OSR.SpatialReference srs, wkbGeometryType geom_type, string[] options) { IntPtr cPtr = OgrPINVOKE.DataSource_CreateLayer(swigCPtr, name, OSGeo.OSR.SpatialReference.getCPtr(srs), (int)geom_type, (options != null)? new OgrPINVOKE.StringListMarshal(options)._ar : null); Layer ret = (cPtr == IntPtr.Zero) ? null : new Layer(cPtr, false, ThisOwn_false()); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Layer CopyLayer(Layer src_layer, string new_name, string[] options) { IntPtr cPtr = OgrPINVOKE.DataSource_CopyLayer(swigCPtr, Layer.getCPtr(src_layer), new_name, (options != null)? new OgrPINVOKE.StringListMarshal(options)._ar : null); Layer ret = (cPtr == IntPtr.Zero) ? null : new Layer(cPtr, false, ThisOwn_false()); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Layer GetLayerByIndex(int index) { IntPtr cPtr = OgrPINVOKE.DataSource_GetLayerByIndex(swigCPtr, index); Layer ret = (cPtr == IntPtr.Zero) ? null : new Layer(cPtr, false, ThisOwn_false()); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Layer GetLayerByName(string layer_name) { IntPtr cPtr = OgrPINVOKE.DataSource_GetLayerByName(swigCPtr, layer_name); Layer ret = (cPtr == IntPtr.Zero) ? null : new Layer(cPtr, false, ThisOwn_false()); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public bool TestCapability(string cap) { bool ret = OgrPINVOKE.DataSource_TestCapability(swigCPtr, cap); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Layer ExecuteSQL(string statement, Geometry spatialFilter, string dialect) { IntPtr cPtr = OgrPINVOKE.DataSource_ExecuteSQL(swigCPtr, statement, Geometry.getCPtr(spatialFilter), dialect); Layer ret = (cPtr == IntPtr.Zero) ? null : new Layer(cPtr, false, ThisOwn_false()); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void ReleaseResultSet(Layer layer) { OgrPINVOKE.DataSource_ReleaseResultSet(swigCPtr, Layer.getCPtrAndDisown(layer, ThisOwn_false())); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); } public StyleTable GetStyleTable() { IntPtr cPtr = OgrPINVOKE.DataSource_GetStyleTable(swigCPtr); StyleTable ret = (cPtr == IntPtr.Zero) ? null : new StyleTable(cPtr, false, ThisOwn_false()); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void SetStyleTable(StyleTable table) { OgrPINVOKE.DataSource_SetStyleTable(swigCPtr, StyleTable.getCPtr(table)); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); } public int StartTransaction(int force) { int ret = OgrPINVOKE.DataSource_StartTransaction(swigCPtr, force); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public int CommitTransaction() { int ret = OgrPINVOKE.DataSource_CommitTransaction(swigCPtr); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } public int RollbackTransaction() { int ret = OgrPINVOKE.DataSource_RollbackTransaction(swigCPtr); if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); return ret; } } }
37.043689
198
0.718779
[ "Apache-2.0" ]
speakeasy/gdal
swig/csharp/ogr/DataSource.cs
7,631
C#
using System.Numerics; namespace _16_CornellBoxLightEmittedDownwardDirection { public class Diffuse_light : Material { public Texture emit; public Diffuse_light(Texture a) { this.emit = a; } public override Vector3 Emitted(Ray r_in, Hit_Record rec, float u, float v, Vector3 p) { if (rec.Front_face) { return this.emit.Value(u, v, p); } else { return Vector3.Zero; } } } }
20.071429
94
0.501779
[ "MIT" ]
Jorgemagic/RaytracingTheRestOfYourLife
16-CornellBoxLightEmittedDownwardDirection/Materials/Diffuse_light.cs
564
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Plex.ServerApi.Clients.Interfaces; using PlexBlazorServerOAuthExample.Services.Plex; using System; using System.Threading.Tasks; namespace PlexBlazorServerOAuthExample.Controllers { [Route("api/[controller]")] public class PlexLoginController : Controller { private readonly OAuthService _oAuthService; private readonly IPlexAccountClient _plexClient; public PlexLoginController(OAuthService oAuthService, IPlexAccountClient plexClient) { _oAuthService = oAuthService; _plexClient = plexClient; } [HttpGet] public async Task<IActionResult> IndexAsync() { var returnPath = Request.Scheme + "://" + Request.Host + Request.Path + "/PlexReturn"; var oAuthUrl = await _plexClient.CreateOAuthPinAsync(returnPath); _oAuthService.OAuthID = oAuthUrl.Id; return Redirect(oAuthUrl.Url); } [HttpGet] [Route("PlexReturn")] public async Task<IActionResult> PlexReturn() { var test = this.Request.Query; var oAuthId = _oAuthService.OAuthID.ToString(); var oAuthPin = await _plexClient.GetAuthTokenFromOAuthPinAsync(oAuthId); if (string.IsNullOrEmpty(oAuthPin.AuthToken)) { return Content(@"<h3 style=""text-align: center;"">Plex login failed, unable to obtain an authentication token.</h3>","text/html"); } _oAuthService.PlexKey = oAuthPin.AuthToken; await _oAuthService.Login(oAuthPin.AuthToken); return Content(@"<script>window.close();</script>", "text/html"); } } }
33.471698
147
0.642052
[ "MIT" ]
JeffreyMercado/plex-api
Samples/PlexBlazorServerOAuthExample/Controllers/PlexLoginController.cs
1,774
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { public GameObject player; private Vector3 offset; void Start() { offset = transform.position - player.transform.position; } void LateUpdate() { transform.position = player.transform.position + offset; } }
20.352941
58
0.763006
[ "MIT" ]
fallsimply/Roll-A-Ball
Assets/Scripts/CameraController.cs
348
C#
using System.Collections.Generic; using System.Threading.Tasks; using Rollvolet.CRM.Domain.Models; using Rollvolet.CRM.Domain.Models.Query; namespace Rollvolet.CRM.Domain.Contracts.DataProviders { public interface ILanguageDataProvider { Task<IEnumerable<Language>> GetAllAsync(); Task<Language> GetByIdAsync(int id); Task<Language> GetByCustomerNumberAsync(int number); Task<Language> GetByContactIdAsync(int id); Task<Language> GetByBuildingIdAsync(int id); } }
32.25
60
0.742248
[ "MIT" ]
rollvolet/crm-ap
src/Rollvolet.CRM.Domain/Contracts/DataProviders/ILanguageDataProvider.cs
516
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Apollo.Domain.Entity; using Apollo.Persistence.Dao.Interfaces; using Apollo.Persistence.FluentEntity.Interfaces.Select; using Apollo.Persistence.Util; namespace Apollo.Persistence.Dao.Ado { public class SeatDaoAdo : BaseDao<Seat>, ISeatDao { public SeatDaoAdo(IConnectionFactory connectionFactory) : base(connectionFactory) { } public Task<IEnumerable<Seat>> SelectWithRowAndCategoryByCinemaHallAsync(long cinemaHallId) { return SelectWithRowAndCategoryJoin(FluentSelectAll()) .Where(_ => _.Row.CinemaHallId) .Equal(cinemaHallId) .QueryAsync(); } public Task<IEnumerable<Seat>> SelectActiveWithRowAndCategoryByCinemaHallAsync(long cinemaHallId) { return SelectRowAndCategoryAndCinemaHallJoin(SelectWithRowAndCategoryJoin(FluentSelectAll())) .WhereActive() .And(_ => _.Row.Deleted) .Equal(false) .And(_ => _.Row.CinemaHall.Deleted) .Equal(false) .And(_ => _.Row.CinemaHallId) .Equal(cinemaHallId) .QueryAsync(); } public async Task<IEnumerable<Seat>> SelectSeatsFromCinemaHallAsync(long cinemaHallId) { return await FluentSelectAll() .InnerJoin<Seat, Row, long, long>(s => s.Row, s => s.RowId, r => r.Id) .Where(s => s.Row.CinemaHallId) .Equal(cinemaHallId) .QueryAsync(); } public async Task<IEnumerable<Seat>> SelectActiveSeatsWithRowByRowCategoryAsync(long rowCategoryId) { return await FluentSelectAll() .InnerJoin<Seat, Row, long, long>(s => s.Row, s => s.RowId, r => r.Id) .Where(s => s.Row.CategoryId) .Equal(rowCategoryId) .QueryAsync(); } public async Task<IEnumerable<Seat>> SelectActiveSeatsByIdAsync(long rowId) { return await FluentSelectAll() .Where(s => s.RowId) .Equal(rowId) .QueryAsync(); } public Task<IEnumerable<Seat>> SelectActiveSeatsFromCinemaHallByCategoryAsync(long cinemaHallId, long categoryId) { return SelectActiveSeatsFromCinemaHallByCategoryAsync(cinemaHallId, new[] {categoryId}); } public Task<IEnumerable<Seat>> SelectActiveSeatsFromCinemaHallByCategoryAsync(long cinemaHallId, IEnumerable<long> categoryIds) { return SelectRowAndCategoryAndCinemaHallJoin(SelectWithRowAndCategoryJoin(FluentSelectAll())) .WhereActive() .And(s => s.Locked) .Equal(false) .And(_ => _.Row.CinemaHallId) .Equal(cinemaHallId) .And(_ => _.Row.Deleted) .Equal(false) .And(_ => _.Row.CategoryId) .In(categoryIds) .QueryAsync(); } public async Task<int> UpdateSeatLockStateAsync(long seatId, bool locked) { var seat = await SelectSingleByIdAsync(seatId); seat.Locked = locked; return await FluentUpdate(seat).ExecuteAsync(); } private static IFluentEntityJoin<Seat> SelectWithRowAndCategoryJoin(IFluentEntityJoin<Seat> statement) { return statement .InnerJoin<Seat, Row, long, long>(_ => _.Row, _ => _.RowId, _ => _.Id) .InnerJoin<Row, RowCategory, long, long>(_ => _.Row.Category, _ => _.CategoryId, _ => _.Id); } private static IFluentEntityWhereSelect<Seat> SelectRowAndCategoryAndCinemaHallJoin( IFluentEntityJoin<Seat> statement) { return statement .InnerJoin<Row, CinemaHall, long, long>(_ => _.Row.CinemaHall, _ => _.CinemaHallId, _ => _.Id); } public async Task<IEnumerable<Seat>> SelectFreeSeatsByIdAsync(IEnumerable<long> seatIds) { return await FluentSelectAll() .WhereActive() .And(s => s.Locked) .Equal(false) .And(s => s.Id) .NotIn(seatIds) .QueryAsync(); } } }
37.576271
111
0.577357
[ "MIT" ]
EnvyIT/apollo
Apollo/Apollo.Persistence/Dao/Ado/SeatDaoAdo.cs
4,436
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Abp.Modules; using Abp.Reflection.Extensions; using MyFirstProject.Configuration; namespace MyFirstProject.Web.Host.Startup { [DependsOn( typeof(MyFirstProjectWebCoreModule))] public class MyFirstProjectWebHostModule: AbpModule { private readonly IWebHostEnvironment _env; private readonly IConfigurationRoot _appConfiguration; public MyFirstProjectWebHostModule(IWebHostEnvironment env) { _env = env; _appConfiguration = env.GetAppConfiguration(); } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(MyFirstProjectWebHostModule).GetAssembly()); } } }
28.428571
103
0.713568
[ "MIT" ]
ayyse/boilerplate-car
6.0.0/aspnet-core/src/MyFirstProject.Web.Host/Startup/MyFirstProjectWebHostModule.cs
798
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("WebKitCore.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebKitCore.Tests")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("46f96546-dbe2-4209-8471-813e525a9417")] // 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.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.916667
84
0.748718
[ "BSD-2-Clause" ]
ArmyMedalMei/webkitdotnet
WebKitBrowser.Tests/Properties/AssemblyInfo.cs
1,368
C#
using System.Linq; using System.Web.Mvc; using IDeliverable.Slides.Filters; using IDeliverable.Slides.Models; using IDeliverable.Slides.ViewModels; using Orchard.ContentManagement; using Orchard.Layouts.Framework.Elements; using Orchard.Layouts.Services; using Orchard.Localization; using Orchard.UI.Admin; using Orchard.UI.Notify; using Orchard.Layouts.Helpers; namespace IDeliverable.Slides.Controllers { [Admin] [Dialog] public class SlideController : Controller, IUpdateModel { private readonly INotifier _notifier; private readonly IObjectStore _objectStore; private readonly IElementManager _elementManager; private readonly ILayoutModelMapper _mapper; private readonly ILayoutSerializer _serializer; private readonly ILayoutEditorFactory _layoutEditorFactory; public SlideController( INotifier notifier, IObjectStore objectStore, IElementManager elementManager, ILayoutModelMapper mapper, ILayoutSerializer serializer, ILayoutEditorFactory layoutEditorFactory) { _notifier = notifier; _objectStore = objectStore; _elementManager = elementManager; _mapper = mapper; _serializer = serializer; _layoutEditorFactory = layoutEditorFactory; T = NullLocalizer.Instance; } public Localizer T { get; set; } public ActionResult Edit(string id, string returnUrl) { var slide = _objectStore.Get<Slide>(id); var viewModel = new SlideEditorViewModel { ReturnUrl = returnUrl, LayoutEditor = _layoutEditorFactory.Create(slide.LayoutData, id, slide.TemplateId) }; return View(viewModel); } [HttpPost] [ValidateInput(false)] public ActionResult Edit(SlideEditorViewModel viewModel) { var elementInstances = _mapper.ToLayoutModel(viewModel.LayoutEditor.Data, DescribeElementsContext.Empty).ToArray(); var context = new LayoutSavingContext { Updater = this, Elements = elementInstances, }; _elementManager.Saving(context); var slide = new Slide { LayoutData = _serializer.Serialize(elementInstances), TemplateId = viewModel.LayoutEditor.TemplateId }; _objectStore.Set(viewModel.LayoutEditor.SessionKey, slide); return RedirectToEditor(viewModel.ReturnUrl, T("That slide has been updated.")); } private RedirectResult RedirectToEditor(string returnUrl, LocalizedString notification) { _notifier.Information(notification); return Redirect(returnUrl); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.Text); } } }
35.27957
133
0.65224
[ "BSD-3-Clause" ]
IDeliverable/IDeliverable.Slides
Controllers/SlideController.cs
3,283
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Squidex.Infrastructure; using Squidex.Shared.Users; namespace Squidex.Domain.Users { public sealed class DefaultUserResolver : IUserResolver { private readonly UserManager<IdentityUser> userManager; private readonly IUserFactory userFactory; public DefaultUserResolver(UserManager<IdentityUser> userManager, IUserFactory userFactory) { Guard.NotNull(userManager, nameof(userManager)); Guard.NotNull(userFactory, nameof(userFactory)); this.userManager = userManager; this.userFactory = userFactory; } public async Task<bool> CreateUserIfNotExists(string email, bool invited) { var user = userFactory.Create(email); try { var result = await userManager.CreateAsync(user); if (result.Succeeded) { var values = new UserValues { DisplayName = email, Invited = invited }; await userManager.UpdateAsync(user, values); } return result.Succeeded; } catch { return false; } } public async Task<IUser> FindByIdOrEmailAsync(string idOrEmail) { if (userFactory.IsId(idOrEmail)) { return await userManager.FindByIdWithClaimsAsync(idOrEmail); } else { return await userManager.FindByEmailWithClaimsAsyncAsync(idOrEmail); } } public async Task<List<IUser>> QueryByEmailAsync(string email) { var result = await userManager.QueryByEmailAsync(email); return result.OfType<IUser>().ToList(); } } }
31.135135
99
0.534722
[ "MIT" ]
mgnz/squidex
src/Squidex.Domain.Users/DefaultUserResolver.cs
2,306
C#
// Copyright (C) 20134 Pat Laplante // // 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 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 MonoTouch.UIKit; namespace Coc.MvxAdvancedPresenter.Touch.Attributes { [AttributeUsage(AttributeTargets.Class)] public class PresenterAttribute : Attribute { public Type PresenterType { get; private set; } public virtual Type TransitionType { get; set; } public virtual float Duration { get; set; } public PresenterAttribute () { } public PresenterAttribute (Type classType) { PresenterType = classType; } public virtual BaseTouchViewPresenter CreatePresenter() { if (PresenterType != null) { BaseTouchViewPresenter presenter = (BaseTouchViewPresenter) PresenterType.GetConstructor(new Type[] {}).Invoke(new object[] {}); UIViewControllerAnimatedTransitioning transition = null; if (TransitionType != null) { transition = (UIViewControllerAnimatedTransitioning) TransitionType.GetConstructor(new Type[] {typeof(float)}).Invoke(new object[] {Duration}); } presenter.Transition = transition; return presenter; } return null; } } }
38.355932
148
0.707026
[ "MIT" ]
patbonecrusher/MvxAdvancedPresenter.Touch
MvxAdvancedPresenter.Touch/Attributes/PresenterAttributes.cs
2,265
C#
using System; using System.Linq; using System.Threading.Tasks; using Administrator.Common; using Administrator.Extensions; using Disqord; using Microsoft.Extensions.DependencyInjection; using Qmmands; namespace Administrator.Commands { public sealed class EmojiParser : TypeParser<IEmoji> { public override ValueTask<TypeParserResult<IEmoji>> ParseAsync(Parameter parameter, string value, CommandContext ctx) { var context = (AdminCommandContext) ctx; var random = context.ServiceProvider.GetRequiredService<Random>(); var validSearchableEmojis = context.Client.Guilds.Values.SelectMany(x => x.Emojis.Values).ToList(); if (!EmojiTools.TryParse(value, out var emoji)) { if (Snowflake.TryParse(value, out var id)) { emoji = validSearchableEmojis.FirstOrDefault(x => x.Id == id); } else { var matchingEmojis = validSearchableEmojis .Where(x => x.Name.Equals(value, StringComparison.OrdinalIgnoreCase)).ToList(); if (matchingEmojis.Count > 0 && !parameter.Checks.OfType<RequireGuildEmojiAttribute>().Any()) { emoji = matchingEmojis.GetRandomElement(random); } } } return !(emoji is null) ? TypeParserResult<IEmoji>.Successful(emoji) : TypeParserResult<IEmoji>.Unsuccessful(context.Localize("emojiparser_notfound")); } } }
37.627907
125
0.595797
[ "MIT" ]
QuantumToasted/Administrator
Administrator/Commands/Parsers/EmojiParser.cs
1,620
C#
// Released under the MIT License. // // Copyright (c) 2018 Ntreev Soft co., Ltd. // Copyright (c) 2020 Jeesu Choi // // 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. // // Forked from https://github.com/NtreevSoft/Crema // Namespaces and files starting with "Ntreev" have been renamed to "JSSoft". using JSSoft.Crema.ServiceModel; using System; using System.Threading.Tasks; namespace JSSoft.Crema.Services.Domains { class DomainMember : DomainMemberBase, IDomainMember { private readonly Domain domain; private Authentication authentication; public DomainMember(Domain domain, string userID, string name, DomainAccessType accessType) { this.domain = domain; base.DomainMemberInfo = new DomainMemberInfo() { ID = userID, Name = name, AccessType = accessType, }; } public override string ToString() { return base.DomainMemberInfo.ID; } public Task BeginEditAsync(Authentication authentication, DomainLocationInfo location) { return this.domain.BeginUserEditAsync(authentication, location); } public Task EndEditAsync(Authentication authentication) { return this.domain.EndUserEditAsync(authentication); } public Task SetLocationAsync(Authentication authentication, DomainLocationInfo location) { return this.domain.SetUserLocationAsync(authentication, location); } public Task KickAsync(Authentication authentication, string comment) { return this.domain.KickAsync(authentication, base.DomainMemberInfo.ID, comment); } public Task SetOwnerAsync(Authentication authentication) { return this.domain.SetOwnerAsync(authentication, base.DomainMemberInfo.ID); } public DomainMemberMetaData GetMetaData() { this.Dispatcher.VerifyAccess(); var metaData = new DomainMemberMetaData() { DomainMemberInfo = base.DomainMemberInfo, DomainLocationInfo = base.DomainLocationInfo, DomainMemberState = base.DomainMemberState, }; return metaData; } public string ID => base.DomainMemberInfo.ID; public Authentication Authentication { get => this.authentication; set { if (this.authentication != null && value != null) throw new NotImplementedException(); if (this.authentication == null && value == null) throw new NotImplementedException(); this.authentication = value; } } public CremaDispatcher Dispatcher => this.domain.Dispatcher; public new event EventHandler DomainMemberInfoChanged { add { this.Dispatcher.VerifyAccess(); base.DomainMemberInfoChanged += value; } remove { this.Dispatcher.VerifyAccess(); base.DomainMemberInfoChanged -= value; } } public new event EventHandler DomainLocationInfoChanged { add { this.Dispatcher.VerifyAccess(); base.DomainLocationInfoChanged += value; } remove { this.Dispatcher.VerifyAccess(); base.DomainLocationInfoChanged -= value; } } public new event EventHandler DomainMemberStateChanged { add { this.Dispatcher.VerifyAccess(); base.DomainMemberStateChanged += value; } remove { this.Dispatcher.VerifyAccess(); base.DomainMemberStateChanged -= value; } } #region IServiceProvider object IServiceProvider.GetService(System.Type serviceType) { if (serviceType == typeof(IDomain)) return this.domain; return (this.domain as IServiceProvider).GetService(serviceType); } #endregion } }
34.229299
121
0.61016
[ "MIT" ]
s2quake/JSSoft.Crema
server/JSSoft.Crema.Services/Domains/DomainMember.cs
5,376
C#
using EventStore.Core.Index; using NUnit.Framework; namespace EventStore.Core.Tests.Index.Index64Bit { [TestFixture] public class adding_four_items_to_empty_index_map_with_two_tables_per_level_causes_double_merge: Index32Bit.adding_four_items_to_empty_index_map_with_two_tables_per_level_causes_double_merge { public adding_four_items_to_empty_index_map_with_two_tables_per_level_causes_double_merge() { _ptableVersion = PTableVersions.Index64Bit; } } }
36.142857
194
0.806324
[ "Apache-2.0" ]
rodolfograve/EventStore
src/EventStore.Core.Tests/Index/Index64Bit/adding_four_items_to_empty_index_map_with_two_tables_per_level_causes_double_merge.cs
506
C#
// T4 code generation is enabled for model 'D:\Demo\GalaxyLibrary\SA47Team10a_GalaxyLibrary\GalaxyEDM.edmx'. // To enable legacy code generation, change the value of the 'Code Generation Strategy' designer // property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model // is open in the designer. // If no context and entity classes have been generated, it may be because you created an empty model but // have not yet chosen which version of Entity Framework to use. To generate a context class and entity // classes for your model, open the model in the designer, right-click on the designer surface, and // select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation // Item...'.
77.6
111
0.759021
[ "MIT" ]
NgYanBo/GdipSA_LibraryManagementSystem
SA47Team10a_GalaxyLibrary/GalaxyEDM.Designer.cs
778
C#
///////////////////////////////////////////////////////////////////////////////// // paint.net // // Copyright (C) dotPDN LLC, Rick Brewster, and contributors. // // All Rights Reserved. // ///////////////////////////////////////////////////////////////////////////////// using System; using System.Diagnostics; using System.Threading; namespace PaintDotNet { [Serializable] public abstract class Disposable : IDisposable { private int isDisposed; // 0 for false, 1 for true public bool IsDisposed { get { return Volatile.Read(ref this.isDisposed) == 1; } } protected Disposable() { } ~Disposable() { Debug.Assert(!this.IsDisposed); int oldIsDisposed = Interlocked.Exchange(ref this.isDisposed, 1); if (oldIsDisposed == 0) { Dispose(false); } } public void Dispose() { int oldIsDisposed = Interlocked.Exchange(ref this.isDisposed, 1); if (oldIsDisposed == 0) { try { Dispose(true); } finally { GC.SuppressFinalize(this); } } } protected virtual void Dispose(bool disposing) { } } }
25.677419
82
0.374372
[ "MIT" ]
ScriptBox99/PaintDotNet.Quantization
PaintDotNet/Disposable.cs
1,594
C#
/* * Copyright(c) 2018 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.ComponentModel; using Tizen.NUI.XamlBinding; using static Tizen.NUI.BaseComponents.View; using Tizen.NUI.BaseComponents; namespace Tizen.NUI.Xaml.Forms.BaseComponents { /// <summary> /// View is the base class for all views. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] [ContentProperty("Content")] public class View : Tizen.NUI.Xaml.Forms.Container, Tizen.NUI.Binding.IResourcesProvider { private Tizen.NUI.BaseComponents.View _view; internal Tizen.NUI.BaseComponents.View view { get { if (null == _view) { _view = handleInstance as Tizen.NUI.BaseComponents.View; } return _view; } } /// <summary> /// Creates a new instance of a Xaml View. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View() : this(new Tizen.NUI.BaseComponents.View()) { } /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Tizen.NUI.BaseComponents.View ViewInstance { get { return _view; } } internal View(Tizen.NUI.BaseComponents.View nuiInstance) : base(nuiInstance) { _view = nuiInstance; SetNUIInstance(nuiInstance); } /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] bool Tizen.NUI.Binding.IResourcesProvider.IsResourcesCreated => _resources != null; ResourceDictionary _resources; /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ResourceDictionary Resources { get { if (_resources != null) return _resources; _resources = new ResourceDictionary(); ((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged; return _resources; } set { if (_resources == value) return; OnPropertyChanging(); if (_resources != null) ((IResourceDictionary)_resources).ValuesChanged -= OnResourcesChanged; _resources = value; OnResourcesChanged(value); if (_resources != null) ((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged; OnPropertyChanged(); } } /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ResourceDictionary XamlResources { get { if (_resources != null) return _resources; _resources = new ResourceDictionary(); ((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged; return _resources; } set { if (_resources == value) return; OnPropertyChanging(); if (_resources != null) ((IResourceDictionary)_resources).ValuesChanged -= OnResourcesChanged; _resources = value; OnResourcesChanged(value); if (_resources != null) ((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged; OnPropertyChanged(); } } /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ContentProperty = BindableProperty.Create("Content", typeof(View), typeof(ContentPage), null, propertyChanged: (bindable, oldValue, newValue) => { var self = (View)bindable; if (newValue != null) { self.Add((View)newValue); } }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty StyleNameProperty = BindableProperty.Create("StyleName", typeof(string), typeof(View), string.Empty, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.StyleName = (string)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.StyleName; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty BackgroundColorProperty = BindableProperty.Create("BackgroundColor", typeof(Color), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.BackgroundColor = (Color)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.BackgroundColor; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty BackgroundImageProperty = BindableProperty.Create("BackgroundImage", typeof(string), typeof(View), default(string), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.BackgroundImage = (string)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.BackgroundImage; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty BackgroundProperty = BindableProperty.Create("Background", typeof(PropertyMap), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Background = (PropertyMap)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Background; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty StateProperty = BindableProperty.Create("State", typeof(States), typeof(View), States.Normal, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.State = (States)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.State; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty SubStateProperty = BindableProperty.Create("SubState", typeof(States), typeof(View), States.Normal, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.SubState = (States)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.SubState; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty TooltipProperty = BindableProperty.Create("Tooltip", typeof(PropertyMap), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Tooltip = (PropertyMap)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Tooltip; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty FlexProperty = BindableProperty.Create("Flex", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Flex = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Flex; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty AlignSelfProperty = BindableProperty.Create("AlignSelf", typeof(int), typeof(View), default(int), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.AlignSelf = (int)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.AlignSelf; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty FlexMarginProperty = BindableProperty.Create("FlexMargin", typeof(Vector4), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.FlexMargin = (Vector4)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.FlexMargin; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty CellIndexProperty = BindableProperty.Create("CellIndex", typeof(Vector2), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.CellIndex = (Vector2)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.CellIndex; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty RowSpanProperty = BindableProperty.Create("RowSpan", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.RowSpan = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.RowSpan; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ColumnSpanProperty = BindableProperty.Create("ColumnSpan", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.ColumnSpan = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.ColumnSpan; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty CellHorizontalAlignmentProperty = BindableProperty.Create("CellHorizontalAlignment", typeof(HorizontalAlignmentType), typeof(View), HorizontalAlignmentType.Left, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.CellHorizontalAlignment = (HorizontalAlignmentType)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.CellHorizontalAlignment; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty CellVerticalAlignmentProperty = BindableProperty.Create("CellVerticalAlignment", typeof(VerticalAlignmentType), typeof(View), VerticalAlignmentType.Top, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.CellVerticalAlignment = (VerticalAlignmentType)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.CellVerticalAlignment; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty LeftFocusableViewProperty = BindableProperty.Create(nameof(View.LeftFocusableView), typeof(Tizen.NUI.BaseComponents.View), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.LeftFocusableView = (Tizen.NUI.BaseComponents.View)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.LeftFocusableView; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty RightFocusableViewProperty = BindableProperty.Create(nameof(View.RightFocusableView), typeof(Tizen.NUI.BaseComponents.View), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.RightFocusableView = (Tizen.NUI.BaseComponents.View)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.RightFocusableView; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty UpFocusableViewProperty = BindableProperty.Create(nameof(View.UpFocusableView), typeof(Tizen.NUI.BaseComponents.View), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.UpFocusableView = (Tizen.NUI.BaseComponents.View)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.UpFocusableView; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty DownFocusableViewProperty = BindableProperty.Create(nameof(View.DownFocusableView), typeof(Tizen.NUI.BaseComponents.View), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.DownFocusableView = (Tizen.NUI.BaseComponents.View)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.DownFocusableView; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty FocusableProperty = BindableProperty.Create("Focusable", typeof(bool), typeof(View), false, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Focusable = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Focusable; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty Size2DProperty = BindableProperty.Create("Size2D", typeof(Size2D), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Size2D = (Size2D)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Size2D; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty OpacityProperty = BindableProperty.Create("Opacity", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Opacity = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Opacity; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty Position2DProperty = BindableProperty.Create("Position2D", typeof(Position2D), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Position2D = (Position2D)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Position2D; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty PositionUsesPivotPointProperty = BindableProperty.Create("PositionUsesPivotPoint", typeof(bool), typeof(View), true, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.PositionUsesPivotPoint = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.PositionUsesPivotPoint; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty SiblingOrderProperty = BindableProperty.Create("SiblingOrder", typeof(int), typeof(View), default(int), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.SiblingOrder = (int)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; var parentChildren = view.GetParent()?.Children; int currentOrder = 0; if (parentChildren != null) { currentOrder = parentChildren.IndexOf(view); if (currentOrder < 0) { return 0; } else if (currentOrder < parentChildren.Count) { return currentOrder; } } return 0; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ParentOriginProperty = BindableProperty.Create("ParentOrigin", typeof(Position), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.ParentOrigin = (Position)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.ParentOrigin; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty PivotPointProperty = BindableProperty.Create("PivotPoint", typeof(Position), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.PivotPoint = (Position)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.PivotPoint; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty SizeWidthProperty = BindableProperty.Create("SizeWidth", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.SizeWidth = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.SizeWidth; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty SizeHeightProperty = BindableProperty.Create("SizeHeight", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.SizeHeight = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.SizeHeight; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty PositionProperty = BindableProperty.Create("Position", typeof(Position), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Position = (Position)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Position; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty PositionXProperty = BindableProperty.Create("PositionX", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.PositionX = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.PositionX; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty PositionYProperty = BindableProperty.Create("PositionY", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.PositionY = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.PositionY; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty PositionZProperty = BindableProperty.Create("PositionZ", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.PositionZ = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.PositionZ; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty OrientationProperty = BindableProperty.Create("Orientation", typeof(Rotation), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Orientation = (Rotation)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Orientation; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScaleProperty = BindableProperty.Create("Scale", typeof(Vector3), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Scale = (Vector3)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Scale; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScaleXProperty = BindableProperty.Create("ScaleX", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.ScaleX = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.ScaleX; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScaleYProperty = BindableProperty.Create("ScaleY", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.ScaleY = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.ScaleY; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScaleZProperty = BindableProperty.Create("ScaleZ", typeof(float), typeof(View), default(float), propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.ScaleZ = (float)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.ScaleZ; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty NameProperty = BindableProperty.Create("Name", typeof(string), typeof(View), string.Empty, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Name = (string)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Name; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty SensitiveProperty = BindableProperty.Create("Sensitive", typeof(bool), typeof(View), false, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Sensitive = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Sensitive; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty LeaveRequiredProperty = BindableProperty.Create("LeaveRequired", typeof(bool), typeof(View), false, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.LeaveRequired = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.LeaveRequired; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty InheritOrientationProperty = BindableProperty.Create("InheritOrientation", typeof(bool), typeof(View), false, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.InheritOrientation = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.InheritOrientation; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty InheritScaleProperty = BindableProperty.Create("InheritScale", typeof(bool), typeof(View), false, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.InheritScale = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.InheritScale; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty DrawModeProperty = BindableProperty.Create("DrawMode", typeof(DrawModeType), typeof(View), DrawModeType.Normal, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.DrawMode = (DrawModeType)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.DrawMode; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty SizeModeFactorProperty = BindableProperty.Create("SizeModeFactor", typeof(Vector3), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.SizeModeFactor = (Vector3)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.SizeModeFactor; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty WidthResizePolicyProperty = BindableProperty.Create("WidthResizePolicy", typeof(ResizePolicyType), typeof(View), ResizePolicyType.Fixed, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.WidthResizePolicy = (ResizePolicyType)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.WidthResizePolicy; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty HeightResizePolicyProperty = BindableProperty.Create("HeightResizePolicy", typeof(ResizePolicyType), typeof(View), ResizePolicyType.Fixed, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.HeightResizePolicy = (ResizePolicyType)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.HeightResizePolicy; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty SizeScalePolicyProperty = BindableProperty.Create("SizeScalePolicy", typeof(SizeScalePolicyType), typeof(View), SizeScalePolicyType.UseSizeSet, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.SizeScalePolicy = (SizeScalePolicyType)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.SizeScalePolicy; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty WidthForHeightProperty = BindableProperty.Create("WidthForHeight", typeof(bool), typeof(View), false, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.WidthForHeight = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.WidthForHeight; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty HeightForWidthProperty = BindableProperty.Create("HeightForWidth", typeof(bool), typeof(View), false, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.HeightForWidth = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.HeightForWidth; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty PaddingProperty = BindableProperty.Create("Padding", typeof(Extents), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Padding = (Extents)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Padding; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty SizeProperty = BindableProperty.Create("Size", typeof(Size), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Size = (Size)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Size; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty MinimumSizeProperty = BindableProperty.Create("MinimumSize", typeof(Size2D), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.MinimumSize = (Size2D)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.MinimumSize; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty MaximumSizeProperty = BindableProperty.Create("MaximumSize", typeof(Size2D), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.MaximumSize = (Size2D)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.MaximumSize; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty InheritPositionProperty = BindableProperty.Create("InheritPosition", typeof(bool), typeof(View), false, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.InheritPosition = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.InheritPosition; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ClippingModeProperty = BindableProperty.Create("ClippingMode", typeof(ClippingModeType), typeof(View), ClippingModeType.Disabled, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.ClippingMode = (ClippingModeType)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.ClippingMode; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty InheritLayoutDirectionProperty = BindableProperty.Create("InheritLayoutDirection", typeof(bool), typeof(View), false, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.InheritLayoutDirection = (bool)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.InheritLayoutDirection; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty LayoutDirectionProperty = BindableProperty.Create("LayoutDirection", typeof(ViewLayoutDirectionType), typeof(View), ViewLayoutDirectionType.LTR, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.LayoutDirection = (ViewLayoutDirectionType)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.LayoutDirection; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty MarginProperty = BindableProperty.Create("Margin", typeof(Extents), typeof(View), null, propertyChanged: (bindable, oldValue, newValue) => { var view = ((View)bindable).view; view.Margin = (Extents)newValue; }, defaultValueCreator: (bindable) => { var view = ((View)bindable).view; return view.Margin; }); /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty StyleProperty = BindableProperty.Create("Style", typeof(Style), typeof(View), default(Style), propertyChanged: (bindable, oldvalue, newvalue) => ((View)bindable).mergedStyle.Style = (Style)newvalue); /// <summary> /// Event argument passed through the ChildAdded event. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public class ChildAddedEventArgs : EventArgs { /// <summary> /// Added child view at moment. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View Added { get; set; } } /// <summary> /// Event when a child is added. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler<ChildAddedEventArgs> ChildAdded; // From Container Base class /// <summary> /// Adds a child view to this view. /// </summary> /// <seealso cref="Container.Add" /> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public override void Add(View child) { (child as IElement).Parent = this; view.Add(child.view); if (ChildAdded != null) { ChildAddedEventArgs e = new ChildAddedEventArgs { Added = child }; ChildAdded(this, e); } } /// <summary> /// Event argument passed through the ChildRemoved event. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public class ChildRemovedEventArgs : EventArgs { /// <summary> /// Removed child view at moment. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View Removed { get; set; } } /// <summary> /// Event when a child is removed. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler<ChildRemovedEventArgs> ChildRemoved; /// <summary> /// Removes a child view from this View. If the view was not a child of this view, this is a no-op. /// </summary> /// <seealso cref="Container.Remove" /> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public override void Remove(View child) { (child as IElement).Parent = null; view.Remove(child.view); if (ChildRemoved != null) { ChildRemovedEventArgs e = new ChildRemovedEventArgs { Removed = child }; ChildRemoved(this, e); } } /// <summary> /// Retrieves a child view by index. /// </summary> /// <seealso cref="Container.GetChildAt" /> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public override View GetChildAt(uint index) { if (index < view.Children.Count) { return BaseHandle.GetHandle(view.Children[Convert.ToInt32(index)]) as View; } else { return null; } } /// <summary> /// Retrieves the number of children held by the view. /// </summary> /// <seealso cref="Container.GetChildCount" /> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public override uint GetChildCount() { return Convert.ToUInt32(view.Children.Count); } /// <summary> /// Gets the views parent. /// </summary> /// <seealso cref="Container.GetParent()" /> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public override Container GetParent() { return BaseHandle.GetHandle(view.GetParent()) as Container; } /// <summary> /// An event for the KeyInputFocusGained signal which can be used to subscribe or unsubscribe the event handler provided by the user.<br /> /// The KeyInputFocusGained signal is emitted when the control gets the key input focus.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler FocusGained { add { view.FocusGained += value; } remove { view.FocusGained -= value; } } /// <summary> /// An event for the KeyInputFocusLost signal which can be used to subscribe or unsubscribe the event handler provided by the user.<br /> /// The KeyInputFocusLost signal is emitted when the control loses the key input focus.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler FocusLost { add { view.FocusLost += value; } remove { view.FocusLost -= value; } } /// <summary> /// An event for the KeyPressed signal which can be used to subscribe or unsubscribe the event handler provided by the user.<br /> /// The KeyPressed signal is emitted when the key event is received.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandlerWithReturnType<object, KeyEventArgs, bool> KeyEvent { add { view.KeyEvent += value; } remove { view.KeyEvent -= value; } } /// <summary> /// An event for the OnRelayout signal which can be used to subscribe or unsubscribe the event handler.<br /> /// The OnRelayout signal is emitted after the size has been set on the view during relayout.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler Relayout { add { view.Relayout += value; } remove { view.Relayout -= value; } } /// <summary> /// An event for the touched signal which can be used to subscribe or unsubscribe the event handler provided by the user.<br /> /// The touched signal is emitted when the touch input is received.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandlerWithReturnType<object, TouchEventArgs, bool> TouchEvent { add { view.TouchEvent += value; } remove { view.TouchEvent -= value; } } /// <summary> /// An event for the hovered signal which can be used to subscribe or unsubscribe the event handler provided by the user.<br /> /// The hovered signal is emitted when the hover input is received.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandlerWithReturnType<object, HoverEventArgs, bool> HoverEvent { add { view.HoverEvent += value; } remove { view.HoverEvent -= value; } } /// <summary> /// An event for the WheelMoved signal which can be used to subscribe or unsubscribe the event handler provided by the user.<br /> /// The WheelMoved signal is emitted when the wheel event is received.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandlerWithReturnType<object, WheelEventArgs, bool> WheelEvent { add { view.WheelEvent += value; } remove { view.WheelEvent -= value; } } /// <summary> /// An event for the OnWindow signal which can be used to subscribe or unsubscribe the event handler.<br /> /// The OnWindow signal is emitted after the view has been connected to the window.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler AddedToWindow { add { view.AddedToWindow += value; } remove { view.AddedToWindow -= value; } } /// <summary> /// An event for the OffWindow signal, which can be used to subscribe or unsubscribe the event handler.<br /> /// OffWindow signal is emitted after the view has been disconnected from the window.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler RemovedFromWindow { add { view.RemovedFromWindow += value; } remove { view.RemovedFromWindow -= value; } } /// <summary> /// An event for visibility change which can be used to subscribe or unsubscribe the event handler.<br /> /// This signal is emitted when the visible property of this or a parent view is changed.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler<VisibilityChangedEventArgs> VisibilityChanged { add { view.VisibilityChanged += value; } remove { view.VisibilityChanged -= value; } } /// <summary> /// Event for layout direction change which can be used to subscribe/unsubscribe the event handler.<br /> /// This signal is emitted when the layout direction property of this or a parent view is changed.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler<LayoutDirectionChangedEventArgs> LayoutDirectionChanged { add { view.LayoutDirectionChanged += value; } remove { view.LayoutDirectionChanged -= value; } } /// <summary> /// An event for the ResourcesLoadedSignal signal which can be used to subscribe or unsubscribe the event handler provided by the user.<br /> /// This signal is emitted after all resources required by a view are loaded and ready.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public event EventHandler ResourcesLoaded { add { view.ResourcesLoaded += value; } remove { view.ResourcesLoaded -= value; } } /// <summary> /// Queries whether the view has a focus. /// </summary> /// <returns>True if this view has a focus.</returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool HasFocus() { return view.HasFocus(); } /// <summary> /// Sets the name of the style to be applied to the view. /// </summary> /// <param name="styleName">A string matching a style described in a stylesheet.</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetStyleName(string styleName) { view.SetStyleName(styleName); } /// <summary> /// Retrieves the name of the style to be applied to the view (if any). /// </summary> /// <returns>A string matching a style, or an empty string.</returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public string GetStyleName() { return view.GetStyleName(); } /// <summary> /// Clears the background. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void ClearBackground() { view.ClearBackground(); } /// <summary> /// The contents of ContentPage can be added into it. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View Content { get { return (View)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } /// <summary> /// The StyleName, type string. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public string StyleName { get { return (string)GetValue(StyleNameProperty); } set { SetValue(StyleNameProperty, value); } } /// <summary> /// The mutually exclusive with BACKGROUND_IMAGE and BACKGROUND type Vector4. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Color BackgroundColor { get { return (Color)GetValue(BackgroundColorProperty); } set { SetValue(BackgroundColorProperty, value); } } /// <summary> /// Creates an animation to animate the background color visual. If there is no /// background visual, creates one with transparent black as it's mixColor. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Animation AnimateBackgroundColor(object destinationValue, int startTime, int endTime, AlphaFunction.BuiltinFunctions? alphaFunction = null, object initialValue = null) { return view.AnimateBackgroundColor(destinationValue, startTime, endTime, alphaFunction, initialValue); } /// <summary> /// Creates an animation to animate the mixColor of the named visual. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Animation AnimateColor(string targetVisual, object destinationColor, int startTime, int endTime, AlphaFunction.BuiltinFunctions? alphaFunction = null, object initialColor = null) { return view.AnimateColor(targetVisual, destinationColor, startTime, endTime, alphaFunction, initialColor); } /// <summary> /// The mutually exclusive with BACKGROUND_COLOR and BACKGROUND type Map. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public string BackgroundImage { get { return (string)GetValue(BackgroundImageProperty); } set { SetValue(BackgroundImageProperty, value); } } /// <summary> /// The background of view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Tizen.NUI.PropertyMap Background { get { return (PropertyMap)GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// The current state of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public States State { get { return (States)GetValue(StateProperty); } set { SetValue(StateProperty, value); } } /// <summary> /// The current sub state of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public States SubState { get { return (States)GetValue(SubStateProperty); } set { SetValue(SubStateProperty, value); } } /// <summary> /// Displays a tooltip /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Tizen.NUI.PropertyMap Tooltip { get { return (PropertyMap)GetValue(TooltipProperty); } set { SetValue(TooltipProperty, value); } } /// <summary> /// Displays a tooltip as a text. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public string TooltipText { set { view.TooltipText = value; } } /// <summary> /// The Child property of FlexContainer.<br /> /// The proportion of the free space in the container, the flex item will receive.<br /> /// If all items in the container set this property, their sizes will be proportional to the specified flex factor.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float Flex { get { return (float)GetValue(FlexProperty); } set { SetValue(FlexProperty, value); } } /// <summary> /// The Child property of FlexContainer.<br /> /// The alignment of the flex item along the cross axis, which, if set, overides the default alignment for all items in the container.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public int AlignSelf { get { return (int)GetValue(AlignSelfProperty); } set { SetValue(AlignSelfProperty, value); } } /// <summary> /// The Child property of FlexContainer.<br /> /// The space around the flex item.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector4 FlexMargin { get { return (Vector4)GetValue(FlexMarginProperty); } set { SetValue(FlexMarginProperty, value); } } /// <summary> /// The top-left cell this child occupies, if not set, the first available cell is used. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector2 CellIndex { get { return (Vector2)GetValue(CellIndexProperty); } set { SetValue(CellIndexProperty, value); } } /// <summary> /// The number of rows this child occupies, if not set, the default value is 1. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float RowSpan { get { return (float)GetValue(RowSpanProperty); } set { SetValue(RowSpanProperty, value); } } /// <summary> /// The number of columns this child occupies, if not set, the default value is 1. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float ColumnSpan { get { return (float)GetValue(ColumnSpanProperty); } set { SetValue(ColumnSpanProperty, value); } } /// <summary> /// The horizontal alignment of this child inside the cells, if not set, the default value is 'left'. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Tizen.NUI.HorizontalAlignmentType CellHorizontalAlignment { get { return (HorizontalAlignmentType)GetValue(CellHorizontalAlignmentProperty); } set { SetValue(CellHorizontalAlignmentProperty, value); } } /// <summary> /// The vertical alignment of this child inside the cells, if not set, the default value is 'top'. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Tizen.NUI.VerticalAlignmentType CellVerticalAlignment { get { return (VerticalAlignmentType)GetValue(CellVerticalAlignmentProperty); } set { SetValue(CellVerticalAlignmentProperty, value); } } /// <summary> /// The left focusable view.<br /> /// This will return null if not set.<br /> /// This will also return null if the specified left focusable view is not on a window.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View LeftFocusableView { // As native side will be only storing IDs so need a logic to convert View to ID and vice-versa. get { return (View)GetValue(LeftFocusableViewProperty); } set { SetValue(LeftFocusableViewProperty, value); } } /// <summary> /// The right focusable view.<br /> /// This will return null if not set.<br /> /// This will also return null if the specified right focusable view is not on a window.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View RightFocusableView { // As native side will be only storing IDs so need a logic to convert View to ID and vice-versa. get { return (View)GetValue(RightFocusableViewProperty); } set { SetValue(RightFocusableViewProperty, value); } } /// <summary> /// The up focusable view.<br /> /// This will return null if not set.<br /> /// This will also return null if the specified up focusable view is not on a window.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View UpFocusableView { // As native side will be only storing IDs so need a logic to convert View to ID and vice-versa. get { return (View)GetValue(UpFocusableViewProperty); } set { SetValue(UpFocusableViewProperty, value); } } /// <summary> /// The down focusable view.<br /> /// This will return null if not set.<br /> /// This will also return null if the specified down focusable view is not on a window.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View DownFocusableView { // As native side will be only storing IDs so need a logic to convert View to ID and vice-versa. get { return (View)GetValue(DownFocusableViewProperty); } set { SetValue(DownFocusableViewProperty, value); } } /// <summary> /// Whether the view should be focusable by keyboard navigation. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool Focusable { set { SetValue(FocusableProperty, value); } get { return (bool)GetValue(FocusableProperty); } } /// <summary> /// Retrieves the position of the view.<br /> /// The coordinates are relative to the view's parent.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Position CurrentPosition { get { return view.CurrentPosition; } } /// <summary> /// Sets the size of a view for the width and the height.<br /> /// Geometry can be scaled to fit within this area.<br /> /// This does not interfere with the view's scale factor.<br /> /// The views default depth is the minimum of width and height.<br /> /// </summary> /// <remarks> /// This NUI object (Size2D) typed property can be configured by multiple cascade setting. <br /> /// For example, this code ( view.Size2D.Width = 100; view.Size2D.Height = 100; ) is equivalent to this ( view.Size2D = new Size2D(100, 100); ). <br /> /// Please note that this multi-cascade setting is especially possible for this NUI object (Size2D). <br /> /// This means by default others are impossible so it is recommended that NUI object typed properties are configured by their constructor with parameters. <br /> /// For example, this code is working fine : view.Scale = new Vector3( 2.0f, 1.5f, 0.0f); <br /> /// but this will not work! : view.Scale.X = 2.0f; view.Scale.Y = 1.5f; <br /> /// It may not match the current value in some cases, i.e. when the animation is progressing or the maximum or minimu size is set. <br /> /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Size2D Size2D { get { return (Size2D)GetValue(Size2DProperty); } set { SetValue(Size2DProperty, value); } } private void OnSize2DChanged(int width, int height) { Size2D = new Size2D(width, height); } /// <summary> /// Retrieves the size of the view.<br /> /// The coordinates are relative to the view's parent.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Size2D CurrentSize { get { return view.CurrentSize; } } /// <summary> /// Retrieves and sets the view's opacity.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float Opacity { get { return (float)GetValue(OpacityProperty); } set { SetValue(OpacityProperty, value); } } /// <summary> /// Sets the position of the view for X and Y.<br /> /// By default, sets the position vector between the parent origin and the pivot point (default).<br /> /// If the position inheritance is disabled, sets the world position.<br /> /// </summary> /// <remarks> /// This NUI object (Position2D) typed property can be configured by multiple cascade setting. <br /> /// For example, this code ( view.Position2D.X = 100; view.Position2D.Y = 100; ) is equivalent to this ( view.Position2D = new Position2D(100, 100); ). <br /> /// Please note that this multi-cascade setting is especially possible for this NUI object (Position2D). <br /> /// This means by default others are impossible so it is recommended that NUI object typed properties are configured by their constructor with parameters. <br /> /// For example, this code is working fine : view.Scale = new Vector3( 2.0f, 1.5f, 0.0f); <br /> /// but this will not work! : view.Scale.X = 2.0f; view.Scale.Y = 1.5f; <br /> /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Position2D Position2D { get { return (Position2D)GetValue(Position2DProperty); } set { SetValue(Position2DProperty, value); } } private void OnPosition2DChanged(int x, int y) { Position2D = new Position2D(x, y); } /// <summary> /// Retrieves the screen postion of the view.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector2 ScreenPosition { get { return view.ScreenPosition; } } /// <summary> /// Determines whether the pivot point should be used to determine the position of the view. /// This is true by default. /// </summary> /// <remarks>If false, then the top-left of the view is used for the position. /// Setting this to false will allow scaling or rotation around the anchor-point without affecting the view's position. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool PositionUsesPivotPoint { get { return (bool)GetValue(PositionUsesPivotPointProperty); } set { SetValue(PositionUsesPivotPointProperty, value); } } /// <summary> /// Please do not use! this will be deprecated. /// </summary> /// Please do not use! this will be deprecated! /// Instead please use PositionUsesPivotPoint. /// <since_tizen> 6 </since_tizen> [Obsolete("Please do not use! This will be deprecated! Please use PositionUsesPivotPoint instead! " + "Like: " + "View view = new View(); " + "view.PivotPoint = PivotPoint.Center; " + "view.PositionUsesPivotPoint = true;")] [EditorBrowsable(EditorBrowsableState.Never)] public bool PositionUsesAnchorPoint { get { return view.PositionUsesPivotPoint; } set { view.PositionUsesPivotPoint = value; } } /// <summary> /// Queries whether the view is connected to the stage.<br /> /// When a view is connected, it will be directly or indirectly parented to the root view.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool IsOnWindow { get { return view.IsOnWindow; } } /// <summary> /// Gets the depth in the hierarchy for the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public int HierarchyDepth { get { return view.HierarchyDepth; } } /// <summary> /// Sets the sibling order of the view so the depth position can be defined within the same parent. /// </summary> /// <remarks> /// Note the initial value is 0. SiblingOrder should be bigger than 0 or equal to 0. /// Raise, Lower, RaiseToTop, LowerToBottom, RaiseAbove, and LowerBelow will override the sibling order. /// The values set by this property will likely change. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public int SiblingOrder { get { return (int)GetValue(SiblingOrderProperty); } set { SetValue(SiblingOrderProperty, value); } } /// <summary> /// Returns the natural size of the view. /// </summary> /// <remarks> /// Deriving classes stipulate the natural size and by default a view has a zero natural size. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector3 NaturalSize { get { return view.NaturalSize; } } /// <summary> /// Returns the natural size (Size2D) of the view. /// </summary> /// <remarks> /// Deriving classes stipulate the natural size and by default a view has a zero natural size. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Size2D NaturalSize2D { get { return view.NaturalSize2D; } } /// <summary> /// Shows the view. /// </summary> /// <remarks> /// This is an asynchronous method. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void Show() { view.Show(); } /// <summary> /// Hides the view. /// </summary> /// <remarks> /// This is an asynchronous method. /// If the view is hidden, then the view and its children will not be rendered. /// This is regardless of the individual visibility of the children, i.e., the view will only be rendered if all of its parents are shown. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void Hide() { view.Hide(); } /// <summary> /// Raises the view above all other views. /// </summary> /// <remarks> /// Sibling order of views within the parent will be updated automatically. /// Once a raise or lower API is used, that view will then have an exclusive sibling order independent of insertion. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void RaiseToTop() { view.RaiseToTop(); } /// <summary> /// Lowers the view to the bottom of all views. /// </summary> /// <remarks> /// The sibling order of views within the parent will be updated automatically. /// Once a raise or lower API is used that view will then have an exclusive sibling order independent of insertion. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void LowerToBottom() { view.LowerToBottom(); } /// <summary> /// Queries if all resources required by a view are loaded and ready. /// </summary> /// <remarks>Most resources are only loaded when the control is placed on the stage. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool IsResourceReady() { return view.IsResourceReady(); } /// <summary> /// Gets the parent layer of this view.If a view has no parent, this method does not do anything. /// </summary> /// <pre>The view has been initialized. </pre> /// <returns>The parent layer of view </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Layer GetLayer() { return BaseHandle.GetHandle(view.GetLayer()) as Layer; } /// <summary> /// Removes a view from its parent view or layer. If a view has no parent, this method does nothing. /// </summary> /// <pre>The (child) view has been initialized. </pre> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void Unparent() { view.GetParent()?.Remove(view); } /// <summary> /// Search through this view's hierarchy for a view with the given name. /// The view itself is also considered in the search. /// </summary> /// <pre>The view has been initialized.</pre> /// <param name="viewName">The name of the view to find.</param> /// <returns>A handle to the view if found, or an empty handle if not.</returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View FindChildByName(string viewName) { return BaseHandle.GetHandle(view.FindChildByName(viewName)) as View; } /// <summary> /// Converts screen coordinates into the view's coordinate system using the default camera. /// </summary> /// <pre>The view has been initialized.</pre> /// <remarks>The view coordinates are relative to the top-left(0.0, 0.0, 0.5).</remarks> /// <param name="localX">On return, the X-coordinate relative to the view.</param> /// <param name="localY">On return, the Y-coordinate relative to the view.</param> /// <param name="screenX">The screen X-coordinate.</param> /// <param name="screenY">The screen Y-coordinate.</param> /// <returns>True if the conversion succeeded.</returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool ScreenToLocal(out float localX, out float localY, float screenX, float screenY) { return view.ScreenToLocal(out localX, out localY, screenX, screenY); } /// <summary> /// Sets the relative to parent size factor of the view.<br /> /// This factor is only used when ResizePolicy is set to either: /// ResizePolicy::SIZE_RELATIVE_TO_PARENT or ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT.<br /> /// This view's size is set to the view's size multiplied by or added to this factor, depending on ResizePolicy.<br /> /// </summary> /// <pre>The view has been initialized.</pre> /// <param name="factor">A Vector3 representing the relative factor to be applied to each axis.</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetSizeModeFactor(Vector3 factor) { view.SetSizeModeFactor(factor); } /// <summary> /// Calculates the height of the view given a width.<br /> /// The natural size is used for default calculation.<br /> /// Size 0 is treated as aspect ratio 1:1.<br /> /// </summary> /// <param name="width">The width to use.</param> /// <returns>The height based on the width.</returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float GetHeightForWidth(float width) { return view.GetHeightForWidth(width); } /// <summary> /// Calculates the width of the view given a height.<br /> /// The natural size is used for default calculation.<br /> /// Size 0 is treated as aspect ratio 1:1.<br /> /// </summary> /// <param name="height">The height to use.</param> /// <returns>The width based on the height.</returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float GetWidthForHeight(float height) { return view.GetWidthForHeight(height); } /// <summary> /// Return the amount of size allocated for relayout. /// </summary> /// <param name="dimension">The dimension to retrieve.</param> /// <returns>Return the size.</returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float GetRelayoutSize(DimensionType dimension) { return view.GetRelayoutSize(dimension); } /// <summary> /// Set the padding for the view. /// </summary> /// <param name="padding">Padding for the view.</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetPadding(PaddingType padding) { view.SetPadding(padding); } /// <summary> /// Return the value of padding for the view. /// </summary> /// <param name="paddingOut">the value of padding for the view</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void GetPadding(PaddingType paddingOut) { view.GetPadding(paddingOut); } /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public uint AddRenderer(Renderer renderer) { return view.AddRenderer(renderer); } /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Renderer GetRendererAt(uint index) { return view.GetRendererAt(index); } /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void RemoveRenderer(Renderer renderer) { view.RemoveRenderer(renderer); } /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void RemoveRenderer(uint index) { view.RemoveRenderer(index); } /// <summary> /// Gets or sets the origin of a view within its parent's area.<br /> /// This is expressed in unit coordinates, such that (0.0, 0.0, 0.5) is the top-left corner of the parent, and (1.0, 1.0, 0.5) is the bottom-right corner.<br /> /// The default parent-origin is ParentOrigin.TopLeft (0.0, 0.0, 0.5).<br /> /// A view's position is the distance between this origin and the view's anchor-point.<br /> /// </summary> /// <pre>The view has been initialized.</pre> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Position ParentOrigin { get { return (Position)GetValue(ParentOriginProperty); } set { SetValue(ParentOriginProperty, value); } } /// <summary> /// Gets or sets the anchor-point of a view.<br /> /// This is expressed in unit coordinates, such that (0.0, 0.0, 0.5) is the top-left corner of the view, and (1.0, 1.0, 0.5) is the bottom-right corner.<br /> /// The default pivot point is PivotPoint.Center (0.5, 0.5, 0.5).<br /> /// A view position is the distance between its parent-origin and this anchor-point.<br /> /// A view's orientation is the rotation from its default orientation, the rotation is centered around its anchor-point.<br /> /// <pre>The view has been initialized.</pre> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Position PivotPoint { get { return (Position)GetValue(PivotPointProperty); } set { SetValue(PivotPointProperty, value); } } /// <summary> /// Gets or sets the size width of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float SizeWidth { get { return (float)GetValue(SizeWidthProperty); } set { SetValue(SizeWidthProperty, value); } } /// <summary> /// Gets or sets the size height of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float SizeHeight { get { return (float)GetValue(SizeHeightProperty); } set { SetValue(SizeHeightProperty, value); } } /// <summary> /// Gets or sets the position of the view.<br /> /// By default, sets the position vector between the parent origin and pivot point (default).<br /> /// If the position inheritance is disabled, sets the world position.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Position Position { get { return (Position)GetValue(PositionProperty); } set { SetValue(PositionProperty, value); } } /// <summary> /// Gets or sets the position X of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float PositionX { get { return (float)GetValue(PositionXProperty); } set { SetValue(PositionXProperty, value); } } /// <summary> /// Gets or sets the position Y of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float PositionY { get { return (float)GetValue(PositionYProperty); } set { SetValue(PositionYProperty, value); } } /// <summary> /// Gets or sets the position Z of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float PositionZ { get { return (float)GetValue(PositionZProperty); } set { SetValue(PositionZProperty, value); } } /// <summary> /// Gets or sets the world position of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector3 WorldPosition { get { return view.WorldPosition; } } /// <summary> /// Gets or sets the orientation of the view.<br /> /// The view's orientation is the rotation from its default orientation, and the rotation is centered around its anchor-point.<br /> /// </summary> /// <remarks>This is an asynchronous method.</remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Rotation Orientation { get { return (Rotation)GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } /// <summary> /// Gets or sets the world orientation of the view.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Rotation WorldOrientation { get { return view.WorldOrientation; } } /// <summary> /// Gets or sets the scale factor applied to the view.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector3 Scale { get { return (Vector3)GetValue(ScaleProperty); } set { SetValue(ScaleProperty, value); } } /// <summary> /// Gets or sets the scale X factor applied to the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float ScaleX { get { return (float)GetValue(ScaleXProperty); } set { SetValue(ScaleXProperty, value); } } /// <summary> /// Gets or sets the scale Y factor applied to the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float ScaleY { get { return (float)GetValue(ScaleYProperty); } set { SetValue(ScaleYProperty, value); } } /// <summary> /// Gets or sets the scale Z factor applied to the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public float ScaleZ { get { return (float)GetValue(ScaleZProperty); } set { SetValue(ScaleZProperty, value); } } /// <summary> /// Gets the world scale of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector3 WorldScale { get { return view.WorldScale; } } /// <summary> /// Retrieves the visibility flag of the view. /// </summary> /// <remarks> /// If the view is not visible, then the view and its children will not be rendered. /// This is regardless of the individual visibility values of the children, i.e., the view will only be rendered if all of its parents have visibility set to true. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool Visibility { get { return view.Visibility; } } /// <summary> /// Gets the view's world color. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector4 WorldColor { get { return view.WorldColor; } } /// <summary> /// Gets or sets the view's name. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public string Name { get { return (string)GetValue(NameProperty); } set { SetValue(NameProperty, value); } } /// <summary> /// Get the number of children held by the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public new uint ChildCount { get { return GetChildCount(); } } /// <summary> /// Gets the view's ID. /// Readonly /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public uint ID { get { return view.ID; } } /// <summary> /// Gets or sets the status of whether the view should emit touch or hover signals. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool Sensitive { get { return (bool)GetValue(SensitiveProperty); } set { SetValue(SensitiveProperty, value); } } /// <summary> /// Gets or sets the status of whether the view should receive a notification when touch or hover motion events leave the boundary of the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool LeaveRequired { get { return (bool)GetValue(LeaveRequiredProperty); } set { SetValue(LeaveRequiredProperty, value); } } /// <summary> /// Gets or sets the status of whether a child view inherits it's parent's orientation. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool InheritOrientation { get { return (bool)GetValue(InheritOrientationProperty); } set { SetValue(InheritOrientationProperty, value); } } /// <summary> /// Gets or sets the status of whether a child view inherits it's parent's scale. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool InheritScale { get { return (bool)GetValue(InheritScaleProperty); } set { SetValue(InheritScaleProperty, value); } } /// <summary> /// Gets or sets the status of how the view and its children should be drawn.<br /> /// Not all views are renderable, but DrawMode can be inherited from any view.<br /> /// If an object is in a 3D layer, it will be depth-tested against other objects in the world, i.e., it may be obscured if other objects are in front.<br /> /// If DrawMode.Overlay2D is used, the view and its children will be drawn as a 2D overlay.<br /> /// Overlay views are drawn in a separate pass, after all non-overlay views within the layer.<br /> /// For overlay views, the drawing order is with respect to tree levels of views, and depth-testing will not be used.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public DrawModeType DrawMode { get { return (DrawModeType)GetValue(DrawModeProperty); } set { SetValue(DrawModeProperty, value); } } /// <summary> /// Gets or sets the relative to parent size factor of the view.<br /> /// This factor is only used when ResizePolicyType is set to either: ResizePolicyType.SizeRelativeToParent or ResizePolicyType.SizeFixedOffsetFromParent.<br /> /// This view's size is set to the view's size multiplied by or added to this factor, depending on ResizePolicyType.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector3 SizeModeFactor { get { return (Vector3)GetValue(SizeModeFactorProperty); } set { SetValue(SizeModeFactorProperty, value); } } /// <summary> /// Gets or sets the width resize policy to be used. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ResizePolicyType WidthResizePolicy { get { return (ResizePolicyType)GetValue(WidthResizePolicyProperty); } set { SetValue(WidthResizePolicyProperty, value); } } /// <summary> /// Gets or sets the height resize policy to be used. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ResizePolicyType HeightResizePolicy { get { return (ResizePolicyType)GetValue(HeightResizePolicyProperty); } set { SetValue(HeightResizePolicyProperty, value); } } /// <summary> /// Gets or sets the policy to use when setting size with size negotiation.<br /> /// Defaults to SizeScalePolicyType.UseSizeSet.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public SizeScalePolicyType SizeScalePolicy { get { return (SizeScalePolicyType)GetValue(SizeScalePolicyProperty); } set { SetValue(SizeScalePolicyProperty, value); } } /// <summary> /// Gets or sets the status of whether the width size is dependent on the height size. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool WidthForHeight { get { return (bool)GetValue(WidthForHeightProperty); } set { SetValue(WidthForHeightProperty, value); } } /// <summary> /// Gets or sets the status of whether the height size is dependent on the width size. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool HeightForWidth { get { return (bool)GetValue(HeightForWidthProperty); } set { SetValue(HeightForWidthProperty, value); } } /// <summary> /// Gets or sets the padding for use in layout. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Extents Padding { get { return (Extents)GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } /// <summary> /// Gets or sets the minimum size the view can be assigned in size negotiation. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Size2D MinimumSize { get { return (Size2D)GetValue(MinimumSizeProperty); } set { SetValue(MinimumSizeProperty, value); } } /// <summary> /// Gets or sets the maximum size the view can be assigned in size negotiation. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Size2D MaximumSize { get { return (Size2D)GetValue(MaximumSizeProperty); } set { // We don't have Layout.Maximum(Width|Height) so we cannot apply it to layout. // MATCH_PARENT spec + parent container size can be used to limit SetValue(MaximumSizeProperty, value); } } /// <summary> /// Gets or sets whether a child view inherits it's parent's position.<br /> /// Default is to inherit.<br /> /// Switching this off means that using position sets the view's world position, i.e., translates from the world origin (0,0,0) to the pivot point of the view.<br /> /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool InheritPosition { get { return (bool)GetValue(InheritPositionProperty); } set { SetValue(InheritPositionProperty, value); } } /// <summary> /// Gets or sets the clipping behavior (mode) of it's children. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ClippingModeType ClippingMode { get { return (ClippingModeType)GetValue(ClippingModeProperty); } set { SetValue(ClippingModeProperty, value); } } /// <summary> /// Gets the number of renderers held by the view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public uint RendererCount { get { return view.RendererCount; } } /// <summary> /// [Obsolete("Please do not use! this will be deprecated")] /// </summary> /// <since_tizen> 6 </since_tizen> /// Please do not use! this will be deprecated! /// Instead please use PivotPoint. /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [Obsolete("Please do not use! This will be deprecated! Please use PivotPoint instead! " + "Like: " + "View view = new View(); " + "view.PivotPoint = PivotPoint.Center; " + "view.PositionUsesPivotPoint = true;")] [EditorBrowsable(EditorBrowsableState.Never)] public Position AnchorPoint { get { return view.AnchorPoint; } set { view.AnchorPoint = value; } } /// <summary> /// Sets the size of a view for the width, the height and the depth.<br /> /// Geometry can be scaled to fit within this area.<br /> /// This does not interfere with the view's scale factor.<br /> /// The views default depth is the minimum of width and height.<br /> /// </summary> /// <remarks> /// Please note that multi-cascade setting is not possible for this NUI object. <br /> /// It is recommended that NUI object typed properties are configured by their constructor with parameters. <br /> /// For example, this code is working fine : view.Size = new Size( 1.0f, 1.0f, 0.0f); <br /> /// but this will not work! : view.Size.Width = 2.0f; view.Size.Height = 2.0f; <br /> /// It may not match the current value in some cases, i.e. when the animation is progressing or the maximum or minimu size is set. <br /> /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Size Size { get { return (Size)GetValue(SizeProperty); } set { SetValue(SizeProperty, value); } } /// <summary> /// "Please DO NOT use! This will be deprecated! Please use 'Container GetParent() for derived class' instead!" /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [Obsolete("Please do not use! This will be deprecated! Please use 'Container GetParent() for derived class' instead! " + "Like: " + "Container parent = view.GetParent(); " + "View view = parent as View;")] [EditorBrowsable(EditorBrowsableState.Never)] public new View Parent { get { return BaseHandle.GetHandle(view.Parent) as View; } } /// <summary> /// Gets/Sets whether inherit parent's the layout Direction. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool InheritLayoutDirection { get { return (bool)GetValue(InheritLayoutDirectionProperty); } set { SetValue(InheritLayoutDirectionProperty, value); } } /// <summary> /// Gets/Sets the layout Direction. /// </summary> /// <since_tizen> 6 </since_tizen> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Tizen.NUI.BaseComponents.ViewLayoutDirectionType LayoutDirection { get { return (Tizen.NUI.BaseComponents.ViewLayoutDirectionType)GetValue(LayoutDirectionProperty); } set { SetValue(LayoutDirectionProperty, value); } } /// <summary> /// Gets or sets the Margin for use in layout. /// </summary> /// <remarks> /// Margin property is supported by Layout algorithms and containers. /// Please Set Layout if you want to use Margin property. /// </remarks> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Extents Margin { get { return (Extents)GetValue(MarginProperty); } set { SetValue(MarginProperty, value); } } private MergedStyle _mergedStyle = null; internal MergedStyle mergedStyle { get { if (_mergedStyle == null) { _mergedStyle = new MergedStyle(GetType(), this); } return _mergedStyle; } } /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Style Style { get { return (Style)GetValue(StyleProperty); } set { SetValue(StyleProperty, value); } } /// <summary> /// [Obsolete("Please do not use! this will be deprecated")] /// </summary> /// Please do not use! this will be deprecated! /// Instead please use Padding. /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [Obsolete("Please do not use! this will be deprecated, instead please use Padding.")] [EditorBrowsable(EditorBrowsableState.Never)] public Extents PaddingEX { get { return view.PaddingEX; } set { view.PaddingEX = value; } } /// <summary> /// Perform an action on a visual registered to this view. <br /> /// Visuals will have actions. This API is used to perform one of these actions with the given attributes. /// </summary> /// <param name="propertyIndexOfVisual">The Property index of the visual.</param> /// <param name="propertyIndexOfActionId">The action to perform. See Visual to find the supported actions.</param> /// <param name="attributes">Optional attributes for the action.</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void DoAction(int propertyIndexOfVisual, int propertyIndexOfActionId, PropertyValue attributes) { view.DoAction(propertyIndexOfVisual, propertyIndexOfActionId, attributes); } } }
41.79143
260
0.579867
[ "Apache-2.0" ]
sungraejo/TizenFX
src/Tizen.NUI.Xaml/src/public/Forms/BaseComponents/View.cs
132,646
C#
namespace SmartHunter.Game.Data { public enum WeaponType { NO_WEAPON, WEAPON_UNKNOWN, BOW, CHARGE_BLADE, GUNLANCE, HAMMER, HEAVY_BOWGUN, HUNTING_HORN, LANCE, LIGHT_BOWGUN, INSECT_GLAIVE, KINSECT, SWORD_AND_SHIELD, SWITCH_AXE, DUAL_BLADES, LONG_SWORD, GREAT_SWORD, SLINGER } }
17.28
31
0.523148
[ "MIT" ]
psjpark/SmartHunter
SmartHunter/Game/Data/WeaponType.cs
432
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { class SetPSSARulesRequest { public static readonly RequestType<object, object> Type = RequestType<object, object>.Create("powerShell/setPSSARules"); } }
29.235294
101
0.732394
[ "MIT" ]
stefb965/PowerShellEditorServices
src/PowerShellEditorServices.Protocol/LanguageServer/SetPSSARulesRequest.cs
499
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.MSHTMLApi { /// <summary> /// DispatchInterface DispHTCDefaultDispatch /// SupportByVersion MSHTML, 4 /// </summary> [SupportByVersion("MSHTML", 4)] [EntityType(EntityType.IsDispatchInterface), BaseType] public class DispHTCDefaultDispatch : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(DispHTCDefaultDispatch); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public DispHTCDefaultDispatch(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public DispHTCDefaultDispatch(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DispHTCDefaultDispatch(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DispHTCDefaultDispatch(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DispHTCDefaultDispatch(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DispHTCDefaultDispatch(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DispHTCDefaultDispatch() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DispHTCDefaultDispatch(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] public NetOffice.MSHTMLApi.IHTMLElement element { get { return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLElement>(this, "element"); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] public object defaults { get { return Factory.ExecuteReferencePropertyGet(this, "defaults"); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("MSHTML", 4), ProxyResult] public object document { get { return Factory.ExecuteReferencePropertyGet(this, "document"); } } #endregion #region Methods /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersion("MSHTML", 4)] [BaseResult] public NetOffice.MSHTMLApi.IHTMLEventObj CreateEventObject() { return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLEventObj>(this, "CreateEventObject"); } #endregion #pragma warning restore } }
28.97076
177
0.698022
[ "MIT" ]
DominikPalo/NetOffice
Source/MSHTML/DispatchInterfaces/DispHTCDefaultDispatch.cs
4,954
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BackEndObjects; using ActionLibrary; using System.Collections; using System.Data; namespace OnLine.Pages.Popups.Contacts { public partial class AllDealsWithContact : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { fillIncomingInvGrid(null); fillOutoingInvGrid(null); } } protected void fillIncomingInvGrid(ArrayList invList) { String[] contactEntId = Request.QueryString.GetValues("contactId"); if(invList==null || invList.Count==0) invList = BackEndObjects.Invoice.getAllInvoicesbyEntId(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString()); DataTable dt = new DataTable(); dt.Columns.Add("rfqId"); dt.Columns.Add("InvId"); dt.Columns.Add("InvNo"); dt.Columns.Add("totalAmnt"); dt.Columns.Add("InvDate"); dt.Columns.Add("pmntStat"); dt.Columns.Add("totalPending"); DateUtility dU = new DateUtility(); int rowCount = 0; for (int i = 0; i < invList.Count; i++) { BackEndObjects.Invoice invObj = (BackEndObjects.Invoice)invList[i]; if (invObj.getRespEntityId().Equals(contactEntId[0])) { float totalPendingAmnt = 0; float totalClearedAmnt = 0; Dictionary<String, Payment> pmntDict = BackEndObjects.Payment.getPaymentDetailsforInvoiceDB(invObj.getInvoiceId()); foreach (KeyValuePair<String, Payment> kvp in pmntDict) { BackEndObjects.Payment pmntObj = kvp.Value; totalClearedAmnt += pmntObj.getClearingStat().Equals(BackEndObjects.Payment.PAYMENT_CLEARING_STAT_CLEAR) ? pmntObj.getAmount() : 0; } totalPendingAmnt = invObj.getTotalAmount() - totalClearedAmnt; dt.Rows.Add(); dt.Rows[rowCount]["rfqId"] = invObj.getRFQId(); dt.Rows[rowCount]["InvId"] = invObj.getInvoiceId(); dt.Rows[rowCount]["InvNo"] = invObj.getInvoiceNo() != null && !invObj.getInvoiceNo().Equals("") ? invObj.getInvoiceNo() : invObj.getInvoiceId(); dt.Rows[rowCount]["totalAmnt"] = invObj.getTotalAmount(); dt.Rows[rowCount]["InvDate"] =dU.getConvertedDate(invObj.getInvoiceDate().Substring(0,invObj.getInvoiceDate().IndexOf(" "))); dt.Rows[rowCount]["pmntStat"] = invObj.getPaymentStatus(); dt.Rows[rowCount]["totalPending"] = totalPendingAmnt; rowCount++; } } GridView_Incoming_Invoices.Visible = true; GridView_Incoming_Invoices.DataSource = dt; GridView_Incoming_Invoices.DataBind(); GridView_Incoming_Invoices.SelectedIndex = -1; Session[SessionFactory.ALL_CONTACT_ALL_DEAL_INCOMING_INV_GRID] = dt; Session[SessionFactory.ALL_CONTACT_ALL_DEAL_INCOMING_INV_ARRAYLIST] = invList; } protected void fillOutoingInvGrid(ArrayList invList) { String[] contactEntId = Request.QueryString.GetValues("contactId"); if(invList==null || invList.Count==0) invList = BackEndObjects.Invoice.getAllInvoicesbyRespEntId(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString()); DataTable dt = new DataTable(); dt.Columns.Add("rfqId"); dt.Columns.Add("InvId"); dt.Columns.Add("InvNo"); dt.Columns.Add("totalAmnt"); dt.Columns.Add("InvDate"); dt.Columns.Add("pmntStat"); dt.Columns.Add("totalPending"); DateUtility dU = new DateUtility(); int counter = 0; for (int i = 0; i < invList.Count; i++) { BackEndObjects.Invoice invObj = (BackEndObjects.Invoice)invList[i]; //Filter out invoices whicha re meant for this contact only BackEndObjects.RFQDetails rfqObj=BackEndObjects.RFQDetails.getRFQDetailsbyIdDB(invObj.getRFQId()); if (rfqObj != null && rfqObj.getEntityId() != null && rfqObj.getEntityId().Equals(contactEntId[0])) { float totalPendingAmnt = 0; float totalClearedAmnt = 0; Dictionary<String, Payment> pmntDict = BackEndObjects.Payment.getPaymentDetailsforInvoiceDB(invObj.getInvoiceId()); foreach (KeyValuePair<String, Payment> kvp in pmntDict) { BackEndObjects.Payment pmntObj = kvp.Value; totalClearedAmnt += pmntObj.getClearingStat().Equals(BackEndObjects.Payment.PAYMENT_CLEARING_STAT_CLEAR) ? pmntObj.getAmount() : 0; } totalPendingAmnt = invObj.getTotalAmount() - totalClearedAmnt; dt.Rows.Add(); dt.Rows[counter]["rfqId"] = invObj.getRFQId(); dt.Rows[counter]["InvId"] = invObj.getInvoiceId(); dt.Rows[counter]["InvNo"] = invObj.getInvoiceNo() != null && !invObj.getInvoiceNo().Equals("") ? invObj.getInvoiceNo() : invObj.getInvoiceId(); dt.Rows[counter]["totalAmnt"] = invObj.getTotalAmount(); dt.Rows[counter]["InvDate"] =dU.getConvertedDate(invObj.getInvoiceDate().Substring(0,invObj.getInvoiceDate().IndexOf(" "))); dt.Rows[counter]["pmntStat"] = invObj.getPaymentStatus(); dt.Rows[counter]["totalPending"] = totalPendingAmnt; counter++; } } GridView_Outgoing_Invoices.Visible = true; GridView_Outgoing_Invoices.DataSource = dt; GridView_Outgoing_Invoices.DataBind(); GridView_Outgoing_Invoices.SelectedIndex = -1; Session[SessionFactory.ALL_CONTACT_ALL_DEAL_OUTGOING_INV_GRID] = dt; Session[SessionFactory.ALL_CONTACT_ALL_DEAL_OUTGOING_INV_ARRAYLIST] = invList; } protected void Button_Filter_Incom_Invoice_Click(object sender, EventArgs e) { String invNo = TextBox_Inv_No.Text; String fromDate = TextBox_From_Date.Text; String toDate = TextBox_To_Date.Text; ActionLibrary.PurchaseActions._dispInvoiceDetails dInv = new ActionLibrary.PurchaseActions._dispInvoiceDetails(); Dictionary<String, String> filterParams = new Dictionary<string, string>(); if (invNo != null && !invNo.Equals("")) filterParams.Add(dInv.FILTER_BY_INVOICE_NO, invNo); if (fromDate != null && !fromDate.Equals("")) filterParams.Add(dInv.FILTER_BY_FROM_DATE, fromDate); if (toDate != null && !toDate.Equals("")) filterParams.Add(dInv.FILTER_BY_TO_DATE, toDate); if (filterParams.Count > 0) fillIncomingInvGrid(dInv.getAllInvDetailsFiltered(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString(), (ArrayList)Session[SessionFactory.ALL_CONTACT_ALL_DEAL_INCOMING_INV_ARRAYLIST], filterParams)); else fillIncomingInvGrid(null); } protected void GridView_Incoming_Invoices_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView_Incoming_Invoices.PageIndex = e.NewPageIndex; GridView_Incoming_Invoices.DataSource = (DataTable)Session[SessionFactory.ALL_CONTACT_ALL_DEAL_INCOMING_INV_GRID]; GridView_Incoming_Invoices.DataBind(); } protected void GridView_Outgoing_Invoices_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView_Outgoing_Invoices.PageIndex = e.NewPageIndex; GridView_Outgoing_Invoices.DataSource = (DataTable)Session[SessionFactory.ALL_CONTACT_ALL_DEAL_OUTGOING_INV_GRID]; GridView_Outgoing_Invoices.DataBind(); } protected void LinkButton_Invoice_Id_No_Incoming_Command(object sender, CommandEventArgs e) { LinkButton linkb = (LinkButton)sender; GridViewRow row = (GridViewRow)linkb.NamingContainer; if (row != null && row.RowIndex != -1 && row.RowIndex != GridView_Incoming_Invoices.SelectedIndex) GridView_Incoming_Invoices.SelectRow(row.RowIndex); ((RadioButton)GridView_Incoming_Invoices.SelectedRow.Cells[0].FindControl("deals_radio")).Checked = true; String forwardString = "/Pages/Popups/Sale/Inv_Details.aspx"; String invId=((Label)GridView_Incoming_Invoices.SelectedRow.Cells[0].FindControl("Label_Inv_Id_Hidden")).Text; String rfqId=((Label)GridView_Incoming_Invoices.SelectedRow.Cells[0].FindControl("Label_rfq_Id_Hidden")).Text; String poId=BackEndObjects.PurchaseOrder.getPurchaseOrderforRFQIdDB(rfqId).getPo_id(); forwardString += "?rfId=" + rfqId; forwardString += "&context=" + "clientInvoiceGrid"; forwardString += "&poId=" + poId; forwardString += "&invId=" + invId; ScriptManager.RegisterStartupScript(this, typeof(string), "DispInvforContactIncoming", "window.open('" + forwardString + "',null,'resizeable=yes,scrollbars=yes,addressbar=no,toolbar=no,width=1000,Height=900');", true); } protected void LinkButton_Invoice_Id_No_Outgoing_Command(object sender, CommandEventArgs e) { LinkButton linkb = (LinkButton)sender; GridViewRow row = (GridViewRow)linkb.NamingContainer; if (row != null && row.RowIndex != -1 && row.RowIndex != GridView_Outgoing_Invoices.SelectedIndex) GridView_Outgoing_Invoices.SelectRow(row.RowIndex); ((RadioButton)GridView_Outgoing_Invoices.SelectedRow.Cells[0].FindControl("deals_radio_outg")).Checked = true; String forwardString = "/Pages/Popups/Sale/Inv_Details.aspx"; String invId = ((Label)GridView_Outgoing_Invoices.SelectedRow.Cells[0].FindControl("Label_Inv_Id_Hidden")).Text; String rfqId = ((Label)GridView_Outgoing_Invoices.SelectedRow.Cells[0].FindControl("Label_rfq_Id_Hidden")).Text; String poId = BackEndObjects.PurchaseOrder.getPurchaseOrderforRFQIdDB(rfqId).getPo_id(); forwardString += "?rfId=" + rfqId; forwardString += "&context=" + "vendInvoiceGrid"; forwardString += "&poId=" + poId; forwardString += "&invId=" + invId; ScriptManager.RegisterStartupScript(this, typeof(string), "DispInvforContactOutgoing", "window.open('" + forwardString + "',null,'resizeable=yes,scrollbars=yes,addressbar=no,toolbar=no,width=1000,Height=900');", true); } protected void LinkButton_Pmnt_Det_Incoming_Click(object sender, EventArgs e) { LinkButton linkb = (LinkButton)sender; GridViewRow row = (GridViewRow)linkb.NamingContainer; if (row != null && row.RowIndex != -1 && row.RowIndex != GridView_Incoming_Invoices.SelectedIndex) GridView_Incoming_Invoices.SelectRow(row.RowIndex); ((RadioButton)GridView_Incoming_Invoices.SelectedRow.Cells[0].FindControl("deals_radio")).Checked = true; String forwardString = "/Pages/Popups/Purchase/Inv_Payment_Details.aspx"; forwardString += "?rfId=" + ((Label)GridView_Incoming_Invoices.SelectedRow.Cells[0].FindControl("Label_rfq_Id_Hidden")).Text; forwardString += "&context=" + "client"; forwardString += "&invId=" + ((Label)GridView_Incoming_Invoices.SelectedRow.Cells[0].FindControl("Label_Inv_Id_Hidden")).Text; forwardString += "&invNo=" + ((LinkButton)GridView_Incoming_Invoices.SelectedRow.Cells[0].FindControl("LinkButton_Invoice_Id_No_Incoming")).Text; ScriptManager.RegisterStartupScript(this, typeof(string), "DispInvPmntContactDealsIncoming", "window.open('" + forwardString + "',null,'resizeable=yes,scrollbars=yes,addressbar=no,toolbar=no,width=900,Height=700');", true); } protected void LinkButton_Pmnt_Det_Outgoing_Command(object sender, CommandEventArgs e) { LinkButton linkb = (LinkButton)sender; GridViewRow row = (GridViewRow)linkb.NamingContainer; if (row != null && row.RowIndex != -1 && row.RowIndex != GridView_Outgoing_Invoices.SelectedIndex) GridView_Outgoing_Invoices.SelectRow(row.RowIndex); ((RadioButton)GridView_Outgoing_Invoices.SelectedRow.Cells[0].FindControl("deals_radio_outg")).Checked = true; String forwardString = "/Pages/Popups/Purchase/Inv_Payment_Details.aspx"; forwardString += "?rfId=" + ((Label)GridView_Outgoing_Invoices.SelectedRow.Cells[0].FindControl("Label_rfq_Id_Hidden")).Text; forwardString += "&context=" + "vendor"; forwardString += "&invId=" + ((Label)GridView_Outgoing_Invoices.SelectedRow.Cells[0].FindControl("Label_Inv_Id_Hidden")).Text; forwardString += "&invNo=" + ((LinkButton)GridView_Outgoing_Invoices.SelectedRow.Cells[0].FindControl("LinkButton_Invoice_Id_No_Outgoing")).Text; ScriptManager.RegisterStartupScript(this, typeof(string), "DispInvPmntContactDealsOutgoing", "window.open('" + forwardString + "',null,'resizeable=yes,scrollbars=yes,addressbar=no,toolbar=no,width=900,Height=700');", true); } protected void Button_Filter_Outgoing_Invoice_Click(object sender, EventArgs e) { String invNo = TextBox_Inv_No_Outgoing.Text; String fromDate = TextBox_From_Date_Outgoing.Text; String toDate = TextBox_To_Date_Outgoing.Text; ActionLibrary.PurchaseActions._dispInvoiceDetails dInv = new ActionLibrary.PurchaseActions._dispInvoiceDetails(); Dictionary<String, String> filterParams = new Dictionary<string, string>(); if (invNo != null && !invNo.Equals("")) filterParams.Add(dInv.FILTER_BY_INVOICE_NO, invNo); if (fromDate != null && !fromDate.Equals("")) filterParams.Add(dInv.FILTER_BY_FROM_DATE, fromDate); if (toDate != null && !toDate.Equals("")) filterParams.Add(dInv.FILTER_BY_TO_DATE, toDate); if (filterParams.Count > 0) fillOutoingInvGrid(dInv.getAllInvDetailsFiltered(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString(), (ArrayList)Session[SessionFactory.ALL_CONTACT_ALL_DEAL_OUTGOING_INV_ARRAYLIST], filterParams)); else fillOutoingInvGrid(null); } protected void GridView_Incoming_Invoices_RadioSelect(object sender, EventArgs e) { RadioButton linkb = (RadioButton)sender; GridViewRow row = (GridViewRow)linkb.NamingContainer; if (row != null && row.RowIndex != -1) GridView_Incoming_Invoices.SelectRow(row.RowIndex); } protected void GridView_Incoming_Invoices_SelectedIndexChanged(object sender, EventArgs e) { ((RadioButton)GridView_Incoming_Invoices.SelectedRow.Cells[0].FindControl("deals_radio")).Checked = true; } protected void GridView_Outgoing_Invoices_RadioSelect(object sender, EventArgs e) { RadioButton linkb = (RadioButton)sender; GridViewRow row = (GridViewRow)linkb.NamingContainer; if (row != null && row.RowIndex != -1) GridView_Outgoing_Invoices.SelectRow(row.RowIndex); } protected void GridView_Outgoing_Invoices_SelectedIndexChanged(object sender, EventArgs e) { ((RadioButton)GridView_Outgoing_Invoices.SelectedRow.Cells[0].FindControl("deals_radio_outg")).Checked = true; } } }
51.487421
235
0.639162
[ "Apache-2.0" ]
shibathethinker/ChimeraCRM
OnLine/OnLine/Pages/Popups/Contacts/AllDealsWithContact.aspx.cs
16,375
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxNodeExtensions { public static bool IsKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result) where TNode : SyntaxNode { if (node.IsKind(kind)) { result = (TNode)node; return true; } result = null; return false; } public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind) => CodeAnalysis.CSharpExtensions.IsKind(node?.Parent, kind); public static bool IsParentKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result) where TNode : SyntaxNode { if (node.IsParentKind(kind)) { result = (TNode)node.Parent!; return true; } result = null; return false; } public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2) => IsKind(node?.Parent, kind1, kind2); public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) => IsKind(node?.Parent, kind1, kind2, kind3); public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) => IsKind(node?.Parent, kind1, kind2, kind3, kind4); public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10, SyntaxKind kind11) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10 || csharpKind == kind11; } public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken( this SyntaxNode node, SourceText? sourceText = null, bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false) => node.GetFirstToken().GetAllPrecedingTriviaToPreviousToken( sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine); /// <summary> /// Returns all of the trivia to the left of this token up to the previous token (concatenates /// the previous token's trailing trivia and this token's leading trivia). /// </summary> public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken( this SyntaxToken token, SourceText? sourceText = null, bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false) { var prevToken = token.GetPreviousToken(includeSkipped: true); if (prevToken.Kind() == SyntaxKind.None) { return token.LeadingTrivia; } Contract.ThrowIfTrue(sourceText == null && includePreviousTokenTrailingTriviaOnlyIfOnSameLine, "If we are including previous token trailing trivia, we need the text too."); if (includePreviousTokenTrailingTriviaOnlyIfOnSameLine && !sourceText!.AreOnSameLine(prevToken, token)) { return token.LeadingTrivia; } return prevToken.TrailingTrivia.Concat(token.LeadingTrivia); } public static bool IsAnyArgumentList([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node.IsKind(SyntaxKind.ArgumentList) || node.IsKind(SyntaxKind.AttributeArgumentList) || node.IsKind(SyntaxKind.BracketedArgumentList) || node.IsKind(SyntaxKind.TypeArgumentList); } public static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBraces(this SyntaxNode? node) { switch (node) { case NamespaceDeclarationSyntax namespaceNode: return (namespaceNode.OpenBraceToken, namespaceNode.CloseBraceToken); case BaseTypeDeclarationSyntax baseTypeNode: return (baseTypeNode.OpenBraceToken, baseTypeNode.CloseBraceToken); case AccessorListSyntax accessorListNode: return (accessorListNode.OpenBraceToken, accessorListNode.CloseBraceToken); case BlockSyntax blockNode: return (blockNode.OpenBraceToken, blockNode.CloseBraceToken); case SwitchStatementSyntax switchStatementNode: return (switchStatementNode.OpenBraceToken, switchStatementNode.CloseBraceToken); case AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpression: return (anonymousObjectCreationExpression.OpenBraceToken, anonymousObjectCreationExpression.CloseBraceToken); case InitializerExpressionSyntax initializeExpressionNode: return (initializeExpressionNode.OpenBraceToken, initializeExpressionNode.CloseBraceToken); case SwitchExpressionSyntax switchExpression: return (switchExpression.OpenBraceToken, switchExpression.CloseBraceToken); case PropertyPatternClauseSyntax property: return (property.OpenBraceToken, property.CloseBraceToken); case WithExpressionSyntax withExpr: return (withExpr.Initializer.OpenBraceToken, withExpr.Initializer.CloseBraceToken); case ImplicitObjectCreationExpressionSyntax { Initializer: { } initializer }: return (initializer.OpenBraceToken, initializer.CloseBraceToken); } return default; } public static bool IsEmbeddedStatementOwner([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node is DoStatementSyntax || node is ElseClauseSyntax || node is FixedStatementSyntax || node is CommonForEachStatementSyntax || node is ForStatementSyntax || node is IfStatementSyntax || node is LabeledStatementSyntax || node is LockStatementSyntax || node is UsingStatementSyntax || node is WhileStatementSyntax; } public static StatementSyntax? GetEmbeddedStatement(this SyntaxNode? node) => node switch { DoStatementSyntax n => n.Statement, ElseClauseSyntax n => n.Statement, FixedStatementSyntax n => n.Statement, CommonForEachStatementSyntax n => n.Statement, ForStatementSyntax n => n.Statement, IfStatementSyntax n => n.Statement, LabeledStatementSyntax n => n.Statement, LockStatementSyntax n => n.Statement, UsingStatementSyntax n => n.Statement, WhileStatementSyntax n => n.Statement, _ => null, }; public static BaseParameterListSyntax? GetParameterList(this SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).ParameterList, SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).ParameterList, SyntaxKind.OperatorDeclaration => ((OperatorDeclarationSyntax)declaration).ParameterList, SyntaxKind.ConversionOperatorDeclaration => ((ConversionOperatorDeclarationSyntax)declaration).ParameterList, SyntaxKind.ConstructorDeclaration => ((ConstructorDeclarationSyntax)declaration).ParameterList, SyntaxKind.DestructorDeclaration => ((DestructorDeclarationSyntax)declaration).ParameterList, SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ParameterList, SyntaxKind.ParenthesizedLambdaExpression => ((ParenthesizedLambdaExpressionSyntax)declaration).ParameterList, SyntaxKind.LocalFunctionStatement => ((LocalFunctionStatementSyntax)declaration).ParameterList, SyntaxKind.AnonymousMethodExpression => ((AnonymousMethodExpressionSyntax)declaration).ParameterList, _ => null, }; public static SyntaxList<AttributeListSyntax> GetAttributeLists(this SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists, AccessorDeclarationSyntax accessor => accessor.AttributeLists, ParameterSyntax parameter => parameter.AttributeLists, CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists, _ => default, }; public static ConditionalAccessExpressionSyntax? GetParentConditionalAccessExpression(this SyntaxNode? node) { // Walk upwards based on the grammar/parser rules around ?. expressions (can be seen in // LanguageParser.ParseConsequenceSyntax). // These are the parts of the expression that the ?... expression can end with. Specifically: // // 1. x?.y.M() // invocation // 2. x?.y[...]; // element access // 3. x?.y.z // member access // 4. x?.y // member binding // 5. x?[y] // element binding var current = node; if ((current.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == current) || (current.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == current)) { current = current.Parent; } // Effectively, if we're on the RHS of the ? we have to walk up the RHS spine first until we hit the first // conditional access. while (current.IsKind( SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.MemberBindingExpression, SyntaxKind.ElementBindingExpression) && current.Parent is not ConditionalAccessExpressionSyntax) { current = current.Parent; } // Two cases we have to care about: // // 1. a?.b.$$c.d and // 2. a?.b.$$c.d?.e... // // Note that `a?.b.$$c.d?.e.f?.g.h.i` falls into the same bucket as two. i.e. the parts after `.e` are // lower in the tree and are not seen as we walk upwards. // // // To get the root ?. (the one after the `a`) we have to potentially consume the first ?. on the RHS of the // right spine (i.e. the one after `d`). Once we do this, we then see if that itself is on the RHS of a // another conditional, and if so we hten return the one on the left. i.e. for '2' this goes in this direction: // // a?.b.$$c.d?.e // it will do: // -----> // <--------- // // Note that this only one CAE consumption on both sides. GetRootConditionalAccessExpression can be used to // get the root parent in a case like: // // x?.y?.z?.a?.b.$$c.d?.e.f?.g.h.i // it will do: // -----> // <--------- // <--- // <--- // <--- if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) && conditional.Expression == current) { current = conditional; } if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out conditional) && conditional.WhenNotNull == current) { current = conditional; } return current as ConditionalAccessExpressionSyntax; } /// <summary> /// <inheritdoc cref="ISyntaxFacts.GetRootConditionalAccessExpression(SyntaxNode)"/> /// </summary>> public static ConditionalAccessExpressionSyntax? GetRootConditionalAccessExpression(this SyntaxNode? node) { // Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at // the root. For example, if we have `a?.b` and we're on the `.b`, this will give `a?.b`. Similarly with // `a?.b?.c` if we're on either `.b` or `.c` this will result in `a?.b?.c` (i.e. the root of this CAE // sequence). var current = node.GetParentConditionalAccessExpression(); while (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) && conditional.WhenNotNull == current) { current = conditional; } return current; } public static ConditionalAccessExpressionSyntax? GetInnerMostConditionalAccessExpression(this SyntaxNode node) { if (!(node is ConditionalAccessExpressionSyntax)) { return null; } var result = (ConditionalAccessExpressionSyntax)node; while (result.WhenNotNull is ConditionalAccessExpressionSyntax) { result = (ConditionalAccessExpressionSyntax)result.WhenNotNull; } return result; } public static bool IsAsyncSupportingFunctionSyntax([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node.IsKind(SyntaxKind.MethodDeclaration) || node.IsAnyLambdaOrAnonymousMethod() || node.IsKind(SyntaxKind.LocalFunctionStatement); } public static bool IsAnyLambda([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) || node.IsKind(SyntaxKind.SimpleLambdaExpression); } public static bool IsAnyLambdaOrAnonymousMethod([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node.IsAnyLambda() || node.IsKind(SyntaxKind.AnonymousMethodExpression); public static bool IsAnyAssignExpression(this SyntaxNode node) => SyntaxFacts.IsAssignmentExpression(node.Kind()); public static bool IsCompoundAssignExpression(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.CoalesceAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: return true; } return false; } public static bool IsLeftSideOfAssignExpression([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment) && assignment.Left == node; public static bool IsLeftSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node) { return node?.Parent != null && node.Parent.IsAnyAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Left == node; } public static bool IsRightSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node) { return node?.Parent != null && node.Parent.IsAnyAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Right == node; } public static bool IsLeftSideOfCompoundAssignExpression([NotNullWhen(true)] this SyntaxNode? node) { return node?.Parent != null && node.Parent.IsCompoundAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Left == node; } /// <summary> /// Returns the list of using directives that affect <paramref name="node"/>. The list will be returned in /// top down order. /// </summary> public static IEnumerable<UsingDirectiveSyntax> GetEnclosingUsingDirectives(this SyntaxNode node) { return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Usings .Concat(node.GetAncestorsOrThis<NamespaceDeclarationSyntax>() .Reverse() .SelectMany(n => n.Usings)); } public static IEnumerable<ExternAliasDirectiveSyntax> GetEnclosingExternAliasDirectives(this SyntaxNode node) { return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Externs .Concat(node.GetAncestorsOrThis<NamespaceDeclarationSyntax>() .Reverse() .SelectMany(n => n.Externs)); } public static bool IsUnsafeContext(this SyntaxNode node) { if (node.GetAncestor<UnsafeStatementSyntax>() != null) { return true; } return node.GetAncestors<MemberDeclarationSyntax>().Any( m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword)); } public static bool IsInStaticContext(this SyntaxNode node) { // this/base calls are always static. if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null) { return true; } var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>(); if (memberDeclaration == null) { return false; } switch (memberDeclaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword) || node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: // Inside a field one can only access static members of a type (unless it's top-level). return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit); case SyntaxKind.DestructorDeclaration: return false; } // Global statements are not a static context. if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null) { return false; } // any other location is considered static return true; } public static NamespaceDeclarationSyntax? GetInnermostNamespaceDeclarationWithUsings(this SyntaxNode contextNode) { var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>(); if (usingDirectiveAncestor == null) { return contextNode.GetAncestorsOrThis<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0); } else { // We are inside a using directive. In this case, we should find and return the first 'parent' namespace with usings. var containingNamespace = usingDirectiveAncestor.GetAncestor<NamespaceDeclarationSyntax>(); if (containingNamespace == null) { // We are inside a top level using directive (i.e. one that's directly in the compilation unit). return null; } else { return containingNamespace.GetAncestors<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0); } } } public static bool IsBreakableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return true; } return false; } public static bool IsContinuableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return true; } return false; } public static bool IsReturnableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.LocalFunctionStatement: case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; } return false; } public static bool SpansPreprocessorDirective<TSyntaxNode>(this IEnumerable<TSyntaxNode> list) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.SpansPreprocessorDirective(list); [return: NotNullIfNotNull("node")] public static TNode? ConvertToSingleLine<TNode>(this TNode? node, bool useElasticTrivia = false) where TNode : SyntaxNode { if (node == null) { return node; } var rewriter = new SingleLineRewriter(useElasticTrivia); return (TNode)rewriter.Visit(node); } /// <summary> /// Returns true if the passed in node contains an interleaved pp directive. /// /// i.e. The following returns false: /// /// void Goo() { /// #if true /// #endif /// } /// /// #if true /// void Goo() { /// } /// #endif /// /// but these return true: /// /// #if true /// void Goo() { /// #endif /// } /// /// void Goo() { /// #if true /// } /// #endif /// /// #if true /// void Goo() { /// #else /// } /// #endif /// /// i.e. the method returns true if it contains a PP directive that belongs to a grouping /// constructs (like #if/#endif or #region/#endregion), but the grouping construct isn't /// entirely contained within the span of the node. /// </summary> public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, CancellationToken cancellationToken) => CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(syntaxNode, cancellationToken); /// <summary> /// Similar to <see cref="ContainsInterleavedDirective(SyntaxNode, CancellationToken)"/> except that the span to check /// for interleaved directives can be specified separately to the node passed in. /// </summary> public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, TextSpan span, CancellationToken cancellationToken) => CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(span, syntaxNode, cancellationToken); public static bool ContainsInterleavedDirective( this SyntaxToken token, TextSpan textSpan, CancellationToken cancellationToken) { return ContainsInterleavedDirective(textSpan, token.LeadingTrivia, cancellationToken) || ContainsInterleavedDirective(textSpan, token.TrailingTrivia, cancellationToken); } private static bool ContainsInterleavedDirective( TextSpan textSpan, SyntaxTriviaList list, CancellationToken cancellationToken) { foreach (var trivia in list) { if (textSpan.Contains(trivia.Span)) { if (ContainsInterleavedDirective(textSpan, trivia, cancellationToken)) { return true; } } } return false; } private static bool ContainsInterleavedDirective( TextSpan textSpan, SyntaxTrivia trivia, CancellationToken cancellationToken) { if (trivia.HasStructure) { var structure = trivia.GetStructure()!; if (trivia.GetStructure().IsKind(SyntaxKind.RegionDirectiveTrivia, SyntaxKind.EndRegionDirectiveTrivia, SyntaxKind.IfDirectiveTrivia, SyntaxKind.EndIfDirectiveTrivia)) { var match = ((DirectiveTriviaSyntax)structure).GetMatchingDirective(cancellationToken); if (match != null) { var matchSpan = match.Span; if (!textSpan.Contains(matchSpan.Start)) { // The match for this pp directive is outside // this node. return true; } } } else if (trivia.GetStructure().IsKind(SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElifDirectiveTrivia)) { var directives = ((DirectiveTriviaSyntax)structure).GetMatchingConditionalDirectives(cancellationToken); if (directives != null && directives.Count > 0) { if (!textSpan.Contains(directives[0].SpanStart) || !textSpan.Contains(directives[directives.Count - 1].SpanStart)) { // This else/elif belongs to a pp span that isn't // entirely within this node. return true; } } } } return false; } /// <summary> /// Breaks up the list of provided nodes, based on how they are interspersed with pp /// directives, into groups. Within these groups nodes can be moved around safely, without /// breaking any pp constructs. /// </summary> public static IList<IList<TSyntaxNode>> SplitNodesOnPreprocessorBoundaries<TSyntaxNode>( this IEnumerable<TSyntaxNode> nodes, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var result = new List<IList<TSyntaxNode>>(); var currentGroup = new List<TSyntaxNode>(); foreach (var node in nodes) { var hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken); var hasLeadingDirective = node.GetLeadingTrivia().Any(t => SyntaxFacts.IsPreprocessorDirective(t.Kind())); if (hasUnmatchedInteriorDirective) { // we have a #if/#endif/#region/#endregion/#else/#elif in // this node that belongs to a span of pp directives that // is not entirely contained within the node. i.e.: // // void Goo() { // #if ... // } // // This node cannot be moved at all. It is in a group that // only contains itself (and thus can never be moved). // add whatever group we've built up to now. And reset the // next group to empty. result.Add(currentGroup); currentGroup = new List<TSyntaxNode>(); result.Add(new List<TSyntaxNode> { node }); } else if (hasLeadingDirective) { // We have a PP directive before us. i.e.: // // #if ... // void Goo() { // // That means we start a new group that is contained between // the above directive and the following directive. // add whatever group we've built up to now. And reset the // next group to empty. result.Add(currentGroup); currentGroup = new List<TSyntaxNode>(); currentGroup.Add(node); } else { // simple case. just add ourselves to the current group currentGroup.Add(node); } } // add the remainder of the final group. result.Add(currentGroup); // Now, filter out any empty groups. result = result.Where(group => !group.IsEmpty()).ToList(); return result; } public static ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetLeadingBlankLines(node); public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node); public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node, out strippedTrivia); public static ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetLeadingBannerAndPreprocessorDirectives(node); public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node); public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out strippedTrivia); public static bool IsVariableDeclaratorValue(this SyntaxNode node) => node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax? equalsValue) && equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) && equalsValue.Value == node; public static BlockSyntax? FindInnermostCommonBlock(this IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode<BlockSyntax>(); public static IEnumerable<SyntaxNode> GetAncestorsOrThis(this SyntaxNode? node, Func<SyntaxNode, bool> predicate) { var current = node; while (current != null) { if (predicate(current)) { yield return current; } current = current.Parent; } } /// <summary> /// Returns child node or token that contains given position. /// </summary> /// <remarks> /// This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node. /// </remarks> internal static SyntaxNodeOrToken ChildThatContainsPosition(this SyntaxNode self, int position, out int childIndex) { var childList = self.ChildNodesAndTokens(); var left = 0; var right = childList.Count - 1; while (left <= right) { var middle = left + ((right - left) / 2); var node = childList[middle]; var span = node.FullSpan; if (position < span.Start) { right = middle - 1; } else if (position >= span.End) { left = middle + 1; } else { childIndex = middle; return node; } } // we could check up front that index is within FullSpan, // but we wan to optimize for the common case where position is valid. Debug.Assert(!self.FullSpan.Contains(position), "Position is valid. How could we not find a child?"); throw new ArgumentOutOfRangeException(nameof(position)); } public static (SyntaxToken openParen, SyntaxToken closeParen) GetParentheses(this SyntaxNode node) { switch (node) { case ParenthesizedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case MakeRefExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case RefTypeExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case RefValueExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CheckedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case DefaultExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case TypeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case SizeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CastExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case WhileStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case DoStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ForStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CommonForEachStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case UsingStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case FixedStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case LockStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case IfStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case SwitchStatementSyntax n when n.OpenParenToken != default: return (n.OpenParenToken, n.CloseParenToken); case TupleExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CatchDeclarationSyntax n: return (n.OpenParenToken, n.CloseParenToken); case AttributeArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ConstructorConstraintSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ParameterListSyntax n: return (n.OpenParenToken, n.CloseParenToken); default: return default; } } public static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBrackets(this SyntaxNode node) { switch (node) { case ArrayRankSpecifierSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case BracketedArgumentListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case ImplicitArrayCreationExpressionSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case AttributeListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case BracketedParameterListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); default: return default; } } public static SyntaxTokenList GetModifiers(this SyntaxNode? member) { switch (member) { case MemberDeclarationSyntax memberDecl: return memberDecl.Modifiers; case AccessorDeclarationSyntax accessor: return accessor.Modifiers; } return default; } public static SyntaxNode? WithModifiers(this SyntaxNode? member, SyntaxTokenList modifiers) { switch (member) { case MemberDeclarationSyntax memberDecl: return memberDecl.WithModifiers(modifiers); case AccessorDeclarationSyntax accessor: return accessor.WithModifiers(modifiers); } return null; } public static bool CheckTopLevel(this SyntaxNode node, TextSpan span) { switch (node) { case BlockSyntax block: return block.ContainsInBlockBody(span); case ArrowExpressionClauseSyntax expressionBodiedMember: return expressionBodiedMember.ContainsInExpressionBodiedMemberBody(span); case FieldDeclarationSyntax field: { foreach (var variable in field.Declaration.Variables) { if (variable.Initializer != null && variable.Initializer.Span.Contains(span)) { return true; } } break; } case GlobalStatementSyntax _: return true; case ConstructorInitializerSyntax constructorInitializer: return constructorInitializer.ContainsInArgument(span); } return false; } public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan) { if (initializer == null) { return false; } return initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan)); } public static bool ContainsInBlockBody(this BlockSyntax block, TextSpan textSpan) { if (block == null) { return false; } var blockSpan = TextSpan.FromBounds(block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart); return blockSpan.Contains(textSpan); } public static bool ContainsInExpressionBodiedMemberBody(this ArrowExpressionClauseSyntax expressionBodiedMember, TextSpan textSpan) { if (expressionBodiedMember == null) { return false; } var expressionBodiedMemberBody = TextSpan.FromBounds(expressionBodiedMember.Expression.SpanStart, expressionBodiedMember.Expression.Span.End); return expressionBodiedMemberBody.Contains(textSpan); } public static IEnumerable<MemberDeclarationSyntax> GetMembers(this SyntaxNode? node) { switch (node) { case CompilationUnitSyntax compilation: return compilation.Members; case NamespaceDeclarationSyntax @namespace: return @namespace.Members; case TypeDeclarationSyntax type: return type.Members; case EnumDeclarationSyntax @enum: return @enum.Members; } return SpecializedCollections.EmptyEnumerable<MemberDeclarationSyntax>(); } public static bool IsInExpressionTree( [NotNullWhen(returnValue: true)] this SyntaxNode? node, SemanticModel semanticModel, [NotNullWhen(returnValue: true)] INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken) { if (expressionTypeOpt != null) { for (var current = node; current != null; current = current.Parent) { if (current.IsAnyLambda()) { var typeInfo = semanticModel.GetTypeInfo(current, cancellationToken); if (expressionTypeOpt.Equals(typeInfo.ConvertedType?.OriginalDefinition)) return true; } else if (current is SelectOrGroupClauseSyntax || current is OrderingSyntax) { var info = semanticModel.GetSymbolInfo(current, cancellationToken); if (TakesExpressionTree(info, expressionTypeOpt)) return true; } else if (current is QueryClauseSyntax queryClause) { var info = semanticModel.GetQueryClauseInfo(queryClause, cancellationToken); if (TakesExpressionTree(info.CastInfo, expressionTypeOpt) || TakesExpressionTree(info.OperationInfo, expressionTypeOpt)) { return true; } } } } return false; static bool TakesExpressionTree(SymbolInfo info, INamedTypeSymbol expressionType) { foreach (var symbol in info.GetAllSymbols()) { if (symbol is IMethodSymbol method && method.Parameters.Length > 0 && expressionType.Equals(method.Parameters[0].Type?.OriginalDefinition)) { return true; } } return false; } } public static bool IsInDeconstructionLeft( [NotNullWhen(returnValue: true)] this SyntaxNode? node, [NotNullWhen(returnValue: true)] out SyntaxNode? deconstructionLeft) { SyntaxNode? previous = null; for (var current = node; current != null; current = current.Parent) { if ((current is AssignmentExpressionSyntax assignment && previous == assignment.Left && assignment.IsDeconstruction()) || (current is ForEachVariableStatementSyntax @foreach && previous == @foreach.Variable)) { deconstructionLeft = previous; return true; } if (current is StatementSyntax) { break; } previous = current; } deconstructionLeft = null; return false; } public static bool IsTopLevelOfUsingAliasDirective(this SyntaxToken node) => node switch { { Parent: NameEqualsSyntax { Parent: UsingDirectiveSyntax _ } } => true, { Parent: IdentifierNameSyntax { Parent: UsingDirectiveSyntax _ } } => true, _ => false }; public static T WithCommentsFrom<T>(this T node, SyntaxToken leadingToken, SyntaxToken trailingToken) where T : SyntaxNode => node.WithCommentsFrom( SyntaxNodeOrTokenExtensions.GetTrivia(leadingToken), SyntaxNodeOrTokenExtensions.GetTrivia(trailingToken)); public static T WithCommentsFrom<T>( this T node, IEnumerable<SyntaxToken> leadingTokens, IEnumerable<SyntaxToken> trailingTokens) where T : SyntaxNode => node.WithCommentsFrom(leadingTokens.GetTrivia(), trailingTokens.GetTrivia()); public static T WithCommentsFrom<T>( this T node, IEnumerable<SyntaxTrivia> leadingTrivia, IEnumerable<SyntaxTrivia> trailingTrivia, params SyntaxNodeOrToken[] trailingNodesOrTokens) where T : SyntaxNode => node .WithLeadingTrivia(leadingTrivia.Concat(node.GetLeadingTrivia()).FilterComments(addElasticMarker: false)) .WithTrailingTrivia( node.GetTrailingTrivia().Concat(SyntaxNodeOrTokenExtensions.GetTrivia(trailingNodesOrTokens).Concat(trailingTrivia)).FilterComments(addElasticMarker: false)); public static T KeepCommentsAndAddElasticMarkers<T>(this T node) where T : SyntaxNode => node .WithTrailingTrivia(node.GetTrailingTrivia().FilterComments(addElasticMarker: true)) .WithLeadingTrivia(node.GetLeadingTrivia().FilterComments(addElasticMarker: true)); } }
45.197943
289
0.584841
[ "MIT" ]
Acidburn0zzz/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxNodeExtensions.cs
52,748
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Mqtt.Server.Sdk; namespace System.Net.Mqtt.Sdk { internal class DistanceCalculator { private class Units { public static readonly string Meters = "m"; public static readonly string KiloMeters = "km"; } private static readonly double EarthRadius = 6371e3; //meters /// <summary> /// Wrapper around the method P2PDistanceBetweenLatLon that uses Tuple for lat lon. /// It is suggested to use this wrapper. /// </summary> /// <param name="subscription">The GeoInfos about the subscription</param> /// <param name="publish">The GeoInfos about the publish</param> /// <returns>The distance in meter or kilometers</returns> public static double P2PDistanceBetweenLatLon(GeoInfos subscription, GeoInfos publish) { return P2PDistanceBetweenLatLon(new Tuple<double, double>(subscription.Latitude, subscription.Longitude), new Tuple<double, double>(publish.Latitude, publish.Longitude), subscription.ShapeParametersUnit); } public static double P2PDistanceBetweenLatLon(Tuple<double, double> first, Tuple<double, double> second, string unit) { unit = unit.ToLower(); double multiplicator; // Meters if (!IsCorrectMeasureUnit(unit, out multiplicator)) Console.WriteLine($"Something is wrong with measure unit: ${unit}. " + $"The System understands only ${Units.KiloMeters} and ${Units.Meters}.\n" + $"Will consider meters as default."); var first_latToRad = second.Item1.ToRadians(); var second_latToRad = second.Item1.ToRadians(); var delta_lat = (second.Item1 - first.Item1).ToRadians(); var delta_lon = (second.Item2 - first.Item2).ToRadians(); var a = (Math.Sin(delta_lat / 2) * Math.Sin(delta_lat / 2)) + (Math.Cos(first_latToRad) * Math.Cos(second_latToRad) * Math.Sin(delta_lon / 2) * Math.Sin(delta_lon / 2)); var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); var distance = EarthRadius * c; // in Meters. return distance * multiplicator; } private static bool IsCorrectMeasureUnit(string unit, out double multiplicator) { unit = unit.ToLower(); multiplicator = 1f; if (Convert.ToBoolean(multiplicator)) multiplicator = !Convert.ToBoolean(unit.CompareTo(Units.KiloMeters)) ? (1f / 1000f) : 1f; return Convert.ToBoolean(unit.CompareTo(Units.KiloMeters)) || Convert.ToBoolean(unit.CompareTo(Units.Meters)); } } internal static class DoubleExtension { public static double ToRadians(this double number) { return number * (Math.PI / 180); } } }
32.576471
122
0.680751
[ "MIT" ]
CarloP95/mqtt
src/Client/Sdk/DistanceCalculator.cs
2,771
C#
using Microsoft.Win32; using System; using System.Collections.Generic; using System.Drawing; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; namespace MultiLauncher.UI { public class ProgramLocatorService { public IEnumerable<(string name, string path)> AutoLocatePrograms() { var registry_key_32 = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; var registry_key_64 = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"; var programs = new List<(string name, string path)>(); // Local Machine using (RegistryKey key = Registry.LocalMachine.OpenSubKey(Environment.Is64BitOperatingSystem ? registry_key_64 : registry_key_32)) { foreach (string subkey_name in key.GetSubKeyNames()) { using (RegistryKey subkey = key.OpenSubKey(subkey_name)) { var name = subkey.GetValue("DisplayName"); var path = subkey.GetValue("InstallLocation"); if (name is null) continue; if (string.IsNullOrWhiteSpace(path?.ToString())) continue; programs.Add((name.ToString(), path.ToString())); } } } // Current User using (RegistryKey key = Registry.CurrentUser.OpenSubKey(registry_key_32)) { foreach (string subkey_name in key.GetSubKeyNames()) { using (RegistryKey subkey = key.OpenSubKey(subkey_name)) { var name = subkey.GetValue("DisplayName"); var path = subkey.GetValue("InstallLocation"); if (name is null) continue; if (string.IsNullOrWhiteSpace(path?.ToString())) continue; programs.Add((name.ToString(), path.ToString())); } } } return programs; } public ImageSource IconFromFilePath(string filePath) { try { var icon = Icon.ExtractAssociatedIcon(filePath); ImageSource img = Imaging.CreateBitmapSourceFromHIcon( icon.Handle, new Int32Rect(0, 0, icon.Width, icon.Height), BitmapSizeOptions.FromEmptyOptions()); return img; } catch (Exception) { // swallow and return nothing. You could supply a default Icon here as well } return null; } } }
33.659091
142
0.505402
[ "MIT" ]
NoPoLa/MultiLauncher
src/MultiLauncher.UI/Services/ProgramLocatorService.cs
2,964
C#
using System.Collections.Generic; using System.Linq; using EnvDTE; using EnvDTE80; using Typewriter.Metadata.Interfaces; namespace Typewriter.Metadata.CodeDom { public class CodeDomConstantMetadata : CodeDomFieldMetadata, IConstantMetadata { private CodeDomConstantMetadata(CodeVariable2 codeVariable, CodeDomFileMetadata file) : base(codeVariable, file) { var initValue = codeVariable.InitExpression.ToString(); var value = initValue == "null" ? string.Empty : initValue; if (value.Length >= 2 && value.StartsWith("\"") && value.EndsWith("\"")) { Value = value.Substring(1, value.Length - 2).Replace("\\\"", "\""); } else { Value = value; } } public string Value { get; } internal new static IEnumerable<IConstantMetadata> FromCodeElements(CodeElements codeElements, CodeDomFileMetadata file) { return codeElements.OfType<CodeVariable2>().Where(v => v.IsConstant && v.Access == vsCMAccess.vsCMAccessPublic) .Select(v => new CodeDomConstantMetadata(v, file)); } } }
35.323529
128
0.615321
[ "Apache-2.0" ]
Ackhuman/Typewriter
src/CodeDom/CodeDomConstantMetadata.cs
1,201
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // System.Configuration.InfiniteIntConverterTest.cs - Unit tests // for System.Configuration.InfiniteIntConverter. // // Author: // Chris Toshok <toshok@ximian.com> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Configuration; using Xunit; namespace MonoTests.System.Configuration { public class InfiniteIntConverterTest { [Fact] public void CanConvertFrom() { InfiniteIntConverter cv = new InfiniteIntConverter(); Assert.True(cv.CanConvertFrom(null, typeof(string)), "A1"); Assert.False(cv.CanConvertFrom(null, typeof(TimeSpan)), "A2"); Assert.False(cv.CanConvertFrom(null, typeof(int)), "A3"); Assert.False(cv.CanConvertFrom(null, typeof(object)), "A4"); } [Fact] public void CanConvertTo() { InfiniteIntConverter cv = new InfiniteIntConverter(); Assert.True(cv.CanConvertTo(null, typeof(string)), "A1"); Assert.False(cv.CanConvertTo(null, typeof(TimeSpan)), "A2"); Assert.False(cv.CanConvertTo(null, typeof(int)), "A3"); Assert.False(cv.CanConvertTo(null, typeof(object)), "A4"); } [Fact] public void ConvertFrom() { InfiniteIntConverter cv = new InfiniteIntConverter(); object o; o = cv.ConvertFrom(null, null, "59"); Assert.Equal(typeof(int), o.GetType()); Assert.Equal(59, o); /* and now test infinity */ o = cv.ConvertFrom(null, null, "Infinite"); Assert.Equal(int.MaxValue, o); } [Fact] public void ConvertFrom_FormatError() { InfiniteIntConverter cv = new InfiniteIntConverter(); object o = null; Assert.Throws<FormatException>(() => o = cv.ConvertFrom(null, null, "100.5")); Assert.Null(o); } [Fact] public void ConvertFrom_TypeError() { InfiniteIntConverter cv = new InfiniteIntConverter(); object o = null; Assert.Throws<FormatException>(() => o = cv.ConvertFrom(null, null, "hi")); Assert.Null(o); } [Fact] public void ConvertTo() { InfiniteIntConverter cv = new InfiniteIntConverter(); Assert.Equal("59", cv.ConvertTo(null, null, 59, typeof(string))); Assert.Equal("144", cv.ConvertTo(null, null, 144, typeof(string))); /* infinity tests */ Assert.Equal("Infinite", cv.ConvertTo(null, null, int.MaxValue, typeof(string))); Assert.Equal("2147483646", cv.ConvertTo(null, null, int.MaxValue - 1, typeof(string))); } [Fact] public void ConvertTo_NullError() { InfiniteIntConverter cv = new InfiniteIntConverter(); Assert.Throws<NullReferenceException>(() => cv.ConvertTo(null, null, null, typeof(string))); } [Fact] public void ConvertTo_TypeError1() { InfiniteIntConverter cv = new InfiniteIntConverter(); AssertExtensions.Throws<ArgumentException>(null, () => cv.ConvertTo(null, null, "hi", typeof(string))); } [Fact] public void ConvertTo_TypeError2() { InfiniteIntConverter cv = new InfiniteIntConverter(); Assert.Equal("59", cv.ConvertTo(null, null, 59, typeof(int))); Assert.Equal("59", cv.ConvertTo(null, null, 59, null)); } } }
35.272059
115
0.623932
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Configuration.ConfigurationManager/tests/Mono/InfiniteIntConverterTest.cs
4,797
C#
using Mirage.Urbanization.ZoneConsumption; namespace Mirage.Urbanization.Tilesets { class RoadNoneZoneTileAccessor : BaseNetworkZoneTileAccessor<RoadZoneConsumption> { protected override string NetworkName => "RoadNone"; protected override bool Filter(ZoneInfoSnapshot snapshot) => snapshot.TrafficDensity == TrafficDensity.None; } }
37.1
117
0.757412
[ "MIT" ]
Miragecoder/Urbanization
src/Mirage.Urbanization.Resources/RoadNoneZoneTileAccessor.cs
371
C#
// Ejercicio recomendado 48 // Javier (...) // Calcula las soluciones de y=Ax^2 + Bx + C using System; // y=Ax^2 + Bx + C // Ax^2 + Bx + C-y = 0 // x = (-b +- sqrt(b^2 - 4a(c-y))) /2a class Ecuacion { static void Main() { double a, b, c, discriminante, x1, x2; Console.Write("Introduce el valor de a: "); a = Convert.ToDouble(Console.ReadLine()); Console.Write("Introduce el valor de b: "); b = Convert.ToDouble(Console.ReadLine()); Console.Write("Introduce el valor de c: "); c = Convert.ToDouble(Console.ReadLine()); if (a == 0) { if (b == 0) { if (c == 0) { Console.WriteLine("El resultado es la igualdad 0==0"); } else { Console.WriteLine("No hay solución posible"); } } else { // x=-c/b x1 = -c / b; Console.WriteLine("El resultado es -{0}/{1} = {2}", c, b, x1); } } else { discriminante = b * b - 4 * a * c; if (discriminante < 0) Console.WriteLine("No hay solución posible"); else { x1 = (-b + Math.Sqrt(discriminante)) / (2 * a); x2 = (-b - Math.Sqrt(discriminante)) / (2 * a); Console.WriteLine("Solución 1: {0}", x1); Console.WriteLine("Solución 2: {0}", x2); } } } }
27.050847
78
0.414787
[ "MIT" ]
ncabanes/sv2021-programming
tema03-tiposDeDatosBasicos/048-ecuacSegundoGrado.cs
1,602
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UniRx; using UnityEngine.UI; using UnityEngine.Events; public class DrumGameManagerCircle : DrumGameManagerBase { /* TODOLIST */ public Transform wheelPivotT; public Transform highlightPivotT; public float rotateTime = 0.5f; public DrumGameArcHighlight arcHighlighter; public Text repeatsText; private GameObject uiParent; private Coroutine wheelAnimation; private float baseX; private float baseY; private IntReactiveProperty repeatsRemaining; //iterations left before advancing levelIndex public override void Initialize(DrumSequence firstSequence, int selfIndex, OnSequenceComplete sequenceCallback, List<Color> colorMap) { this.selfIndex = selfIndex; sequenceCompleteCallback = sequenceCallback; uiParent = transform.GetChild(0).gameObject; prompts = new List<DrumGamePrompt>(); promptPrefab.SetActive(false); this.colorMap = colorMap; arcHighlighter.Initialize(); reactiveSequence = new ReactiveProperty<DrumSequence>(firstSequence); repeatsRemaining = new IntReactiveProperty(reactiveSequence.Value.repetitions); sequenceIndex = new IntReactiveProperty(0); isVisible = new BoolReactiveProperty(); isActive = new BoolReactiveProperty(); isActive.Subscribe(active => ToggleActivePromptHighlight(active)); isActive.Subscribe(active => firstFrameActive = active); isVisible.Subscribe(visible => SetVisibility(visible)); reactiveSequence.Subscribe(sequence => SetHiddenState(sequence)); reactiveSequence.Subscribe(sequence => SpawnAndArrangePrompts(sequence)); reactiveSequence.Subscribe(sequence => LabelDrumPrompts(sequence)); reactiveSequence.Subscribe(sequence => ColorDrumPrompts(sequence)); reactiveSequence.Subscribe(sequence => SetRepeatsValue(sequence)); reactiveSequence.Subscribe(sequence => arcHighlighter.DrawArcs(sequence.keys.Count)); sequenceIndex.Subscribe(index => SetPromptHighlight(index)); repeatsRemaining.Subscribe(remaining => SetRepeatsText(remaining)); baseX = highlightPivotT.rotation.eulerAngles.x; baseY = highlightPivotT.rotation.eulerAngles.y; } public virtual void SetVisibility(bool isVisible) { //TODO: animate hide/unhide toggles arcHighlighter.SnapHighlightsToDefault(); uiParent.SetActive(isVisible); } protected override void SpawnAndArrangePrompts(DrumSequence next) { if (next.type != DrumSequence.SequenceType.Circle) return; //Add needed prompts while (prompts.Count < next.keys.Count) { GameObject promptObj = Instantiate(promptPrefab, wheelPivotT); promptObj.SetActive(true); DrumGamePrompt prompt = promptObj.GetComponent<DrumGamePrompt>(); prompt.SetHighlightVisible(false); prompts.Add(prompt); } //Remove extras while (prompts.Count > next.keys.Count) { DrumGamePrompt last = prompts[prompts.Count - 1]; prompts.Remove(last); Destroy(last.gameObject); } //Arrange around a circle float radius = promptPrefab.transform.localPosition.y; for (int i = 0; i < prompts.Count; i++) { float phaseRadians = ((i / (float)prompts.Count) * 360f) * Mathf.Deg2Rad; float x = radius * Mathf.Sin(phaseRadians); float y = radius * Mathf.Cos(phaseRadians); prompts[i].transform.localPosition = new Vector3(x, y, 0); } } protected override void SetRepeatsValue(DrumSequence next) { repeatsRemaining.Value = next.repetitions; } private void SetRepeatsText(int remaining) { repeatsText.text = $"{remaining}x"; } protected override void AdvanceSequence() { arcHighlighter.FlashSegmentHighlight(sequenceIndex.Value); if (sequenceIndex.Value == reactiveSequence.Value.keys.Count - 1) { sequenceIndex.Value = 0; repeatsRemaining.Value--; sequenceCompleteCallback(selfIndex, repeatsRemaining.Value); onFinishRepetitionCallback.Invoke(); } else { sequenceIndex.Value++; onProgressCallback.Invoke(); } //ApplyWheelRotation(GetSequenceProgress(), true); } protected override void ResetSequence() { AnimateErrorAtCurrentPrompt(); sequenceIndex.Value = 0; //ApplyWheelRotation(GetSequenceProgress(), false); } private void ApplyWheelRotation(float sequenceProgress, bool shouldSpinClockwise) { if (!gameObject.activeInHierarchy) return; float targetEulerZ = GetWheelZRotation(sequenceProgress); if (wheelAnimation != null) StopCoroutine(wheelAnimation); wheelAnimation = StartCoroutine(AnimateWheelRotation(targetEulerZ, shouldSpinClockwise)); } private float GetWheelZRotation(float sequenceProgress) { return sequenceProgress * 360f; } private IEnumerator AnimateWheelRotation(float endEuler, bool spinClockwise) { float startEuler = highlightPivotT.rotation.eulerAngles.z; if (endEuler < startEuler && spinClockwise) { //here's the hack: treat a successful return to 0 as a movement to 360 //so it must go clockwise. When we apply the rotation, we should snap to 0 instantly as we finish the timer endEuler += 360f; } //Use Lerp with the rotation hack above to trick Unity into making the choice we want -_- Quaternion endRotation = Quaternion.Euler(baseX, baseY, endEuler); float time = 0f; while (time < rotateTime) { float t = time / rotateTime; highlightPivotT.rotation = Quaternion.Euler(baseX, baseY, Mathf.Lerp(startEuler, endEuler, t)); time += Time.deltaTime; yield return null; } //Snap to the ideal rotation, as deltaTime can miss the mark if (endEuler >= 360f) endEuler -= 360f; highlightPivotT.rotation = Quaternion.Euler(baseX, baseY, endEuler); } }
31.90099
137
0.657976
[ "MIT" ]
Kionius/DacronDuvet
Assets/ScenicAssets/DrumGame/DrumGameManagerCircle.cs
6,446
C#
using Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true, MaxParallelThreads = 1)]
26.25
89
0.809524
[ "MIT" ]
Nilox/ReactiveUI
src/ReactiveUI.Tests/TestConfiguration.cs
107
C#
using System; using IdentityServer3.Core.Services.Contrib.Internals; namespace IdentityServer3.Core.Services.Contrib { public class GlobalizedLocalizationService : ILocalizationService { private readonly OwinEnvironmentService _owinEnvironmentService; private readonly LocaleOptions _internalOpts; public GlobalizedLocalizationService(OwinEnvironmentService owinEnvironmentService, LocaleOptions options = null) { _owinEnvironmentService = owinEnvironmentService; if (owinEnvironmentService == null) { throw new ArgumentException(@"Cannot be null. Is needed for LocaleProvider Func API. Did you register this service correctly?", "owinEnvironmentService"); } _internalOpts = options ?? new LocaleOptions(); _owinEnvironmentService = owinEnvironmentService; } public string GetString(string category, string id) { var service = LocalizationServiceFactory.Create(_internalOpts, _owinEnvironmentService.Environment); return service.GetString(category, id); } } }
38.433333
170
0.701648
[ "MIT" ]
johnkors/IdentityServer3.Contrib.Localization
source/IdentityServer3.Localization/GlobalizedLocalizationService.cs
1,155
C#
using HydroQuebecApi.Infrastructure; using System; using System.Text.Json.Serialization; namespace HydroQuebecApi.Models { public class PeriodData: IEquatable<PeriodData> { [JsonPropertyName("numeroContrat")] public string ContractNumber { get; set; } [JsonPropertyName("dateFinPeriode")] public DateTime? EndDate { get; set; } [JsonPropertyName("dateDebutPeriode")] public DateTime StartDate { get; set; } [JsonPropertyName("dateDerniereLecturePeriode")] public DateTime? LastMeterReadDate { get; set; } [JsonConverter(typeof(TimeSpanJsonConverter))] [JsonPropertyName("heureDerniereLecturePeriode")] public TimeSpan LastMeterReadTime { get; set; } [JsonPropertyName("nbJourLecturePeriode")] public int DayReadCount { get; set; } [JsonPropertyName("nbJourPrevuPeriode")] public int DayCountForecast { get; set; } [JsonPropertyName("consoTotalProjetePeriode")] public int? TotalConsumptionForecast { get; set; } [JsonPropertyName("consoTotalPeriode")] public int TotalConsumption { get; set; } [JsonPropertyName("consoHautPeriode")] public int HighPriceConsumption { get; set; } [JsonPropertyName("consoRegPeriode")] public int RegularPriceConsumption { get; set; } [JsonPropertyName("moyenneKwhJourPeriode")] public double AverageDailyConsumption { get; set; } [JsonPropertyName("montantFacturePeriode")] public double? Bill { get; set; } [JsonPropertyName("moyenneDollarsJourPeriode")] public double? AverageDailyPrice { get; set; } [JsonPropertyName("codeConsPeriode")] public string ConsumptionCode { get; set; } [JsonPropertyName("indMVEPeriode")] public bool IsEqualizedPaymentsPlan { get; set; } [JsonPropertyName("tempMoyennePeriode")] public int AverageTemperature { get; set; } [JsonPropertyName("dateDebutPeriodeComparable")] public DateTime? ComparePeriodStartDate { get; set; } [JsonPropertyName("indConsoAjusteePeriode")] public bool IsAdjustedConsumption { get; set; } [JsonPropertyName("presenceCodeTarifDTPeriode")] public bool IsDualEnergyRate { get; set; } [JsonPropertyName("dernierTarif")] public string LastRateCode { get; set; } [JsonPropertyName("presencePiscineExterieursPeriode")] public bool IsOutsidePoolPresent { get; set; } [JsonPropertyName("indPresenceCodeEvenementPeriode")] public bool IsEventCodePresent { get; set; } [JsonPropertyName("montantProjetePeriode")] public double? ForecastCost { get; set; } [JsonPropertyName("multiplicateurFacturation")] public double BillMultiplier { get; set; } [JsonPropertyName("coutCentkWh")] public double? CostCentKWh { get; set; } public bool Equals(PeriodData other) => GetHashCode() == other.GetHashCode(); public override bool Equals(object other) => Equals(other as PeriodData); public override int GetHashCode() => StartDate.GetHashCode() ^ EndDate?.GetHashCode()??0; } }
71.738095
110
0.722868
[ "MIT" ]
patlaniel/HydroQuebecApi
HydroQuebecApi/Models/PeriodData.cs
3,015
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from shared/wtypes.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="remoteMETAFILEPICT" /> struct.</summary> public static unsafe class remoteMETAFILEPICTTests { /// <summary>Validates that the <see cref="remoteMETAFILEPICT" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<remoteMETAFILEPICT>(), Is.EqualTo(sizeof(remoteMETAFILEPICT))); } /// <summary>Validates that the <see cref="remoteMETAFILEPICT" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(remoteMETAFILEPICT).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="remoteMETAFILEPICT" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(remoteMETAFILEPICT), Is.EqualTo(24)); } else { Assert.That(sizeof(remoteMETAFILEPICT), Is.EqualTo(16)); } } } }
36.568182
145
0.640771
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/shared/wtypes/remoteMETAFILEPICTTests.cs
1,611
C#
using MSyics.Traceyi.Layout; using MSyics.Traceyi.Listeners; using System.Threading.Tasks; namespace MSyics.Traceyi { class UsingLayout : Example { public override string Name => nameof(UsingLayout); public override void Setup() { Traceable.Add("default", TraceFilters.All, new ConsoleLogger { UseLock = true }); Traceable.Add("json", TraceFilters.All, new ConsoleLogger(new LogLayout("{@=>json}")) { UseLock = true }); Traceable.Add("jsonIndented", TraceFilters.All, new ConsoleLogger(new LogLayout("{@=>json,indent}")) { UseLock = true }); defaultTracer = Traceable.Get("default"); jsonTracer = Traceable.Get("json"); jsonIndentedTracer = Traceable.Get("jsonIndented"); } Tracer defaultTracer; Tracer jsonTracer; Tracer jsonIndentedTracer; public override Task ShowAsync() { defaultTracer.Information("default"); jsonTracer.Information("json"); jsonIndentedTracer.Information("jsonIndented"); return Task.CompletedTask; } public override void Teardown() { Traceable.Shutdown(); } } }
31.025
133
0.609992
[ "MIT" ]
MSyics/Traceyi
MSyics.Traceyi.Example/Example/UsingLayout/UsingLayout.cs
1,243
C#
using System.Collections.Generic; using System.Text.Json.Serialization; using Newtonsoft.Json; namespace BasisTheory.net.Permissions.Entities { public class Permission { [JsonProperty("type")] [JsonPropertyName("type")] public string Type { get; set; } [JsonProperty("description")] [JsonPropertyName("description")] public string Description { get; set; } [JsonProperty("application_types")] [JsonPropertyName("application_types")] public List<string> ApplicationTypes { get; set; } } }
26.136364
58
0.66087
[ "Apache-2.0" ]
Basis-Theory/basistheory-dotnet
src/BasisTheory.net/Permissions/Entities/Permission.cs
575
C#
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Net.Http { public static class __HttpContent { public static IObservable<System.String> ReadAsStringAsync(this IObservable<System.Net.Http.HttpContent> HttpContentValue) { return Observable.Select(HttpContentValue, (HttpContentValueLambda) => HttpContentValueLambda.ReadAsStringAsync().ToObservable()).Flatten(); } public static IObservable<System.Byte[]> ReadAsByteArrayAsync(this IObservable<System.Net.Http.HttpContent> HttpContentValue) { return Observable.Select(HttpContentValue, (HttpContentValueLambda) => HttpContentValueLambda.ReadAsByteArrayAsync().ToObservable()).Flatten(); } public static IObservable<System.IO.Stream> ReadAsStreamAsync(this IObservable<System.Net.Http.HttpContent> HttpContentValue) { return Observable.Select(HttpContentValue, (HttpContentValueLambda) => HttpContentValueLambda.ReadAsStreamAsync().ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> CopyToAsync(this IObservable<System.Net.Http.HttpContent> HttpContentValue, IObservable<System.IO.Stream> stream, IObservable<System.Net.TransportContext> context) { return Observable.Zip(HttpContentValue, stream, context, (HttpContentValueLambda, streamLambda, contextLambda) => HttpContentValueLambda.CopyToAsync(streamLambda, contextLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> CopyToAsync(this IObservable<System.Net.Http.HttpContent> HttpContentValue, IObservable<System.IO.Stream> stream) { return Observable.Zip(HttpContentValue, stream, (HttpContentValueLambda, streamLambda) => HttpContentValueLambda.CopyToAsync(streamLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> LoadIntoBufferAsync(this IObservable<System.Net.Http.HttpContent> HttpContentValue) { return Observable.Select(HttpContentValue, (HttpContentValueLambda) => HttpContentValueLambda.LoadIntoBufferAsync().ToObservable()).Flatten().ToUnit(); } public static IObservable<System.Reactive.Unit> LoadIntoBufferAsync(this IObservable<System.Net.Http.HttpContent> HttpContentValue, IObservable<System.Int64> maxBufferSize) { return Observable.Zip(HttpContentValue, maxBufferSize, (HttpContentValueLambda, maxBufferSizeLambda) => HttpContentValueLambda.LoadIntoBufferAsync(maxBufferSizeLambda).ToObservable()).Flatten(); } public static IObservable<System.Reactive.Unit> Dispose(this IObservable<System.Net.Http.HttpContent> HttpContentValue) { return Observable.Do(HttpContentValue, (HttpContentValueLambda) => HttpContentValueLambda.Dispose()).ToUnit(); } public static IObservable<System.Net.Http.Headers.HttpContentHeaders> get_Headers(this IObservable<System.Net.Http.HttpContent> HttpContentValue) { return Observable.Select(HttpContentValue, (HttpContentValueLambda) => HttpContentValueLambda.Headers); } } }
49.621212
219
0.744733
[ "MIT" ]
RixianOpenTech/RxWrappers
Source/Wrappers/Microsoft.Net.Http/System.Net.Http.HttpContent.cs
3,275
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("LynxMagnus.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LynxMagnus.Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("07e32a5d-8b19-4aad-b215-d64a9ed8a80c")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.777778
84
0.751471
[ "MIT" ]
LynxMagnus/lynx-magnus
LynxMagnus.Tests/Properties/AssemblyInfo.cs
1,363
C#
namespace DiscordRP { /// <summary> /// Defines the required fields when updating /// the client's Rich Presence status. /// </summary> public class ClientStatus { /// <value> /// the user's current party status /// </value> public string state = ""; /// <value> /// what the player is currently doing /// </value> public string details = ""; /// <value> /// name of the uploaded image for the large profile artwork /// </value> public string largeImageKey = null; /// <value> /// tooltip for the largeImageKey /// </value> public string largeImageText = null; /// <value> /// name of the uploaded image for the small profile artwork /// </value> public string smallImageKey = null; /// <value> /// tooltip for the smallImageKey /// </value> public string smallImageText = null; } }
22.157895
62
0.634204
[ "MIT" ]
staticfox/DiscordRP-tModLoader
ClientStatus.cs
842
C#
using System.Management.Automation; using Microsoft.SharePoint.Client; using PnP.PowerShell.Commands.Base.PipeBinds; namespace PnP.PowerShell.Commands { [Cmdlet(VerbsCommon.Remove, "PnPIndexedProperty")] public class RemovedIndexedProperty : PnPWebCmdlet { [Parameter(Mandatory = true, Position = 0)] public string Key; [Parameter(Mandatory = false, ValueFromPipeline = true)] public ListPipeBind List; protected override void ExecuteCmdlet() { if (!string.IsNullOrEmpty(Key)) { if (List != null) { var list = List.GetList(CurrentWeb); if (list != null) { list.RemoveIndexedPropertyBagKey(Key); } } else { CurrentWeb.RemoveIndexedPropertyBagKey(Key); } } } } }
27.583333
64
0.515609
[ "MIT" ]
AndersRask/powershell
src/Commands/Web/RemovedIndexedProperty.cs
995
C#
// <copyright file="TeamEntity.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace Microsoft.Teams.Apps.NewHireOnboarding.Models.EntityModels { using Microsoft.WindowsAzure.Storage.Table; /// <summary> /// Class contains team details where application is installed. /// </summary> public class TeamEntity : TableEntity { /// <summary> /// Gets or sets team id where application is installed. /// </summary> public string TeamId { get { return this.PartitionKey; } set { this.PartitionKey = value; this.RowKey = value; } } /// <summary> /// Gets or sets service URL. /// </summary> public string ServiceUrl { get; set; } /// <summary> /// Gets or sets name of team where bot installed. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets Azure Active Directory id of the user who installed the application. /// </summary> public string InstalledByAadObjectId { get; set; } /// <summary> /// Gets or sets group id of team. /// </summary> public string AadGroupId { get; set; } } }
27.634615
94
0.517049
[ "MIT" ]
v-chetsh/at-arm-test-local
Source/Microsoft.Teams.Apps.NewHireOnboarding/Models/EntityModels/TeamEntity.cs
1,439
C#
using Microsoft.AspNetCore.Mvc; using shopping_api.Models; using shopping_api.Utils; using shopping_api.Handler.Default; namespace shopping_api.Controllers { /// <summary> /// Defines a corresponding controller for departments. /// </summary> [ApiController] [Route("department")] public class DepartmentController : ControllerBase { /// <summary> /// Lists all the departments in the database. /// </summary> /// /// <returns> /// A response with a list containing all the departments from the database. /// </returns> [HttpGet("")] public Response<Department> List() { return new DepartmentHandler().List(); } /// <summary> /// Returns a specific department from the database. /// </summary> /// /// <param name="departmentId">The ID of a department.</param> /// /// <returns> /// A response with the corresponding department from the database (if it exists). /// </returns> [HttpGet("{departmentId}")] public Response<Department> Get(int departmentId) { return new DepartmentHandler().Get(departmentId); } } }
29.25
94
0.570319
[ "Apache-2.0" ]
Carzuiliam/CS-ShoppingAPI
Controllers/DepartmentController.cs
1,289
C#
using System.Drawing; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using Microsoft.JSInterop; using MjrChess.Engine; using MjrChess.Engine.Models; using MjrChess.Engine.Utilities; namespace MjrChess.Trainer.Components { /// <summary> /// Representation of a chess game. /// </summary> public class ChessBoardBase : ComponentBase { [Inject] private IJSRuntime JSRuntime { get; set; } = default!; [Parameter] public ChessEngine Engine { get; set; } = new ChessEngine(); [Parameter] public bool UserMovableWhitePieces { get; set; } = true; [Parameter] public bool UserMovableBlackPieces { get; set; } = true; protected ChessGame Game => Engine.Game; protected Move[] LegalMovesForSelectedPiece { get; set; } = new Move[0]; protected Move? LastMove => Game.Moves.LastOrDefault(); private ChessPiece? _selectedPiece; /// <summary> /// Gets or sets the piece the user currently has selected. /// </summary> public ChessPiece? SelectedPiece { get { return _selectedPiece; } set { _selectedPiece = value; // Storing an enumerable in state used by Blazor was causing the enumerable // to be evaluated multiple times. Therefore, store as an array to make sure // that the evaluation is only done once. LegalMovesForSelectedPiece = _selectedPiece == null ? new Move[0] : Engine.GetLegalMoves(_selectedPiece.Position).ToArray(); } } protected const string ElementName = "ChessBoard"; // Tracks whether the component is rendered so that we know whether // to call StateHasChanged or not. private bool _rendered = false; public ChessBoardBase() { Engine = new ChessEngine(); } protected override void OnAfterRender(bool firstRender) { base.OnAfterRender(firstRender); _rendered = true; } public async void HandleMouseDown(MouseEventArgs args) { if (SelectedPiece == null) { (var file, var rank) = await GetMousePositionAsync(args); SelectPiece(file, rank); Render(); } } public async void HandleMouseUp(MouseEventArgs args) { if (SelectedPiece != null) { (var file, var rank) = await GetMousePositionAsync(args); if (SelectedPiece.Position.File == file && SelectedPiece.Position.Rank == rank) { // If the mouse button is released on the same square the // piece was selected from, do nothing. Keep the piece selected since // this could be the initial click to select it. return; } else { PlacePiece(file, rank); Render(); } } } /// <summary> /// Attempts to select a game piece. /// </summary> /// <param name="file">The file of the piece to be selected.</param> /// <param name="rank">The rank of the piece to be selected.</param> /// <returns>True if a piece was successfully selected, false otherwise. Note that this does not guarantee the selected piece has any legal moves.</returns> public bool SelectPiece(int file, int rank) { // Don't select pieces if the game is finished if (Game?.Result != GameResult.Ongoing) { return false; } // Don't select pieces if the user isn't allowed to move the active color's pieces if ((Game.WhiteToMove && !UserMovableWhitePieces) || (!Game.WhiteToMove && !UserMovableBlackPieces)) { return false; } var piece = Game.GetPiece(file, rank); // Don't select pieces if the clicked square doesn't contain a piece or contains a piece for the wrong player if (piece == null || ChessFormatter.IsPieceWhite(piece.PieceType) != Game.WhiteToMove) { return false; } SelectedPiece = piece; return true; } /// <summary> /// Attempts to place a selected piece. This unselects any selected piece. /// </summary> /// <param name="file">The file to place the selected piece on.</param> /// <param name="rank">The rank to place the selected piece on.</param> /// <returns>True if the selected piece was successully and legally placed on the indicated rank and file. False if the move is illegal or if no piece is selected.</returns> private bool PlacePiece(int file, int rank) { var move = LegalMovesForSelectedPiece.SingleOrDefault(m => m.FinalPosition.File == file && m.FinalPosition.Rank == rank); SelectedPiece = null; if (move != null) { // If the piece is placed in a legal move location, // move the piece. Game.Move(move); return true; } else { return false; } } private async Task<(int, int)> GetMousePositionAsync(MouseEventArgs args) { var boardDimensions = await JSRuntime.InvokeAsync<Rectangle>("getBoundingRectangle", new object[] { ElementName }); // Account for the rare case where the user clicks on the final pixel of the board if (args.ClientX >= boardDimensions.Right) { args.ClientX--; } if (args.ClientY >= boardDimensions.Bottom) { args.ClientY--; } var file = ((int)args.ClientX - boardDimensions.X) * Game.BoardSize / boardDimensions.Width; var rank = (Game.BoardSize - 1) - (((int)args.ClientY - boardDimensions.Y) * Game.BoardSize / boardDimensions.Height); return (file, rank); } /// <summary> /// Tells Blazor to re-render the component. /// </summary> private void Render() { if (_rendered) { StateHasChanged(); } } } }
34.086735
181
0.550367
[ "MIT" ]
mjrousos/ChessTrainer
src/ChessTrainerApp/Components/ChessBoardBase.cs
6,683
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace NiVek.GroundStation.Controls { public sealed partial class ConfigValue : UserControl { public ConfigValue() { this.InitializeComponent(); } } }
25.75
96
0.753121
[ "MIT" ]
bytemaster-0xff/DroneTek
NiVek/Software/GroundStation/NiVek.GroundStation/Controls/ConfigValue.xaml.cs
723
C#