content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; 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; namespace IntelligentRetail_Mob.UWP { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Xamarin.Forms.Forms.Init(e); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
37.980392
99
0.624419
[ "MIT" ]
mohamedsaif/IntelligentRetail
Src/IntelligentRetail-Mob/IntelligentRetail-Mob/IntelligentRetail-Mob.UWP/App.xaml.cs
3,876
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.ResourceManager; namespace Azure.ResourceManager.Compute { internal class DiskOperationSource : IOperationSource<DiskResource> { private readonly ArmClient _client; internal DiskOperationSource(ArmClient client) { _client = client; } DiskResource IOperationSource<DiskResource>.CreateResult(Response response, CancellationToken cancellationToken) { using var document = JsonDocument.Parse(response.ContentStream); var data = DiskData.DeserializeDiskData(document.RootElement); return new DiskResource(_client, data); } async ValueTask<DiskResource> IOperationSource<DiskResource>.CreateResultAsync(Response response, CancellationToken cancellationToken) { using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); var data = DiskData.DeserializeDiskData(document.RootElement); return new DiskResource(_client, data); } } }
32.439024
142
0.714286
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/LongRunningOperation/DiskOperationSource.cs
1,330
C#
using System.ComponentModel.DataAnnotations; namespace HeavensHall.Commerce.Web.Models { public class UserModel : UserCredentialsModel { [Display(Name = "Nome completo")] [Required(ErrorMessage = "O nome do usuário é obrigatório.")] [MinLength(5, ErrorMessage = "Digite um nome maior que 5 caracteres.")] public override string Name { get; set; } } }
30.538462
79
0.677582
[ "MIT" ]
phncosta/e-commerce_webapp
src/HeavensHall.Commerce.Web/Models/UserModel.cs
402
C#
using UnityEditor; using UnityEngine; public class LayersAndTags : Editor { #region Load Variables public string[] oldLayerNames = new string[Constants.maxLayerLenght]; public string[] oldTagNames = new string[Constants.maxTagLenght]; string newlayerName; int oldindex; #endregion #region Edita as Layers public string[] editLayers(string[] layerNames, string ln, int index) { //oldLayerNames[20] = "Main Layer"; #region Verifica as layers //bool hasMain = false, bool changeLayers = false, equalLayername = false; bool[] changedLayerName = new bool[Constants.maxLayerLenght]; SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]); SerializedProperty layersProp = tagManager.FindProperty("layers"); for (int i = 0; i <= Constants.maxLayerLenght - 1; i++) { SerializedProperty layerVal = layersProp.GetArrayElementAtIndex(i); layerNames[i] = layerVal.stringValue; if (layerNames[i] != oldLayerNames[i]) { changedLayerName[i] = true; changeLayers = true; } // else if (layerNames[i] == "Main Layer" && i == 20) // { // hasMain = true; // changedLayerName[i] = false; // } else if (layerNames[i] == "") changeLayers = true; else if (index == i && ln != oldLayerNames[i] && ln != "") { changedLayerName[i] = true; changeLayers = true; layerNames[i] = ln; } else changedLayerName[i] = false; } //if (!hasMain) // changeLayers = true; #endregion #region Altera as Layers if (changeLayers) { for (int i = 8; i <= Constants.maxLayerLenght-1; i++) { SerializedProperty layerVal = layersProp.GetArrayElementAtIndex(i); if (changedLayerName[i]) { oldLayerNames[i] = layerNames[i]; layerVal.stringValue = layerNames[i]; } // else if (layerNames[20] == "" && layerNames[20] != "Main Layer" && i == 20) // { // if (!hasMain) // { // layerVal.stringValue = "Main Layer"; // hasMain = true; // } // } else if (layerNames[i] == "") layerVal.stringValue = "Layer " + i; } changeLayers = false; } for (int i = 8; i < Constants.maxLayerLenght; i++) { SerializedProperty layerVal = layersProp.GetArrayElementAtIndex(i); for (int j = 8; j < Constants.maxLayerLenght; j++) { if (oldLayerNames[i] == oldLayerNames[j] && j != i && oldLayerNames[i] != "") { oldindex = index; equalLayername = true; } } if (equalLayername && i == index) { oldLayerNames[i] = "Layer " + i + 100; layerVal.stringValue = oldLayerNames[i]; newlayerName = layerVal.stringValue; } } if (equalLayername && oldindex != index) EditorUtility.DisplayDialog(Constants.errorString, "This layer name is already taken. The layer names was changed to: " + newlayerName, Constants.okString); #endregion //Salva tagManager.ApplyModifiedProperties(); return (oldLayerNames); } #endregion #region Edita as Tags public string[] getTags() { SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]); SerializedProperty tagsProp = tagManager.FindProperty("tags"); for (int i = 0; i < tagsProp.arraySize; i++) { SerializedProperty t = tagsProp.GetArrayElementAtIndex(i); oldTagNames[i] = t.stringValue.ToString(); } return oldTagNames; } #region EditTags public string[] editTag(string[] tagNames, string tn, int index) { bool editTag = false; bool tnIgual = false; bool[] changedTagName = new bool[Constants.maxTagLenght]; SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]); SerializedProperty tagsProp = tagManager.FindProperty("tags"); #region Busca tag alterada if(tn == "") EditorUtility.DisplayDialog(Constants.errorString, "The tag value in textbox cannot be null.", Constants.okString); else { for (int i = 0; i < tagsProp.arraySize; i++) { SerializedProperty t = tagsProp.GetArrayElementAtIndex(i); if (tn == t.stringValue.ToString()) tnIgual = true; } if (!tnIgual) { for (int i = 0; i < tagsProp.arraySize; i++) { SerializedProperty t = tagsProp.GetArrayElementAtIndex(i); tagNames[i] = t.stringValue.ToString(); if (oldTagNames[i] != tagNames[i]) { editTag = true; changedTagName[i] = true; } else if (index == i && tn != oldLayerNames[i]) { editTag = true; changedTagName[i] = true; tagNames[i] = tn; } else changedTagName[i] = false; } } } #endregion #region Altera as Tags if (editTag && !tnIgual) { for (int i = 0; i < tagsProp.arraySize; i++) { SerializedProperty tag = tagsProp.GetArrayElementAtIndex(i); if (changedTagName[i] == true) { oldTagNames[i] = tagNames[i]; tag.stringValue = tagNames[i]; } } editTag = false; } else if (tnIgual) EditorUtility.DisplayDialog(Constants.errorString, "This tag name is already taken.", Constants.okString); //Salva tagManager.ApplyModifiedProperties(); return (oldTagNames); } #endregion #endregion #region Remove Tags public string[] removeTag(string tagName) { bool tagEqual = false; SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]); SerializedProperty tagsProp = tagManager.FindProperty("tags"); //Busca a tag a ser apagada if (tagName == "") EditorUtility.DisplayDialog(Constants.errorString, "The tag value in textbox cannot be null.", Constants.okString); else { for (int i = 0; i < tagsProp.arraySize; i++) { SerializedProperty t = tagsProp.GetArrayElementAtIndex(i); string tag = t.stringValue.ToString(); if (tag == tagName) { t.stringValue = ""; tagEqual = true; } oldTagNames[i] = t.stringValue.ToString(); } } if(!tagEqual) EditorUtility.DisplayDialog(Constants.errorString, "This tag don't exist.", Constants.okString); //Salva tagManager.ApplyModifiedProperties(); return (oldTagNames); } #endregion #region AddTags public string[] addTags(string tagName) { bool addTag = true; SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]); SerializedProperty tagsProp = tagManager.FindProperty("tags"); //Checa para ver se não existe a Tag if (tagName == "") EditorUtility.DisplayDialog(Constants.errorString, "The tag value in textbox cannot be null.", Constants.okString); else { for (int i = 0; i < tagsProp.arraySize; i++) { SerializedProperty t = tagsProp.GetArrayElementAtIndex(i); string tag = t.stringValue.ToString(); if (tag == tagName) addTag = false; } } if (addTag) { tagsProp.InsertArrayElementAtIndex(tagsProp.arraySize); SerializedProperty tag = tagsProp.GetArrayElementAtIndex(tagsProp.arraySize - 1); tag.stringValue = tagName; } else EditorUtility.DisplayDialog(Constants.errorString, "This tag name is already taken.", Constants.okString); for (int i = 0; i < tagsProp.arraySize; i++) { SerializedProperty t = tagsProp.GetArrayElementAtIndex(i); oldTagNames[i] = t.stringValue.ToString(); } //Salva tagManager.ApplyModifiedProperties(); return (oldTagNames); } #endregion #endregion #region Reset /* public void resetLayersAndTags() { SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]); SerializedProperty layersProp = tagManager.FindProperty("layers"); SerializedProperty tagsProp = tagManager.FindProperty("tags"); for (int i = 8; i <= 31; i++) { SerializedProperty layerVal = layersProp.GetArrayElementAtIndex(i); layerVal.stringValue = ""; } for (int i = 0; i < tagsProp.arraySize; i++) { SerializedProperty t = tagsProp.GetArrayElementAtIndex(i); t.stringValue = ""; oldTagNames[i] = t.stringValue.ToString(); } //Salvar tagManager.ApplyModifiedProperties(); } */ #endregion }
32.34375
168
0.53401
[ "MIT" ]
Hysumi/Unity-TileEditor2D
Unity2D-TileEditor/Assets/Editor/LayersAndTags.cs
10,353
C#
// Copyright (c) 2013-2015 Cemalettin Dervis, MIT License. // https://github.com/cemdervis/SharpConfig using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace SharpConfig { /// <summary> /// Represents a configuration. /// Configurations contain one or multiple sections /// that in turn can contain one or multiple settings. /// The <see cref="Configuration"/> class is designed /// to work with classic configuration formats such as /// .ini and .cfg, but is not limited to these. /// </summary> public partial class Configuration : IEnumerable<Section> { #region Fields private static NumberFormatInfo mNumberFormat; private static DateTimeFormatInfo mDateTimeFormat; private static char[] mValidCommentChars; private List<Section> mSections; #endregion #region Construction static Configuration() { mNumberFormat = CultureInfo.InvariantCulture.NumberFormat; mDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat; mValidCommentChars = new[] { '#', ';', '\'' }; IgnoreInlineComments = false; IgnorePreComments = false; IgnoreDuplicateSettings = false; IgnoreDuplicateSettings = false; } /// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class. /// </summary> public Configuration() { mSections = new List<Section>(); } #endregion #region Public Methods /// <summary> /// Gets an enumerator that iterates through the configuration. /// </summary> public IEnumerator<Section> GetEnumerator() { return mSections.GetEnumerator(); } /// <summary> /// Gets an enumerator that iterates through the configuration. /// </summary> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Adds a section to the configuration. /// </summary> /// <param name="section">The section to add.</param> public void Add(Section section) { if (section == null) throw new ArgumentNullException("section"); if (Contains(section)) { throw new ArgumentException( "The specified section already exists in the configuration."); } mSections.Add(section); } /// <summary> /// Clears the configuration of all sections. /// </summary> public void Clear() { mSections.Clear(); } /// <summary> /// Determines whether a specified section is contained in the configuration. /// </summary> /// <param name="section">The section to check for containment.</param> /// <returns>True if the section is contained in the configuration; false otherwise.</returns> public bool Contains(Section section) { return mSections.Contains(section); } /// <summary> /// Determines whether a specifically named setting is contained in the section. /// </summary> /// <param name="sectionName">The name of the section.</param> /// <returns>True if the setting is contained in the section; false otherwise.</returns> public bool Contains(string sectionName) { return GetSection(sectionName) != null; } /// <summary> /// Removes a section from this section by its name. /// </summary> /// <param name="sectionName">The case-sensitive name of the section to remove.</param> public void Remove(string sectionName) { if (string.IsNullOrEmpty(sectionName)) throw new ArgumentNullException("sectionName"); var section = GetSection(sectionName); if (section == null) { throw new ArgumentException( "The specified section does not exist in the section."); } Remove(section); } /// <summary> /// Removes a section from the configuration. /// </summary> /// <param name="section">The section to remove.</param> public void Remove(Section section) { if (section == null) throw new ArgumentNullException("section"); if (!Contains(section)) { throw new ArgumentException( "The specified section does not exist in the section."); } mSections.Remove(section); } #endregion #region Load /// <summary> /// Loads a configuration from a file auto-detecting the encoding and /// using the default parsing settings. /// </summary> /// /// <param name="filename">The location of the configuration file.</param> /// /// <returns> /// The loaded <see cref="Configuration"/> object. /// </returns> public static Configuration LoadFromFile(string filename) { return LoadFromFile(filename, null); } /// <summary> /// Loads a configuration from a file. /// </summary> /// /// <param name="filename">The location of the configuration file.</param> /// <param name="encoding">The encoding applied to the contents of the file. Specify null to auto-detect the encoding.</param> /// /// <returns> /// The loaded <see cref="Configuration"/> object. /// </returns> public static Configuration LoadFromFile(string filename, Encoding encoding) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } if (!File.Exists(filename)) { throw new FileNotFoundException("Configuration file not found.", filename); } return encoding == null ? LoadFromString(File.ReadAllText(filename)) : LoadFromString(File.ReadAllText(filename, encoding)); } /// <summary> /// Loads a configuration from a text stream auto-detecting the encoding and /// using the default parsing settings. /// </summary> /// /// <param name="stream">The text stream to load the configuration from.</param> /// /// <returns> /// The loaded <see cref="Configuration"/> object. /// </returns> public static Configuration LoadFromStream(Stream stream) { return LoadFromStream(stream, null); } /// <summary> /// Loads a configuration from a text stream. /// </summary> /// /// <param name="stream"> The text stream to load the configuration from.</param> /// <param name="encoding"> The encoding applied to the contents of the stream. Specify null to auto-detect the encoding.</param> /// /// <returns> /// The loaded <see cref="Configuration"/> object. /// </returns> public static Configuration LoadFromStream(Stream stream, Encoding encoding) { if (stream == null) { throw new ArgumentNullException("stream"); } string source = null; var reader = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding); using (reader) { source = reader.ReadToEnd(); } return LoadFromString(source); } /// <summary> /// Loads a configuration from text (source code). /// </summary> /// /// <param name="source">The text (source code) of the configuration.</param> /// /// <returns> /// The loaded <see cref="Configuration"/> object. /// </returns> public static Configuration LoadFromString(string source) { if (string.IsNullOrEmpty(source)) { throw new ArgumentNullException("source"); } return Parse(source); } #endregion #region LoadBinary /// <summary> /// Loads a configuration from a binary file using the <b>default</b> <see cref="BinaryReader"/>. /// </summary> /// /// <param name="filename">The location of the configuration file.</param> /// /// <returns> /// The loaded configuration. /// </returns> public static Configuration LoadFromBinaryFile(string filename) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } return DeserializeBinary(null, filename); } /// <summary> /// Loads a configuration from a binary file using a specific <see cref="BinaryReader"/>. /// </summary> /// /// <param name="filename">The location of the configuration file.</param> /// <param name="reader"> The reader to use. Specify null to use the default <see cref="BinaryReader"/>.</param> /// /// <returns> /// The loaded configuration. /// </returns> public static Configuration LoadFromBinaryFile(string filename, BinaryReader reader) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } return DeserializeBinary(reader, filename); } /// <summary> /// Loads a configuration from a binary stream, using the <b>default</b> <see cref="BinaryReader"/>. /// </summary> /// /// <param name="stream">The stream to load the configuration from.</param> /// /// <returns> /// The loaded configuration. /// </returns> public static Configuration LoadFromBinaryStream(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } return DeserializeBinary(null, stream); } /// <summary> /// Loads a configuration from a binary stream, using a specific <see cref="BinaryReader"/>. /// </summary> /// /// <param name="stream">The stream to load the configuration from.</param> /// <param name="reader">The reader to use. Specify null to use the default <see cref="BinaryReader"/>.</param> /// /// <returns> /// The loaded configuration. /// </returns> public static Configuration LoadFromBinaryStream(Stream stream, BinaryReader reader) { if (stream == null) { throw new ArgumentNullException("stream"); } return DeserializeBinary(reader, stream); } #endregion #region Save /// <summary> /// Saves the configuration to a file using the default character encoding, which is UTF8. /// </summary> /// /// <param name="filename">The location of the configuration file.</param> public void SaveToFile(string filename) { SaveToFile(filename, null); } /// <summary> /// Saves the configuration to a file. /// </summary> /// /// <param name="filename">The location of the configuration file.</param> /// <param name="encoding">The character encoding to use. Specify null to use the default encoding, which is UTF8.</param> public void SaveToFile(string filename, Encoding encoding) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } Serialize(filename, encoding); } /// <summary> /// Saves the configuration to a stream using the default character encoding, which is UTF8. /// </summary> /// /// <param name="stream">The stream to save the configuration to.</param> public void SaveToStream(Stream stream) { SaveToStream(stream, null); } /// <summary> /// Saves the configuration to a stream. /// </summary> /// /// <param name="stream">The stream to save the configuration to.</param> /// <param name="encoding">The character encoding to use. Specify null to use the default encoding, which is UTF8.</param> public void SaveToStream(Stream stream, Encoding encoding) { if (stream == null) { throw new ArgumentNullException("stream"); } Serialize(stream, encoding); } #endregion #region SaveBinary /// <summary> /// Saves the configuration to a binary file, using the default <see cref="BinaryWriter"/>. /// </summary> /// /// <param name="filename">The location of the configuration file.</param> public void SaveToBinaryFile(string filename) { SaveToBinaryFile(filename, null); } /// <summary> /// Saves the configuration to a binary file, using a specific <see cref="BinaryWriter"/>. /// </summary> /// /// <param name="filename">The location of the configuration file.</param> /// <param name="writer"> The writer to use. Specify null to use the default writer.</param> public void SaveToBinaryFile(string filename, BinaryWriter writer) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } SerializeBinary(writer, filename); } /// <summary> /// Saves the configuration to a binary stream, using the default <see cref="BinaryWriter"/>. /// </summary> /// /// <param name="stream">The stream to save the configuration to.</param> public void SaveToBinaryStream(Stream stream) { SaveToBinaryStream(stream, null); } /// <summary> /// Saves the configuration to a binary file, using a specific <see cref="BinaryWriter"/>. /// </summary> /// /// <param name="stream">The stream to save the configuration to.</param> /// <param name="writer">The writer to use. Specify null to use the default writer.</param> public void SaveToBinaryStream(Stream stream, BinaryWriter writer) { if (stream == null) { throw new ArgumentNullException("stream"); } SerializeBinary(writer, stream); } #endregion #region Properties /// <summary> /// Gets or sets the number format that is used for value conversion in SharpConfig. /// The default value is CultureInfo.InvariantCulture.NumberFormat. /// </summary> public static NumberFormatInfo NumberFormat { get { return mNumberFormat; } set { if (value == null) { throw new ArgumentNullException("value"); } mNumberFormat = value; } } /// <summary> /// Gets or sets the DateTime format that is used for value conversion in SharpConfig. /// The default value is CultureInfo.InvariantCulture.NumberFormat. /// </summary> public static DateTimeFormatInfo DateTimeFormat { get { return mDateTimeFormat; } set { if (value == null) { throw new ArgumentNullException("value"); } mDateTimeFormat = value; } } /// <summary> /// Gets or sets the array that contains all comment delimiting characters. /// </summary> public static char[] ValidCommentChars { get { return mValidCommentChars; } set { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length == 0) { throw new ArgumentException( "The comment chars array must not be empty.", "value"); } mValidCommentChars = value; } } /// <summary> /// Gets or sets a value indicating whether inline-comments /// should be ignored when parsing a configuration. /// </summary> public static bool IgnoreInlineComments { get; set; } /// <summary> /// Gets or sets a value indicating whether pre-comments /// should be ignored when parsing a configuration. /// </summary> public static bool IgnorePreComments { get; set; } /// <summary> /// Gets or sets a value indicating whether duplicate /// settings should be ignored when parsing a configuration. /// </summary> public static bool IgnoreDuplicateSettings { get; set; } /// <summary> /// Gets or sets a value indicating whether duplicate sections /// should be ignored when parsing a configuration /// </summary> public static bool IgnoreDuplicateSections { get; set; } /// <summary> /// Gets the number of sections that are in the configuration. /// </summary> public int SectionCount { get { return mSections.Count; } } /// <summary> /// Gets or sets a section by index. /// </summary> /// <param name="index">The index of the section in the configuration.</param> public Section this[int index] { get { if (index < 0 || index >= mSections.Count) { throw new ArgumentOutOfRangeException("index"); } return mSections[index]; } set { if (index < 0 || index >= mSections.Count) { throw new ArgumentOutOfRangeException("index"); } mSections[index] = value; } } /// <summary> /// Gets or sets a section by its name. /// </summary> /// /// <param name="name">The name of the section.</param> /// /// <returns> /// The section if found, otherwise a new section with /// the specified name is created, added to the configuration and returned. /// </returns> public Section this[string name] { get { var section = GetSection(name); if (section == null) { section = new Section(name); Add(section); } return section; } set { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name", "The section name must not be null or empty."); } if (value == null) { throw new ArgumentNullException("value", "The specified value must not be null."); } // Check if there already is a section by that name. var section = GetSection(name); int settingIndex = section != null ? mSections.IndexOf(section) : -1; if (settingIndex < 0) { // A section with that name does not exist yet; add it. mSections.Add(section); } else { // A section with that name exists; overwrite. mSections[settingIndex] = section; } } } private Section GetSection(int index) { if (index < 0 || index >= mSections.Count) { throw new ArgumentOutOfRangeException("index"); } return mSections[index]; } private Section GetSection(string name) { foreach (var section in mSections) { if (string.Equals(section.Name, name, StringComparison.OrdinalIgnoreCase)) { return section; } } return null; } #endregion } }
32.220544
137
0.528551
[ "MIT" ]
BOBO41/CasinosClient
_Backup/_Backup7/Common/SharpConfig/Configuration.cs
21,332
C#
using System; using System.Collections.Generic; using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Rest.CometChat.Abstractions; using Rest.CometChat.Requests; using Rest.CometChat.Responses; using Rest.CometChat.ServiceModel; namespace Rest.CometChat { public class FriendService : BaseService, IFriendService { public FriendService(ICometChatConfig config) : base(config) { } public FriendService(ICometChatConfig config, IHttpClientFactory httpClientFactory) : base(config, httpClientFactory) { } public async Task<AddFriendResponse?> AddAsync( string uid, List<string> friendUids, CancellationToken cancellationToken = default) { using var httpClient = this.HttpClient; using var httpRequestMessage = CreateRequest(new Dictionary<string, object> { { "accepted", friendUids } }, HttpMethod.Post, new Uri(this.BaseUri, $"users/{uid}/friends")); using var response = await httpClient.SendAsync(httpRequestMessage, cancellationToken); using var stream = await response.Content.ReadAsStreamAsync(); var result = await JsonSerializer .DeserializeAsync<DataContainer<AddFriendResponse>>(stream, this.JsonSerializerOptions, cancellationToken); return result?.Entity; } public async Task<PaginatedList<User>?> ListAsync( string uid, ListUserOptions? options = default, CancellationToken cancellationToken = default) { var requestUri = new Uri(this.BaseUri, $"users/{uid}/friends"); var requestUrl = requestUri.AbsoluteUri; if (options is not null) { requestUrl = OptionsToUrlQuery(options.Value, requestUrl); } using var httpClient = this.HttpClient; using var stream = await httpClient.GetStreamAsync(requestUrl); return await JsonSerializer .DeserializeAsync<PaginatedList<User>>(stream, this.JsonSerializerOptions, cancellationToken); } public async Task<BaseResponse?> RemoveAsync( string uid, List<string> friendUids, CancellationToken cancellationToken = default) { using var httpClient = this.HttpClient; using var httpRequestMessage = CreateRequest(new Dictionary<string, object> { { "friends", friendUids } }, HttpMethod.Delete, new Uri(this.BaseUri, $"users/{uid}/friends")); using var response = await httpClient.SendAsync(httpRequestMessage, cancellationToken); using var stream = await response.Content.ReadAsStreamAsync(); var result = await JsonSerializer .DeserializeAsync<DataContainer<BaseResponse>>(stream, this.JsonSerializerOptions, cancellationToken); return result?.Entity; } } }
30.905882
111
0.754853
[ "MIT" ]
diegostamigni/Rest.CometChat
Rest.CometChat/FriendService.cs
2,627
C#
namespace Steepshot.Core.Models.Responses { ///{ /// "message": "Comment created" ///} public class CreateCommentResponse : MessageField { public bool IsCreated => Message.Equals("Comment created"); } }
23.5
67
0.629787
[ "Unlicense" ]
AnCh7/sweetshot
src/Steepshot.Core/Models/Responses/CreateCommentResponse.cs
235
C#
#region Usings using System; using System.Collections.Generic; using System.Runtime.Serialization; #endregion namespace FinancialCharting.Library.Models.MarketData.Common { /// ASX ["Date","Open","High","Low","Settle","Volume","Open Interest (OI)"] /// EUREX ["Date","Open","High","Low","Settle","Volume","Prev. Day Open Interest"] /// LIFFE ["Date","Open","High","Low","Settle","Volume","Interest"] /// MGEX ["Date","Open","High","Low","Last","Volume","Prev. Day Open Interest"] /// PXDATA ["Date","Open","High","Low","Settle","Volume","Open Interest (OI)"] [DataContract] public class OhlcvOpenInterestData : OhlcvData { public OhlcvOpenInterestData(List<object> data) : base(data) { OpenInterest = Convert.ToDouble(data[6]); } [DataMember(Name = "openInterest", Order = 7)] public double OpenInterest { get; set; } } }
30.285714
83
0.675708
[ "MIT" ]
AnCh7/FinancialCharting
src/FinancialCharting.Library/Models/MarketData/Common/OhlcvOpenInterestData.cs
848
C#
using System; using Swastika.Domain.Data.ViewModels; using Microsoft.EntityFrameworkCore.Storage; using System.Threading.Tasks; using Swastika.IO.Domain.Core.ViewModels; using Swastika.Identity.Data; using Swastika.IO.Identity.Identity.Entities; namespace Swastika.IO.Identity.ViewModels { public class RefreshTokenViewModel : ViewModelBase<ApplicationDbContext, RefreshToken, RefreshTokenViewModel> { public string Id { get; set; } public string Subject { get; set; } public string ClientId { get; set; } public DateTime IssuedUtc { get; set; } public DateTime ExpiresUtc { get; set; } public string Email { get; set; } public RefreshTokenViewModel(RefreshToken model, ApplicationDbContext _context = null, IDbContextTransaction _transaction = null) : base(model, _context, _transaction) { } #region Expands public static async Task<RepositoryResponse<bool>> LogoutOther(string refreshTokenId) { ApplicationDbContext context = new ApplicationDbContext(); IDbContextTransaction transaction = context.Database.BeginTransaction(); try { var token = await RefreshTokenViewModel.Repository.GetSingleModelAsync(t => t.Id == refreshTokenId, context, transaction); if (token.IsSucceed) { var result = await RefreshTokenViewModel.Repository.RemoveListModelAsync(t => t.Id != refreshTokenId && t.Email == token.Data.Email); if (result.IsSucceed) { if (transaction == null) { transaction.Commit(); } return new RepositoryResponse<bool>() { IsSucceed = true, Data = true }; } else { if (transaction == null) { transaction.Rollback(); } return new RepositoryResponse<bool>() { IsSucceed = false, Data = false }; } } else { if (transaction == null) { transaction.Rollback(); } return new RepositoryResponse<bool>() { IsSucceed = false, Data = false }; } } catch (Exception ex) { transaction.Rollback(); return new RepositoryResponse<bool>() { IsSucceed = false, Data = false, Exception = ex }; } finally { context.Dispose(); } } #endregion } }
32.717172
175
0.456931
[ "MIT" ]
fossabot/Swastika-IO-Identity
src/Swastika.Identity/Identity/ViewModels/RefreshTokenViewModel.cs
3,241
C#
namespace Gu.Wpf.Reactive.Tests.Views { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Threading; using System.Threading.Tasks; using System.Windows; using Gu.Reactive; using Gu.Reactive.Tests.Helpers; using Gu.Wpf.Reactive; using Gu.Wpf.Reactive.Tests.FakesAndHelpers; using Microsoft.Reactive.Testing; using NUnit.Framework; [Apartment(ApartmentState.STA)] public class ThrottledViewTests { [OneTimeSetUp] public void OneTimeSetUp() { App.Start(); } [Test] public void AddToSourceTestScheduler() { var source = new ObservableCollection<int> { 1, 2, 3 }; var scheduler = new TestScheduler(); using var view = new ThrottledView<int>(source, TimeSpan.FromMilliseconds(10), scheduler, leaveOpen: true); scheduler.Start(); using var expected = source.SubscribeAll(); using var actual = view.SubscribeAll(); source.Add(4); scheduler.Start(); CollectionAssert.AreEqual(source, view); CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default); } [Test] public void AddToSourceExplicitRefresh() { var source = new ObservableCollection<int> { 1, 2, 3 }; using var view = source.AsThrottledView(TimeSpan.FromMilliseconds(10)); using var expected = source.SubscribeAll(); using var actual = view.SubscribeAll(); source.Add(4); view.Refresh(); CollectionAssert.AreEqual(source, view); CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default); } [Test] public async Task AddToSourceAwait() { var source = new ObservableCollection<int> { 1, 2, 3 }; using var view = source.AsThrottledView(TimeSpan.FromMilliseconds(10)); using var expected = source.SubscribeAll(); using var actual = view.SubscribeAll(); source.Add(4); await Task.Delay(TimeSpan.FromMilliseconds(40)).ConfigureAwait(false); CollectionAssert.AreEqual(source, view); CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default); } [Test] public void ManyAddsOneResetThrottledExplicitRefresh() { var source = new ObservableCollection<int> { 1, 2, 3 }; var scheduler = new TestScheduler(); using var view = new ThrottledView<int>(source, TimeSpan.FromMilliseconds(100), scheduler, leaveOpen: true); using var actual = view.SubscribeAll(); for (var i = 4; i < 10; i++) { source.Add(i); } CollectionAssert.AreEqual(new[] { 1, 2, 3 }, view); CollectionAssert.IsEmpty(actual); view.Refresh(); CollectionAssert.AreEqual(source, view); var expected = new EventArgs[] { CachedEventArgs.CountPropertyChanged, CachedEventArgs.IndexerPropertyChanged, CachedEventArgs.NotifyCollectionReset, }; CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default); } [Test] public void ManyAddsOneResetThrottledTestScheduler() { var source = new ObservableCollection<int> { 1, 2, 3 }; var scheduler = new TestScheduler(); using var view = new ThrottledView<int>(source, TimeSpan.FromMilliseconds(100), scheduler, leaveOpen: true); scheduler.Start(); CollectionAssert.AreEqual(source, view); using var actual = view.SubscribeAll(); for (var i = 4; i < 10; i++) { source.Add(i); } CollectionAssert.AreEqual(new[] { 1, 2, 3 }, view); CollectionAssert.IsEmpty(actual); scheduler.Start(); CollectionAssert.AreEqual(source, view); var expected = new EventArgs[] { CachedEventArgs.CountPropertyChanged, CachedEventArgs.IndexerPropertyChanged, CachedEventArgs.NotifyCollectionReset, }; CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default); } [Test] public void TwoBurstsTwoResets() { var changes = new List<NotifyCollectionChangedEventArgs>(); var source = new ObservableCollection<int> { 1, 2, 3 }; var deferTime = TimeSpan.FromMilliseconds(10); using var throttledView = source.AsThrottledView(deferTime); throttledView.CollectionChanged += (_, e) => changes.Add(e); for (var i = 0; i < 10; i++) { source.Add(i); } throttledView.Refresh(); for (var i = 0; i < 10; i++) { source.Add(i); } throttledView.Refresh(); CollectionAssert.AreEqual(source, throttledView); var expected = new[] { new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset), new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset), }; CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default); } [Test] public async Task WhenAddToSourceWithBufferTime() { var source = new ObservableCollection<int>(); using var expected = source.SubscribeAll(); var bufferTime = TimeSpan.FromMilliseconds(20); using var view = source.AsThrottledView(bufferTime); using var actual = view.SubscribeAll(); source.Add(1); ////await Application.Current.Dispatcher.SimulateYield(); CollectionAssert.IsEmpty(view); CollectionAssert.IsEmpty(actual); await Task.Delay(bufferTime).ConfigureAwait(false); await Application.Current.Dispatcher.SimulateYield(); await Application.Current.Dispatcher.SimulateYield(); CollectionAssert.AreEqual(source, view); CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default); } [Test] public async Task WhenManyAddsToSourceWithBufferTime() { var source = new ObservableCollection<int>(); var bufferTime = TimeSpan.FromMilliseconds(20); using var view = source.AsThrottledView(bufferTime); using var actual = view.SubscribeAll(); source.Add(1); source.Add(1); await Application.Current.Dispatcher.SimulateYield(); CollectionAssert.IsEmpty(view); CollectionAssert.IsEmpty(actual); await Task.Delay(bufferTime).ConfigureAwait(false); await Task.Delay(bufferTime).ConfigureAwait(false); await Application.Current.Dispatcher.SimulateYield(); CollectionAssert.AreEqual(source, view); var expected = new EventArgs[] { CachedEventArgs.CountPropertyChanged, CachedEventArgs.IndexerPropertyChanged, CachedEventArgs.NotifyCollectionReset, }; CollectionAssert.AreEqual(expected, actual, EventArgsComparer.Default); } } }
38.580808
120
0.592093
[ "MIT" ]
GuOrg/Gu.Reactive
Gu.Wpf.Reactive.Tests/Views/ThrottledViewTests.cs
7,641
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class enemyController : MonoBehaviour { public float velocity = 2f; private Rigidbody2D rb2d; // Use this for initialization void Start () { rb2d = GetComponent<Rigidbody2D>(); rb2d.velocity = Vector2.left * velocity; } // Update is called once per frame void Update () { } }
20.1
48
0.686567
[ "MIT" ]
juandiemore/Juego-Unity
VIDEOJUEGO/Shaffer/ClaseNivelMario-master/CharacterController2D-master/Animation2D/Assets/Scripts Master/enemyController.cs
404
C#
using UnityEngine; namespace UnityAtoms { [CreateAssetMenu(menuName = "Unity Atoms/Lists/Vector2", fileName = "Vector2List", order = 4)] public class Vector2List : ScriptableObjectList<Vector2, Vector2Event> { } }
25.555556
98
0.721739
[ "MIT" ]
mbryne/unity-atoms
Assets/UnityAtoms/Lists/Vector2List.cs
230
C#
namespace Explorer.Queries { using System; using System.Text.Json; public class DatetimeProjection : ColumnProjection { private readonly string dateInterval; private readonly Random rng = new Random(); public DatetimeProjection(string column, int index, string dateInterval) : base(column, index) { this.dateInterval = dateInterval; } public override string Project() { return $"date_trunc('{dateInterval}', \"{Column}\")"; } public override object? Invert(JsonElement value) { if (value.ValueKind == JsonValueKind.Null) { return null; } var lowerBound = value.GetDateTime(); return dateInterval switch { // Add a random offset at the next lower level of granularity. "year" => lowerBound.AddMonths(rng.Next(12)), "quarter" => lowerBound.AddMonths(rng.Next(3)), "month" => lowerBound.AddDays(rng.NextDouble() * DateTime.DaysInMonth(lowerBound.Year, lowerBound.Month)), "day" => lowerBound.AddHours(rng.NextDouble() * 24), "hour" => lowerBound.AddMinutes(rng.NextDouble() * 60), "minute" => lowerBound.AddSeconds(rng.NextDouble() * 60), "second" => lowerBound.AddMilliseconds(rng.NextDouble() * 1000), _ => lowerBound, }; } } }
33.688889
122
0.554749
[ "MIT" ]
diffix/explorer
src/explorer/Queries/ColumnProjections/DatetimeProjection.cs
1,516
C#
using System; using System.Linq; using System.Reactive.Linq; using System.Windows; using System.Windows.Navigation; using Caliburn.Micro; using ChronoPlurk.Resources.i18n; using ChronoPlurk.Services; using HtmlAgilityPack; using Microsoft.Phone.Controls; namespace ChronoPlurk.Views { public partial class LoginBrowserPage { private static readonly string[] AllowedUrls = new string[] { "/m/login", "/m/authorize", "/login/authorize", // authorize* wildcard "/OAuth/authorize", "/OAuth/authorizeDone", }; public LoginBrowserPage() { InitializeComponent(); // AnimationContext = LayoutRoot; } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); string deviceName; if (!NavigationContext.QueryString.TryGetValue("DeviceName", out deviceName) || deviceName.IsNullOrEmpty()) { deviceName = null; } var plurkService = IoC.Get<IPlurkService>(); plurkService.GetRequestToken(deviceName) .ObserveOnDispatcher() .Catch<Uri, Exception>(ex => { Execute.OnUIThread(() => { MessageBox.Show(AppResources.unhandledErrorMessage.Replace("\\n", Environment.NewLine)); NavigationService.GoBack(); }); return Observable.Empty<Uri>(); }) .Subscribe(uri => { Browser.Source = uri; }); } private void Browser_Navigating(object sender, NavigatingEventArgs e) { if (LoadingGrid.Visibility != Visibility.Visible) { var progressService = IoC.Get<IProgressService>(); progressService.Show(); } var path = e.Uri.AbsolutePath; if (AllowedUrls.All(url => !path.StartsWith(url))) { e.Cancel = true; NavigationService.GoBack(); } } private void Browser_Navigated(object sender, NavigationEventArgs e) { var progressService = IoC.Get<IProgressService>(); progressService.Hide(); if (LoadingGrid.Visibility == Visibility.Visible) { loadedStoryboard.Begin(); } } private void Browser_LoadCompleted(object sender, NavigationEventArgs e) { if (e.Uri.OriginalString.Contains("authorizeDone")) { ProcessVerifier(); NavigationService.GoBack(); } } private void ProcessVerifier() { // verifierText = Browser.InvokeScript("eval", "document.getElementById('oauth_verifier').textContent") as string; var document = new HtmlDocument(); document.LoadHtml(Browser.SaveToString()); var element = document.GetElementbyId("oauth_verifier"); if (element != null && element.InnerText != null) { var verifier = element.InnerText.Trim(); var plurkService = IoC.Get<IPlurkService>(); plurkService.VerifierTemp = verifier; } } private void loadedStoryboard_Completed(object sender, EventArgs e) { LoadingGrid.Visibility = Visibility.Collapsed; } } }
32.903509
127
0.521461
[ "MIT" ]
pH200/chronoplurk-wp
src/ChronoPlurk/Views/LoginBrowserPage.xaml.cs
3,753
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Mod.Ethics.Infrastructure.Migrations { public partial class AddOgeForm450 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "OgeForm450", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column<string>(type: "nvarchar(max)", nullable: true), Year = table.Column<int>(type: "int", nullable: false), ReportingStatus = table.Column<string>(type: "nvarchar(max)", nullable: true), DueDate = table.Column<DateTime>(type: "datetime2", nullable: false), EmployeesName = table.Column<string>(type: "nvarchar(max)", nullable: true), EmailAddress = table.Column<string>(type: "nvarchar(max)", nullable: true), PositionTitle = table.Column<string>(type: "nvarchar(max)", nullable: true), Agency = table.Column<string>(type: "nvarchar(max)", nullable: true), BranchUnitAndAddress = table.Column<string>(type: "nvarchar(max)", nullable: true), WorkPhone = table.Column<string>(type: "nvarchar(max)", nullable: true), DateOfAppointment = table.Column<DateTime>(type: "datetime2", nullable: true), Grade = table.Column<string>(type: "nvarchar(max)", nullable: true), IsSpecialGovernmentEmployee = table.Column<bool>(type: "bit", nullable: false), SgeMailingAddress = table.Column<string>(type: "nvarchar(max)", nullable: true), HasAssetsOrIncome = table.Column<bool>(type: "bit", nullable: false), HasLiabilities = table.Column<bool>(type: "bit", nullable: false), HasOutsidePositions = table.Column<bool>(type: "bit", nullable: false), HasAgreementsOrArrangements = table.Column<bool>(type: "bit", nullable: false), HasGiftsOrTravelReimbursements = table.Column<bool>(type: "bit", nullable: false), DaysExtended = table.Column<int>(type: "int", nullable: false), CorrelationId = table.Column<string>(type: "nvarchar(max)", nullable: true), FormFlags = table.Column<int>(type: "int", nullable: false), FormStatus = table.Column<string>(type: "nvarchar(max)", nullable: true), CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), ModifiedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), ModifiedTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatedTime = table.Column<DateTime>(type: "datetime2", nullable: false), IsDeleted = table.Column<bool>(type: "bit", nullable: false), DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), DeletedTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_OgeForm450", x => x.Id); }); migrationBuilder.CreateTable( name: "OgeForm450ExtensionRequest", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Reason = table.Column<string>(type: "nvarchar(max)", nullable: true), DaysRequested = table.Column<int>(type: "int", nullable: false), OgeForm450Id = table.Column<int>(type: "int", nullable: false), CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), ModifiedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), ModifiedTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatedTime = table.Column<DateTime>(type: "datetime2", nullable: false), IsDeleted = table.Column<bool>(type: "bit", nullable: false), DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), DeletedTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_OgeForm450ExtensionRequest", x => x.Id); table.ForeignKey( name: "FK_OgeForm450ExtensionRequest_OgeForm450_OgeForm450Id", column: x => x.OgeForm450Id, principalTable: "OgeForm450", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "OgeForm450ReportableInformation", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Type = table.Column<string>(type: "nvarchar(max)", nullable: true), Name = table.Column<string>(type: "nvarchar(max)", nullable: true), Description = table.Column<string>(type: "nvarchar(max)", nullable: true), AdditionalInfo = table.Column<string>(type: "nvarchar(max)", nullable: true), NoLongerHeld = table.Column<bool>(type: "bit", nullable: false), OgeForm450Id = table.Column<int>(type: "int", nullable: false), CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), ModifiedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), ModifiedTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatedTime = table.Column<DateTime>(type: "datetime2", nullable: false), IsDeleted = table.Column<bool>(type: "bit", nullable: false), DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), DeletedTime = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_OgeForm450ReportableInformation", x => x.Id); table.ForeignKey( name: "FK_OgeForm450ReportableInformation_OgeForm450_OgeForm450Id", column: x => x.OgeForm450Id, principalTable: "OgeForm450", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "OgeForm450Status", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Status = table.Column<string>(type: "nvarchar(max)", nullable: true), EmployeeId = table.Column<int>(type: "int", nullable: false), Comment = table.Column<string>(type: "nvarchar(max)", nullable: true), OgeForm450Id = table.Column<int>(type: "int", nullable: false), CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), ModifiedBy = table.Column<string>(type: "nvarchar(max)", nullable: true), ModifiedTime = table.Column<DateTime>(type: "datetime2", nullable: false), CreatedTime = table.Column<DateTime>(type: "datetime2", nullable: false) }, constraints: table => { table.PrimaryKey("PK_OgeForm450Status", x => x.Id); table.ForeignKey( name: "FK_OgeForm450Status_OgeForm450_OgeForm450Id", column: x => x.OgeForm450Id, principalTable: "OgeForm450", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_OgeForm450ExtensionRequest_OgeForm450Id", table: "OgeForm450ExtensionRequest", column: "OgeForm450Id"); migrationBuilder.CreateIndex( name: "IX_OgeForm450ReportableInformation_OgeForm450Id", table: "OgeForm450ReportableInformation", column: "OgeForm450Id"); migrationBuilder.CreateIndex( name: "IX_OgeForm450Status_OgeForm450Id", table: "OgeForm450Status", column: "OgeForm450Id"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "OgeForm450ExtensionRequest"); migrationBuilder.DropTable( name: "OgeForm450ReportableInformation"); migrationBuilder.DropTable( name: "OgeForm450Status"); migrationBuilder.DropTable( name: "OgeForm450"); } } }
57.769231
103
0.54051
[ "CC0-1.0" ]
EOP-OMB/ethics-portal
Server/Mod.Ethics.Infrastructure/Migrations/20210322190739_AddOgeForm450.cs
9,765
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.OutboundBot.Model.V20191226 { public class DeleteScriptResponse : AcsResponse { private string requestId; private bool? success; private string code; private string message; private int? httpStatusCode; public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Success { get { return success; } set { success = value; } } public string Code { get { return code; } set { code = value; } } public string Message { get { return message; } set { message = value; } } public int? HttpStatusCode { get { return httpStatusCode; } set { httpStatusCode = value; } } } }
17.646465
63
0.631368
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-outboundbot/OutboundBot/Model/V20191226/DeleteScriptResponse.cs
1,747
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq; namespace ApplicationModelWebSite { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class MultipleAreasAttribute : Attribute { public MultipleAreasAttribute(string area1, string area2, params string[] areaNames) { AreaNames = new string[] { area1, area2 }.Concat(areaNames).ToArray(); } public string[] AreaNames { get; } } }
30.05
92
0.69218
[ "MIT" ]
48355746/AspNetCore
src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/MultipleAreasAttribute.cs
603
C#
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2019 Jiang Yin. All rights reserved. // Homepage: http://gameframework.cn/ // Feedback: mailto:jiangyin@gameframework.cn //------------------------------------------------------------ namespace UnityGameFramework.Editor.AssetBundleTools { public sealed partial class AssetBundleAnalyzerController { private struct Stamp { private readonly string m_HostAssetName; private readonly string m_DependencyAssetName; public Stamp(string hostAssetName, string dependencyAssetName) { m_HostAssetName = hostAssetName; m_DependencyAssetName = dependencyAssetName; } public string HostAssetName { get { return m_HostAssetName; } } public string DependencyAssetName { get { return m_DependencyAssetName; } } } } }
27.878049
74
0.48119
[ "BSD-3-Clause" ]
AriesPlaysNation/PokemonUnity
Pokemon Unity/Assets/GameFramework/Scripts/Editor/AssetBundleAnalyzer/AssetBundleAnalyzerController.Stamp.cs
1,146
C#
// Copyright 2018 Andrew White // // 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.Threading.Tasks; using Finbuckle.MultiTenant.Core; using Microsoft.Extensions.Logging; namespace Finbuckle.MultiTenant.Stores { /// <summary> /// A multitenant store decorator that handles exception handling and logging. /// </summary> public class MultiTenantStoreWrapper<TStore> : IMultiTenantStore where TStore : IMultiTenantStore { public TStore Store { get; } private readonly ILogger logger; public MultiTenantStoreWrapper(TStore store, ILogger<TStore> logger) { this.Store = store; this.logger = logger; } public async Task<TenantInfo> TryGetAsync(string id) { if (id == null) { throw new ArgumentNullException(nameof(id)); } TenantInfo result = null; try { result = await Store.TryGetAsync(id); } catch (Exception e) { var errorMessage = $"Exception in {typeof(TStore)}.TryGetAsync."; Utilities.TryLogError(logger, errorMessage, e); } if (result != null) { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryGetAsync: Tenant Id \"{id}\" found."); } else { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryGetAsync: Unable to find Tenant Id \"{id}\"."); } return result; } public async Task<TenantInfo> TryGetByIdentifierAsync(string identifier) { if (identifier == null) { throw new ArgumentNullException(nameof(identifier)); } TenantInfo result = null; try { result = await Store.TryGetByIdentifierAsync(identifier); } catch (Exception e) { var errorMessage = $"Exception in {typeof(TStore)}.TryGetByIdentifierAsync."; Utilities.TryLogError(logger, errorMessage, e); } if (result != null) { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryGetByIdentifierAsync: Tenant found with identifier \"{identifier}\"."); } else { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryGetByIdentifierAsync: Unable to find Tenant with identifier \"{identifier}\"."); } return result; } public async Task<bool> TryAddAsync(TenantInfo tenantInfo) { if (tenantInfo == null) { throw new ArgumentNullException(nameof(tenantInfo)); } if (tenantInfo.Id == null) { throw new ArgumentNullException(nameof(tenantInfo.Id)); } if (tenantInfo.Identifier == null) { throw new ArgumentNullException(nameof(tenantInfo.Identifier)); } var result = false; try { var existing = await TryGetAsync(tenantInfo.Id); if (existing != null) { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryAddAsync: Tenant already exists. Id: \"{tenantInfo.Id}\", Identifier: \"{tenantInfo.Identifier}\""); goto end; } existing = await TryGetByIdentifierAsync(tenantInfo.Identifier); if (existing != null) { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryAddAsync: Tenant already exists. Id: \"{tenantInfo.Id}\", Identifier: \"{tenantInfo.Identifier}\""); goto end; } result = await Store.TryAddAsync(tenantInfo); } catch (Exception e) { var errorMessage = $"Exception in {typeof(TStore)}.TryAddAsync."; Utilities.TryLogError(logger, errorMessage, e); } end: if (result) { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryAddAsync: Tenant added. Id: \"{tenantInfo.Id}\", Identifier: \"{tenantInfo.Identifier}\""); } else { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryAddAsync: Unable to add Tenant. Id: \"{tenantInfo.Id}\", Identifier: \"{tenantInfo.Identifier}\""); } return result; } public async Task<bool> TryRemoveAsync(string id) { if (id == null) { throw new ArgumentNullException(nameof(id)); } var result = false; try { result = await Store.TryRemoveAsync(id); } catch (Exception e) { var errorMessage = $"Exception in {typeof(TStore)}.TryRemoveAsync."; Utilities.TryLogError(logger, errorMessage, e); } if (result) { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryRemoveAsync: Tenant Id: \"{id}\" removed."); } else { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryRemoveAsync: Unable to remove Tenant Id: \"{id}\"."); } return result; } public async Task<bool> TryUpdateAsync(TenantInfo tenantInfo) { if (tenantInfo == null) { throw new ArgumentNullException(nameof(tenantInfo)); } if (tenantInfo.Id == null) { throw new ArgumentNullException(nameof(tenantInfo.Id)); } var result = false; try { var existing = await TryGetAsync(tenantInfo.Id); if (existing == null) { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryUpdateAsync: Tenant Id: \"{tenantInfo.Id}\" not found."); goto end; } result = await Store.TryUpdateAsync(tenantInfo); } catch (Exception e) { var errorMessage = $"Exception in {typeof(TStore)}.TryUpdateAsync."; Utilities.TryLogError(logger, errorMessage, e); } end: if (result) { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryUpdateAsync: Tenant Id: \"{tenantInfo.Id}\" updated."); } else { Utilities.TryLogInfo(logger, $"{typeof(TStore)}.TryUpdateAsync: Unable to update Tenant Id: \"{tenantInfo.Id}\"."); } return result; } } }
32.465517
171
0.518322
[ "Apache-2.0" ]
GordonBlahut/Finbuckle.MultiTenant
src/Finbuckle.MultiTenant.Core/Stores/MultiTenantStoreWrapper.cs
7,532
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for VaultsOperations. /// </summary> public static partial class VaultsOperationsExtensions { /// <summary> /// Fetches all the resources of the specified type in the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Vault> ListBySubscriptionId(this IVaultsOperations operations) { return operations.ListBySubscriptionIdAsync().GetAwaiter().GetResult(); } /// <summary> /// Fetches all the resources of the specified type in the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Vault>> ListBySubscriptionIdAsync(this IVaultsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionIdWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of Vaults. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> public static IPage<Vault> ListByResourceGroup(this IVaultsOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of Vaults. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Vault>> ListByResourceGroupAsync(this IVaultsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get the Vault details. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> public static Vault Get(this IVaultsOperations operations, string resourceGroupName, string vaultName) { return operations.GetAsync(resourceGroupName, vaultName).GetAwaiter().GetResult(); } /// <summary> /// Get the Vault details. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Vault> GetAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, vaultName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a Recovery Services vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='vault'> /// Recovery Services Vault to be created. /// </param> public static Vault CreateOrUpdate(this IVaultsOperations operations, string resourceGroupName, string vaultName, Vault vault) { return operations.CreateOrUpdateAsync(resourceGroupName, vaultName, vault).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a Recovery Services vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='vault'> /// Recovery Services Vault to be created. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Vault> CreateOrUpdateAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, Vault vault, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vaultName, vault, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> public static void Delete(this IVaultsOperations operations, string resourceGroupName, string vaultName) { operations.DeleteAsync(resourceGroupName, vaultName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, vaultName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Updates the vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='vault'> /// Recovery Services Vault to be created. /// </param> public static Vault Update(this IVaultsOperations operations, string resourceGroupName, string vaultName, PatchVault vault) { return operations.UpdateAsync(resourceGroupName, vaultName, vault).GetAwaiter().GetResult(); } /// <summary> /// Updates the vault. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='vault'> /// Recovery Services Vault to be created. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Vault> UpdateAsync(this IVaultsOperations operations, string resourceGroupName, string vaultName, PatchVault vault, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, vaultName, vault, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Fetches all the resources of the specified type in the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Vault> ListBySubscriptionIdNext(this IVaultsOperations operations, string nextPageLink) { return operations.ListBySubscriptionIdNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Fetches all the resources of the specified type in the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Vault>> ListBySubscriptionIdNextAsync(this IVaultsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionIdNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieve a list of Vaults. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Vault> ListByResourceGroupNext(this IVaultsOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of Vaults. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Vault>> ListByResourceGroupNextAsync(this IVaultsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
44.713433
221
0.556245
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/recoveryservices/Microsoft.Azure.Management.RecoveryServices/src/Generated/VaultsOperationsExtensions.cs
14,979
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Scriban; using Scriban.Parsing; using Scriban.Runtime; using Scriban.Syntax; namespace Kalk.Core { public abstract class KalkExpressionWithMembers : KalkExpression { protected abstract (string, Func<KalkExpressionWithMembers, object> getter)[] Members { get; } public override int Count => Members.Length; public override IEnumerable<string> GetMembers() { foreach (var memberPair in Members) yield return memberPair.Item1; } public override bool Contains(string member) { foreach (var memberPair in Members) if (memberPair.Item1 == member) return true; return false; } public override bool IsReadOnly { get; set; } public override bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value) { value = null; foreach (var memberPair in Members) { if (memberPair.Item1 == member) { value = memberPair.Item2(this); return true; } } return false; } public override bool CanWrite(string member) => false; public override bool TrySetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly) => false; public override bool Remove(string member) => false; public override void SetReadOnly(string member, bool readOnly) => throw new NotSupportedException("A member of Unit is readonly by default and cannot be modified"); } }
31.375
172
0.621514
[ "BSD-2-Clause" ]
thild/kalk
src/Kalk.Core/Model/KalkExpressionWithMembers.cs
1,759
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Wirehome.Core.Contracts; using Wirehome.Core.Diagnostics; using Wirehome.Core.MessageBus; using Wirehome.Core.Model; using Wirehome.Core.Resources; using Wirehome.Core.Storage; using Wirehome.Core.System; namespace Wirehome.Core.Notifications { /// <summary> /// TODO: Expose publish method to function pool. /// TODO: Expose publish method to message bus. /// /// TODO: Add a dictionary of parameters to each notifications. They can be shown in the UI. /// </summary> public class NotificationsService : IService { private const string StorageFilename = "Notifications.json"; private readonly List<Notification> _notifications = new List<Notification>(); private readonly StorageService _storageService; private readonly ResourceService _resourcesService; private readonly MessageBusService _messageBusService; private readonly SystemCancellationToken _systemCancellationToken; private readonly ILogger _logger; public NotificationsService( StorageService storageService, SystemStatusService systemStatusService, ResourceService resourcesService, MessageBusService messageBusService, SystemCancellationToken systemCancellationToken, ILogger<NotificationsService> logger) { _storageService = storageService ?? throw new ArgumentNullException(nameof(storageService)); _resourcesService = resourcesService ?? throw new ArgumentNullException(nameof(resourcesService)); _messageBusService = messageBusService ?? throw new ArgumentNullException(nameof(messageBusService)); _systemCancellationToken = systemCancellationToken ?? throw new ArgumentNullException(nameof(systemCancellationToken)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); if (systemStatusService == null) throw new ArgumentNullException(nameof(systemStatusService)); systemStatusService.Set("notifications.count", () => { lock (_notifications) { return _notifications.Count; } }); } public void Start() { lock (_notifications) { Load(); } Task.Run(() => RemoveNotificationsAsync(_systemCancellationToken.Token), _systemCancellationToken.Token); } public List<Notification> GetNotifications() { lock (_notifications) { return new List<Notification>(_notifications); } } public void PublishFromResource(PublishFromResourceParameters parameters) { if (parameters == null) throw new ArgumentNullException(nameof(parameters)); var message = _resourcesService.GetResourceValue(parameters.ResourceUid); message = _resourcesService.FormatValue(message, parameters.Parameters); Publish(parameters.Type, message, parameters.TimeToLive); } public void Publish(NotificationType type, string message, TimeSpan? timeToLive) { if (!timeToLive.HasValue) { if (!_storageService.TryReadOrCreate(out NotificationsServiceOptions options, NotificationsServiceOptions.Filename)) { options = new NotificationsServiceOptions(); } if (type == NotificationType.Information) { timeToLive = options.DefaultTimeToLiveForInformation; } else if (type == NotificationType.Warning) { timeToLive = options.DefaultTimeToLiveForWarning; } else { timeToLive = options.DefaultTimeToLiveForError; } } var notification = new Notification { Uid = Guid.NewGuid(), Type = type, Message = message, Timestamp = DateTime.Now, TimeToLive = timeToLive.Value }; Publish(notification); } public void DeleteNotification(Guid uid) { lock (_notifications) { _notifications.RemoveAll(n => n.Uid.Equals(uid)); Save(); _logger.Log(LogLevel.Information, $"Removed notification '{uid}'."); } } public void Clear() { lock (_notifications) { _notifications.Clear(); Save(); _logger.Log(LogLevel.Information, "Removed all notifications."); } } private void Publish(Notification notification) { lock (_notifications) { _notifications.Add(notification); Save(); } _messageBusService.Publish(new WirehomeDictionary() .WithType("notifications.event.published") .WithValue("notification_type", notification.Type.ToString().ToLowerInvariant()) .WithValue("message", notification.Message) .WithValue("time_to_live", notification.TimeToLive.ToString("c"))); } private async Task RemoveNotificationsAsync(CancellationToken cancellationToken) { try { while (!cancellationToken.IsCancellationRequested) { var now = DateTime.Now; var saveIsRequired = false; lock (_notifications) { for (var i = _notifications.Count - 1; i >= 0; i--) { var notification = _notifications[i]; if (notification.Timestamp.Add(notification.TimeToLive) >= now) { continue; } _notifications.RemoveAt(i); saveIsRequired = true; } if (saveIsRequired) { Save(); } } await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { } catch (Exception exception) { _logger.Log(LogLevel.Error, exception, "Unhandled exception while removing notifications."); } } private void Load() { if (!_storageService.TryRead<List<Notification>>(out var notifications, "Notifications.json")) { return; } lock (_notifications) { foreach (var notification in notifications) { _notifications.Add(notification); } } } private void Save() { _storageService.Write(_notifications, StorageFilename); } } }
33.865471
132
0.548729
[ "Apache-2.0" ]
SeppPenner/Wirehome.Core
Wirehome.Core/Notifications/NotificationsService.cs
7,554
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using FlatRedBall.Arrow.DataTypes; using FlatRedBall.Instructions.Reflection; namespace FlatRedBall.Arrow.Managers { public class GuiCommands { ItemsControl mAllElementsTreeView; TreeView mSingleElementTreeView; internal void Initialize(ItemsControl treeView, TreeView singleElementTreeView) { mAllElementsTreeView = treeView; mSingleElementTreeView = singleElementTreeView; } public void RefreshAll() { } } }
21
87
0.680492
[ "MIT" ]
coldacid/FlatRedBall
FRBDK/Arrow/Arrow/Managers/GuiCommands.cs
653
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TronDotNet { public static class TronUnit { private static long _sun_unit = 1_000_000L; public static long TRXToSun(decimal trx) { return Convert.ToInt64(trx * _sun_unit); } public static decimal SunToTRX(long sun) { return Convert.ToDecimal(sun) / _sun_unit; } } }
19.56
54
0.631902
[ "MIT" ]
maftooh/ICO-Platform-Client
Src/IOCPlatform/IOCPlatform.USDT/ICOPlatform.USDT.TRC20/TronDotNet/Extensions/TronUnit.cs
491
C#
/* Copyright (c) 2015-2017 topameng(topameng@qq.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.Globalization; using System.Reflection; namespace LuaInterface { //代表一个反射属性 public sealed class LuaProperty { PropertyInfo property = null; Type kclass = null; [NoToLuaAttribute] public LuaProperty(PropertyInfo prop, Type t) { property = prop; kclass = t; } public int Get(IntPtr L) { int count = LuaDLL.lua_gettop(L); if (count == 3) { object arg0 = ToLua.CheckVarObject(L, 2, kclass); object[] arg1 = ToLua.CheckObjectArray(L, 3); object o = property.GetValue(arg0, arg1); ToLua.Push(L, o); return 1; } else if (count == 6) { object arg0 = ToLua.CheckVarObject(L, 2, kclass); BindingFlags arg1 = (BindingFlags)LuaDLL.luaL_checknumber(L, 3); Binder arg2 = (Binder)ToLua.CheckObject(L, 4, typeof(Binder)); object[] arg3 = ToLua.CheckObjectArray(L, 5); CultureInfo arg4 = (CultureInfo)ToLua.CheckObject(L, 6, typeof(CultureInfo)); object o = property.GetValue(arg0, arg1, arg2, arg3, arg4); ToLua.Push(L, o); return 1; } else { return LuaDLL.luaL_throw(L, "invalid arguments to method: LuaInterface.LuaProperty.Get"); } } public int Set(IntPtr L) { int count = LuaDLL.lua_gettop(L); if (count == 4) { object arg0 = ToLua.CheckVarObject(L, 2, kclass); object arg1 = ToLua.ToVarObject(L, 3); if (arg1 != null) arg1 = TypeChecker.ChangeType(arg1, property.PropertyType); object[] arg2 = ToLua.CheckObjectArray(L, 4); property.SetValue(arg0, arg1, arg2); return 0; } else if (count == 7) { object arg0 = ToLua.CheckVarObject(L, 2, kclass); object arg1 = ToLua.ToVarObject(L, 3); if (arg1 != null) arg1 = TypeChecker.ChangeType(arg1, property.PropertyType); BindingFlags arg2 = (BindingFlags)LuaDLL.luaL_checknumber(L, 4); Binder arg3 = (Binder)ToLua.CheckObject(L, 5, typeof(Binder)); object[] arg4 = ToLua.CheckObjectArray(L, 6); CultureInfo arg5 = (CultureInfo)ToLua.CheckObject(L, 7, typeof(CultureInfo)); property.SetValue(arg0, arg1, arg2, arg3, arg4, arg5); return 0; } else { return LuaDLL.luaL_throw(L, "invalid arguments to method: LuaInterface.LuaProperty.Set"); } } } }
39.705882
109
0.576543
[ "Apache-2.0" ]
871041532/LuaProfiler-For-Unity
ToLuaClient/Assets/ToLua/Reflection/LuaProperty.cs
4,068
C#
// This file is part of Hangfire. // Copyright © 2013-2014 Sergey Odinokov. // // Hangfire is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation, either version 3 // of the License, or any later version. // // Hangfire is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with Hangfire. If not, see <http://www.gnu.org/licenses/>. using Hangfire.Client; using Hangfire.Server; using Hangfire.States; namespace Hangfire.Common { /// <summary> /// Defines values that specify the order in which Hangfire filters /// run within the same filter type and filter order. /// </summary> /// /// <remarks> /// Hangfire supports the following types of filters: /// /// <list type="number"> /// <item> /// <description> /// Client / Server filters, which implement /// <see cref="IClientFilter"/> and <see cref="IServerFilter"/> /// interfaces respectively. /// </description> /// </item> /// <item> /// <description> /// State changing filters, which implement the /// <see cref="IElectStateFilter"/> interface. /// </description> /// </item> /// <item> /// <description> /// State changed filters, which implement the /// <see cref="IApplyStateFilter"/> interface. /// </description> /// </item> /// <item> /// <description> /// Client / Server exception filters, which implement /// <see cref="IClientExceptionFilter"/> or /// <see cref="IServerExceptionFilter"/> interfaces /// respectively. /// </description> /// </item> /// </list> /// /// Порядок запуска указанных типов фильтров строго фиксирован, например, /// фильтры исключений всегда выполняются после всех остальных фильтров, /// а фильтры состояний всегда запускаются внутри клиентских и серверных /// фильтров. /// /// Внутри же одного типа фильтров, порядок выполнения сначала определяется /// значением Order, а затем значением Scope. Перечисление <see cref="JobFilterScope"/> /// определяет следующие значения (в порядке, в котором они будут выполнены): /// /// <list type="number"> /// <item> /// <description> /// <see cref="JobFilterScope.Global"/>. /// </description> /// </item> /// <item> /// <description> /// <see cref="Type"/>. /// </description> /// </item> /// <item> /// <description> /// <see cref="Method"/>. /// </description> /// </item> /// </list> /// /// Для примера, клиентский фильтр, у которого свойство Order имеет значение 0, /// а значение filter scope равно <see cref="JobFilterScope.Global"/>, /// будет выполнен раньше фильтра с тем же самым значением Order, /// но c filter scope, равным <see cref="Type"/>. /// /// Значения Scope задаются, в основном, в реализациях интерфейса /// <see cref="IJobFilterProvider"/>. Так, класс <see cref="JobFilterCollection"/> /// определяет значение Scope как <see cref="JobFilterScope.Global"/>. /// /// Порядок выполнения фильтров одинакового типа, с одинаковым значением /// Order и с одинаковым scope, не оговаривается. /// </remarks> public enum JobFilterScope { /// <summary> /// Specifies an order before the <see cref="Type"/>. /// </summary> Global = 10, /// <summary> /// Specifies an order after the <see cref="Global"/> and /// before the <see cref="Method"/>. /// </summary> Type = 20, /// <summary> /// Specifies an order after the <see cref="Type"/>. /// </summary> Method = 30, } }
37.169492
92
0.568855
[ "MIT" ]
Fleetingold/Hangfire.Topshelf-myTest
Hangfire.Core/Common/JobFilterScope.cs
5,022
C#
namespace palettetool { partial class frmMain { /// <summary> /// 必要なデザイナー変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナーで生成されたコード /// <summary> /// デザイナー サポートに必要なメソッドです。このメソッドの内容を /// コード エディターで変更しないでください。 /// </summary> private void InitializeComponent() { this.pictPicture = new System.Windows.Forms.PictureBox(); this.picPalette = new System.Windows.Forms.PictureBox(); this.dlgSave = new System.Windows.Forms.SaveFileDialog(); this.dlgOpen = new System.Windows.Forms.OpenFileDialog(); this.btnLoad = new System.Windows.Forms.Button(); this.btnPalette = new System.Windows.Forms.Button(); this.picIndexed = new System.Windows.Forms.PictureBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.btnSave = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.pictPicture)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picPalette)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picIndexed)).BeginInit(); this.SuspendLayout(); // // pictPicture // this.pictPicture.BackColor = System.Drawing.Color.White; this.pictPicture.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pictPicture.Location = new System.Drawing.Point(12, 41); this.pictPicture.Name = "pictPicture"; this.pictPicture.Size = new System.Drawing.Size(287, 384); this.pictPicture.TabIndex = 0; this.pictPicture.TabStop = false; // // picPalette // this.picPalette.BackColor = System.Drawing.Color.White; this.picPalette.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picPalette.Location = new System.Drawing.Point(329, 41); this.picPalette.Name = "picPalette"; this.picPalette.Size = new System.Drawing.Size(320, 32); this.picPalette.TabIndex = 1; this.picPalette.TabStop = false; // // btnLoad // this.btnLoad.Location = new System.Drawing.Point(329, 78); this.btnLoad.Name = "btnLoad"; this.btnLoad.Size = new System.Drawing.Size(75, 23); this.btnLoad.TabIndex = 2; this.btnLoad.Text = "読み込み"; this.btnLoad.UseVisualStyleBackColor = true; this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); // // btnPalette // this.btnPalette.Location = new System.Drawing.Point(410, 78); this.btnPalette.Name = "btnPalette"; this.btnPalette.Size = new System.Drawing.Size(75, 23); this.btnPalette.TabIndex = 3; this.btnPalette.Text = "パレット抽出"; this.btnPalette.UseVisualStyleBackColor = true; this.btnPalette.Click += new System.EventHandler(this.btnPalette_Click); // // picIndexed // this.picIndexed.BackColor = System.Drawing.Color.White; this.picIndexed.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picIndexed.Location = new System.Drawing.Point(329, 188); this.picIndexed.Name = "picIndexed"; this.picIndexed.Size = new System.Drawing.Size(287, 237); this.picIndexed.TabIndex = 4; this.picIndexed.TabStop = false; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("MS UI Gothic", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.label1.Location = new System.Drawing.Point(325, 13); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(74, 22); this.label1.TabIndex = 5; this.label1.Text = "パレット"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("MS UI Gothic", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.label2.Location = new System.Drawing.Point(325, 164); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(114, 22); this.label2.TabIndex = 6; this.label2.Text = "インデクス化"; this.label2.Click += new System.EventHandler(this.label2_Click); // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("MS UI Gothic", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.label3.Location = new System.Drawing.Point(12, 12); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(76, 22); this.label3.TabIndex = 7; this.label3.Text = "元画像"; // // btnSave // this.btnSave.Location = new System.Drawing.Point(491, 78); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(75, 23); this.btnSave.TabIndex = 8; this.btnSave.Text = "保存"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // frmMain // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(660, 438); this.Controls.Add(this.btnSave); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.picIndexed); this.Controls.Add(this.btnPalette); this.Controls.Add(this.btnLoad); this.Controls.Add(this.picPalette); this.Controls.Add(this.pictPicture); this.Name = "frmMain"; this.Text = "パレットツール"; this.Load += new System.EventHandler(this.frmMain_Load); ((System.ComponentModel.ISupportInitialize)(this.pictPicture)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picPalette)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picIndexed)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox pictPicture; private System.Windows.Forms.PictureBox picPalette; private System.Windows.Forms.SaveFileDialog dlgSave; private System.Windows.Forms.OpenFileDialog dlgOpen; private System.Windows.Forms.Button btnLoad; private System.Windows.Forms.Button btnPalette; private System.Windows.Forms.PictureBox picIndexed; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button btnSave; } }
38.541899
151
0.691405
[ "MIT" ]
boxerprogrammer/Tools
palettetool/palettetool/frmMain.Designer.cs
7,231
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código foi gerado por uma ferramenta. // Versão de Tempo de Execução: 4.0.30319.42000 // // As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se // o código for recriado // </auto-generated> //------------------------------------------------------------------------------ namespace SistemaHotel.Properties { /// <summary> /// Uma classe de recurso fortemente tipados, para pesquisar cadeias de caracteres localizadas etc. /// </summary> // Esta classe foi gerada automaticamente pela StronglyTypedResourceBuilder // classe através de uma ferramenta como ResGen ou Visual Studio. // Para adicionar ou remover um associado, edite o arquivo .ResX e execute ResGen novamente // com a opção /str ou reconstrua seu projeto VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Retorna a instância cacheada de ResourceManager utilizada por esta classe. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SistemaHotel.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Substitui a propriedade CurrentUICulture do thread atual para todas /// as pesquisas de recursos que usam esta classe de recursos fortemente tipados. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
40.458333
178
0.618606
[ "Unlicense" ]
mannuscritto/SistemaHotel
Properties/Resources.Designer.cs
2,928
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace LjusbolagetSyd.Web { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
24.416667
99
0.590444
[ "MIT" ]
Jesper87/ljusbolagetsydv2
src/LjusbolagetSyd.Web/App_Start/RouteConfig.cs
588
C#
using CommandLine; using K4AdotNet.Sensor; using System; using System.IO; namespace K4AdotNet.Samples.Core.Recorder { /// <summary>Command line options.</summary> internal sealed class Options { [Option("device", Required = false, Default = 0, HelpText = "Specify the device index to use.")] public int DeviceIndex { get; set; } [Option('l', "record-length", Required = false, Default = 0, HelpText = "Limit the recording to N seconds (0 means 'till key press').")] public int RecordLengthSeconds { get; set; } [Option('c', "color-mode", Required = false, Default = "1080p", HelpText = "Set the color sensor mode.\n" + "Available options: 3072p, 2160p, 1536p, 1440p, 1080p, 720p, 720p_NV12, 720p_YUY2, OFF")] public string ColorMode { get; set; } = "1080p"; [Option('d', "depth-mode", Required = false, Default = "NFOV_UNBINNED", HelpText = "Set the depth sensor mode.\n" + "Available options: NFOV_2X2BINNED, NFOV_UNBINNED, WFOV_2X2BINNED, WFOV_UNBINNED, PASSIVE_IR, OFF")] public string DepthMode { get; set; } = "NFOV_UNBINNED"; [Option("depth-delay", Required = false, Default = 0, HelpText = "Set the time offset between color and depth frames in microseconds.\n" + "A negative value means depth frames will arrive before color frames.\n" + "The delay must be less than 1 frame period.")] public int DepthDelayMicroseconds { get; set; } [Option('r', "rate", Required = false, Default = 30, HelpText = "Set the camera frame rate in Frames per Second.\n" + "Available options: 30, 15, 5")] public int FrameRate { get; set; } [Value(0, Default = null, Required = false, MetaValue = "output.mkv", HelpText = "Output file name. Default: 'yyyy-MM-dd H_mm_ss.mkv' file in 'My Videos' folder.")] public string? Output { get; set; } public int GetDeviceIndex() { if (DeviceIndex < 0) throw new ApplicationException($"Invalid value {DeviceIndex} of parameter --device"); return DeviceIndex; } public string GetOutputFilePath() { var res = Output; if (string.IsNullOrEmpty(res)) { var dstPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos); res = Path.Combine(dstPath, string.Format("{0:yyyy-MM-dd H_mm_ss}.mkv", DateTime.Now)); } return res; } public DeviceConfiguration GetConfiguration() { var config = DeviceConfiguration.DisableAll; config.CameraFps = GetFrameRate(); config.DepthMode = GetDepthMode(); config.DepthDelayOffColor = new Microseconds32(DepthDelayMicroseconds); (config.ColorResolution, config.ColorFormat) = GetColorResolutionAndFormat(); return config; } private (ColorResolution resolution, ImageFormat format) GetColorResolutionAndFormat() => (ColorMode.ToUpperInvariant()) switch { "3072P" => (ColorResolution.R3072p, ImageFormat.ColorMjpg), "2160P" => (ColorResolution.R2160p, ImageFormat.ColorMjpg), "1536P" => (ColorResolution.R1536p, ImageFormat.ColorMjpg), "1440P" => (ColorResolution.R1440p, ImageFormat.ColorMjpg), "1080P" => (ColorResolution.R1080p, ImageFormat.ColorMjpg), "720P" => (ColorResolution.R720p, ImageFormat.ColorMjpg), "720P_NV12" => (ColorResolution.R720p, ImageFormat.ColorNV12), "720P_YUY2" => (ColorResolution.R720p, ImageFormat.ColorYUY2), "OFF" => (ColorResolution.Off, ImageFormat.ColorMjpg), _ => throw new ApplicationException($"Invalid value {ColorMode} of parameter --color-mode (-c)"), }; private DepthMode GetDepthMode() => (DepthMode.ToUpperInvariant()) switch { "NFOV_2X2BINNED" => Sensor.DepthMode.NarrowView2x2Binned, "NFOV_UNBINNED" => Sensor.DepthMode.NarrowViewUnbinned, "WFOV_2X2BINNED" => Sensor.DepthMode.WideView2x2Binned, "WFOV_UNBINNED" => Sensor.DepthMode.WideViewUnbinned, "PASSIVE_IR" => Sensor.DepthMode.PassiveIR, "OFF" => Sensor.DepthMode.Off, _ => throw new ApplicationException($"Invalid value {DepthMode} of parameter --depth-mode (-d)"), }; private FrameRate GetFrameRate() => FrameRate switch { 5 => Sensor.FrameRate.Five, 15 => Sensor.FrameRate.Fifteen, 30 => Sensor.FrameRate.Thirty, _ => throw new ApplicationException($"Invalid value {FrameRate} of parameter --rate (-r)"), }; } }
46.926606
117
0.581623
[ "MIT" ]
bibigone/k4a.net
K4AdotNet.Samples.Core.Recorder/Options.cs
5,117
C#
using System; namespace DanSerialiser { /// <summary> /// This will return null if it was not possible generate a member setter for the specified type (if the type is a non-sealed class, for example, then the fields and /// properties can not be known at analysis time because a type derived from it may add more fields or properties) /// </summary> public delegate MemberSetterDetails MemberSetterDetailsRetriever(Type type); }
43.5
166
0.767816
[ "MIT" ]
ProductiveRage/DanSerialiser
DanSerialiser/TypeConverters/MemberSetterDetailsRetriever.cs
437
C#
using System; using System.Collections.Generic; using System.Linq; using EventStore.Core.Bus; namespace EventStore.Projections.Core.Services.Processing { public sealed class WriteQueryResultProjectionProcessingPhase : WriteQueryResultProjectionProcessingPhaseBase { public WriteQueryResultProjectionProcessingPhase( IPublisher publisher, int phase, string resultStream, ICoreProjectionForProcessingPhase coreProjection, PartitionStateCache stateCache, ICoreProjectionCheckpointManager checkpointManager, IEmittedEventWriter emittedEventWriter) : base(publisher, phase, resultStream, coreProjection, stateCache, checkpointManager, emittedEventWriter) { } protected override IEnumerable<EmittedEventEnvelope> WriteResults(CheckpointTag phaseCheckpointTag) { var items = _stateCache.Enumerate(); EmittedStream.WriterConfiguration.StreamMetadata streamMetadata = null; return from item in items let partitionState = item.Item2 select new EmittedEventEnvelope( new EmittedDataEvent( _resultStream, Guid.NewGuid(), "Result", true, partitionState.Result, null, phaseCheckpointTag, null), streamMetadata); } } }
37.72093
117
0.583847
[ "Apache-2.0" ]
bartelink/EventStore
src/EventStore.Projections.Core/Services/Processing/WriteQueryResultProjectionProcessingPhase.cs
1,622
C#
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. using Microsoft.CST.AttackSurfaceAnalyzer.Objects; using Microsoft.CST.AttackSurfaceAnalyzer.Utils; using Serilog; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Threading; using WindowsFirewallHelper; namespace Microsoft.CST.AttackSurfaceAnalyzer.Collectors { /// <summary> /// Collects metadata from the local firewall. /// </summary> public class FirewallCollector : BaseCollector { public FirewallCollector(CollectorOptions? opts = null, Action<CollectObject>? changeHandler = null) : base(opts, changeHandler) { } public override bool CanRunOnPlatform() { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux); } internal override void ExecuteInternal(CancellationToken cancellationToken) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { ExecuteWindows(cancellationToken); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { ExecuteMacOs(cancellationToken); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { ExecuteLinux(cancellationToken); } } /// <summary> /// Dumps from iptables. /// </summary> internal void ExecuteLinux(CancellationToken cancellationToken) { if (ExternalCommandRunner.RunExternalCommand("iptables", "-S", out string result, out string _) == 0) { var lines = new List<string>(result.Split('\n')); Dictionary<string, FirewallAction> defaultPolicies = new Dictionary<string, FirewallAction>(); foreach (var line in lines) { if (cancellationToken.IsCancellationRequested) { return; } if (line.StartsWith("-P")) { var chainName = line.Split(' ')[1]; defaultPolicies.Add(chainName, line.Contains("ACCEPT") ? FirewallAction.Allow : FirewallAction.Block); var obj = new FirewallObject($"Default {chainName} policy") { Action = defaultPolicies[chainName], FriendlyName = $"Default {chainName} policy", Scope = FirewallScope.All }; if (!chainName.Equals("FORWARD")) { obj.Direction = chainName.Equals("INPUT") ? FirewallDirection.Inbound : FirewallDirection.Outbound; } HandleChange(obj); } else if (line.StartsWith("-A")) { var splits = line.Split(' '); var chainName = splits[1]; var obj = new FirewallObject(line) { Action = (splits[Array.IndexOf(splits, "-j") + 1] == "ACCEPT") ? FirewallAction.Allow : FirewallAction.Block, FriendlyName = line, Scope = FirewallScope.All, Protocol = splits[Array.IndexOf(splits, "-p") + 1] }; if (Array.IndexOf(splits, "--dport") > 0) { obj.RemotePorts = splits[Array.IndexOf(splits, "--dport") + 1].OfType<string>().ToList(); } if (Array.IndexOf(splits, "-d") > 0) { obj.RemoteAddresses = splits[Array.IndexOf(splits, "-d") + 1].OfType<string>().ToList(); } if (Array.IndexOf(splits, "-s") > 0) { obj.LocalAddresses = splits[Array.IndexOf(splits, "-s") + 1].OfType<string>().ToList(); } if (Array.IndexOf(splits, "--sport") > 0) { obj.LocalPorts = splits[Array.IndexOf(splits, "--sport") + 1].OfType<string>().ToList(); } if (!chainName.Equals("FORWARD")) { obj.Direction = chainName.Equals("INPUT") ? FirewallDirection.Inbound : FirewallDirection.Outbound; } HandleChange(obj); } } } } /// <summary> /// Talks to socketfilterfw /// </summary> internal void ExecuteMacOs(CancellationToken cancellationToken) { // Example output: "Firewall is enabled. (State = 1)" var result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--getglobalstate"); var enabled = result.Contains("1"); var obj = new FirewallObject("Firewall Enabled") { Action = FirewallAction.Block, Direction = FirewallDirection.Inbound, IsEnable = enabled, FriendlyName = "Firewall Enabled", Scope = FirewallScope.All }; HandleChange(obj); // Example output: "Stealth mode disabled" result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--getglobalstate"); obj = new FirewallObject("Stealth Mode") { Action = FirewallAction.Block, Direction = FirewallDirection.Inbound, IsEnable = result.Contains("enabled"), FriendlyName = "Stealth Mode", Scope = FirewallScope.All }; HandleChange(obj); /* Example Output: * Automatically allow signed built-in software ENABLED * Automatically allow downloaded signed software ENABLED */ result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--getallowsigned"); obj = new FirewallObject("Allow signed built-in software") { Action = FirewallAction.Allow, Direction = FirewallDirection.Inbound, IsEnable = result.Split('\n')[0].Contains("ENABLED"), FriendlyName = "Allow signed built-in software", Scope = FirewallScope.All }; HandleChange(obj); obj = new FirewallObject("Allow downloaded signed software") { Action = FirewallAction.Allow, Direction = FirewallDirection.Inbound, IsEnable = result.Split('\n')[1].Contains("ENABLED"), FriendlyName = "Allow downloaded signed software", Scope = FirewallScope.All }; HandleChange(obj); /* Example Output: ALF: total number of apps = 2 1 : /Applications/AppName.app ( Allow incoming connections ) 2 : /Applications/AppName2.app ( Block incoming connections ) */ result = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--listapps"); string appName = ""; Regex startsWithNumber = new Regex("^[1-9]"); var lines = new List<string>(result.Split('\n')); if (lines.Any()) { lines = lines.Skip(2).ToList(); foreach (var line in lines) { if (cancellationToken.IsCancellationRequested) { return; } if (startsWithNumber.IsMatch(line)) { appName = line.Substring(line.IndexOf('/')); } else if (line.Contains("incoming connections")) { obj = new FirewallObject(appName) { Action = (line.Contains("Allow")) ? FirewallAction.Allow : FirewallAction.Block, Direction = FirewallDirection.Inbound, FriendlyName = appName, Scope = FirewallScope.All }; HandleChange(obj); } } } } /// <summary> /// Uses a library to access the Windows Firewall. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "The specific exceptions thrown by this library are not documented.")] internal void ExecuteWindows(CancellationToken cancellationToken) { try { foreach (IFirewallRule rule in FirewallManager.Instance.Rules) { if (cancellationToken.IsCancellationRequested) { return; } try { var obj = new FirewallObject(rule.Name) { Action = rule.Action, ApplicationName = rule.ApplicationName, Direction = rule.Direction, FriendlyName = rule.FriendlyName, IsEnable = rule.IsEnable, LocalPortType = rule.LocalPortType, Profiles = rule.Profiles, Protocol = rule.Protocol.ProtocolNumber.ToString(CultureInfo.InvariantCulture), Scope = rule.Scope, ServiceName = rule.ServiceName }; obj.LocalAddresses = rule.LocalAddresses.ToList().ConvertAll(address => address.ToString()); obj.LocalPorts = rule.LocalPorts.ToList().ConvertAll(port => port.ToString(CultureInfo.InvariantCulture)); obj.RemoteAddresses = rule.RemoteAddresses.ToList().ConvertAll(address => address.ToString()); obj.RemotePorts = rule.RemotePorts.ToList().ConvertAll(port => port.ToString(CultureInfo.InvariantCulture)); HandleChange(obj); } catch (Exception e) { Log.Debug(e, "Exception hit while processing Firewall rules"); Dictionary<string, string> ExceptionEvent = new Dictionary<string, string>(); ExceptionEvent.Add("Exception Type", e.GetType().ToString()); AsaTelemetry.TrackEvent("WindowsFirewallObjectCreationException", ExceptionEvent); } } } catch (Exception e) when ( e is COMException || e is NotSupportedException) { Log.Warning(Strings.Get("CollectorNotSupportedOnPlatform"), GetType().ToString()); } } } }
44.034091
200
0.512602
[ "MIT" ]
FardinA143/AttackSurfaceAnalyzer
Lib/Collectors/FirewallCollector.cs
11,627
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using starsky.foundation.database.Helpers; using starsky.foundation.database.Models; using starsky.foundation.platform.Models; using starskytest.FakeMocks; namespace starskytest.starsky.foundation.database.Helpers { [TestClass] public class StatusCodesHelperTest { [TestMethod] public void IsDeletedStatus_Null_Default() { DetailView detailView = null; // ReSharper disable once ExpressionIsAlwaysNull var status = new StatusCodesHelper().IsDeletedStatus(detailView); Assert.AreEqual(FileIndexItem.ExifStatus.Default,status); } [TestMethod] public void IsReadOnlyStatus_Null_Default() { DetailView detailView = null; var appSettings = new AppSettings(); // ReSharper disable once ExpressionIsAlwaysNull var status = new StatusCodesHelper(appSettings).IsReadOnlyStatus(detailView); Assert.AreEqual(FileIndexItem.ExifStatus.Default,status); } [TestMethod] public void IsReadOnlyStatus_DetailView_DirReadOnly() { // this is the only diff -->> var appSettings = new AppSettings{ReadOnlyFolders = new List<string>{"/"}}; var detailView = new DetailView { IsDirectory = true, SubPath = "/" }; var status = new StatusCodesHelper(appSettings).IsReadOnlyStatus(detailView); Assert.AreEqual(FileIndexItem.ExifStatus.DirReadOnly,status); } [TestMethod] [ExpectedException(typeof(DllNotFoundException))] public void IsReadOnlyStatus_DetailView_AppSettingsNull() { DetailView detailView = null; // ReSharper disable once ExpressionIsAlwaysNull new StatusCodesHelper(null).IsReadOnlyStatus(detailView); // expect DllNotFoundException } [TestMethod] public void IsReadOnlyStatus_DetailView_Null() { DetailView detailView = null; // ReSharper disable once ExpressionIsAlwaysNull var status = new StatusCodesHelper(new AppSettings()).IsReadOnlyStatus(detailView); Assert.AreEqual(FileIndexItem.ExifStatus.Default,status); } [TestMethod] public void IsReadOnlyStatus_FileIndexItem_DirReadOnly() { // this is the only diff -->> var appSettings = new AppSettings{ReadOnlyFolders = new List<string>{"/"}}; var detailView = new FileIndexItem { IsDirectory = true, FilePath = "/" }; var status = new StatusCodesHelper(appSettings).IsReadOnlyStatus(detailView); Assert.AreEqual(FileIndexItem.ExifStatus.DirReadOnly,status); } [TestMethod] public void StatusCodesHelperTest_InjectFakeIStorage_FileDeletedTag() { var appSettings = new AppSettings(); var detailView = new DetailView { IsDirectory = false, SubPath = "/test.jpg", FileIndexItem = new FileIndexItem{ParentDirectory = "/", Tags = "!delete!", FileName = "test.jpg", CollectionPaths = new List<string>{"/test.jpg"}} }; var istorage = new FakeIStorage(new List<string> {"/"}, new List<string> {"/test.jpg"}); var status = new StatusCodesHelper(appSettings).IsDeletedStatus(detailView); Assert.AreEqual(FileIndexItem.ExifStatus.Deleted,status); } [TestMethod] public void StatusCodesHelperTest_ReturnExifStatusError_DirReadOnly() { var appSettings = new AppSettings(); var statusModel = new FileIndexItem(); var statusResults = FileIndexItem.ExifStatus.DirReadOnly; var fileIndexResultsList = new List<FileIndexItem>(); var statusBool = new StatusCodesHelper().ReturnExifStatusError(statusModel, statusResults, fileIndexResultsList); Assert.AreEqual(true,statusBool); } [TestMethod] public void StatusCodesHelperTest_ReturnExifStatusError_NotFoundNotInIndex() { var appSettings = new AppSettings(); var statusModel = new FileIndexItem(); var statusResults = FileIndexItem.ExifStatus.NotFoundNotInIndex; var fileIndexResultsList = new List<FileIndexItem>(); var statusBool = new StatusCodesHelper().ReturnExifStatusError(statusModel, statusResults, fileIndexResultsList); Assert.AreEqual(true,statusBool); } [TestMethod] public void StatusCodesHelperTest_ReturnExifStatusError_NotFoundSourceMissing() { var appSettings = new AppSettings(); var statusModel = new FileIndexItem(); var statusResults = FileIndexItem.ExifStatus.NotFoundSourceMissing; var fileIndexResultsList = new List<FileIndexItem>(); var statusBool = new StatusCodesHelper().ReturnExifStatusError(statusModel, statusResults, fileIndexResultsList); Assert.AreEqual(true,statusBool); } [TestMethod] public void StatusCodesHelperTest_ReturnExifStatusError_ReadOnly() { var statusModel = new FileIndexItem(); var statusResults = FileIndexItem.ExifStatus.ReadOnly; var fileIndexResultsList = new List<FileIndexItem>(); var statusBool = new StatusCodesHelper().ReturnExifStatusError(statusModel, statusResults, fileIndexResultsList); Assert.AreEqual(true,statusBool); } [TestMethod] public void StatusCodesHelperTest_ReadonlyDenied_true() { var statusModel = new FileIndexItem(); var statusResults = FileIndexItem.ExifStatus.ReadOnly; var fileIndexResultsList = new List<FileIndexItem>(); var statusBool = new StatusCodesHelper().ReadonlyDenied(statusModel, statusResults, fileIndexResultsList); Assert.AreEqual(true,statusBool); } [TestMethod] public void StatusCodesHelperTest_ReadonlyDenied_false() { var statusModel = new FileIndexItem(); var statusResults = FileIndexItem.ExifStatus.Ok; var fileIndexResultsList = new List<FileIndexItem>(); var statusBool = new StatusCodesHelper().ReadonlyDenied(statusModel, statusResults, fileIndexResultsList); Assert.AreEqual(false,statusBool); } [TestMethod] public void StatusCodesHelperTest_ReadonlyAllowed_true() { var statusModel = new FileIndexItem(); var statusResults = FileIndexItem.ExifStatus.ReadOnly; var fileIndexResultsList = new List<FileIndexItem>(); new StatusCodesHelper().ReadonlyAllowed(statusModel, statusResults, fileIndexResultsList); Assert.AreEqual(FileIndexItem.ExifStatus.ReadOnly,fileIndexResultsList.FirstOrDefault().Status); } } }
34.272222
99
0.75928
[ "MIT" ]
qdraw/starsky
starsky/starskytest/starsky.foundation.database/Helpers/StatusCodesHelperTest.cs
6,171
C#
using System; using System.Collections.Generic; using System.Text; using MessagePack; namespace REstate.Remote.Models { [MessagePackObject] public class GetSchematicRequest { [Key(0)] public string SchematicName { get; set; } } [MessagePackObject] public class GetSchematicResponse { [Key(0)] public byte[] SchematicBytes { get; set; } } }
18.5
50
0.646192
[ "MIT" ]
BPHartel/REstate
src/REstate.Remote/Models/GetSchematic.cs
409
C#
namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /wxaapi/newtmpl/deltemplate 接口的请求。</para> /// </summary> public class WxaApiNewTemplateDeleteTemplateRequest : WechatApiRequest { /// <summary> /// 获取或设置要删除的模板 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("priTmplId")] [System.Text.Json.Serialization.JsonPropertyName("priTmplId")] public string PrivateTemplateId { get; set; } = string.Empty; } }
31.875
74
0.637255
[ "MIT" ]
ZUOXIANGE/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/WxaApi/NewTemplate/WxaApiNewTemplateDeleteTemplateRequest.cs
552
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:2.4.0.0 // SpecFlow Generator Version:2.4.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace SFA.Tl.Matching.Automation.Tests.Project.Tests.Features { using TechTalk.SpecFlow; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "2.4.0.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("Error messages on the Select Providers page")] public partial class ErrorMessagesOnTheSelectProvidersPageFeature { private TechTalk.SpecFlow.ITestRunner testRunner; #line 1 "SelectProviders_ErrorMessages.feature" #line hidden [NUnit.Framework.OneTimeSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Error messages on the Select Providers page", "\tThis feature is used to confirm the error message on the Select providers page w" + "hen a postcode is not entered. ", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.OneTimeTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioInitialize(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioInitialize(scenarioInfo); testRunner.ScenarioContext.ScenarioContainer.RegisterInstanceAs<NUnit.Framework.TestContext>(NUnit.Framework.TestContext.CurrentContext); } public virtual void ScenarioStart() { testRunner.OnScenarioStart(); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } public virtual void FeatureBackground() { #line 4 #line 5 testRunner.Given("I have navigated to the IDAMS login page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 6 testRunner.And("I have logged in as an \"Admin User\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 7 testRunner.And("I navigate to the Select Providers page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Select Providers page - A postcode must be entered when searching")] [NUnit.Framework.CategoryAttribute("regression")] public virtual void SelectProvidersPage_APostcodeMustBeEnteredWhenSearching() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Select Providers page - A postcode must be entered when searching", null, new string[] { "regression"}); #line 10 this.ScenarioInitialize(scenarioInfo); this.ScenarioStart(); #line 4 this.FeatureBackground(); #line 11 testRunner.Given("I clear the postcode field on the Select providers page and Search Again", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 12 testRunner.Then("I am shown an error for blank postcode stating \"You must enter a postcode\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Select Providers page - A real postcode must be entered when searching")] [NUnit.Framework.CategoryAttribute("regression")] public virtual void SelectProvidersPage_ARealPostcodeMustBeEnteredWhenSearching() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Select Providers page - A real postcode must be entered when searching", null, new string[] { "regression"}); #line 15 this.ScenarioInitialize(scenarioInfo); this.ScenarioStart(); #line 4 this.FeatureBackground(); #line 16 testRunner.Given("I enter an invalid postcode on the Select providers page and Search again", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 17 testRunner.Then("I am shown an error for invalid postcode stating \"You must enter a real postcode\"" + "", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Select Providers page - A provider must be selected before pressing Continue")] [NUnit.Framework.CategoryAttribute("regression")] public virtual void SelectProvidersPage_AProviderMustBeSelectedBeforePressingContinue() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Select Providers page - A provider must be selected before pressing Continue", null, new string[] { "regression"}); #line 20 this.ScenarioInitialize(scenarioInfo); this.ScenarioStart(); #line 4 this.FeatureBackground(); #line 21 testRunner.When("I have filled in the search form on the Search Providers page with criteria which" + " returns some results", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 22 testRunner.When("I press Continue without selecting Providers", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 23 testRunner.Then("I am shown an error for no provider selected stating \"You must select at least on" + "e provider\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } } } #pragma warning restore #endregion
44.272727
270
0.651951
[ "MIT" ]
SkillsFundingAgency/das-tlevels-automation-suite
src/SFA.Tl.Matching.Automation.Tests/Project/Tests/Features/SelectProviders_ErrorMessages.feature.cs
6,820
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Cors { internal static class CORSLoggerExtensions { private static readonly Action<ILogger, Exception?> _isPreflightRequest; private static readonly Action<ILogger, string, Exception?> _requestHasOriginHeader; private static readonly Action<ILogger, Exception?> _requestDoesNotHaveOriginHeader; private static readonly Action<ILogger, Exception?> _policySuccess; private static readonly Action<ILogger, Exception?> _policyFailure; private static readonly Action<ILogger, string, Exception?> _originNotAllowed; private static readonly Action<ILogger, string, Exception?> _accessControlMethodNotAllowed; private static readonly Action<ILogger, string, Exception?> _requestHeaderNotAllowed; private static readonly Action<ILogger, Exception?> _failedToSetCorsHeaders; private static readonly Action<ILogger, Exception?> _noCorsPolicyFound; private static readonly Action<ILogger, Exception?> _isNotPreflightRequest; static CORSLoggerExtensions() { _isPreflightRequest = LoggerMessage.Define( LogLevel.Debug, new EventId(1, "IsPreflightRequest"), "The request is a preflight request." ); _requestHasOriginHeader = LoggerMessage.Define<string>( LogLevel.Debug, new EventId(2, "RequestHasOriginHeader"), "The request has an origin header: '{origin}'." ); _requestDoesNotHaveOriginHeader = LoggerMessage.Define( LogLevel.Debug, new EventId(3, "RequestDoesNotHaveOriginHeader"), "The request does not have an origin header." ); _policySuccess = LoggerMessage.Define( LogLevel.Information, new EventId(4, "PolicySuccess"), "CORS policy execution successful." ); _policyFailure = LoggerMessage.Define( LogLevel.Information, new EventId(5, "PolicyFailure"), "CORS policy execution failed." ); _originNotAllowed = LoggerMessage.Define<string>( LogLevel.Information, new EventId(6, "OriginNotAllowed"), "Request origin {origin} does not have permission to access the resource." ); _accessControlMethodNotAllowed = LoggerMessage.Define<string>( LogLevel.Information, new EventId(7, "AccessControlMethodNotAllowed"), "Request method {accessControlRequestMethod} not allowed in CORS policy." ); _requestHeaderNotAllowed = LoggerMessage.Define<string>( LogLevel.Information, new EventId(8, "RequestHeaderNotAllowed"), "Request header '{requestHeader}' not allowed in CORS policy." ); _failedToSetCorsHeaders = LoggerMessage.Define( LogLevel.Warning, new EventId(9, "FailedToSetCorsHeaders"), "Failed to apply CORS Response headers." ); _noCorsPolicyFound = LoggerMessage.Define( LogLevel.Information, new EventId(10, "NoCorsPolicyFound"), "No CORS policy found for the specified request." ); _isNotPreflightRequest = LoggerMessage.Define( LogLevel.Debug, new EventId(12, "IsNotPreflightRequest"), "This request uses the HTTP OPTIONS method but does not have an Access-Control-Request-Method header. This request will not be treated as a CORS preflight request." ); } public static void IsPreflightRequest(this ILogger logger) { _isPreflightRequest(logger, null); } public static void RequestHasOriginHeader(this ILogger logger, string origin) { _requestHasOriginHeader(logger, origin, null); } public static void RequestDoesNotHaveOriginHeader(this ILogger logger) { _requestDoesNotHaveOriginHeader(logger, null); } public static void PolicySuccess(this ILogger logger) { _policySuccess(logger, null); } public static void PolicyFailure(this ILogger logger) { _policyFailure(logger, null); } public static void OriginNotAllowed(this ILogger logger, string origin) { _originNotAllowed(logger, origin, null); } public static void AccessControlMethodNotAllowed( this ILogger logger, string accessControlMethod ) { _accessControlMethodNotAllowed(logger, accessControlMethod, null); } public static void RequestHeaderNotAllowed(this ILogger logger, string requestHeader) { _requestHeaderNotAllowed(logger, requestHeader, null); } public static void FailedToSetCorsHeaders(this ILogger logger, Exception? exception) { _failedToSetCorsHeaders(logger, exception); } public static void NoCorsPolicyFound(this ILogger logger) { _noCorsPolicyFound(logger, null); } public static void IsNotPreflightRequest(this ILogger logger) { _isNotPreflightRequest(logger, null); } } }
38.152318
180
0.622288
[ "Apache-2.0" ]
belav/aspnetcore
src/Middleware/CORS/src/CORSLoggerExtensions.cs
5,761
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using System.Net.Http; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Routing; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.Web.Virtualization; using Microsoft.JSInterop; using MudBlazor; using FixaticApp; using FixaticApp.Shared; using FixaticApp.Components; using Fixatic.Services; using Fixatic.Types; using Fixatic.DO.Types; namespace FixaticApp.Pages { public partial class PropertiesPage { [Inject] private ICustomPropertiesService? CustomPropertiesService { get; set; } [Inject] private IDialogService? DialogService { get; set; } [Inject] private ICurrentUserService? CurrentUserService { get; set; } [Inject] private NavigationManager? NavigationManager { get; set; } private List<CustomProperty> _cumProps = new(); protected override async Task OnInitializedAsync() { var user = await CurrentUserService!.GetUserInfoAsync(); if (!user.IsInGroup(UserGroupType.Admin)) { NavigationManager!.NavigateTo("/"); return; } await LoadDataAsync(); } private async Task LoadDataAsync() { var res = await CustomPropertiesService!.GetAllAsync(); if (!res.IsSuccess) return; _cumProps = res.Item!; } private async Task PropertySelectedAsync(TableRowClickEventArgs<CustomProperty> args) { if (args?.Item == null) return; await ShowPropertyDialogAsync(args.Item); } private async Task OnAddClickedAsync() { var item = new CustomProperty { CustomPropertyId = DB.IgnoredID, Name = string.Empty, Description = string.Empty, }; await ShowPropertyDialogAsync(item); } private async Task ShowPropertyDialogAsync(CustomProperty item) { var parameters = new DialogParameters { { "Property", item } }; var options = new DialogOptions { CloseOnEscapeKey = true, MaxWidth = MaxWidth.Medium, FullWidth = true }; var dialog = DialogService!.Show<CumPropDialog>("Custom property", parameters, options); var result = await dialog.Result; if (!result.Cancelled) { await LoadDataAsync(); StateHasChanged(); } } } }
25.138298
109
0.740584
[ "MIT" ]
Fjarik/Fixatic
src/Fixatic/FixaticApp/Pages/PropertiesPage.razor.cs
2,363
C#
namespace Kongrevsky.Infrastructure.Repository.Utils { #region << Using >> using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using AutoMapper; using Kongrevsky.Infrastructure.Repository.Attributes; using Kongrevsky.Infrastructure.Repository.Models; using Z.EntityFramework.Plus; #endregion public static class AutoMapperDomainUtils { public static Action<IMapperConfigurationExpression> CommonConfiguration { get; set; } = config => { }; public static IMapper GetMapper(Action<IMapperConfigurationExpression> configure) { return GetConfigurationProvider(configure).CreateMapper(); } public static IConfigurationProvider GetConfigurationProvider(Action<IMapperConfigurationExpression> configure) { return new MapperConfiguration(conf => { CommonConfiguration?.Invoke(conf); configure?.Invoke(conf); }); } public static IMappingExpression<TSource, TDestination> LoadProperties<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression, RepositoryPagingModel<TDestination> filter, DbContext context = null) where TSource : class { var destType = typeof(TDestination); var infos = destType.GetProperties(); if (!string.IsNullOrEmpty(filter.Distinct)) filter.LoadProperties = new List<string>() { filter.Distinct.Split(new[] { '.' }, 2)[0] }; var properties = (filter.LoadProperties ?? (filter.LoadProperties = new List<string>())).ToList(); if (!properties.Any()) { var propertyInfoIgnore = infos.Where(x => x.GetCustomAttributes(typeof(NotLoadByDefault), true).Any()).ToList(); foreach (var property in propertyInfoIgnore) expression.ForMember(property.Name, opt => opt.Ignore()); return expression; } var orderProperties = filter.OrderProperty?.Split(new[] { ',', ' ', '/', '\\' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List<string>(); if (string.IsNullOrEmpty(filter.Distinct) && context != null) orderProperties.AddRange(context.GetKeyNames<TSource>()); if (orderProperties.Any()) { foreach (var property in orderProperties) { var split = property.Split(new[] { '.' }, 2)[0]; if(string.IsNullOrEmpty(split)) continue; var orderProperty = infos.FirstOrDefault(x => string.Equals(x.Name, split, StringComparison.InvariantCultureIgnoreCase)); if (orderProperty != null && !properties.Contains(orderProperty.Name, StringComparer.OrdinalIgnoreCase)) properties.Add(orderProperty.Name); } } var orderPropertyDefault = infos.FirstOrDefault(x => x.GetCustomAttributes(typeof(DefaultSortPropertyAttribute), true).Any()); if (orderPropertyDefault != null && !properties.Contains(orderPropertyDefault.Name, StringComparer.OrdinalIgnoreCase)) properties.Add(orderPropertyDefault.Name); if (filter.Filters?.Any() ?? false) { var propertyValuePairs = QueryableUtils.ToPropertyValuePairs(filter.Filters, destType); properties.AddRange(propertyValuePairs.SelectMany(x => x.Select(c => c.Property.Name))); } var propertyInfos = infos.Where(x => !properties.Contains(x.Name, StringComparer.OrdinalIgnoreCase) && (!x.GetCustomAttributes(typeof(LoadAlways), true).Any() || x.GetCustomAttributes(typeof(NotLoadByDefault), true).Any())).ToList(); foreach (var property in propertyInfos) expression.ForMember(property.Name, opt => opt.Ignore()); return expression; } } }
45.967033
245
0.605785
[ "MIT" ]
gpcaretti/libraries
Kongrevsky.Libraries/Infrastructure/Infrastructure.Repository/Utils/AutoMapperDomainUtils.cs
4,185
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace BoDi.Tests { [TestFixture] public class RegisterFactoryDelegateTests { [Test] public void ShouldBeAbleToRegisterAFactoryDelegate() { // given var container = new ObjectContainer(); container.RegisterFactoryAs<IInterface1>(() => new VerySimpleClass()); // when var obj = container.Resolve<IInterface1>(); // then Assert.IsNotNull(obj); Assert.IsInstanceOf(typeof(VerySimpleClass), obj); } [Test] public void ShouldReturnTheSameIfResolvedTwice() { // given var container = new ObjectContainer(); container.RegisterFactoryAs<IInterface1>(() => new VerySimpleClass()); // when var obj1 = container.Resolve<IInterface1>(); var obj2 = container.Resolve<IInterface1>(); // then Assert.AreSame(obj1, obj2); } [Test] public void ShouldBeAbleToRegisterAFactoryDelegateWithDependencies() { // given var container = new ObjectContainer(); var dependency = new VerySimpleClass(); container.RegisterInstanceAs<IInterface1>(dependency); container.RegisterFactoryAs<IInterface3>(new Func<IInterface1, IInterface3>(if1 => new ClassWithSimpleDependency(if1))); // when var obj = container.Resolve<IInterface3>(); // then Assert.IsNotNull(obj); Assert.IsInstanceOf(typeof(ClassWithSimpleDependency), obj); Assert.AreSame(dependency, ((ClassWithSimpleDependency)obj).Dependency); } [Test] public void ShouldBeAbleToRegisterAFactoryDelegateWithDependencyToTheContainer() { // given var container = new ObjectContainer(); var dependency = new VerySimpleClass(); container.RegisterInstanceAs<IInterface1>(dependency); container.RegisterFactoryAs<IInterface3>(c => new ClassWithSimpleDependency(c.Resolve<IInterface1>())); // when var obj = container.Resolve<IInterface3>(); // then Assert.IsNotNull(obj); Assert.IsInstanceOf(typeof(ClassWithSimpleDependency), obj); Assert.AreSame(dependency, ((ClassWithSimpleDependency)obj).Dependency); } [Test/*, ExpectedException(typeof(ObjectContainerException), ExpectedMessage = "Circular dependency", MatchType = MessageMatch.Contains)*/] [Ignore("dynamic circles not detected yet, this leads to stack overflow")] public void ShouldThrowExceptionForDynamicCircularDependencies() { // given var container = new ObjectContainer(); container.RegisterFactoryAs<ClassWithCircularDependency1>(c => new ClassWithCircularDependency1(c.Resolve<ClassWithCircularDependency2>())); // when Assert.Throws<ObjectContainerException>(() => container.Resolve<ClassWithCircularDependency1>(), "Circular dependency"); } [Test/*, ExpectedException(typeof(ObjectContainerException), ExpectedMessage = "Circular dependency", MatchType = MessageMatch.Contains)*/] public void ShouldThrowExceptionForStaticCircularDependencies() { // given var container = new ObjectContainer(); container.RegisterFactoryAs<ClassWithCircularDependency1>(new Func<ClassWithCircularDependency2, ClassWithCircularDependency1>(dep1 => new ClassWithCircularDependency1(dep1))); // when Assert.Throws<ObjectContainerException>(() => container.Resolve<ClassWithCircularDependency1>(), "Circular dependency"); } [Test/*, ExpectedException(typeof(ObjectContainerException), ExpectedMessage = "Circular dependency", MatchType = MessageMatch.Contains)*/] public void ShouldThrowExceptionForStaticCircularDependenciesWithMultipleFactoriesInPath() { // given var container = new ObjectContainer(); container.RegisterFactoryAs<ClassWithCircularDependency1>(new Func<ClassWithCircularDependency2, ClassWithCircularDependency1>(dep2 => new ClassWithCircularDependency1(dep2))); container.RegisterFactoryAs<ClassWithCircularDependency2>(new Func<ClassWithCircularDependency1, ClassWithCircularDependency2>(dep1 => new ClassWithCircularDependency2(dep1))); // when Assert.Throws<ObjectContainerException>(() => container.Resolve<ClassWithCircularDependency1>(), "Circular dependency"); } [Test] public void ShouldAlwaysCreateInstanceOnPerRequestStrategy() { // given var container = new ObjectContainer(); // when container.RegisterFactoryAs<IInterface1>(() => new SimpleClassWithDefaultCtor()).InstancePerDependency(); // then var obj1 = (SimpleClassWithDefaultCtor)container.Resolve<IInterface1>(); var obj2 = (SimpleClassWithDefaultCtor)container.Resolve<IInterface1>(); Assert.AreNotSame(obj1, obj2); } [Test] public void ShouldAlwaysCreateSameObjectOnPerContextStrategy() { // given var container = new ObjectContainer(); // when container.RegisterFactoryAs<IInterface1>(() => new SimpleClassWithDefaultCtor()).InstancePerContext(); // then var obj1 = (SimpleClassWithDefaultCtor)container.Resolve<IInterface1>(); var obj2 = (SimpleClassWithDefaultCtor)container.Resolve<IInterface1>(); Assert.AreSame(obj1, obj2); } } }
37.282209
189
0.630574
[ "Apache-2.0" ]
SpecFlowOSS/BoDi
BoDi.Tests/RegisterFactoryDelegateTests.cs
6,079
C#
using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Events; using System.IO; namespace TheLion.AwesomeProfessions { internal class ArrowPointerUpdateTickedEvent : UpdateTickedEvent { /// <inheritdoc/> public override void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { Utility.ArrowPointer ??= new ArrowPointer(AwesomeProfessions.Content.Load<Texture2D>(Path.Combine("assets", "cursor.png"))); if (e.Ticks % 4 == 0) Utility.ArrowPointer.Bob(); } } }
30.625
127
0.763265
[ "MIT" ]
lshtech/StardewValleyMods
WalkOfLife/Framework/Events/UpdateTicked/ArrowPointerUpdateTickedEvent.cs
492
C#
using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NBitcoin; using Stratis.Bitcoin.Builder.Feature; using Stratis.Bitcoin.Features.Wallet.Interfaces; using Stratis.Bitcoin.Features.Wallet.Models; using Stratis.Bitcoin.Features.Wallet.Services; using Stratis.Bitcoin.Utilities.JsonErrors; namespace Stratis.Bitcoin.Features.Wallet.Controllers { /// <summary> /// Controller providing operations on a wallet. /// </summary> [ApiVersion("1")] [Route("api/[controller]")] public class WalletController : FeatureControllerBase { private readonly IWalletService walletService; private readonly IWalletManager walletManager; private readonly IWalletSyncManager walletSyncManager; private readonly ChainIndexer chainIndexer; public WalletController( ILoggerFactory loggerFactory, IWalletService walletService, IWalletManager walletManager, IWalletSyncManager walletSyncManager, ChainIndexer chainIndexer) : base(loggerFactory.CreateLogger(typeof(WalletController).FullName)) { this.walletService = walletService; this.walletManager = walletManager; this.walletSyncManager = walletSyncManager; this.chainIndexer = chainIndexer; } /// <summary> /// Generates a mnemonic to use for an HD wallet. /// </summary> /// <param name="language">The language for the words in the mnemonic. The options are: English, French, Spanish, Japanese, ChineseSimplified and ChineseTraditional. Defaults to English.</param> /// <param name="wordCount">The number of words in the mnemonic. The options are: 12,15,18,21 or 24. Defaults to 12.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the generated mnemonic.</returns> /// <response code="200">Returns mnemonic</response> /// <response code="400">Unexpected exception occurred</response> [Route("mnemonic")] [HttpGet] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] public async Task<IActionResult> GenerateMnemonic([FromQuery] string language = "English", int wordCount = 12, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(new { Language = language, WordCount = wordCount }, cancellationToken, (req, token) => // Generate the Mnemonic this.Json(new Mnemonic(language, (WordCount)wordCount).ToString())); } /// <summary> /// Creates a new wallet on this full node. /// </summary> /// <param name="request">An object containing the necessary parameters to create a wallet.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the mnemonic created for the new wallet.</returns> /// <response code="200">Returns mnemonic</response> /// <response code="400">Invalid request or problem creating wallet</response> /// <response code="409">Wallet already exists</response> /// <response code="500">Request is null</response> [Route("create")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.Conflict)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> Create([FromBody] WalletCreationRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.CreateWallet(req, token))); } /// <summary> /// Signs a message and returns the signature. /// </summary> /// <param name="request">The object containing the parameters used to sign a message.</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>A JSON object containing the generated signature.</returns> /// <response code="200">Returns signature</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("signmessage")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> SignMessage([FromBody] SignMessageRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => { string signature = this.walletManager.SignMessage(req.Password, req.WalletName, req.ExternalAddress, req.Message); return this.Json(signature); }); } /// <summary> /// Gets the public key for an address. /// </summary> /// <param name="request">The object containing the parameters used to get the public key.</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>A Jstring containing the public key.</returns> /// <response code="200">Returns public key</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("pubkey")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> GetPubKey([FromBody] PubKeyRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => { string pubKey = this.walletManager.GetPubKey(req.WalletName, req.ExternalAddress); return this.Json(pubKey); }); } /// <summary> /// Verifies the signature of a message. /// </summary> /// <param name="request">The object containing the parameters verify a signature.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the result of the verification.</returns> /// <response code="200">Returns verification result</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("verifymessage")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> VerifyMessage([FromBody] VerifyRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => { bool result = this.walletManager.VerifySignedMessage(request.ExternalAddress, req.Message, req.Signature); return this.Json(result.ToString()); }); } /// <summary> /// Loads a previously created wallet. /// </summary> /// <param name="request">An object containing the necessary parameters to load an existing wallet</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>Ok or Error result</returns> /// <response code="200">Wallet loaded</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="403">Incorrect password</response> /// <response code="404">Wallet not found</response> /// <response code="500">Request is null</response> [Route("load")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.Forbidden)] [ProducesResponseType((int)HttpStatusCode.NotFound)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> Load([FromBody] WalletLoadRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => { await this.walletService.LoadWallet(req, token); return Ok(); }); } /// <summary> /// Recovers an existing wallet. /// </summary> /// <param name="request">An object containing the parameters used to recover a wallet.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A value of Ok if the wallet was successfully recovered.</returns> /// <response code="200">Wallet recovered</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="404">Wallet not found</response> /// <response code="409">Wallet already exists</response> /// <response code="500">Request is null</response> [Route("recover")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.NotFound)] [ProducesResponseType((int)HttpStatusCode.Conflict)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> Recover([FromBody] WalletRecoveryRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => { await this.walletService.RecoverWallet(req, token); return Ok(); }); } /// <summary> /// Recovers a wallet using its extended public key. Note that the recovered wallet will not have a private key and is /// only suitable for returning the wallet history using further API calls. /// </summary> /// <param name="request">An object containing the parameters used to recover a wallet using its extended public key.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A value of Ok if the wallet was successfully recovered.</returns> /// <response code="200">Wallet recovered</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="404">Wallet not found</response> /// <response code="409">Wallet already exists</response> /// <response code="500">Request is null</response> [Route("recover-via-extpubkey")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.NotFound)] [ProducesResponseType((int)HttpStatusCode.Conflict)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> RecoverViaExtPubKey([FromBody] WalletExtPubRecoveryRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => { await this.walletService.RecoverViaExtPubKey(req, token); return Ok(); }); } /// <summary> /// Gets some general information about a wallet. This includes the network the wallet is for, /// the creation date and time for the wallet, the height of the blocks the wallet currently holds, /// and the number of connected nodes. /// </summary> /// <param name="request">The name of the wallet to get the information for.</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>A JSON object containing the wallet information.</returns> /// <response code="200">Returns wallet information</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("general-info")] [HttpGet] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public Task<IActionResult> GetGeneralInfo([FromQuery] WalletName request, CancellationToken cancellationToken = default(CancellationToken)) { return this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.GetWalletGeneralInfo(req.Name, token))); } /// <summary> /// Get the transaction count for the specified Wallet and Account. /// </summary> /// <param name="request">The Transaction Count request Object</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>Transaction Count</returns> [Route("transactionCount")] [HttpGet] public async Task<IActionResult> GetTransactionCount([FromQuery] WalletTransactionCountRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => this.Json(new { TransactionCount = this.walletManager.GetTransactionCount(req.WalletName, req.AccountName) })); } /// <summary> /// Gets the history of a wallet. This includes the transactions held by the entire wallet /// or a single account if one is specified. /// </summary> /// <param name="request">An object containing the parameters used to retrieve a wallet's history.</param> /// <returns>A JSON object containing the wallet history.</returns> /// <response code="200">Returns wallet history</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("history")] [HttpGet] public IActionResult GetHistory([FromQuery] WalletHistoryRequest request) { return this.Execute(request, (req) => this.Json(this.walletService.GetHistory(req))); } /// <summary> /// Gets the balance of a wallet in STRAT (or sidechain coin). Both the confirmed and unconfirmed balance are returned. /// </summary> /// <param name="request">An object containing the parameters used to retrieve a wallet's balance.</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>A JSON object containing the wallet balance.</returns> /// <response code="200">Returns wallet balances</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("balance")] [HttpGet] public async Task<IActionResult> GetBalance([FromQuery] WalletBalanceRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.GetBalance(req.WalletName, req.AccountName, req.IncludeBalanceByAddress, token)) ); } /// <summary> /// Gets the balance at a specific wallet address in STRAT (or sidechain coin). /// Both the confirmed and unconfirmed balance are returned. /// This method gets the UTXOs at the address which the wallet can spend. /// </summary> /// <param name="request">An object containing the parameters used to retrieve the balance /// at a specific wallet address.</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>A JSON object containing the balance, fee, and an address for the balance.</returns> /// <response code="200">Returns wallet address balances</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("received-by-address")] [HttpGet] public async Task<IActionResult> GetReceivedByAddress([FromQuery] ReceivedByAddressRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.GetReceivedByAddress(request.Address, cancellationToken))); } /// <summary> /// Gets the maximum spendable balance for an account along with the fee required to spend it. /// </summary> /// <param name="request">An object containing the parameters used to retrieve the /// maximum spendable balance on an account.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the maximum spendable balance for an account /// along with the fee required to spend it.</returns> /// <response code="200">Returns spendable balance</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("maxbalance")] [HttpGet] public async Task<IActionResult> GetMaximumSpendableBalance([FromQuery] WalletMaximumBalanceRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.GetMaximumSpendableBalance(request, cancellationToken))); } /// <summary> /// Gets the spendable transactions for an account with the option to specify how many confirmations /// a transaction needs to be included. /// </summary> /// <param name="request">An object containing the parameters used to retrieve the spendable /// transactions for an account.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the spendable transactions for an account.</returns> /// <response code="200">Returns spendable transactions</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("spendable-transactions")] [HttpGet] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> GetSpendableTransactions([FromQuery] SpendableTransactionsRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => Json(await this.walletService.GetSpendableTransactions(req, token))); } /// <summary> /// Gets a fee estimate for a specific transaction. /// Fee can be estimated by creating a <see cref="TransactionBuildContext"/> with no password /// and then building the transaction and retrieving the fee from the context. /// </summary> /// <param name="request">An object containing the parameters used to estimate the fee /// for a specific transaction.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>The estimated fee for the transaction.</returns> /// <response code="200">Returns fee estimate</response> /// <response code="400">Invalid request or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("estimate-txfee")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> GetTransactionFeeEstimate([FromBody] TxFeeEstimateRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => Json(await this.walletService.GetTransactionFeeEstimate(req, token))); } /// <summary> /// Builds a transaction and returns the hex to use when executing the transaction. /// </summary> /// <param name="request">An object containing the parameters used to build a transaction.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object including the transaction ID, the hex used to execute /// the transaction, and the transaction fee.</returns> /// <response code="200">Returns transaction information</response> /// <response code="400">Invalid request, account not found, change address not found, or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("build-transaction")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> BuildTransaction([FromBody] BuildTransactionRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => Json(await this.walletService.BuildTransaction(req, token))); } /// <summary> /// Same as <see cref="BuildTransaction"/> but overrides OP_RETURN data and encodes destination chain and address for InterFlux transaction. /// </summary> [Route("build-interflux-transaction")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> BuildInterFluxTransaction([FromBody] BuildInterFluxTransactionRequest request, CancellationToken cancellationToken = default(CancellationToken)) { request.OpReturnData = InterFluxOpReturnEncoder.Encode(request.DestinationChain, request.DestinationAddress); return await this.Execute(request, cancellationToken, async (req, token) => Json(await this.walletService.BuildTransaction(req, token))); } /// <summary> /// Sends a transaction that has already been built. /// Use the /api/Wallet/build-transaction call to create transactions. /// </summary> /// <param name="request">An object containing the necessary parameters used to a send transaction request.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing information about the sent transaction.</returns> /// <response code="200">Returns transaction details</response> /// <response code="400">Invalid request, cannot broadcast transaction, or unexpected exception occurred</response> /// <response code="403">No connected peers</response> /// <response code="500">Request is null</response> [Route("send-transaction")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.Forbidden)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> SendTransaction([FromBody] SendTransactionRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => Json(await this.walletService.SendTransaction(req, token))); } /// <summary> /// Lists all the files found in the database /// </summary> /// <returns>A JSON object containing the available wallet name /// </returns> /// <param name="cancellationToken">The Cancellation Token</param> [Route("list-wallets")] [HttpGet] public async Task<IActionResult> ListWallets(CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync((object)null, cancellationToken, (req, token) => this.Json(new WalletInfoModel(this.walletManager.GetWalletsNames(), this.walletManager.GetWatchOnlyWalletsNames())), false); } /// <summary> /// Creates a new account for a wallet. /// Accounts are given the name "account i", where i is an incremental index which starts at 0. /// According to BIP44. an account at index i can only be created when the account at index (i - 1) /// contains at least one transaction. For example, if three accounts named "account 0", "account 1", /// and "account 2" already exist and contain at least one transaction, then the /// the function will create "account 3". However, if "account 2", for example, instead contains no /// transactions, then this API call returns "account 2". /// Accounts are created deterministically, which means that on any device, the accounts and addresses /// for a given seed (or mnemonic) are always the same. /// </summary> /// <param name="request">An object containing the necessary parameters to create a new account in a wallet.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the name of the new account or an existing account /// containing no transactions.</returns> /// <response code="200">Returns account name</response> /// <response code="400">Invalid request, or unexpected exception occurred</response> /// <response code="403">Wallet is watch-only</response> /// <response code="500">Request is null</response> [Route("account")] [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.Forbidden)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> CreateNewAccount([FromBody] GetUnusedAccountModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => { try { HdAccount result = this.walletManager.GetUnusedAccount(request.WalletName, request.Password); return this.Json(result.Name); } catch (CannotAddAccountToXpubKeyWalletException e) { this.Logger.LogError("Exception occurred: {0}", e.ToString()); return ErrorHelpers.BuildErrorResponse(HttpStatusCode.Forbidden, e.Message, string.Empty); } }); } /// <summary> /// Gets a list of accounts for the specified wallet. /// </summary> /// <param name="request">An object containing the necessary parameters to list the accounts for a wallet.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing a list of accounts for the specified wallet.</returns> /// <response code="200">Returns account names</response> /// <response code="400">Invalid request, or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("accounts")] [HttpGet] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> ListAccounts([FromQuery] ListAccountsModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => { IEnumerable<HdAccount> result = this.walletManager.GetAccounts(request.WalletName); return this.Json(result.Select(a => a.Name)); }); } /// <summary> /// Gets an unused address (in the Base58 format) for a wallet account. This address will not have been assigned /// to any known UTXO (neither to pay funds into the wallet or to pay change back to the wallet). /// </summary> /// <param name="request">An object containing the necessary parameters to retrieve an /// unused address for a wallet account.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the last created and unused address (in Base58 format).</returns> /// <response code="200">Returns address</response> /// <response code="400">Invalid request, or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("unusedaddress")] [HttpGet] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> GetUnusedAddress([FromQuery] GetUnusedAddressModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => { HdAddress result = this.walletManager.GetUnusedAddress(new WalletAccountReference( request.WalletName, request.AccountName)); return this.Json(request.Segwit ? result.Bech32Address : result.Address); }); } /// <summary> /// Gets a specified number of unused addresses (in the Base58 format) for a wallet account. These addresses /// will not have been assigned to any known UTXO (neither to pay funds into the wallet or to pay change back /// to the wallet). /// </summary> /// <param name="request">An object containing the necessary parameters to retrieve /// unused addresses for a wallet account.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the required amount of unused addresses (in Base58 format).</returns> /// <response code="200">Returns address list</response> /// <response code="400">Invalid request, or unexpected exception occurred</response> /// <response code="500">Request is null or cannot be parsed</response> [Route("unusedaddresses")] [HttpGet] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> GetUnusedAddresses([FromQuery] GetUnusedAddressesModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => { var result = this.walletManager.GetUnusedAddresses( new WalletAccountReference(request.WalletName, req.AccountName), int.Parse(req.Count)) .Select(x => request.Segwit ? x.Bech32Address : x.Address).ToArray(); return this.Json(result); }); } /// <summary> /// Gets a specified number of new addresses (in the Base58 format) for a wallet account. These addresses /// will be newly created and will not have had any transactional activity. /// <remarks>This differs from the unusedaddress(es) endpoints; the addresses will be added to the wallet without respecting the gap limit. /// Therefore, each time the request is made a new set of addresses will be returned.</remarks> /// </summary> /// <param name="request">An object containing the necessary parameters to retrieve /// new addresses for a wallet account.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the required amount of new addresses (in Base58 format).</returns> /// <response code="200">Returns address list</response> /// <response code="400">Invalid request, or unexpected exception occurred</response> /// <response code="500">Request is null or cannot be parsed</response> [Route("newaddresses")] [HttpGet] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.InternalServerError)] public async Task<IActionResult> GetNewAddresses([FromQuery] GetNewAddressesModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => { var result = this.walletManager.GetNewAddresses( new WalletAccountReference(request.WalletName, req.AccountName), int.Parse(req.Count)) .Select(x => request.Segwit ? x.Bech32Address : x.Address).ToArray(); return this.Json(result); }); } /// <summary> /// Gets all addresses for a wallet account. /// </summary> /// <param name="request">An object containing the necessary parameters to retrieve /// all addresses for a wallet account.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing all addresses for a wallet account (in Base58 format).</returns> /// <response code="200">Returns address information list</response> /// <response code="400">Invalid request, or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("addresses")] [HttpGet] public async Task<IActionResult> GetAllAddresses([FromQuery] GetAllAddressesModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.GetAllAddresses(req, token))); } /// <summary> /// Removes transactions from the wallet. /// You might want to remove transactions from a wallet if some unconfirmed transactions disappear /// from the blockchain or the transaction fields within the wallet are updated and a refresh is required to /// populate the new fields. /// In one situation, you might notice several unconfirmed transaction in the wallet, which you now know were /// never confirmed. You can use this API to correct this by specifying a date and time before the first /// unconfirmed transaction thereby removing all transactions after this point. You can also request a resync as /// part of the call, which calculates the block height for the earliest removal. The wallet sync manager then /// proceeds to resync from there reinstating the confirmed transactions in the wallet. You can also cherry pick /// transactions to remove by specifying their transaction ID. /// </summary> /// <param name="request">An object containing the necessary parameters to remove transactions /// from a wallet. The includes several options for specifying the transactions to remove.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing all removed transactions identified by their /// transaction ID and creation time.</returns> /// <response code="200">Returns transaction list</response> /// <response code="400">Invalid request, or an exception occurred</response> /// <response code="500">Request is null</response> [Route("remove-transactions")] [HttpDelete] public async Task<IActionResult> RemoveTransactions([FromQuery] RemoveTransactionsModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.RemoveTransactions(req, token))); } [Route("remove-wallet")] [HttpDelete] public async Task<IActionResult> RemoveWallet([FromQuery] RemoveWalletModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => { await this.walletService.RemoveWallet(req, token); return this.Ok(); }); } /// <summary> /// Gets the extended public key of a specified wallet account. /// </summary> /// <param name="request">An object containing the necessary parameters to retrieve.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the extended public key for a wallet account.</returns> /// <response code="200">Returns extended public key</response> /// <response code="400">Invalid request, or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("extpubkey")] [HttpGet] public async Task<IActionResult> GetExtPubKey([FromQuery] GetExtPubKeyModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => this.Json(this.walletManager.GetExtPubKey(new WalletAccountReference(request.WalletName, request.AccountName)))); } /// <summary> /// Gets the private key of a specified wallet address. /// </summary> /// <param name="request">An object containing the necessary parameters to retrieve.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A JSON object containing the private key of the address in WIF representation.</returns> /// <response code="200">Returns private key</response> /// <response code="400">Invalid request, or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("privatekey")] [HttpPost] public async Task<IActionResult> RetrievePrivateKey([FromBody] RetrievePrivateKeyModel request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => this.Json(this.walletManager.RetrievePrivateKey(request.Password, request.WalletName, request.Address))); } /// <summary> /// Requests the node resyncs from a block specified by its block hash. /// Internally, the specified block is taken as the new wallet tip /// and all blocks after it are resynced. /// </summary> /// <param name="model">The Hash of the block to Sync From</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A value of Ok if the re-sync was successful.</returns> [HttpPost] [Route("sync")] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] public async Task<IActionResult> Sync([FromBody] HashModel model, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(model, cancellationToken, (req, token) => { ChainedHeader block = this.chainIndexer.GetHeader(uint256.Parse(model.Hash)); if (block == null) { return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, $"Block with hash {model.Hash} was not found on the blockchain.", string.Empty); } this.walletSyncManager.SyncFromHeight(block.Height); return this.Ok(); }); } /// <summary> /// Request the node resyncs starting from a given date and time. /// Internally, the first block created on or after the supplied date and time /// is taken as the new wallet tip and all blocks after it are resynced. /// </summary> /// <param name="request">An object containing the necessary parameters /// to request a resync.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <returns>A value of Ok if the resync was successful.</returns> /// <response code="200">Resync requested</response> /// <response code="400">Invalid request</response> [HttpPost] [Route("sync-from-date")] public async Task<IActionResult> SyncFromDate([FromBody] WalletSyncRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.ExecuteAsAsync(request, cancellationToken, (req, token) => { if (!request.All) { this.walletSyncManager.SyncFromDate(request.Date, request.WalletName); } else { this.walletSyncManager.SyncFromHeight(0, request.WalletName); } return this.Ok(); }); } /// <summary> /// Retrieves information about the wallet /// </summary> /// <param name="request">Parameters to request wallet stats</param> /// <returns>Stats about the wallet</returns> /// <response code="200">Returns wallet stats</response> /// <response code="400">Invalid request, or unexpected exception occurred</response> /// <response code="500">Request is null</response> [Route("wallet-stats")] [HttpGet] public async Task<IActionResult> WalletStats([FromQuery] WalletStatsRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.GetWalletStats(req, token))); } /// <summary>Creates requested amount of UTXOs each of equal value.</summary> /// <returns><placeholder>A <see cref="Task"/> representing the asynchronous operation.</placeholder></returns> /// <param name="request">An object containing the necessary parameters.</param> /// <param name="cancellationToken">The Cancellation Token</param> /// <response code="200">Returns transaction details</response> /// <response code="400">Invalid request, cannot broadcast transaction, or unexpected exception occurred</response> /// <response code="403">No connected peers</response> /// <response code="500">Request is null</response> [HttpPost] [Route("splitcoins")] public async Task<IActionResult> SplitCoins([FromBody] SplitCoinsRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.SplitCoins(req, token))); } /// <summary>Splits and distributes UTXOs across wallet addresses</summary> /// <returns><placeholder>A <see cref="Task"/> representing the asynchronous operation.</placeholder></returns> /// <param name="request">An object containing the necessary parameters.</param> /// <param name="cancellationToken">The Cancellation Token</param> [HttpPost] [Route("distribute-utxos")] public async Task<IActionResult> DistributeUtxos([FromBody] DistributeUtxosRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.DistributeUtxos(req, token))); } [HttpPost] [Route("sweep")] public async Task<IActionResult> Sweep([FromBody] SweepRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.Sweep(req, token))); } [Route("build-offline-sign-request")] [HttpPost] public async Task<IActionResult> BuildOfflineSignRequest([FromBody] BuildOfflineSignRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.BuildOfflineSignRequest(req, token))); } // TODO: Make this support PSBT directly? [Route("offline-sign-request")] [HttpPost] public async Task<IActionResult> OfflineSignRequest([FromBody] OfflineSignRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.OfflineSignRequest(req, token))); } [HttpPost] [Route("consolidate")] public async Task<IActionResult> Consolidate([FromBody] ConsolidationRequest request, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Execute(request, cancellationToken, async (req, token) => this.Json(await this.walletService.Consolidate(req, token))); } } }
55.039194
202
0.651312
[ "MIT" ]
fr0stnk/StratisFullNode
src/Stratis.Bitcoin.Features.Wallet/Controllers/WalletController.cs
49,152
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Editor { public class BaseMixedRealityServiceInspector : IMixedRealityServiceInspector { public virtual bool DrawProfileField { get { return true; } } public virtual bool AlwaysDrawSceneGUI { get { return false; } } public virtual void DrawGizmos(object target) { } public virtual void DrawInspectorGUI(object target) { } public virtual void DrawSceneGUI(object target, SceneView sceneView) { } } }
28.904762
81
0.718287
[ "MIT" ]
AdrianaMusic/MixedRealityToolkit-Unity
Assets/MRTK/Core/Inspectors/ServiceInspectors/BaseMixedRealityServiceInspector.cs
611
C#
// Jeebs Unit Tests // Copyright (c) bfren - licensed under https://mit.bfren.dev/2013 using Jeebs.Data.Mapping; using Jeebs.Data.Querying.Exceptions; using Xunit; using static F.DataF.QueryBuilderF; namespace F.DataF.QueryBuilderF_Tests; public class GetColumnFromExpression_Tests { [Fact] public void Unable_To_Get_Column_Throws_UnableToGetColumnFromExpressionException() { // Arrange // Act var a0 = void () => GetColumnFromExpression<BrokenTable>(t => t.Bar); var a1 = void () => GetColumnFromExpression(new BrokenTable(), t => t.Bar); // Assert Assert.Throws<UnableToGetColumnFromExpressionException<BrokenTable>>(a0); Assert.Throws<UnableToGetColumnFromExpressionException<BrokenTable>>(a1); } [Fact] public void Returns_Column_With_Property_Value_As_Name_And_Property_Name_As_Alias() { // Arrange var tableName = Rnd.Str; var table = new TestTable(tableName); // Act var r0 = GetColumnFromExpression(table, t => t.Foo); var r1 = GetColumnFromExpression<TestTable>(t => t.Foo); // Assert Assert.Equal(tableName, r0.Table.Name); Assert.Equal(table.Foo, r0.Name); Assert.Equal(nameof(table.Foo), r0.Alias); Assert.Equal(nameof(TestTable), r1.Table.Name); Assert.Equal(table.Foo, r1.Name); Assert.Equal(nameof(table.Foo), r1.Alias); } public record class BrokenTable : TestTable { internal string Bar => Prefix + nameof(Bar); public BrokenTable() : base(Rnd.Str) { } } public record class TestTable : Table { public static readonly string Prefix = "Bar_"; public string Foo => Prefix + nameof(Foo); public TestTable() : base(nameof(TestTable)) { } public TestTable(string name) : base(name) { } } }
24.882353
84
0.723404
[ "MIT" ]
bfren/jeebs
tests/Tests.Jeebs.Data.Querying/Functions/QueryBuilder/GetColumnFromExpression_Tests.cs
1,694
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Antlr.Runtime; namespace CompilerTests.CompilerUnitTests { [TestFixture] class Assignment : BaseTest { [Test] public void TestGoodAssignments() { string test = @" integer i = 4; float f; string s = ((string)4); func() { f += 0.3; i *= 4; s += ""\nd""; vector v; v *= <1,1,1,1>; integer j = -1; j = -2; } default { state_entry() {} } "; Compiler.Compile(new ANTLRStringStream(test)); Assert.IsTrue(Listener.ErrorCount == 0); } [Test] public void TestBadTypeForDiv() { string test = @" string s = ((string)4); func() { integer i; i /= <1,1,1>; } default { state_entry() {} } "; Compiler.Compile(new ANTLRStringStream(test)); Assert.IsTrue(Listener.ErrorCount > 0); Assert.IsTrue(Listener.MessagesContain("not a valid operation between integer and vector")); } [Test] public void TestBadTypeForMul() { string test = @" string s = ((string)4); func() { vector v; rotation r; r *= v; } default { state_entry() {} } "; Compiler.Compile(new ANTLRStringStream(test)); Assert.IsTrue(Listener.ErrorCount > 0); Assert.IsTrue(Listener.MessagesContain("not a valid operation between rotation and vector")); } [Test] public void TestBadTypeForMod() { string test = @" func() { vector v; v %= 5; } default {} "; Compiler.Compile(new ANTLRStringStream(test)); Assert.IsTrue(Listener.ErrorCount > 0); Assert.IsTrue(Listener.MessagesContain("not a valid operation between vector and integer")); } [Test] public void TestAssignBeforeDef() { string test = @" func() { v = <1,1,1>; vector v; } default { state_entry() {} } "; Compiler.Compile(new ANTLRStringStream(test)); Assert.IsTrue(Listener.ErrorCount > 0); Assert.IsTrue(Listener.MessagesContain("can not be used before it is defined")); } [Test] public void TestGoodAssignmentBeforeAndAfterShadowing() { string test = @" func(vector v) { v = <1,1,1>; vector v; v = <2,2,2>; } default { state_entry() {} } "; Halcyon.Phlox.Glue.CompilerFrontend fe = Compiler.Compile(new ANTLRStringStream(test)); Assert.IsTrue(Listener.ErrorCount == 0); Assert.IsTrue(fe.GeneratedByteCode.Contains("store 0")); Assert.IsTrue(fe.GeneratedByteCode.Contains("store 1")); } [Test] public void TestGoodAssignmentReferenceToParamFromShadow() { string test = @" func(vector v) { v = <1.0, 1.0, 1.0>; vector v = v; v = <1.0, 1.0, 1.0>; } default { state_entry() {} } "; Halcyon.Phlox.Glue.CompilerFrontend fe = Compiler.Compile(new ANTLRStringStream(test)); Assert.IsTrue(Listener.ErrorCount == 0); Console.WriteLine(fe.GeneratedByteCode); Assert.IsTrue(fe.GeneratedByteCode.Contains("load 0")); Assert.IsTrue(fe.GeneratedByteCode.Contains("store 1")); } [Test] public void TestGoodAssignBeforeDefWithGlobal() { string test = @" vector v; func() { v = <1,1,1>; vector v; } default { state_entry() {} } "; Compiler.Compile(new ANTLRStringStream(test)); Assert.IsTrue(Listener.ErrorCount == 0); } [Test] public void TestAssignmentWithParensSurrounding() { string test = @" func() { integer f; (f = 4); } default { state_entry() {} } "; Compiler.Compile(new ANTLRStringStream(test)); Assert.IsTrue(Listener.ErrorCount == 0); } } }
29.328205
105
0.392726
[ "Apache-2.0" ]
HalcyonGrid/phlox
Source/CompilerTests/CompilerTests/Assignment.cs
5,721
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Inputs.Certmanager.V1 { /// <summary> /// PKCS12 configures options for storing a PKCS12 keystore in the `spec.secretName` Secret resource. /// </summary> public class CertificateSpecKeystoresPkcs12Args : Pulumi.ResourceArgs { /// <summary> /// Create enables PKCS12 keystore creation for the Certificate. If true, a file named `keystore.p12` will be created in the target Secret resource, encrypted using the password stored in `passwordSecretRef`. The keystore file will only be updated upon re-issuance. A file named `truststore.p12` will also be created in the target Secret resource, encrypted using the password stored in `passwordSecretRef` containing the issuing Certificate Authority /// </summary> [Input("create", required: true)] public Input<bool> Create { get; set; } = null!; /// <summary> /// PasswordSecretRef is a reference to a key in a Secret resource containing the password used to encrypt the PKCS12 keystore. /// </summary> [Input("passwordSecretRef", required: true)] public Input<Pulumi.Kubernetes.Types.Inputs.Certmanager.V1.CertificateSpecKeystoresPkcs12PasswordSecretRefArgs> PasswordSecretRef { get; set; } = null!; public CertificateSpecKeystoresPkcs12Args() { } } }
47.085714
459
0.714199
[ "MIT" ]
WhereIsMyTransport/Pulumi.Crds.CertManager
crd/dotnet/Certmanager/V1/Inputs/CertificateSpecKeystoresPkcs12Args.cs
1,648
C#
/* * Copyright (c) Contributors, http://virtual-planets.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * For an explanation of the license of each contributor and the content it * covers please see the Licenses directory. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Virtual Universe Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; namespace Universe.ScriptEngine.VirtualScript.MiniModule { public interface IMRMModule { void RegisterExtension<T>(T instance); void InitializeMRM(MRMBase mmb, uint localID, UUID itemID); void GetGlobalEnvironment(uint localID, out IWorld world, out IHost host); } }
52.725
83
0.738265
[ "MIT" ]
johnfelipe/Virtual-Universe
Universe/ScriptEngine/VirtualScript/CompilerTools/Minimodule/IMRMModule.cs
2,109
C#
namespace EventStore.Projections.Core.Services.Processing { public interface IEventWriter { void ValidateOrderAndEmitEvents(EmittedEventEnvelope[] events); } }
27.333333
65
0.823171
[ "Apache-2.0", "CC0-1.0" ]
01100010011001010110010101110000/EventStore
src/EventStore.Projections.Core/Services/Processing/IEventWriter.cs
164
C#
using System.Collections.Generic; using Microsoft.OpenApi.Models; namespace Blockfrost.Api.Generate { public class SchemaContext : GeneratorContext { public SchemaNode node { get; internal set; } public OpenApiSchema schema => node.schema; public SchemaContext items => schema.Items != null ? new(this, new SchemaNode(classname, schema.Items)) : null; public IEnumerable<SchemaNode> vars => node.GetVars(); public string classname => node.name; public string modelName => classname; public string itemname => $"{classname}Item"; public string collectionname => $"{classname}Collection"; public string description => schema.Description ?? items?.description; public bool isArray => node.isArray; public bool isEnum => node.isEnum; public SchemaContext(GeneratorContext context, KeyValuePair<string, OpenApiSchema> schemaNode) : this(context, new SchemaNode(schemaNode)) { } /// <summary> /// asdasd /// </summary> /// <param name="context"></param> /// <param name="schemaNode"></param> public SchemaContext(GeneratorContext context, SchemaNode schemaNode) : base(context) { node = schemaNode; } public override string ToString() { return node.baseName; } } }
34.170732
146
0.62955
[ "Apache-2.0" ]
blockfrost/blockfrost-donet
tools/Blockfrost.Api.Generate/Deprecated/SchemaContext.cs
1,403
C#
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using NewRelic.Agent.IntegrationTestHelpers.RemoteServiceFixtures; using Xunit; namespace NewRelic.Agent.IntegrationTests.RemoteServiceFixtures { public class BasicWebFormsApplication : RemoteApplicationFixture { public BasicWebFormsApplication() : base(new RemoteWebApplication("BasicWebFormsApplication", ApplicationType.Bounded)) { Actions ( exerciseApplication: Get ); } public void Get() { var address = $"http://{DestinationServerName}:{Port}/WebForm1.aspx"; DownloadStringAndAssertContains(address, "<html"); } public void GetSlow() { var address = $"http://{DestinationServerName}:{Port}/WebFormSlow.aspx"; DownloadStringAndAssertContains(address, "<html"); } public void Get404() { var address = $"http://{DestinationServerName}:{Port}/WebFormThatDoesNotExist.aspx"; try { new WebClient().DownloadString(address); } catch (Exception) { // swallow } } public void GetWithQueryString(IEnumerable<KeyValuePair<string, string>> parameters, bool expectException) { var parametersAsStrings = parameters.Select(param => $"{param.Key}={param.Value}"); var parametersAsString = string.Join("&", parametersAsStrings); var address = $"http://{DestinationServerName}:{Port}/WebForm1.aspx?{parametersAsString}"; var exceptionOccurred = false; try { var result = new WebClient().DownloadString(address); Assert.NotNull(result); } catch { exceptionOccurred = true; } Assert.Equal(expectException, exceptionOccurred); } } }
29.777778
127
0.585821
[ "Apache-2.0" ]
Faithlife/newrelic-dotnet-agent
tests/Agent/IntegrationTests/IntegrationTests/RemoteServiceFixtures/BasicWebFormsApplication.cs
2,144
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("StreamingServer.DependencyInjection")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StreamingServer.DependencyInjection")] [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("ff2f0bd6-0883-4f8f-8116-155a9193704d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39
84
0.751906
[ "MIT" ]
AnCh7/StreamingServer
src/Core/StreamingServer.DependencyInjection/Properties/AssemblyInfo.cs
1,446
C#
#region License // Jdenticon-net // https://github.com/dmester/jdenticon-net // Copyright © Daniel Mester Pirttijärvi 2018 // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace Jdenticon.AspNetCore { /// <summary> /// Tag helper used to display an identicon in &lt;img&gt; elements. /// </summary> /// <remarks> /// <para> /// The following attributes are available for this tag helper. /// </para> /// <list type="table"> /// <title>Tag helper attributes</title> /// <listheader> /// <term>Attribute name</term> /// <term>Description</term> /// </listheader> /// <item> /// <term><see cref="Value">identicon-value</see></term> /// <term>Value that will be hashed using SHA1 and then used as base for this icon.</term> /// </item> /// <item> /// <term><see cref="Hash">identicon-hash</see></term> /// <term>Hash that will be used as base for this icon.</term> /// </item> /// <item> /// <term><see cref="Format">identicon-format</see></term> /// <term>Format of the generated icon. This attribute is optional and defaults to PNG.</term> /// </item> /// <item> /// <term>width</term> /// <term>The width of the generated icon.</term> /// </item> /// <item> /// <term>height</term> /// <term>The height of the generated icon.</term> /// </item> /// </list> /// <para> /// The size of the icon is determined from the specified width and height of the /// <c>&lt;img&gt;</c> tag. /// </para> /// <note type="note"> /// Only square icons are supported. Specifying different width and height will end up in a distorted icon. /// </note> /// </remarks> /// <example> /// <para> /// In the following example <see cref="Value">identicon-value</see> is used /// to render an identicon for a user id. /// </para> /// <code language="html" title="Using identicon-value"> /// @{ /// var userId = "TestIcon"; /// } /// &lt;img identicon-value="userId" width="100" height="100" /&lt; /// </code> /// </example> [HtmlTargetElement("img", Attributes = IdenticonValueAttributeName)] [HtmlTargetElement("img", Attributes = IdenticonHashAttributeName)] public class IdenticonTagHelper : TagHelper { private byte[] hash; private const string IdenticonValueAttributeName = "identicon-value"; private const string IdenticonHashAttributeName = "identicon-hash"; private const string IdenticonFormatAttributeName = "identicon-format"; /// <summary> /// Gets or sets the value that will be hashed using SHA1 and then used as base for this icon. /// </summary> /// <remarks> /// <para> /// <c>null</c> values for this property is allowed and handled as empty strings. /// </para> /// <para> /// If both <see cref="Hash">identicon-hash</see> and <see cref="Value">identicon-value</see> /// is specified, <see cref="Hash">identicon-hash</see> has precedence. /// </para> /// </remarks> /// <example> /// <para> /// In the following example <see cref="Value">identicon-value</see> is used /// to render an identicon for a user id. /// </para> /// <code language="html" title="Using identicon-value"> /// @{ /// var userId = "TestIcon"; /// } /// &lt;img identicon-value="userId" width="100" height="100" /&lt; /// </code> /// </example> [HtmlAttributeName(IdenticonValueAttributeName)] public object Value { get; set; } /// <summary> /// Gets or sets a hash that will be used as base for this icon. /// </summary> /// <remarks> /// <para> /// The hash must contain at least 6 bytes. /// </para> /// <para> /// If both <see cref="Hash">identicon-hash</see> and <see cref="Value">identicon-value</see> /// is specified, <see cref="Hash">identicon-hash</see> has precedence. /// </para> /// </remarks> /// <exception cref="ArgumentException"><paramref name="hash"/> does not contain 6 bytes.</exception> /// <example> /// <para> /// In the following example <see cref="Hash">identicon-hash</see> is used /// to render an identicon for a user id. /// </para> /// <code language="html" title="Using identicon-hash"> /// @{ /// var userIdHash = new byte[] { 242, 94, 85, 42, 87, 222, 222, 190, 155, 231, 226, 21, 195, 40, 18, 137 }; /// } /// &lt;img identicon-hash="userIdHash" width="100" height="100" /&lt; /// </code> /// </example> [HtmlAttributeName(IdenticonHashAttributeName)] public byte[] Hash { get => hash; set => hash = value == null || value.Length >= 6 ? value : throw new ArgumentException($"The value of identicon-hash must contain at least 6 bytes.", nameof(value)); } /// <summary> /// Gets or sets the format of the generated icon. This attribute is optional and defaults to PNG. /// </summary> /// <example> /// <para> /// In the following example <see cref="Format">identicon-format</see> is used /// to render SVG icons instead of PNG icons. /// </para> /// <code language="html" title="Using identicon-format"> /// @{ /// var userId = "TestIcon"; /// } /// &lt;img identicon-value="userId" identicon-format="Svg" width="100" height="100" /&lt; /// </code> /// </example> [HtmlAttributeName(IdenticonFormatAttributeName)] public ExportImageFormat Format { get; set; } = ExportImageFormat.Png; /// <exclude/> [ViewContext] public ViewContext ViewContext { get; set; } /// <exclude/> public override void Process(TagHelperContext context, TagHelperOutput output) { output.Attributes.RemoveAll(IdenticonValueAttributeName); output.Attributes.RemoveAll(IdenticonHashAttributeName); output.Attributes.RemoveAll(IdenticonFormatAttributeName); var sizeAttributes = new[] { "width", "height" }; var size = sizeAttributes .Select(name => { var attribute = output.Attributes[name]; if (attribute != null && int.TryParse( attribute.Value.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var iWidth)) { return (int?)iWidth; } return (int?)null; }) .Where(value => value != null) .FirstOrDefault() ?? 100; var url = IdenticonUrl.Create(ViewContext.HttpContext, hash: Hash ?? HashGenerator.ComputeHash(Value, "SHA1"), size: size, format: Format, style: null); output.Attributes.SetAttribute("src", url); } } }
39.885845
122
0.574242
[ "MIT" ]
topikon-de/jdenticon-net
Extensions/Jdenticon.AspNetCore/IdenticonTagHelper.cs
8,739
C#
using System; using System.Collections; using System.IO; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; namespace cilToMango { public class MainClass { private static System.IO.StreamWriter outputFile; private static Instruction currentInstruction; public static void Main(string[] args) { // startup things if (args.Length < 1 || args.Length > 2) { Console.WriteLine("Please give the input file as first argument. Second for outputfile may be optional."); return; } Console.WriteLine("Input File: " + args[0]); string inputFileName = Path.GetFileName(args[0]); if (args.Length > 1) { outputFile = new System.IO.StreamWriter(args[1]); } else { outputFile = new System.IO.StreamWriter(inputFileName + ".mango"); } ModuleDefinition module = ModuleDefinition.ReadModule(args[0]); //begin writing to outputfile PrintLn("module Main\n{"); int externMethodCounter = 0; TypeDefinition mainClass = module.Types.Single(type => type.Name == "MainClass"); // handle c# structs foreach (TypeDefinition type in mainClass.NestedTypes) { PrintLn("\ttype " + type.Name); PrintLn("\t{"); foreach (FieldDefinition field in type.Fields) { PrintLn("\t\tfield\t " + GetMangoType(field.FieldType) + " " + field.Name); } PrintLn("\t}\n\n"); } foreach (MethodDefinition method in mainClass.Methods) { String methodName = method.Name.ToLower(); if (methodName.StartsWith(".")) // not relevant for the mango code { Console.WriteLine("//Ignoring Instructions of Method " + methodName + "\n"); continue; } if (methodName.StartsWith("sys") && methodName.Length > 3) // extern systemcall { PrintLn("\tdeclare " + GetMangoType(method.ReturnType) + " @" + methodName + "(" + GetArgumentsFromMethod(method) + ") " + (100 + externMethodCounter++) + "\n"); continue; } // normal function Print("\tdefine " + GetMangoType(method.ReturnType) + " @" + methodName + "("); Print(GetArgumentsFromMethod(method)); PrintLn(")"); PrintLn("\t{"); ArrayList labelOffsets = new ArrayList(); // search for branching instructions foreach (Instruction i in method.Body.Instructions) { currentInstruction = i; String opcodeName = i.OpCode.Name; switch (opcodeName) { case "beq": case "beq.s": case "bge": case "bge.s": case "bge.un": case "bge.un.s": case "bgt": case "bgt.s": case "bgt.un": case "bgt.un.s": case "ble": case "ble.s": case "ble.un": case "ble.un.s": case "blt": case "blt.s": case "blt.un": case "blt.un.s": case "bne.un": case "bne.un.s": case "br": case "br.s": case "brfalse": case "brfalse.s": case "brnull": case "brnull.s": case "brtrue": case "brtrue.s": if (!labelOffsets.Contains(((Instruction)i.Operand).Offset)) { labelOffsets.Add(((Instruction)i.Operand).Offset); } break; } } // prepare use of Variables int localVarIndex = 0; foreach (VariableDefinition var in method.Body.Variables) { string varType; if (var.VariableType.IsPrimitive) { varType = GetMangoVariableType(var.VariableType); } else { varType = var.VariableType.Name; } outputFile.WriteLine("\t\tlocal\t" + varType + "\t%loc" + localVarIndex++); } // translate instructions from cil to mango foreach (Instruction i in method.Body.Instructions) { currentInstruction = i; String opcodeName = i.OpCode.Name; // check for Labels if (labelOffsets.Contains(i.Offset)) { Print("l" + labelOffsets.IndexOf(i.Offset) + ":\t\t"); } else { Print("\t\t"); } // fancy Debug output Console.Write(i.Offset + "\t" + i.OpCode.Name); if (i.Operand != null) { switch (i.Operand.GetType().Name) { case "Instruction": Console.WriteLine("\t->\t" + ((Instruction)i.Operand).Offset); break; case "MethodDefinition": Console.WriteLine("\t->\t" + ((MethodDefinition)i.Operand).Name); break; case "VariableDefinition": Console.WriteLine("\t->\t" + ((VariableDefinition)i.Operand).ToString()); break; default: Console.WriteLine("\t\t" + i.Operand); break; } } else { Console.WriteLine(""); } int targetOffset; // used for branching FieldReference targetField; // used for stfld string fieldName; // used for stfld switch (opcodeName) { case "add": outputFile.WriteLine("add"); break; case "beq": case "beq.s": case "bge": case "bge.s": case "bge.un": case "bge.un.s": case "bgt": case "bgt.s": case "bgt.un": case "bgt.un.s": case "ble": case "ble.s": case "ble.un": case "ble.un.s": case "blt": case "blt.s": case "blt.un": case "blt.un.s": case "bne.un": case "bne.un.s": case "br": case "br.s": String mangoInstruction; if (opcodeName.EndsWith(".s")) { mangoInstruction = opcodeName.Substring(0, opcodeName.Length - 2); } else { mangoInstruction = opcodeName; } targetOffset = ((Instruction)i.Operand).Offset; outputFile.WriteLine(mangoInstruction + "\tl" + labelOffsets.IndexOf(targetOffset)); break; case "brfalse": case "brfalse.s": case "brnull": case "brnull.s": targetOffset = ((Instruction)i.Operand).Offset; outputFile.WriteLine("brfalse\tl" + labelOffsets.IndexOf(targetOffset)); break; case "brtrue": case "brtrue.s": targetOffset = ((Instruction)i.Operand).Offset; outputFile.WriteLine("brtrue\tl" + labelOffsets.IndexOf(targetOffset)); break; case "call": MethodDefinition targetMethod = ((MethodDefinition)i.Operand); if (targetMethod.Name.ToLower().StartsWith("sys")) { outputFile.Write("sys"); } outputFile.WriteLine("call\t" + GetMangoType(targetMethod.ReturnType) + "\t@" + targetMethod.Name.ToLower() + "(" + GetArgumentsFromMethod(targetMethod, false) + ")" ); break; case "ceq": case "cgt": case "cgt.un": case "clt": case "clt.un": case "dup": outputFile.WriteLine(opcodeName); break; case "idind.u8": // not ldind.u8 ! outputFile.WriteLine("ldind i64"); break; case "ldarg.0": case "ldarg.1": case "ldarg.2": case "ldarg.3": outputFile.WriteLine("ldarg\t%arg" + opcodeName.Substring(6, 1)); break; case "ldarg.s": outputFile.WriteLine("ldarg\t%arg" + ((ParameterDefinition)i.Operand).Sequence); break; case "ldc.i4.m1": case "ldc.i4.M1": outputFile.WriteLine("ldc i32 -1"); break; case "ldc.i4.0": case "ldc.i4.1": case "ldc.i4.2": case "ldc.i4.3": case "ldc.i4.4": case "ldc.i4.5": case "ldc.i4.6": case "ldc.i4.7": case "ldc.i4.8": outputFile.WriteLine("ldc\ti32\t" + opcodeName.Substring(7, 1)); break; case "ldc.i4": case "ldc.i4.s": outputFile.WriteLine("ldc\ti32\t" + i.Operand); break; case "ldfld": case "ldflda": if (i.Operand is FieldReference) { targetField = (FieldReference)i.Operand; outputFile.Write(opcodeName + "\t"); if (targetField.FieldType.IsPrimitive) { outputFile.Write(GetMangoType(targetField.FieldType) + "\t"); } else { outputFile.Write(targetField.FieldType.Name + "\t"); } fieldName = targetField.FullName; // e.g. "System.Int32 SimpleExample.MainClass/Point2D::x" fieldName = fieldName.Substring(fieldName.IndexOf('/') + 1); // e.g. "Point2D::x" fieldName = fieldName.Replace("::", "/"); // e.g. "Point2D/x" outputFile.WriteLine(fieldName); } break; // case "ldind.i": case "ldind.i1": outputFile.WriteLine("ldind i8"); outputFile.WriteLine("\t\tconv i32"); break; case "ldind.i2": outputFile.WriteLine("ldind i16"); outputFile.WriteLine("\t\tconv i32"); break; case "ldind.i4": outputFile.WriteLine("ldind i32"); break; case "ldind.i8": outputFile.WriteLine("ldind i64"); break; case "ldind.r4": outputFile.WriteLine("ldind f32"); break; case "ldind.r8": outputFile.WriteLine("ldind f64"); break; //case "ldind.ref": case "ldind.u1": outputFile.WriteLine("ldind u8"); outputFile.WriteLine("\t\tconv i32"); break; case "ldind.u2": outputFile.WriteLine("ldind u16"); outputFile.WriteLine("\t\tconv i32"); break; case "ldind.u4": outputFile.WriteLine("ldind u32"); outputFile.WriteLine("\t\tconv i32"); break; case "ldloca": case "ldloca.s": if (i.Operand != null && i.Operand.ToString().StartsWith("V_") && i.Operand.ToString().Length >= 3) { outputFile.WriteLine("ldloca\t%loc" + i.Operand.ToString().Substring(2)); } break; case "ldloc.0": case "ldloc.1": case "ldloc.2": case "ldloc.3": outputFile.WriteLine("ldloc\t%loc" + opcodeName.Substring(6, 1)); break; case "ldloc.s": if (i.Operand != null && i.Operand.ToString().StartsWith("V_") && i.Operand.ToString().Length >= 3) { outputFile.WriteLine("ldloc\t%loc" + i.Operand.ToString().Substring(2)); } break; case "mul": case "neg": case "nop": case "ret": outputFile.WriteLine(opcodeName); break; case "stfld": if (i.Operand is FieldReference) { targetField = (FieldReference) i.Operand; outputFile.Write("stfld\t"); if (targetField.FieldType.IsPrimitive) { outputFile.Write(GetMangoType(targetField.FieldType) + "\t"); } else { outputFile.Write(targetField.FieldType.Name + "\t"); } fieldName = targetField.FullName; // e.g. "System.Int32 SimpleExample.MainClass/Point2D::x" fieldName = fieldName.Substring(fieldName.IndexOf('/') + 1); // e.g. "Point2D::x" fieldName = fieldName.Replace("::", "/"); // e.g. "Point2D/x" outputFile.WriteLine(fieldName); } break; //case "stind.ref": case "stind.i1": outputFile.WriteLine("stind i8"); break; case "stind.i2": outputFile.WriteLine("stind i16"); break; case "stind.i4": outputFile.WriteLine("stind i32"); break; case "stind.i8": outputFile.WriteLine("stind i64"); break; case "stind.r4": outputFile.WriteLine("stind f32"); break; case "stind.r8": outputFile.WriteLine("stind f64"); break; case "stloc.0": case "stloc.1": case "stloc.2": case "stloc.3": outputFile.WriteLine("stloc\t%loc" + opcodeName.Substring(6,1)); break; case "stloc.s": if (i.Operand != null && i.Operand.ToString().StartsWith("V_") && i.Operand.ToString().Length >= 3) { outputFile.WriteLine("stloc\t%loc" + i.Operand.ToString().Substring(2)); break; } break; case "sub": outputFile.WriteLine(opcodeName); break; default: Console.WriteLine(">> Unknown Opcode:\t" + currentInstruction.OpCode.Name); Console.WriteLine(">> Operand:\t" + currentInstruction.Operand); outputFile.WriteLine(""); break; } } PrintLn("\t}\n\n"); } outputFile.WriteLine("}"); outputFile.Close(); } // converts a cil return type into a mango return type private static String GetMangoType(TypeReference cilType) { if (!cilType.IsPrimitive) { if (cilType.Name == "Void") { return "void"; } return cilType.Name.ToString(); } switch (cilType.Name) { case "Int32": return "i32"; case "Boolean": return "bool"; default: Console.WriteLine("Unknown Type:\t" + cilType.FullName); return "void"; } } // converts a cil variable type into a mango variable type private static String GetMangoVariableType(TypeReference cilType) { String result = GetMangoType(cilType); // in most cases the result is equal to the normal return type in mango if (result == "bool") { // bool is only supported for return types of functions, but not // for using it with local variables by now - even if u can // declare, but not use boolean local variables... return "i32"; } return result; } // should return something like "int32, f32, int32" or "int32 %arg0, f32 %arg1" private static String GetArgumentsFromMethod(MethodDefinition m, bool withArgumentName = true) { string result = ""; bool firstParameter = true; int argumentCounter = 0; foreach (ParameterDefinition p in m.Parameters) { if (!firstParameter) { result += ", "; } else { firstParameter = false; } result += GetMangoType(p.ParameterType); if (withArgumentName) { result += " %arg" + argumentCounter++; } } return result; } private static void Print(String s) { Console.Write(s); outputFile.Write(s); } private static void PrintLn(String s) { Print(s + "\n"); } } }
43.359528
123
0.361531
[ "MIT" ]
janmoehl/cil-to-mango-compiler
cilToMangoCompiler/cilToMangoCompiler/Program.cs
22,072
C#
using System.Windows.Input; namespace MattermostAddinConnect.Settings { public class SettingsViewModel { public SettingsViewModel(AddInSettings settings, ICommand saveCommand, ICommand cancelCommand) { Save = saveCommand; Cancel = cancelCommand; MattermostUrl = settings.MattermostUrl; TeamId = settings.TeamId; Username = settings.Username; Version = settings.Version; } public string MattermostUrl { get; set; } public string TeamId { get; set; } public string Username { get; set; } public ICommand Save { get; private set; } public ICommand Cancel { get; private set; } public MattermostVersion Version { get; set; } } }
32.625
102
0.624521
[ "MIT" ]
casanovg/Mattermost-Addin
MattermostAddin-Connect/Settings/SettingsViewModel.cs
785
C#
using System.Collections.Generic; using System.Linq; namespace EFlogger.Profiling.Helpers { /// <summary> /// Help to build out sql /// </summary> public class SqlBuilder { Dictionary<string, Clauses> data = new Dictionary<string, Clauses>(); int seq; class Clause { public string Sql { get; set; } public object Parameters { get; set; } } class Clauses : List<Clause> { string joiner; string prefix; string postfix; public Clauses(string joiner, string prefix = "", string postfix = "") { this.joiner = joiner; this.prefix = prefix; this.postfix = postfix; } public string ResolveClauses(DynamicParameters p) { foreach (var item in this) { p.AddDynamicParams(item.Parameters); } return prefix + string.Join(joiner, this.Select(c => c.Sql)) + postfix; } } /// <summary> /// Template helper class for SqlBuilder /// </summary> public class Template { readonly string sql; readonly SqlBuilder builder; readonly object initParams; int dataSeq = -1; // Unresolved /// <summary> /// Template constructor /// </summary> /// <param name="builder"></param> /// <param name="sql"></param> /// <param name="parameters"></param> public Template(SqlBuilder builder, string sql, dynamic parameters) { this.initParams = parameters; this.sql = sql; this.builder = builder; } static readonly System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\/\*\*.+\*\*\/", System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Multiline); void ResolveSql() { if (dataSeq != builder.seq) { var p = new DynamicParameters(initParams); rawSql = sql; foreach (var pair in builder.data) { rawSql = rawSql.Replace("/**" + pair.Key + "**/", pair.Value.ResolveClauses(p)); } parameters = p; // replace all that is left with empty rawSql = regex.Replace(rawSql, ""); dataSeq = builder.seq; } } string rawSql; object parameters; /// <summary> /// Raw Sql returns by the <see cref="SqlBuilder"/> /// </summary> public string RawSql { get { ResolveSql(); return rawSql; } } /// <summary> /// Parameters being used /// </summary> public object Parameters { get { ResolveSql(); return parameters; } } } /// <summary> /// Add a template to the SqlBuilder /// </summary> /// <param name="sql"></param> /// <param name="parameters"></param> /// <returns></returns> public Template AddTemplate(string sql, dynamic parameters = null) { return new Template(this, sql, parameters); } void AddClause(string name, string sql, object parameters, string joiner, string prefix = "", string postfix = "") { Clauses clauses; if (!data.TryGetValue(name, out clauses)) { clauses = new Clauses(joiner, prefix, postfix); data[name] = clauses; } clauses.Add(new Clause { Sql = sql, Parameters = parameters }); seq++; } /// <summary> /// Add a Left Join /// </summary> /// <returns>itself</returns> public SqlBuilder LeftJoin(string sql, dynamic parameters = null) { AddClause("leftjoin", sql, parameters, joiner: "\nLEFT JOIN ", prefix: "\nLEFT JOIN ", postfix: "\n"); return this; } /// <summary> /// Add a Where Clause /// </summary> /// <returns>itself</returns> public SqlBuilder Where(string sql, dynamic parameters = null) { AddClause("where", sql, parameters, " AND ", prefix: "WHERE ", postfix: "\n"); return this; } /// <summary> /// Add an OrderBy Clause /// </summary> /// <returns>itself</returns> public SqlBuilder OrderBy(string sql, dynamic parameters = null) { AddClause("orderby", sql, parameters, " , ", prefix: "ORDER BY ", postfix: "\n"); return this; } /// <summary> /// Add the Select section /// </summary> /// <returns>itself</returns> public SqlBuilder Select(string sql, dynamic parameters = null) { AddClause("select", sql, parameters, " , ", prefix: "", postfix: "\n"); return this; } /// <summary> /// Add a parameters to the query /// </summary> /// <returns>itself</returns> public SqlBuilder AddParameters(dynamic parameters) { AddClause("--parameters", "", parameters, ""); return this; } /// <summary> /// Add a Join statement /// </summary> /// <returns>itself</returns> public SqlBuilder Join(string sql, dynamic parameters = null) { AddClause("join", sql, parameters, joiner: "\nJOIN ", prefix: "\nJOIN ", postfix: "\n"); return this; } /// <summary> /// Add a Group By section /// </summary> /// <returns>itself</returns> public SqlBuilder GroupBy(string sql, dynamic parameters = null) { AddClause("groupby", sql, parameters, joiner: " , ", prefix: "\nGROUP BY ", postfix: "\n"); return this; } /// <summary> /// Add a Having section /// </summary> /// <returns>itself</returns> public SqlBuilder Having(string sql, dynamic parameters = null) { AddClause("having", sql, parameters, joiner: "\nAND ", prefix: "HAVING ", postfix: "\n"); return this; } } }
31.770335
186
0.490512
[ "MIT" ]
Diaver/eflogger
EFlogger.Profiling/Helpers/SqlBuilder.cs
6,642
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vowels_Sum { class Program { static void Main(string[] args) { var word = Console.ReadLine(); var sum = 0; for (int i = 0; i < word.Length; i++) { switch (word[i]) { case 'a': sum += 1; break; case 'e': sum += 2; break; case 'i': sum += 3; break; case 'o': sum += 4; break; case 'u': sum += 5; break; } Console.WriteLine(sum); } } } }
20.25
49
0.410151
[ "MIT" ]
StefanDimitrov97/SoftUni-Basic
Cycles/Vowels Sum/Vowels Sum/Vowels Sum.cs
731
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sns-2010-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SimpleNotificationService.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.SimpleNotificationService.Model.Internal.MarshallTransformations { /// <summary> /// SetSubscriptionAttributes Request Marshaller /// </summary> public class SetSubscriptionAttributesRequestMarshaller : IMarshaller<IRequest, SetSubscriptionAttributesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((SetSubscriptionAttributesRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(SetSubscriptionAttributesRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.SimpleNotificationService"); request.Parameters.Add("Action", "SetSubscriptionAttributes"); request.Parameters.Add("Version", "2010-03-31"); if(publicRequest != null) { if(publicRequest.IsSetAttributeName()) { request.Parameters.Add("AttributeName", StringUtils.FromString(publicRequest.AttributeName)); } if(publicRequest.IsSetAttributeValue()) { request.Parameters.Add("AttributeValue", StringUtils.FromString(publicRequest.AttributeValue)); } if(publicRequest.IsSetSubscriptionArn()) { request.Parameters.Add("SubscriptionArn", StringUtils.FromString(publicRequest.SubscriptionArn)); } } return request; } private static SetSubscriptionAttributesRequestMarshaller _instance = new SetSubscriptionAttributesRequestMarshaller(); internal static SetSubscriptionAttributesRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static SetSubscriptionAttributesRequestMarshaller Instance { get { return _instance; } } } }
36.926316
165
0.642816
[ "Apache-2.0" ]
AltairMartinez/aws-sdk-unity-net
src/Services/SimpleNotificationService/Generated/Model/Internal/MarshallTransformations/SetSubscriptionAttributesRequestMarshaller.cs
3,508
C#
#if XNA using Microsoft.Xna.Framework; #endif using System; using System.Runtime.Serialization; namespace SadConsole.Controls { /// <summary> /// Represents a scrollbar control. /// </summary> [DataContract] public class ScrollBar : ControlBase { public event EventHandler ValueChanged; private bool _initialized; protected int _topOrLeftCharacter; protected int _bottomOrRightCharacter; protected int _sliderCharacter; protected int _sliderBarCharacter; [DataMember(Name = "Minimum")] protected int _minValue = 0; protected int _maxValue = 1; protected int _value = 0; protected int _valueStep = 1; protected int[] _sliderPositionValues; public Orientation Orientation { get; private set; } public int SliderBarSize { get; private set; } public int CurrentSliderPosition { get; private set; } /// <summary> /// Gets or sets the value of the scrollbar between the minimum and maximum values. /// </summary> [DataMember] public int Value { get => _value; set { if (_value != value) { _value = value; if (_value < 0) _value = 0; else if (_value > _maxValue) _value = _maxValue; if (_value == 0) CurrentSliderPosition = 0; else if (_value == _maxValue) CurrentSliderPosition = SliderBarSize - 1; else { // Find which slot is < value where the slot after is > value for (int i = 1; i < SliderBarSize - 1; i++) { if (_sliderPositionValues[i] == _value) { CurrentSliderPosition = i; break; } if (_sliderPositionValues[i] > _value && _sliderPositionValues[i - 1] < _value && _sliderPositionValues[i] != -1) { CurrentSliderPosition = i; break; } } } IsDirty = true; ValueChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Gets or sets the maximum value for the scrollbar. /// </summary> public int Maximum { get => _maxValue; set { _maxValue = value; if (_maxValue <= 0) _maxValue = 1; DetermineSliderPositions(); IsDirty = true; } } public int Minimum => 0; /// <summary> /// Gets or sets the amount of values to add or substract to the <see cref="Value"/> when the up or down arrows are used. /// </summary> [DataMember] public int Step { get => _valueStep; set => _valueStep = value; } /// <summary> /// Creates a new ScrollBar control. /// </summary> /// <param name="orientation">Sets the control to either horizontal or vertical.</param> /// <param name="size">The height or width of the control.</param> /// <returns>The new control instance.</returns> public ScrollBar(Orientation orientation, int size): base(orientation == Orientation.Horizontal ? size : 1, orientation == Orientation.Vertical ? size : 1) { if (size <= 2) throw new Exception("The scroll bar must be 4 or more in size."); _initialized = true; Orientation = orientation; _sliderCharacter = 219; if (orientation == Orientation.Horizontal) { _sliderBarCharacter = 176; _topOrLeftCharacter = 17; _bottomOrRightCharacter = 16; } else { _sliderBarCharacter = 176; _topOrLeftCharacter = 30; _bottomOrRightCharacter = 31; } if (Width > Height) SliderBarSize = Width - 2; else SliderBarSize = Height - 2; _sliderPositionValues = new int[SliderBarSize]; DetermineSliderPositions(); } // Locking the mouse to this control is actually locking the parent console to the engine, and then // letting the controls console know that this control wants exclusive focus until mouse is unclicked. public override bool ProcessMouse(Input.MouseConsoleState state) { if (IsEnabled) { base.ProcessMouse(state); var mouseControlPosition = new Point(state.CellPosition.X - this.Position.X, state.CellPosition.Y - this.Position.Y); // This becomes the active mouse subject when the bar is being dragged. if (Parent.CapturedControl == null) { if (state.CellPosition.X >= this.Position.X && state.CellPosition.X < this.Position.X + Width && state.CellPosition.Y >= this.Position.Y && state.CellPosition.Y < this.Position.Y + Height) { if (state.Mouse.ScrollWheelValueChange != 0) { Value += state.Mouse.ScrollWheelValueChange / 20; return true; } if (state.Mouse.LeftClicked) { if (Orientation == Orientation.Horizontal) { if (mouseControlPosition.X == 0) Value -= Step; if (mouseControlPosition.X == Width - 1) Value += Step; } else { if (mouseControlPosition.Y == 0) Value -= Step; if (mouseControlPosition.Y == Height - 1) Value += Step; } Parent.FocusedControl = this; } // Need to set a flag signalling that we've locked in a drag. // When the mouse button is let go, clear the flag. if (state.Mouse.LeftButtonDown) { if (Orientation == Orientation.Horizontal) { if (mouseControlPosition.Y == 0) if (mouseControlPosition.X == CurrentSliderPosition + 1) { Parent.CaptureControl(this); } } else { if (mouseControlPosition.X == 0) if (mouseControlPosition.Y == CurrentSliderPosition + 1) { Parent.CaptureControl(this); } } Parent.FocusedControl = this; } return true; } } else if (Parent.CapturedControl == this) { if (!state.Mouse.LeftButtonDown) { Parent.ReleaseControl(); return false; } if (state.CellPosition.X >= this.Position.X - 2 && state.CellPosition.X < this.Position.X + Width + 2 && state.CellPosition.Y >= this.Position.Y - 3 && state.CellPosition.Y < this.Position.Y + Height + 3) { if (Orientation == Orientation.Horizontal) { //if (mouseControlPosition.Y == 0) //{ // if (mouseControlPosition.X == _currentSliderPosition + 1) // Value -= Step; //} if (mouseControlPosition.X >= 1 && mouseControlPosition.X <= SliderBarSize) { CurrentSliderPosition = mouseControlPosition.X - 1; if (_sliderPositionValues[CurrentSliderPosition] != -1) { _value = _sliderPositionValues[CurrentSliderPosition]; if (ValueChanged != null) ValueChanged.Invoke(this, EventArgs.Empty); this.IsDirty = true; } } } else { if (mouseControlPosition.Y >= 1 && mouseControlPosition.Y <= SliderBarSize) { CurrentSliderPosition = mouseControlPosition.Y - 1; if (_sliderPositionValues[CurrentSliderPosition] != -1) { _value = _sliderPositionValues[CurrentSliderPosition]; if (ValueChanged != null) ValueChanged.Invoke(this, EventArgs.Empty); this.IsDirty = true; } } } return true; } } //else if(Parent.CapturedControl == this && !info.LeftButtonDown) //{ // Parent.ReleaseControl(); //} } return false; } /// <summary> /// Not Used. /// </summary> /// <param name="state"></param> public override bool ProcessKeyboard(Input.Keyboard state) { return false; } private void DetermineSliderPositions() { _sliderPositionValues[0] = 0; _sliderPositionValues[SliderBarSize - 1] = _maxValue; // Clear other spots for (int i = 1; i < SliderBarSize - 1; i++) { _sliderPositionValues[i] = -1; } int rest = SliderBarSize - 2; if (_maxValue == 1) { // Do nothing. } // Throw other item in middle else if (_maxValue == 2) { if (rest == 1) _sliderPositionValues[1] = _maxValue - 1; else if (rest % 2 != 0) _sliderPositionValues[((rest - 1) / 2) + 1] = _maxValue - 1; else _sliderPositionValues[rest / 2] = _maxValue - 1; } else if (rest >= _maxValue - 1) { for (int i = 1; i < _maxValue; i++) { _sliderPositionValues[i] = i; } } else { float itemValue = (float)(_maxValue - 1) / rest; for (int i = 1; i < SliderBarSize - 1; i++) { _sliderPositionValues[i] = (int)((float)i * itemValue); } } } [OnDeserialized] private void AfterDeserialized(StreamingContext context) { _initialized = true; var temp = _value; _value = -22; Value = temp; IsDirty = true; DetermineState(); } } }
35.201657
141
0.409401
[ "MIT" ]
LtLi0n/SadConsole
src/SadConsole/Controls/ScrollBar.cs
12,745
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace ClusterAnalysis.Common.Config { using System; // TODO: I may refactor this a bit in future. [Flags] public enum RunMode { /// <summary> /// It's a once box cluster /// </summary> OneBoxCluster = 1, /// <summary> /// It's a multi node environment. /// </summary> MultiNodeCluster = 2, /// <summary> /// We are supposed to use Azure Event Store /// </summary> AzureEventStore = 4, /// <summary> /// We are supposed to use Local Event Store /// </summary> LocalEventStore = 8 } }
27.558824
98
0.481323
[ "MIT" ]
AndreyTretyak/service-fabric
src/prod/src/managed/ClusterAnalysis/Common/Config/RunMode.cs
939
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Core; namespace Azure.ResourceManager.Compute { /// <summary> A class representing collection of CloudServiceRole and their operations over its parent. </summary> public partial class CloudServiceRoleCollection : ArmCollection, IEnumerable<CloudServiceRole>, IAsyncEnumerable<CloudServiceRole> { private readonly ClientDiagnostics _cloudServiceRoleClientDiagnostics; private readonly CloudServiceRolesRestOperations _cloudServiceRoleRestClient; /// <summary> Initializes a new instance of the <see cref="CloudServiceRoleCollection"/> class for mocking. </summary> protected CloudServiceRoleCollection() { } /// <summary> Initializes a new instance of the <see cref="CloudServiceRoleCollection"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the parent resource that is the target of operations. </param> internal CloudServiceRoleCollection(ArmClient client, ResourceIdentifier id) : base(client, id) { _cloudServiceRoleClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Compute", CloudServiceRole.ResourceType.Namespace, DiagnosticOptions); Client.TryGetApiVersion(CloudServiceRole.ResourceType, out string cloudServiceRoleApiVersion); _cloudServiceRoleRestClient = new CloudServiceRolesRestOperations(_cloudServiceRoleClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, cloudServiceRoleApiVersion); #if DEBUG ValidateResourceId(Id); #endif } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != CloudService.ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, CloudService.ResourceType), nameof(id)); } /// <summary> Gets a role from a cloud service. </summary> /// <param name="roleName"> Name of the role. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="roleName"/> is empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="roleName"/> is null. </exception> public async virtual Task<Response<CloudServiceRole>> GetAsync(string roleName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(roleName, nameof(roleName)); using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.Get"); scope.Start(); try { var response = await _cloudServiceRoleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, roleName, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _cloudServiceRoleClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new CloudServiceRole(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets a role from a cloud service. </summary> /// <param name="roleName"> Name of the role. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="roleName"/> is empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="roleName"/> is null. </exception> public virtual Response<CloudServiceRole> Get(string roleName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(roleName, nameof(roleName)); using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.Get"); scope.Start(); try { var response = _cloudServiceRoleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, roleName, cancellationToken); if (response.Value == null) throw _cloudServiceRoleClientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new CloudServiceRole(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets a list of all roles in a cloud service. Use nextLink property in the response to get the next page of roles. Do this till nextLink is null to fetch all the roles. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="CloudServiceRole" /> that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<CloudServiceRole> GetAllAsync(CancellationToken cancellationToken = default) { async Task<Page<CloudServiceRole>> FirstPageFunc(int? pageSizeHint) { using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.GetAll"); scope.Start(); try { var response = await _cloudServiceRoleRestClient.ListAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new CloudServiceRole(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<CloudServiceRole>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.GetAll"); scope.Start(); try { var response = await _cloudServiceRoleRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new CloudServiceRole(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Gets a list of all roles in a cloud service. Use nextLink property in the response to get the next page of roles. Do this till nextLink is null to fetch all the roles. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="CloudServiceRole" /> that may take multiple service requests to iterate over. </returns> public virtual Pageable<CloudServiceRole> GetAll(CancellationToken cancellationToken = default) { Page<CloudServiceRole> FirstPageFunc(int? pageSizeHint) { using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.GetAll"); scope.Start(); try { var response = _cloudServiceRoleRestClient.List(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new CloudServiceRole(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<CloudServiceRole> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.GetAll"); scope.Start(); try { var response = _cloudServiceRoleRestClient.ListNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new CloudServiceRole(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Checks to see if the resource exists in azure. </summary> /// <param name="roleName"> Name of the role. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="roleName"/> is empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="roleName"/> is null. </exception> public async virtual Task<Response<bool>> ExistsAsync(string roleName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(roleName, nameof(roleName)); using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.Exists"); scope.Start(); try { var response = await GetIfExistsAsync(roleName, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Checks to see if the resource exists in azure. </summary> /// <param name="roleName"> Name of the role. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="roleName"/> is empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="roleName"/> is null. </exception> public virtual Response<bool> Exists(string roleName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(roleName, nameof(roleName)); using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.Exists"); scope.Start(); try { var response = GetIfExists(roleName, cancellationToken: cancellationToken); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="roleName"> Name of the role. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="roleName"/> is empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="roleName"/> is null. </exception> public async virtual Task<Response<CloudServiceRole>> GetIfExistsAsync(string roleName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(roleName, nameof(roleName)); using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.GetIfExists"); scope.Start(); try { var response = await _cloudServiceRoleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, roleName, cancellationToken: cancellationToken).ConfigureAwait(false); if (response.Value == null) return Response.FromValue<CloudServiceRole>(null, response.GetRawResponse()); return Response.FromValue(new CloudServiceRole(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="roleName"> Name of the role. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="roleName"/> is empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="roleName"/> is null. </exception> public virtual Response<CloudServiceRole> GetIfExists(string roleName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(roleName, nameof(roleName)); using var scope = _cloudServiceRoleClientDiagnostics.CreateScope("CloudServiceRoleCollection.GetIfExists"); scope.Start(); try { var response = _cloudServiceRoleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, roleName, cancellationToken: cancellationToken); if (response.Value == null) return Response.FromValue<CloudServiceRole>(null, response.GetRawResponse()); return Response.FromValue(new CloudServiceRole(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } IEnumerator<CloudServiceRole> IEnumerable<CloudServiceRole>.GetEnumerator() { return GetAll().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetAll().GetEnumerator(); } IAsyncEnumerator<CloudServiceRole> IAsyncEnumerable<CloudServiceRole>.GetAsyncEnumerator(CancellationToken cancellationToken) { return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); } } }
52.680412
207
0.640248
[ "MIT" ]
danielortega-msft/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/CloudServiceRoleCollection.cs
15,330
C#
using System; namespace ZZXUnit.Tests.Entities.SpiderOdds { [Serializable] public enum ThirdPartyEnum { None = 0, CmdBet = 1, MaxBet = 2, SboBet = 3, } }
12.176471
43
0.541063
[ "MIT" ]
az0day/BaseUnits
ZZXUnit.Tests/Entities/SpiderOdds/ThirdPartyEnum.cs
209
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Utilities { internal struct StringSlice : IEquatable<StringSlice> { private readonly string _underlyingString; private readonly TextSpan _span; public StringSlice(string underlyingString, TextSpan span) { _underlyingString = underlyingString; _span = span; Debug.Assert(span.Start >= 0); Debug.Assert(span.End <= underlyingString.Length); } public StringSlice(string value) : this(value, new TextSpan(0, value.Length)) { } public int Length => _span.Length; public char this[int index] => _underlyingString[_span.Start + index]; public Enumerator GetEnumerator() { return new Enumerator(this); } public override bool Equals(object obj) => Equals((StringSlice)obj); public bool Equals(StringSlice other) => EqualsOrdinal(other); internal bool EqualsOrdinal(StringSlice other) { if (this._span.Length != other._span.Length) { return false; } var end = this._span.End; for (int i = this._span.Start, j = other._span.Start; i < end; i++, j++) { if (this._underlyingString[i] != other._underlyingString[j]) { return false; } } return true; } internal bool EqualsOrdinalIgnoreCase(StringSlice other) { if (this._span.Length != other._span.Length) { return false; } var end = this._span.End; for (int i = this._span.Start, j = other._span.Start; i < end; i++, j++) { var thisChar = this._underlyingString[i]; var otherChar = other._underlyingString[j]; if (!EqualsOrdinalIgnoreCase(thisChar, otherChar)) { return false; } } return true; } private static bool EqualsOrdinalIgnoreCase(char thisChar, char otherChar) { // Do a fast check first before converting to lowercase characters. return thisChar == otherChar || CaseInsensitiveComparison.ToLower(thisChar) == CaseInsensitiveComparison.ToLower(otherChar); } public override int GetHashCode() => GetHashCodeOrdinal(); internal int GetHashCodeOrdinal() { return Hash.GetFNVHashCode(this._underlyingString, this._span.Start, this._span.Length); } internal int GetHashCodeOrdinalIgnoreCase() { return Hash.GetCaseInsensitiveFNVHashCode(this._underlyingString, this._span.Start, this._span.Length); } internal int CompareToOrdinal(StringSlice other) { var thisEnd = this._span.End; var otherEnd = other._span.End; for (int i = this._span.Start, j = other._span.Start; i < thisEnd && j < otherEnd; i++, j++) { var diff = this._underlyingString[i] - other._underlyingString[j]; if (diff != 0) { return diff; } } // Choose the one that is shorter if their prefixes match so far. return this.Length - other.Length; } internal int CompareToOrdinalIgnoreCase(StringSlice other) { var thisEnd = this._span.End; var otherEnd = other._span.End; for (int i = this._span.Start, j = other._span.Start; i < thisEnd && j < otherEnd; i++, j++) { var diff = CaseInsensitiveComparison.ToLower(this._underlyingString[i]) - CaseInsensitiveComparison.ToLower(other._underlyingString[j]); if (diff != 0) { return diff; } } // Choose the one that is shorter if their prefixes match so far. return this.Length - other.Length; } public struct Enumerator { private readonly StringSlice _stringSlice; private int index; public Enumerator(StringSlice stringSlice) { _stringSlice = stringSlice; index = -1; } public bool MoveNext() { index++; return index < _stringSlice.Length; } public char Current => _stringSlice[index]; } } internal abstract class StringSliceComparer : IComparer<StringSlice>, IEqualityComparer<StringSlice> { public static readonly StringSliceComparer Ordinal = new OrdinalComparer(); public static readonly StringSliceComparer OrdinalIgnoreCase = new OrdinalIgnoreCaseComparer(); private class OrdinalComparer : StringSliceComparer { public override int Compare(StringSlice x, StringSlice y) => x.CompareToOrdinal(y); public override bool Equals(StringSlice x, StringSlice y) => x.EqualsOrdinal(y); public override int GetHashCode(StringSlice obj) => obj.GetHashCodeOrdinal(); } private class OrdinalIgnoreCaseComparer : StringSliceComparer { public override int Compare(StringSlice x, StringSlice y) => x.CompareToOrdinalIgnoreCase(y); public override bool Equals(StringSlice x, StringSlice y) => x.EqualsOrdinalIgnoreCase(y); public override int GetHashCode(StringSlice obj) => obj.GetHashCodeOrdinalIgnoreCase(); } public abstract int Compare(StringSlice x, StringSlice y); public abstract bool Equals(StringSlice x, StringSlice y); public abstract int GetHashCode(StringSlice obj); } }
32.685279
161
0.560801
[ "Apache-2.0" ]
CyrusNajmabadi/PatternMatching
PatternMatcher/StringSlice.cs
6,441
C#
using System; namespace OpenVIII.Fields.Scripts.Instructions { /// <summary> /// Push animation on stack? /// </summary> /// <see cref="http://wiki.ffrtt.ru/index.php?title=FF8/Field/Script/Opcodes/14A_PUSHANIME&action=edit&redlink=1"/> public sealed class PUSHANIME : JsmInstruction { public PUSHANIME() { } public PUSHANIME(Int32 parameter, IStack<IJsmExpression> stack) : this() { } public override String ToString() { return $"{nameof(PUSHANIME)}()"; } } }
22.653846
119
0.570458
[ "MIT" ]
MattLisson/OpenVIII
Core/Field/JSM/Instructions/PUSHANIME.cs
591
C#
using UnityEngine; using System.Reflection; using System.Collections; using System.Collections.Generic; namespace wxb { class ArrayAnyType : IListAnyType { public ArrayAnyType(System.Type arrayType) : base(arrayType, arrayType.GetElementType()) { } protected override IList Create(int lenght) { return System.Array.CreateInstance(elementType, lenght); } } class ListAnyType : IListAnyType { ConstructorInfo ctor_info; object elementDefaultValue = null; static System.Type[] ctor_type_param= new System.Type[1] { typeof(int) }; static object[] ctor_param = new object[1] { 0 }; public ListAnyType(System.Type listType) : base(listType, IL.Help.GetElementByList(listType)) { Init(); } public ListAnyType(FieldInfo fieldInfo) : base(fieldInfo.FieldType, IL.Help.GetElementByList(fieldInfo)) { Init(); } void Init() { try { ctor_info = arrayType.GetConstructor(ctor_type_param); if (!elementType.IsClass) elementDefaultValue = elementType.Assembly.CreateInstance(elementType.FullName); } catch (System.Exception ex) { wxb.L.LogException(ex); } } protected override IList Create(int lenght) { ctor_param[0] = lenght; try { IList list = ctor_info.Invoke(ctor_param) as IList; for (int i = 0; i < lenght; ++i) list.Add(elementDefaultValue); return list; } catch (System.Exception ex) { wxb.L.LogException(ex); return null; } } } }
27.042857
112
0.537242
[ "MIT" ]
BlueMonk1107/XILTestProject
Assets/XIL/Scripts/Serialize/ArrayAnyType.cs
1,895
C#
using DapperCSharp.Domain.Entities; using DapperCSharp.Domain.ValueObjects; using Dapper; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; using System; namespace DapperCSharp.Infra.Data.Queries { public class CategoryQuery { private readonly SqlConnection _connection; public CategoryQuery() { _connection = new SqlConnection(); _connection.ConnectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DapperCSharpDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; _connection.Open(); } public int Count() { return _connection.ExecuteScalar<int>("SELECT count(*) FROM Category;"); } public List<Category> GetAll() { return _connection.Query<Category>("SELECT Id, Description FROM Category;") .ToList(); } public Category GetById(Guid id) { var parameters = new { id }; return _connection .Query<Category>("SELECT Id, Description FROM Category WHERE Id = @id;", parameters) .First(); } } }
31.952381
253
0.610283
[ "MIT" ]
tiagopariz/DapperCSharp
src/DapperCSharp.Data.Infra/Queries/CategoryQuery.cs
1,342
C#
#define PSR_FULL #if DEMO #undef PSR_FULL #endif using UnityEngine; using UnityEditor; using System.IO; namespace sr { [System.Serializable] public class ReplaceItemQuaternion : ReplaceItem<DynamicTypeQuaternion, Vector4Serializable> { public OptionalFloatField xField; public OptionalFloatField yField; public OptionalFloatField zField; public OptionalFloatField wField; public override void Draw() { #if PSR_FULL GUILayout.BeginHorizontal(); drawHeader(); SRWindow.Instance.CVS(); if(!SRWindow.Instance.Compact()) { GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); } xField.Draw(showMoreOptions); yField.Draw(showMoreOptions); if(!SRWindow.Instance.Compact()) { GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); } zField.Draw(showMoreOptions); wField.Draw(showMoreOptions); if(!SRWindow.Instance.Compact()) { GUILayout.EndHorizontal(); GUILayout.EndVertical(); } SRWindow.Instance.CVE(); if(xField.updated || yField.updated || zField.updated || wField.updated) { Vector4 updatedValue = new Vector4(xField.fieldValue, yField.fieldValue, zField.fieldValue, wField.fieldValue); replaceValue = Vector4Serializable.FromVector4(updatedValue); SRWindow.Instance.PersistCurrentSearch(); } drawSwap(); GUILayout.EndHorizontal(); #endif } public override void OnDeserialization() { #if PSR_FULL if(xField == null) { xField = new OptionalFloatField("X", replaceValue.x); } if(yField == null ) { yField = new OptionalFloatField("Y", replaceValue.y); } if(zField == null ) { zField = new OptionalFloatField("Z", replaceValue.z); } if(wField == null ) { wField = new OptionalFloatField("W", replaceValue.w); } #endif } protected override void Swap() { xField.Swap(parent.xField); yField.Swap(parent.yField); zField.Swap(parent.zField); wField.Swap(parent.wField); base.Swap(); } protected override void replace(SearchJob job, SerializedProperty prop, SearchResult result) { #if PSR_FULL Quaternion q2 = prop.quaternionValue; q2.x = xField.Replace(q2.x); q2.y = yField.Replace(q2.y); q2.z = zField.Replace(q2.z); q2.w = wField.Replace(q2.w); prop.quaternionValue = q2; result.replaceStrRep = q2.ToString(); #endif } } }
23.527273
119
0.631762
[ "MIT" ]
zaguarman/StarFox-RailMovement
Assets/Editor/searchreplace/ReplaceItemQuaternion.cs
2,588
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Control_Aleatorio_Covid_19_Mendoza_Fabian { public partial class Formulario : Form { public Formulario() { InitializeComponent(); } private void Formulario_Load(object sender, EventArgs e) { btnEnviar.Enabled = false; } void Enviar_Datos() { Form1 frmForm1 = new Form1(); frmForm1.txtRecibirCantSintoma.Text = txtEnviarSintoma.Text; frmForm1.txtRecibirCantSalida.Text = txtEnviarSalida.Text; frmForm1.txtRecibirCantDirectos.Text = txtEnviarDirecto.Text; this.Hide(); frmForm1.Show(); } private void CheckBox1_CheckedChanged(object sender, EventArgs e) { if (chkDeclaracion.Checked == true) { btnEnviar.Enabled = true; } } private void BtnEnviar_Click(object sender, EventArgs e) { btnEnviar.Enabled = false; Inicio datos = new Inicio(); int acumulador = 0; int contador = 0; if (cmbDolor.Text=="SI") { contador ++; } if (cmbAgotamiento.Text == "SI") { contador ++; } if (cmbTos.Text == "SI") { contador ++; } if (cmbFiebre.Text == "SI" || contador > 1) { acumulador = Convert.ToInt32(txtEnviarSintoma.Text); acumulador = acumulador + 1; txtEnviarSintoma.Text = acumulador.ToString(); Enviar_Datos(); datos.Solicitar_hisopado(); } else { acumulador = Convert.ToInt32(txtEnviarSalida.Text); acumulador = acumulador + 1; txtEnviarSalida.Text = acumulador.ToString(); Enviar_Datos(); datos.Mostrar_salida(); } } } }
25.931818
73
0.513585
[ "Apache-2.0" ]
FabianEzequielMendoza/TrabajosAcademicos
winforms-c#/Control_Aleatorio_Covid_19_Mendoza_Fabian/Control_Aleatorio_Covid_19_Mendoza_Fabian/Formulario.cs
2,284
C#
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace Ams.Utils.NPOI.SS.Formula.Udf { using System; using Ams.Utils.NPOI.SS.Formula.Atp; using Ams.Utils.NPOI.SS.Formula.Functions; /** * Common interface for "Add-in" libraries and user defined function libraries. * * @author PUdalau */ public abstract class UDFFinder { public static UDFFinder DEFAULT = new AggregatingUDFFinder(AnalysisToolPak.instance); /** * Returns executor by specified name. Returns <code>null</code> if the function name is unknown. * * @param name Name of function. * @return Function executor. */ public abstract FreeRefFunction FindFunction(String name); } }
39.214286
105
0.646023
[ "MIT" ]
SkyGrass/hippos_api_vm
Ams.Utils/Document/Excel/NPOI/SS/Formula/Udf/UDFFinder.cs
1,647
C#
using System; using System.Collections.Generic; using ToyStore.Models.DBModels; namespace ToyStore.Models.ControllerModels { #nullable enable public class OrderModel { public List<Guid>? addedStacks { get; set; } public Token? token { get; set; } // public override string ToString() // { // string s = "OrderModel:\n"; // s += "UpdateStack: " + UpdateStack.SellableStackId + " " + UpdateStack.location.LocationName + " --> " + UpdateStack.Item.SellableName; // s += "UpdateCount: " + UpdateCount; // s += "newOrder: " + newOrder; // s += "removedStacks: " + removedStacks; // s += "addedStacks: " + addedStacks; // s += "countChangedStacks: " + countChangedStacks; // s += "token: " + token.TokenValue; // return "UpdateStack: "; // } } }
34.653846
150
0.556049
[ "MIT" ]
03012021-dotnet-uta/NoureldinKamel_P1
ToyStore.Models/ControllerModels/OrderModel.cs
901
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("Fishland")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Fishland")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("6111bd94-ca9a-4386-b70b-58ed07f7102a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.540541
84
0.743701
[ "MIT" ]
SimeonShterev/2016.12.10-2017.03.23-ProgramingBasics
2017.03.15 - exam prep (2016.Nov.20)/Fishland/Properties/AssemblyInfo.cs
1,392
C#
using System; using System.Threading.Tasks; using Uintra.Features.LinkPreview.Models; namespace Uintra.Features.LinkPreview.Services { public interface IActivityLinkPreviewService { LinkPreviewModel GetActivityLinkPreview(Guid activityId); void RemovePreviewRelations(Guid activityId); void AddLinkPreview(Guid activityId, int previewId); void UpdateLinkPreview(Guid activityId, int previewId); Task<LinkPreviewModel> GetActivityLinkPreviewAsync(Guid activityId); Task RemovePreviewRelationsAsync(Guid activityId); Task AddLinkPreviewAsync(Guid activityId, int previewId); Task UpdateLinkPreviewAsync(Guid activityId, int previewId); } }
37.526316
76
0.765778
[ "MIT" ]
Uintra/Uintra
src/Uintra/Features/LinkPreview/Services/IActivityLinkPreviewService.cs
715
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Orderkeeper.Core; using OrderKeeper.Infrastructure; namespace Orderkeeper.WebUI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddOrderkeeperCore(); services.AddInfrastructure(Configuration); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Orderkeeper API", Version = "v1" }); }); services.AddControllersWithViews(); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); if (!env.IsDevelopment()) { app.UseSpaStaticFiles(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Orderkeeper V1"); }); app.UseAuthentication(); app.UseRouting(); app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); } } }
31.684783
106
0.55506
[ "MIT" ]
pkritiotis/orderkeeper-clean
Orderkeeper.WebUI/Startup.cs
2,915
C#
using Retina.Configuration; using System.Collections.Generic; using System.IO; using System.Linq; namespace Retina.Stages { class ListStage : AtomicStage { public ListStage(Config config, History history, bool registerByDefault, List<string> patterns, List<string> substitutions, string separatorSubstitutionSource) : base(config, history, registerByDefault, patterns, substitutions, separatorSubstitutionSource) { } protected override string Process(string input, TextWriter output) { var values = Matches.Select(m => new string( m.Replacement.Where((_, i) => Config.GetLimit(1).IsInRange(i, m.Replacement.Length)).ToArray() )); if (Config.Reverse) values = values.Reverse(); return Config.FormatAsList(values); } } }
33.538462
167
0.650229
[ "MIT" ]
m-ender/retina
Retina/Retina/Stages/AtomicStages/ListStage.cs
874
C#
using System; using System.Collections.Generic; using AMQ.Wrapper; using Apache.NMS; namespace Example1 { class Program { static void Main(string[] args) { var queueHandler = new DefaultQueueHandler("activemq:tcp://localhost:61616", "amq.test1", new List<IMessageHandler>() { new SampleMessageHandler() }); queueHandler.QueueHandlingErrorListener = QueueHandlingErrorListener; queueHandler.StartSession(); Console.ReadKey(); queueHandler.Dispose(); } private static void QueueHandlingErrorListener(Exception exception, IMessage message, bool handled, bool acknowledged) { Console.WriteLine("ERROR | error occurred while processing message '{0}' Error: {1}", message.NMSCorrelationID, exception.Message); } } }
28.833333
143
0.650867
[ "Apache-2.0" ]
mvcguy/AMQ.Wrapper
Example1/Program.cs
867
C#
#region Copyright // // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion #region Usings using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using DotNetNuke.Common; using DotNetNuke.Common.Internal; using DotNetNuke.Common.Lists; using DotNetNuke.Common.Utilities; using DotNetNuke.ComponentModel; using DotNetNuke.Data; using DotNetNuke.Entities.Content.Workflow; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals.Internal; using DotNetNuke.Entities.Profile; using DotNetNuke.Entities.Urls; using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users; using DotNetNuke.Entities.Users.Social; using DotNetNuke.Framework; using DotNetNuke.Instrumentation; using DotNetNuke.Security.Membership; using DotNetNuke.Security.Permissions; using DotNetNuke.Security.Roles; using DotNetNuke.Services.Cache; using DotNetNuke.Services.Cryptography; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.FileSystem; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Log.EventLog; //using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; using DotNetNuke.Services.Search.Entities; using DotNetNuke.Web.Client; using ICSharpCode.SharpZipLib.Zip; using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; using IAbPortalSettings = DotNetNuke.Abstractions.Portals.IPortalSettings; #endregion namespace DotNetNuke.Entities.Portals { /// <summary> /// PoralController provides business layer of poatal. /// </summary> /// <remarks> /// DotNetNuke supports the concept of virtualised sites in a single install. This means that multiple sites, /// each potentially with multiple unique URL's, can exist in one instance of DotNetNuke i.e. one set of files and one database. /// </remarks> public partial class PortalController : ServiceLocator<IPortalController, PortalController>, IPortalController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (PortalController)); public const string HtmlText_TimeToAutoSave = "HtmlText_TimeToAutoSave"; public const string HtmlText_AutoSaveEnabled = "HtmlText_AutoSaveEnabled"; protected const string HttpContextKeyPortalSettingsDictionary = "PortalSettingsDictionary{0}{1}"; protected override Func<IPortalController> GetFactory() { return () => new PortalController(); } #region Private Methods private void AddFolderPermissions(int portalId, int folderId) { var portal = GetPortal(portalId); var folderManager = FolderManager.Instance; var folder = folderManager.GetFolder(folderId); var permissionController = new PermissionController(); foreach (PermissionInfo permission in permissionController.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "")) { var folderPermission = new FolderPermissionInfo(permission) { FolderID = folder.FolderID, RoleID = portal.AdministratorRoleId, AllowAccess = true }; folder.FolderPermissions.Add(folderPermission); if (permission.PermissionKey == "READ") { //add READ permissions to the All Users Role folderManager.AddAllUserReadPermission(folder, permission); } } FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); } private static void CreateDefaultPortalRoles(int portalId, int administratorId, ref int administratorRoleId, ref int registeredRoleId, ref int subscriberRoleId, int unverifiedRoleId) { //create required roles if not already created if (administratorRoleId == -1) { administratorRoleId = CreateRole(portalId, "Administrators", "Administrators of this Website", 0, 0, "M", 0, 0, "N", false, false); } if (registeredRoleId == -1) { registeredRoleId = CreateRole(portalId, "Registered Users", "Registered Users", 0, 0, "M", 0, 0, "N", false, true); } if (subscriberRoleId == -1) { subscriberRoleId = CreateRole(portalId, "Subscribers", "A public role for site subscriptions", 0, 0, "M", 0, 0, "N", true, true); } if (unverifiedRoleId == -1) { CreateRole(portalId, "Unverified Users", "Unverified Users", 0, 0, "M", 0, 0, "N", false, false); } RoleController.Instance.AddUserRole(portalId, administratorId, administratorRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); RoleController.Instance.AddUserRole(portalId, administratorId, registeredRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); RoleController.Instance.AddUserRole(portalId, administratorId, subscriberRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); } private void CreatePortalInternal(int portalId, string portalName, UserInfo adminUser, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal, ref string message) { // Add default workflows try { SystemWorkflowManager.Instance.CreateSystemWorkflows(portalId); } catch (Exception ex) { Exceptions.LogException(ex); } string templatePath, templateFile; PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); string mergedTemplatePath = Path.Combine(templatePath, templateFile); if (String.IsNullOrEmpty(homeDirectory)) { homeDirectory = "Portals/" + portalId; } string mappedHomeDirectory = String.Format(Globals.ApplicationMapPath + "\\" + homeDirectory + "\\").Replace("/", "\\"); if(Directory.Exists(mappedHomeDirectory)) { message += string.Format(Localization.GetString("CreatePortalHomeFolderExists.Error"), homeDirectory); throw new Exception(message); } message += CreateProfileDefinitions(portalId, mergedTemplatePath); if (String.IsNullOrEmpty(message)) { try { //the upload directory may already exist if this is a new DB working with a previously installed application if (Directory.Exists(mappedHomeDirectory)) { Globals.DeleteFolderRecursive(mappedHomeDirectory); } } catch (Exception Exc) { Logger.Error(Exc); message += Localization.GetString("DeleteUploadFolder.Error") + Exc.Message + Exc.StackTrace; } //Set up Child Portal if (message == Null.NullString) { if (isChildPortal) { message = CreateChildPortalFolder(childPath); } } else { throw new Exception(message); } if (message == Null.NullString) { try { //create the upload directory for the new portal Directory.CreateDirectory(mappedHomeDirectory); //ensure that the Templates folder exists string templateFolder = String.Format("{0}Templates", mappedHomeDirectory); if (!Directory.Exists(templateFolder)) { Directory.CreateDirectory(templateFolder); } //ensure that the Users folder exists string usersFolder = String.Format("{0}Users", mappedHomeDirectory); if (!Directory.Exists(usersFolder)) { Directory.CreateDirectory(usersFolder); } //copy the default page template CopyPageTemplate("Default.page.template", mappedHomeDirectory); // process zip resource file if present if (File.Exists(template.ResourceFilePath)) { ProcessResourceFileExplicit(mappedHomeDirectory, template.ResourceFilePath); } } catch (Exception Exc) { Logger.Error(Exc); message += Localization.GetString("ChildPortal.Error") + Exc.Message + Exc.StackTrace; } } else { throw new Exception(message); } if (message == Null.NullString) { try { FolderMappingController.Instance.AddDefaultFolderTypes(portalId); } catch (Exception Exc) { Logger.Error(Exc); message += Localization.GetString("DefaultFolderMappings.Error") + Exc.Message + Exc.StackTrace; } } else { throw new Exception(message); } LocaleCollection newPortalLocales = null; if (message == Null.NullString) { try { CreatePredefinedFolderTypes(portalId); ParseTemplateInternal(portalId, templatePath, templateFile, adminUser.UserID, PortalTemplateModuleAction.Replace, true, out newPortalLocales); } catch (Exception Exc) { Logger.Error(Exc); message += Localization.GetString("PortalTemplate.Error") + Exc.Message + Exc.StackTrace; } } else { throw new Exception(message); } if (message == Null.NullString) { var portal = GetPortal(portalId); portal.Description = description; portal.KeyWords = keyWords; portal.UserTabId = TabController.GetTabByTabPath(portal.PortalID, "//UserProfile", portal.CultureCode); if (portal.UserTabId == -1) { portal.UserTabId = TabController.GetTabByTabPath(portal.PortalID, "//ActivityFeed", portal.CultureCode); } portal.SearchTabId = TabController.GetTabByTabPath(portal.PortalID, "//SearchResults", portal.CultureCode); UpdatePortalInfo(portal); adminUser.Profile.PreferredLocale = portal.DefaultLanguage; var portalSettings = new PortalSettings(portal); adminUser.Profile.PreferredTimeZone = portalSettings.TimeZone; UserController.UpdateUser(portal.PortalID, adminUser); DesktopModuleController.AddDesktopModulesToPortal(portalId); AddPortalAlias(portalId, portalAlias); UpdatePortalSetting(portalId, "DefaultPortalAlias", portalAlias, false); DataCache.ClearPortalCache(portalId, true); if (newPortalLocales != null) { foreach (Locale newPortalLocale in newPortalLocales.AllValues) { Localization.AddLanguageToPortal(portalId, newPortalLocale.LanguageId, false); if (portalSettings.ContentLocalizationEnabled) { MapLocalizedSpecialPages(portalId, newPortalLocale.Code); } } } try { RelationshipController.Instance.CreateDefaultRelationshipsForPortal(portalId); } catch (Exception Exc) { Logger.Error(Exc); } //add profanity list to new portal try { const string listName = "ProfanityFilter"; var listController = new ListController(); var entry = new ListEntryInfo { PortalID = portalId, SystemList = false, ListName = listName + "-" + portalId }; listController.AddListEntry(entry); } catch (Exception Exc) { Logger.Error(Exc); } //add banned password list to new portal try { const string listName = "BannedPasswords"; var listController = new ListController(); var entry = new ListEntryInfo { PortalID = portalId, SystemList = false, ListName = listName + "-" + portalId }; listController.AddListEntry(entry); } catch (Exception Exc) { Logger.Error(Exc); } ServicesRoutingManager.ReRegisterServiceRoutesWhileSiteIsRunning(); try { var log = new LogInfo { BypassBuffering = true, LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.LogProperties.Add(new LogDetailInfo("Install Portal:", portalName)); log.LogProperties.Add(new LogDetailInfo("FirstName:", adminUser.FirstName)); log.LogProperties.Add(new LogDetailInfo("LastName:", adminUser.LastName)); log.LogProperties.Add(new LogDetailInfo("Username:", adminUser.Username)); log.LogProperties.Add(new LogDetailInfo("Email:", adminUser.Email)); log.LogProperties.Add(new LogDetailInfo("Description:", description)); log.LogProperties.Add(new LogDetailInfo("Keywords:", keyWords)); log.LogProperties.Add(new LogDetailInfo("Template:", template.TemplateFilePath)); log.LogProperties.Add(new LogDetailInfo("TemplateCulture:", template.CultureCode)); log.LogProperties.Add(new LogDetailInfo("HomeDirectory:", homeDirectory)); log.LogProperties.Add(new LogDetailInfo("PortalAlias:", portalAlias)); log.LogProperties.Add(new LogDetailInfo("ServerPath:", serverPath)); log.LogProperties.Add(new LogDetailInfo("ChildPath:", childPath)); log.LogProperties.Add(new LogDetailInfo("IsChildPortal:", isChildPortal.ToString())); LogController.Instance.AddLog(log); } catch (Exception exc) { Logger.Error(exc); } EventManager.Instance.OnPortalCreated(new PortalCreatedEventArgs { PortalId = portalId }); } else { throw new Exception(message); } } else { DeletePortalInternal(portalId); throw new Exception(message); } } private static string CreateProfileDefinitions(int portalId, string templateFilePath) { string strMessage = Null.NullString; try { //add profile definitions XmlDocument xmlDoc = new XmlDocument { XmlResolver = null }; //open the XML template file try { xmlDoc.Load(templateFilePath); } catch (Exception ex) { Logger.Error(ex); } //parse profile definitions if available var node = xmlDoc.SelectSingleNode("//portal/profiledefinitions"); if (node != null) { ParseProfileDefinitions(node, portalId); } else //template does not contain profile definitions ( ie. was created prior to DNN 3.3.0 ) { ProfileController.AddDefaultDefinitions(portalId); } } catch (Exception ex) { strMessage = Localization.GetString("CreateProfileDefinitions.Error"); Exceptions.LogException(ex); } return strMessage; } private static int CreatePortal(string portalName, string homeDirectory, string cultureCode) { //add portal int PortalId = -1; try { //Use host settings as default values for these parameters //This can be overwritten on the portal template var datExpiryDate = Host.Host.DemoPeriod > Null.NullInteger ? Convert.ToDateTime(Globals.GetMediumDate(DateTime.Now.AddDays(Host.Host.DemoPeriod).ToString(CultureInfo.InvariantCulture))) : Null.NullDate; PortalId = DataProvider.Instance().CreatePortal(portalName, Host.Host.HostCurrency, datExpiryDate, Host.Host.HostFee, Host.Host.HostSpace, Host.Host.PageQuota, Host.Host.UserQuota, 0, //site log history function has been removed. homeDirectory, cultureCode, UserController.Instance.GetCurrentUserInfo().UserID); //clear portal cache DataCache.ClearHostCache(true); EventLogController.Instance.AddLog("PortalName", portalName, GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_CREATED); } catch (Exception ex) { Exceptions.LogException(ex); } try { EnsureRequiredEventLogTypesExist(); } catch (Exception) { //should be no exception, but suppress just in case } return PortalId; } private static int CreateRole(RoleInfo role) { int roleId; //First check if the role exists var objRoleInfo = RoleController.Instance.GetRole(role.PortalID, r => r.RoleName == role.RoleName); if (objRoleInfo == null) { roleId = RoleController.Instance.AddRole(role); } else { roleId = objRoleInfo.RoleID; } return roleId; } private static int CreateRole(int portalId, string roleName, string description, float serviceFee, int billingPeriod, string billingFrequency, float trialFee, int trialPeriod, string trialFrequency, bool isPublic, bool isAuto) { RoleInfo objRoleInfo = new RoleInfo(); objRoleInfo.PortalID = portalId; objRoleInfo.RoleName = roleName; objRoleInfo.RoleGroupID = Null.NullInteger; objRoleInfo.Description = description; objRoleInfo.ServiceFee = Convert.ToSingle(serviceFee < 0 ? 0 : serviceFee); objRoleInfo.BillingPeriod = billingPeriod; objRoleInfo.BillingFrequency = billingFrequency; objRoleInfo.TrialFee = Convert.ToSingle(trialFee < 0 ? 0 : trialFee); objRoleInfo.TrialPeriod = trialPeriod; objRoleInfo.TrialFrequency = trialFrequency; objRoleInfo.IsPublic = isPublic; objRoleInfo.AutoAssignment = isAuto; return CreateRole(objRoleInfo); } private static void CreateRoleGroup(RoleGroupInfo roleGroup) { //First check if the role exists var objRoleGroupInfo = RoleController.GetRoleGroupByName(roleGroup.PortalID, roleGroup.RoleGroupName); if (objRoleGroupInfo == null) { roleGroup.RoleGroupID = RoleController.AddRoleGroup(roleGroup); } else { roleGroup.RoleGroupID = objRoleGroupInfo.RoleGroupID; } } private static void DeletePortalInternal(int portalId) { UserController.DeleteUsers(portalId, false, true); DataProvider.Instance().DeletePortalInfo(portalId); EventLogController.Instance.AddLog("PortalId", portalId.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_DELETED); DataCache.ClearHostCache(true); // queue remove portal from search index var document = new SearchDocumentToDelete { PortalId = portalId, }; DataProvider.Instance().AddSearchDeletedItems(document); } private static bool DoesLogTypeExists(string logTypeKey) { LogTypeInfo logType; Dictionary<string, LogTypeInfo> logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); logTypeDictionary.TryGetValue(logTypeKey, out logType); if (logType == null) { return false; } return true; } internal static void EnsureRequiredEventLogTypesExist() { if (!DoesLogTypeExists(EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString())) { //Add 404 Log var logTypeInfo = new LogTypeInfo { LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), LogTypeFriendlyName = "HTTP Error Code 404 Page Not Found", LogTypeDescription = "", LogTypeCSSClass = "OperationFailure", LogTypeOwner = "DotNetNuke.Logging.EventLogType" }; LogController.Instance.AddLogType(logTypeInfo); //Add LogType var logTypeConf = new LogTypeConfigInfo { LoggingIsActive = true, LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), KeepMostRecent = "100", NotificationThreshold = 1, NotificationThresholdTime = 1, NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, MailFromAddress = Null.NullString, MailToAddress = Null.NullString, LogTypePortalID = "*" }; LogController.Instance.AddLogTypeConfigInfo(logTypeConf); } if (!DoesLogTypeExists(EventLogController.EventLogType.IP_LOGIN_BANNED.ToString())) { //Add IP filter log type var logTypeFilterInfo = new LogTypeInfo { LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), LogTypeFriendlyName = "HTTP Error Code Forbidden IP address rejected", LogTypeDescription = "", LogTypeCSSClass = "OperationFailure", LogTypeOwner = "DotNetNuke.Logging.EventLogType" }; LogController.Instance.AddLogType(logTypeFilterInfo); //Add LogType var logTypeFilterConf = new LogTypeConfigInfo { LoggingIsActive = true, LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), KeepMostRecent = "100", NotificationThreshold = 1, NotificationThresholdTime = 1, NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, MailFromAddress = Null.NullString, MailToAddress = Null.NullString, LogTypePortalID = "*" }; LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); } if (!DoesLogTypeExists(EventLogController.EventLogType.TABURL_CREATED.ToString())) { var logTypeInfo = new LogTypeInfo { LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), LogTypeFriendlyName = "TabURL created", LogTypeDescription = "", LogTypeCSSClass = "OperationSuccess", LogTypeOwner = "DotNetNuke.Logging.EventLogType" }; LogController.Instance.AddLogType(logTypeInfo); logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); logTypeInfo.LogTypeFriendlyName = "TabURL updated"; LogController.Instance.AddLogType(logTypeInfo); logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; LogController.Instance.AddLogType(logTypeInfo); //Add LogType var logTypeUrlConf = new LogTypeConfigInfo { LoggingIsActive = false, LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), KeepMostRecent = "100", NotificationThreshold = 1, NotificationThresholdTime = 1, NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, MailFromAddress = Null.NullString, MailToAddress = Null.NullString, LogTypePortalID = "*" }; LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); } if (!DoesLogTypeExists(EventLogController.EventLogType.SCRIPT_COLLISION.ToString())) { //Add IP filter log type var logTypeFilterInfo = new LogTypeInfo { LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), LogTypeFriendlyName = "Javscript library registration resolved script collision", LogTypeDescription = "", LogTypeCSSClass = "OperationFailure", LogTypeOwner = "DotNetNuke.Logging.EventLogType" }; LogController.Instance.AddLogType(logTypeFilterInfo); //Add LogType var logTypeFilterConf = new LogTypeConfigInfo { LoggingIsActive = true, LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), KeepMostRecent = "100", NotificationThreshold = 1, NotificationThresholdTime = 1, NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, MailFromAddress = Null.NullString, MailToAddress = Null.NullString, LogTypePortalID = "*" }; LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); } } private static PortalSettings GetCurrentPortalSettingsInternal() { PortalSettings objPortalSettings = null; if (HttpContext.Current != null) { objPortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; } return objPortalSettings; } private static PortalInfo GetPortalInternal(int portalId, string cultureCode) { return Instance.GetPortalList(cultureCode).SingleOrDefault(p => p.PortalID == portalId); } private static object GetPortalDefaultLanguageCallBack(CacheItemArgs cacheItemArgs) { int portalID = (int)cacheItemArgs.ParamList[0]; return DataProvider.Instance().GetPortalDefaultLanguage(portalID); } private static object GetPortalDictionaryCallback(CacheItemArgs cacheItemArgs) { var portalDic = new Dictionary<int, int>(); if (Host.Host.PerformanceSetting != Globals.PerformanceSettings.NoCaching) { //get all tabs int intField = 0; IDataReader dr = DataProvider.Instance().GetTabPaths(Null.NullInteger, Null.NullString); try { while (dr.Read()) { //add to dictionary portalDic[Convert.ToInt32(Null.SetNull(dr["TabID"], intField))] = Convert.ToInt32(Null.SetNull(dr["PortalID"], intField)); } } catch (Exception exc) { Exceptions.LogException(exc); } finally { //close datareader CBO.CloseDataReader(dr, true); } } return portalDic; } private static object GetPortalSettingsDictionaryCallback(CacheItemArgs cacheItemArgs) { var portalId = (int)cacheItemArgs.ParamList[0]; var dicSettings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); if (portalId <= -1) return dicSettings; var cultureCode = Convert.ToString(cacheItemArgs.ParamList[1]); if (string.IsNullOrEmpty(cultureCode)) { cultureCode = GetActivePortalLanguage(portalId); } var dr = DataProvider.Instance().GetPortalSettings(portalId, cultureCode); try { while (dr.Read()) { if (dr.IsDBNull(1)) continue; var key = dr.GetString(0); if (dicSettings.ContainsKey(key)) { dicSettings[key] = dr.GetString(1); var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString() }; log.AddProperty("Duplicate PortalSettings Key", key); LogController.Instance.AddLog(log); } else { dicSettings.Add(key, dr.GetString(1)); } } } catch (Exception exc) { Exceptions.LogException(exc); } finally { CBO.CloseDataReader(dr, true); } return dicSettings; } private static void ParseFiles(XmlNodeList nodeFiles, int portalId, FolderInfo folder) { var fileManager = FileManager.Instance; foreach (XmlNode node in nodeFiles) { var fileName = XmlUtils.GetNodeValue(node.CreateNavigator(), "filename"); //First check if the file exists var file = fileManager.GetFile(folder, fileName); if (file != null) continue; file = new FileInfo { PortalId = portalId, FileName = fileName, Extension = XmlUtils.GetNodeValue(node.CreateNavigator(), "extension"), Size = XmlUtils.GetNodeValueInt(node, "size"), Width = XmlUtils.GetNodeValueInt(node, "width"), Height = XmlUtils.GetNodeValueInt(node, "height"), ContentType = XmlUtils.GetNodeValue(node.CreateNavigator(), "contenttype"), SHA1Hash = XmlUtils.GetNodeValue(node.CreateNavigator(), "sha1hash"), FolderId = folder.FolderID, Folder = folder.FolderPath, Title = "", StartDate = DateTime.Now, EndDate = Null.NullDate, EnablePublishPeriod = false, ContentItemID = Null.NullInteger }; //Save new File try { //Initially, install files are on local system, then we need the Standard folder provider to read the content regardless the target folderprovider using (var fileContent = FolderProvider.Instance("StandardFolderProvider").GetFileStream(file)) { var contentType = FileContentTypeManager.Instance.GetContentType(Path.GetExtension(fileName)); var userId = UserController.Instance.GetCurrentUserInfo().UserID; file.FileId = fileManager.AddFile(folder, fileName, fileContent, false, false, true, contentType, userId).FileId; } fileManager.UpdateFile(file); } catch (InvalidFileExtensionException ex) //when the file is not allowed, we should not break parse process, but just log the error. { Logger.Error(ex.Message); } } } private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, int portalId, FolderInfo folder) { PermissionController permissionController = new PermissionController(); int permissionId = 0; //Clear the current folder permissions folder.FolderPermissions.Clear(); foreach (XmlNode xmlFolderPermission in nodeFolderPermissions) { string permissionKey = XmlUtils.GetNodeValue(xmlFolderPermission.CreateNavigator(), "permissionkey"); string permissionCode = XmlUtils.GetNodeValue(xmlFolderPermission.CreateNavigator(), "permissioncode"); string roleName = XmlUtils.GetNodeValue(xmlFolderPermission.CreateNavigator(), "rolename"); bool allowAccess = XmlUtils.GetNodeValueBoolean(xmlFolderPermission, "allowaccess"); foreach (PermissionInfo permission in permissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey)) { permissionId = permission.PermissionID; } int roleId = int.MinValue; switch (roleName) { case Globals.glbRoleAllUsersName: roleId = Convert.ToInt32(Globals.glbRoleAllUsers); break; case Globals.glbRoleUnauthUserName: roleId = Convert.ToInt32(Globals.glbRoleUnauthUser); break; default: RoleInfo objRole = RoleController.Instance.GetRole(portalId, r => r.RoleName == roleName); if (objRole != null) { roleId = objRole.RoleID; } break; } //if role was found add, otherwise ignore if (roleId != int.MinValue) { var folderPermission = new FolderPermissionInfo { FolderID = folder.FolderID, PermissionID = permissionId, RoleID = roleId, UserID = Null.NullInteger, AllowAccess = allowAccess }; bool canAdd = !folder.FolderPermissions.Cast<FolderPermissionInfo>() .Any(fp => fp.FolderID == folderPermission.FolderID && fp.PermissionID == folderPermission.PermissionID && fp.RoleID == folderPermission.RoleID && fp.UserID == folderPermission.UserID); if (canAdd) { folder.FolderPermissions.Add(folderPermission); } } } FolderPermissionController.SaveFolderPermissions(folder); } private void CreatePredefinedFolderTypes(int portalId) { try { EnsureRequiredProvidersForFolderTypes(); } catch (Exception ex) { Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error"), ex); } var webConfig = Config.Load(); foreach (FolderTypeConfig folderTypeConfig in FolderMappingsConfigController.Instance.FolderTypes) { try { EnsureFolderProviderRegistration<FolderProvider>(folderTypeConfig, webConfig); FolderMappingController.Instance.AddFolderMapping(GetFolderMappingFromConfig(folderTypeConfig, portalId)); } catch (Exception ex) { Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error") + ": " + folderTypeConfig.Name, ex); } } } private static void EnsureRequiredProvidersForFolderTypes() { if (ComponentFactory.GetComponent<CryptographyProvider>() == null) { ComponentFactory.InstallComponents(new ProviderInstaller("cryptography", typeof(CryptographyProvider), typeof(FipsCompilanceCryptographyProvider))); ComponentFactory.RegisterComponentInstance<CryptographyProvider>(new FipsCompilanceCryptographyProvider()); } } private static void EnsureFolderProviderRegistration<TAbstract>(FolderTypeConfig folderTypeConfig, XmlDocument webConfig) where TAbstract : class { var providerBusinessClassNode = webConfig.SelectSingleNode("configuration/dotnetnuke/folder/providers/add[@name='"+folderTypeConfig.Provider+"']"); var typeClass = Type.GetType(providerBusinessClassNode.Attributes["type"].Value); if (typeClass != null) { ComponentFactory.RegisterComponentInstance<TAbstract>(folderTypeConfig.Provider, Activator.CreateInstance(typeClass)); } } private void ParseExtensionUrlProviders(XPathNavigator providersNavigator, int portalId) { var providers = ExtensionUrlProviderController.GetProviders(portalId); foreach (XPathNavigator providerNavigator in providersNavigator.Select("extensionUrlProvider")) { HtmlUtils.WriteKeepAlive(); var providerName = XmlUtils.GetNodeValue(providerNavigator, "name"); var provider = providers.SingleOrDefault(p => p.ProviderName.Equals(providerName, StringComparison.OrdinalIgnoreCase)); if (provider == null) { continue; } var active = XmlUtils.GetNodeValueBoolean(providerNavigator, "active"); if (active) { ExtensionUrlProviderController.EnableProvider(provider.ExtensionUrlProviderId, portalId); } else { ExtensionUrlProviderController.DisableProvider(provider.ExtensionUrlProviderId, portalId); } var settingsNavigator = providerNavigator.SelectSingleNode("settings"); if (settingsNavigator != null) { foreach (XPathNavigator settingNavigator in settingsNavigator.Select("setting")) { var name = XmlUtils.GetAttributeValue(settingNavigator, "name"); var value = XmlUtils.GetAttributeValue(settingNavigator, "value"); ExtensionUrlProviderController.SaveSetting(provider.ExtensionUrlProviderId, portalId, name, value); } } } } private static bool EnableBrowserLanguageInDefault(int portalId) { bool retValue = Null.NullBoolean; try { string setting; GetPortalSettingsDictionary(portalId, Localization.SystemLocale).TryGetValue("EnableBrowserLanguage", out setting); if (string.IsNullOrEmpty(setting)) { retValue = Host.Host.EnableBrowserLanguage; } else { retValue = (setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)); } } catch (Exception exc) { Logger.Error(exc); } return retValue; } private string EnsureSettingValue(string folderProviderType, FolderTypeSettingConfig settingNode, int portalId) { var ensuredSettingValue = settingNode.Value.Replace("{PortalId}", (portalId != -1) ? portalId.ToString(CultureInfo.InvariantCulture) : "_default").Replace("{HostId}", Host.Host.GUID); if (settingNode.Encrypt) { return FolderProvider.Instance(folderProviderType).EncryptValue(ensuredSettingValue); //return PortalSecurity.Instance.Encrypt(Host.Host.GUID, ensuredSettingValue.Trim()); } return ensuredSettingValue; } private string GetCultureCode(string languageFileName) { //e.g. "default template.template.en-US.resx" return languageFileName.GetLocaleCodeFromFileName(); } private FolderMappingInfo GetFolderMappingFromConfig(FolderTypeConfig node, int portalId) { var folderMapping = new FolderMappingInfo { PortalID = portalId, MappingName = node.Name, FolderProviderType = node.Provider }; foreach (FolderTypeSettingConfig settingNode in node.Settings) { var settingValue = EnsureSettingValue(folderMapping.FolderProviderType, settingNode, portalId); folderMapping.FolderMappingSettings.Add(settingNode.Name, settingValue); } return folderMapping; } private FolderMappingInfo GetFolderMappingFromStorageLocation(int portalId, XmlNode folderNode) { var storageLocation = Convert.ToInt32(XmlUtils.GetNodeValue(folderNode, "storagelocation", "0")); switch (storageLocation) { case (int)FolderController.StorageLocationTypes.SecureFileSystem: return FolderMappingController.Instance.GetFolderMapping(portalId, "Secure"); case (int)FolderController.StorageLocationTypes.DatabaseSecure: return FolderMappingController.Instance.GetFolderMapping(portalId, "Database"); default: return FolderMappingController.Instance.GetDefaultFolderMapping(portalId); } } private static Dictionary<string, string> GetPortalSettingsDictionary(int portalId, string cultureCode) { var httpContext = HttpContext.Current; if (string.IsNullOrEmpty(cultureCode) && portalId > -1) { cultureCode = GetActivePortalLanguageFromHttpContext(httpContext, portalId); } //Get PortalSettings from Context or from cache var dictionaryKey = String.Format(HttpContextKeyPortalSettingsDictionary, portalId, cultureCode); Dictionary<string, string> dictionary = null; if (httpContext != null) { dictionary = httpContext.Items[dictionaryKey] as Dictionary<string, string>; } if (dictionary == null) { var cacheKey = string.Format(DataCache.PortalSettingsCacheKey, portalId, cultureCode); dictionary = CBO.GetCachedObject<Dictionary<string, string>>(new CacheItemArgs(cacheKey, DataCache.PortalSettingsCacheTimeOut, DataCache.PortalSettingsCachePriority, portalId, cultureCode), GetPortalSettingsDictionaryCallback, true); if (httpContext != null) { httpContext.Items[dictionaryKey] = dictionary; } } return dictionary; } private static string GetActivePortalLanguageFromHttpContext(HttpContext httpContext, int portalId) { var cultureCode = string.Empty; //Lookup culturecode but cache it in the HttpContext for performance var activeLanguageKey = String.Format("ActivePortalLanguage{0}", portalId); if (httpContext != null) { cultureCode = (string)httpContext.Items[activeLanguageKey]; } if (string.IsNullOrEmpty(cultureCode)) { cultureCode = GetActivePortalLanguage(portalId); if (httpContext != null) { httpContext.Items[activeLanguageKey] = cultureCode; } } return cultureCode; } private string GetTemplateName(string languageFileName) { //e.g. "default template.template.en-US.resx" return languageFileName.GetFileNameFromLocalizedResxFile(); } private static LocaleCollection ParseEnabledLocales(XmlNode nodeEnabledLocales, int portalId) { var defaultLocale = LocaleController.Instance.GetDefaultLocale(portalId); var returnCollection = new LocaleCollection { { defaultLocale.Code, defaultLocale } }; var clearCache = false; foreach (XmlNode node in nodeEnabledLocales.SelectNodes("//locale")) { var cultureCode = node.InnerText; var locale = LocaleController.Instance.GetLocale(cultureCode); if (locale == null) { // if language does not exist in the installation, create it locale = new Locale { Code = cultureCode, Fallback = Localization.SystemLocale, Text = CultureInfo.GetCultureInfo(cultureCode).NativeName }; Localization.SaveLanguage(locale,false); clearCache = true; } if (locale.Code != defaultLocale.Code) { returnCollection.Add(locale.Code, locale); } } if (clearCache) { DataCache.ClearHostCache(true); } return returnCollection; } private void ParseFolders(XmlNode nodeFolders, int portalId) { var folderManager = FolderManager.Instance; var folderMappingController = FolderMappingController.Instance; var xmlNodeList = nodeFolders.SelectNodes("//folder"); if (xmlNodeList != null) { foreach (XmlNode node in xmlNodeList) { HtmlUtils.WriteKeepAlive(); var folderPath = XmlUtils.GetNodeValue(node.CreateNavigator(), "folderpath"); //First check if the folder exists var objInfo = folderManager.GetFolder(portalId, folderPath); if (objInfo == null) { FolderMappingInfo folderMapping; try { folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, folderPath) ?? GetFolderMappingFromStorageLocation(portalId, node); } catch (Exception ex) { Logger.Error(ex); folderMapping = folderMappingController.GetDefaultFolderMapping(portalId); } var isProtected = XmlUtils.GetNodeValueBoolean(node, "isprotected"); try { //Save new folder objInfo = folderManager.AddFolder(folderMapping, folderPath); } catch (Exception ex) { Logger.Error(ex); //Retry with default folderMapping var defaultFolderMapping = folderMappingController.GetDefaultFolderMapping(portalId); if (folderMapping.FolderMappingID != defaultFolderMapping.FolderMappingID) { objInfo = folderManager.AddFolder(defaultFolderMapping, folderPath); } else { throw; } } objInfo.IsProtected = isProtected; folderManager.UpdateFolder(objInfo); } var nodeFolderPermissions = node.SelectNodes("folderpermissions/permission"); ParseFolderPermissions(nodeFolderPermissions, portalId, (FolderInfo) objInfo); var nodeFiles = node.SelectNodes("files/file"); ParseFiles(nodeFiles, portalId, (FolderInfo) objInfo); } } } private static void ParseProfileDefinitions(XmlNode nodeProfileDefinitions, int portalId) { var listController = new ListController(); Dictionary<string, ListEntryInfo> colDataTypes = listController.GetListEntryInfoDictionary("DataType"); int orderCounter = -1; ProfilePropertyDefinition objProfileDefinition; bool preferredTimeZoneFound = false; foreach (XmlNode node in nodeProfileDefinitions.SelectNodes("//profiledefinition")) { orderCounter += 2; ListEntryInfo typeInfo; if (!colDataTypes.TryGetValue("DataType:" + XmlUtils.GetNodeValue(node.CreateNavigator(), "datatype"), out typeInfo)) { typeInfo = colDataTypes["DataType:Unknown"]; } objProfileDefinition = new ProfilePropertyDefinition(portalId); objProfileDefinition.DataType = typeInfo.EntryID; objProfileDefinition.DefaultValue = ""; objProfileDefinition.ModuleDefId = Null.NullInteger; objProfileDefinition.PropertyCategory = XmlUtils.GetNodeValue(node.CreateNavigator(), "propertycategory"); objProfileDefinition.PropertyName = XmlUtils.GetNodeValue(node.CreateNavigator(), "propertyname"); objProfileDefinition.Required = false; objProfileDefinition.Visible = true; objProfileDefinition.ViewOrder = orderCounter; objProfileDefinition.Length = XmlUtils.GetNodeValueInt(node, "length"); switch (XmlUtils.GetNodeValueInt(node, "defaultvisibility", 2)) { case 0: objProfileDefinition.DefaultVisibility = UserVisibilityMode.AllUsers; break; case 1: objProfileDefinition.DefaultVisibility = UserVisibilityMode.MembersOnly; break; case 2: objProfileDefinition.DefaultVisibility = UserVisibilityMode.AdminOnly; break; } if (objProfileDefinition.PropertyName == "PreferredTimeZone") { preferredTimeZoneFound = true; } ProfileController.AddPropertyDefinition(objProfileDefinition); } //6.0 requires the old TimeZone property to be marked as Deleted ProfilePropertyDefinition pdf = ProfileController.GetPropertyDefinitionByName(portalId, "TimeZone"); if (pdf != null) { ProfileController.DeletePropertyDefinition(pdf); } // 6.0 introduced a new property called as PreferredTimeZone. If this property is not present in template // it should be added. Situation will mostly happen while using an older template file. if (!preferredTimeZoneFound) { orderCounter += 2; ListEntryInfo typeInfo = colDataTypes["DataType:TimeZoneInfo"]; if (typeInfo == null) { typeInfo = colDataTypes["DataType:Unknown"]; } objProfileDefinition = new ProfilePropertyDefinition(portalId); objProfileDefinition.DataType = typeInfo.EntryID; objProfileDefinition.DefaultValue = ""; objProfileDefinition.ModuleDefId = Null.NullInteger; objProfileDefinition.PropertyCategory = "Preferences"; objProfileDefinition.PropertyName = "PreferredTimeZone"; objProfileDefinition.Required = false; objProfileDefinition.Visible = true; objProfileDefinition.ViewOrder = orderCounter; objProfileDefinition.Length = 0; objProfileDefinition.DefaultVisibility = UserVisibilityMode.AdminOnly; ProfileController.AddPropertyDefinition(objProfileDefinition); } } private static void ParsePortalDesktopModules(XPathNavigator nav, int portalID) { foreach (XPathNavigator desktopModuleNav in nav.Select("portalDesktopModule")) { HtmlUtils.WriteKeepAlive(); var friendlyName = XmlUtils.GetNodeValue(desktopModuleNav, "friendlyname"); if (!string.IsNullOrEmpty(friendlyName)) { var desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); if (desktopModule != null) { //Parse the permissions DesktopModulePermissionCollection permissions = new DesktopModulePermissionCollection(); foreach (XPathNavigator permissionNav in desktopModuleNav.Select("portalDesktopModulePermissions/portalDesktopModulePermission")) { string code = XmlUtils.GetNodeValue(permissionNav, "permissioncode"); string key = XmlUtils.GetNodeValue(permissionNav, "permissionkey"); DesktopModulePermissionInfo desktopModulePermission = null; ArrayList arrPermissions = new PermissionController().GetPermissionByCodeAndKey(code, key); if (arrPermissions.Count > 0) { PermissionInfo permission = arrPermissions[0] as PermissionInfo; if (permission != null) { desktopModulePermission = new DesktopModulePermissionInfo(permission); } } desktopModulePermission.AllowAccess = bool.Parse(XmlUtils.GetNodeValue(permissionNav, "allowaccess")); string rolename = XmlUtils.GetNodeValue(permissionNav, "rolename"); if (!string.IsNullOrEmpty(rolename)) { RoleInfo role = RoleController.Instance.GetRole(portalID, r => r.RoleName == rolename); if (role != null) { desktopModulePermission.RoleID = role.RoleID; } } permissions.Add(desktopModulePermission); } DesktopModuleController.AddDesktopModuleToPortal(portalID, desktopModule, permissions, false); } } } } private void ParsePortalSettings(XmlNode nodeSettings, int portalId) { String currentCulture = GetActivePortalLanguage(portalId); var objPortal = GetPortal(portalId); objPortal.LogoFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "logofile")); objPortal.FooterText = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "footertext"); if (nodeSettings.SelectSingleNode("expirydate") != null) { objPortal.ExpiryDate = XmlUtils.GetNodeValueDate(nodeSettings, "expirydate", Null.NullDate); } objPortal.UserRegistration = XmlUtils.GetNodeValueInt(nodeSettings, "userregistration"); objPortal.BannerAdvertising = XmlUtils.GetNodeValueInt(nodeSettings, "banneradvertising"); if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "currency"))) { objPortal.Currency = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "currency"); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostfee"))) { objPortal.HostFee = XmlUtils.GetNodeValueSingle(nodeSettings, "hostfee"); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostspace"))) { objPortal.HostSpace = XmlUtils.GetNodeValueInt(nodeSettings, "hostspace"); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "pagequota"))) { objPortal.PageQuota = XmlUtils.GetNodeValueInt(nodeSettings, "pagequota"); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "userquota"))) { objPortal.UserQuota = XmlUtils.GetNodeValueInt(nodeSettings, "userquota"); } objPortal.BackgroundFile = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "backgroundfile"); objPortal.PaymentProcessor = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "paymentprocessor"); objPortal.DefaultLanguage = XmlUtils.GetNodeValue(nodeSettings, "defaultlanguage", "en-US"); UpdatePortalInfo(objPortal); if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrc", ""))) { UpdatePortalSetting(portalId, "DefaultPortalSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrc", ""), true, currentCulture); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", ""))) { UpdatePortalSetting(portalId, "DefaultAdminSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", ""), true, currentCulture); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrc", ""))) { UpdatePortalSetting(portalId, "DefaultPortalContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrc", ""), true, currentCulture); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", ""))) { UpdatePortalSetting(portalId, "DefaultAdminContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", ""), true, currentCulture); } //Enable Skin Widgets Setting if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", ""))) { UpdatePortalSetting(portalId, "EnableSkinWidgets", XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", "")); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", ""))) { UpdatePortalSetting(portalId, "ShowCookieConsent", XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", "False")); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", ""))) { UpdatePortalSetting(portalId, "CookieMoreLink", XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", ""), true, currentCulture); } //Enable AutoSAve feature if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableautosave", ""))) { UpdatePortalSetting(portalId, HtmlText_AutoSaveEnabled, XmlUtils.GetNodeValue(nodeSettings, "enableautosave", "")); //Time to autosave, only if enableautosave exists if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", ""))) { UpdatePortalSetting(portalId, HtmlText_TimeToAutoSave, XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", "")); } } //Set Auto alias mapping if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "portalaliasmapping", "CANONICALURL"))) { UpdatePortalSetting(portalId, "PortalAliasMapping", XmlUtils.GetNodeValue(nodeSettings, "portalaliasmapping", "CANONICALURL").ToUpperInvariant()); } //Set Time Zone maping if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "timezone", Localization.SystemTimeZone))) { UpdatePortalSetting(portalId, "TimeZone", XmlUtils.GetNodeValue(nodeSettings, "timezone", Localization.SystemTimeZone)); } if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "contentlocalizationenabled"))) { UpdatePortalSetting(portalId, "ContentLocalizationEnabled", XmlUtils.GetNodeValue(nodeSettings, "contentlocalizationenabled")); } if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "inlineeditorenabled"))) { UpdatePortalSetting(portalId, "InlineEditorEnabled", XmlUtils.GetNodeValue(nodeSettings, "inlineeditorenabled")); } if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enablepopups"))) { UpdatePortalSetting(portalId, "EnablePopUps", XmlUtils.GetNodeValue(nodeSettings, "enablepopups")); } if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "hidefoldersenabled"))) { UpdatePortalSetting(portalId, "HideFoldersEnabled", XmlUtils.GetNodeValue(nodeSettings, "hidefoldersenabled")); } if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode"))) { UpdatePortalSetting(portalId, "ControlPanelMode", XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode")); } if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity"))) { UpdatePortalSetting(portalId, "ControlPanelSecurity", XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity")); } if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility"))) { UpdatePortalSetting(portalId, "ControlPanelVisibility", XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility")); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", ""))) { UpdatePortalSetting(portalId, "PageHeadText", XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", "")); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", ""))) { UpdatePortalSetting(portalId, "InjectModuleHyperLink", XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", "")); } if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", ""))) { UpdatePortalSetting(portalId, "AddCompatibleHttpHeader", XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", "")); } } private void ParseRoleGroups(XPathNavigator nav, int portalID, int administratorId) { var administratorRoleId = -1; var registeredRoleId = -1; var subscriberRoleId = -1; var unverifiedRoleId = -1; foreach (XPathNavigator roleGroupNav in nav.Select("rolegroup")) { HtmlUtils.WriteKeepAlive(); var roleGroup = CBO.DeserializeObject<RoleGroupInfo>(new StringReader(roleGroupNav.OuterXml)); if (roleGroup.RoleGroupName != "GlobalRoles") { roleGroup.PortalID = portalID; CreateRoleGroup(roleGroup); } foreach (var role in roleGroup.Roles.Values) { role.PortalID = portalID; role.RoleGroupID = roleGroup.RoleGroupID; role.Status = RoleStatus.Approved; switch (role.RoleType) { case RoleType.Administrator: administratorRoleId = CreateRole(role); break; case RoleType.RegisteredUser: registeredRoleId = CreateRole(role); break; case RoleType.Subscriber: subscriberRoleId = CreateRole(role); break; case RoleType.None: CreateRole(role); break; case RoleType.UnverifiedUser: unverifiedRoleId = CreateRole(role); break; } } } CreateDefaultPortalRoles(portalID, administratorId, ref administratorRoleId, ref registeredRoleId, ref subscriberRoleId, unverifiedRoleId); //update portal setup var portal = GetPortal(portalID); UpdatePortalSetup(portalID, administratorId, administratorRoleId, registeredRoleId, portal.SplashTabId, portal.HomeTabId, portal.LoginTabId, portal.RegisterTabId, portal.UserTabId, portal.SearchTabId, portal.Custom404TabId, portal.Custom500TabId, portal.TermsTabId, portal.PrivacyTabId, portal.AdminTabId, GetActivePortalLanguage(portalID)); } private void ParseRoles(XPathNavigator nav, int portalID, int administratorId) { var administratorRoleId = -1; var registeredRoleId = -1; var subscriberRoleId = -1; var unverifiedRoleId = -1; foreach (XPathNavigator roleNav in nav.Select("role")) { HtmlUtils.WriteKeepAlive(); var role = CBO.DeserializeObject<RoleInfo>(new StringReader(roleNav.OuterXml)); role.PortalID = portalID; role.RoleGroupID = Null.NullInteger; switch (role.RoleType) { case RoleType.Administrator: administratorRoleId = CreateRole(role); break; case RoleType.RegisteredUser: registeredRoleId = CreateRole(role); break; case RoleType.Subscriber: subscriberRoleId = CreateRole(role); break; case RoleType.None: CreateRole(role); break; case RoleType.UnverifiedUser: unverifiedRoleId = CreateRole(role); break; } } //create required roles if not already created CreateDefaultPortalRoles(portalID, administratorId, ref administratorRoleId, ref registeredRoleId, ref subscriberRoleId, unverifiedRoleId); //update portal setup var portal = GetPortal(portalID); UpdatePortalSetup(portalID, administratorId, administratorRoleId, registeredRoleId, portal.SplashTabId, portal.HomeTabId, portal.LoginTabId, portal.RegisterTabId, portal.UserTabId, portal.SearchTabId, portal.Custom404TabId, portal.Custom500TabId, portal.TermsTabId, portal.PrivacyTabId, portal.AdminTabId, GetActivePortalLanguage(portalID)); } private void ParseTab(XmlNode nodeTab, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, ref Hashtable hModules, ref Hashtable hTabs, bool isNewPortal) { TabInfo tab = null; string strName = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "name"); var portal = GetPortal(portalId); if (!String.IsNullOrEmpty(strName)) { if (!isNewPortal) //running from wizard: try to find the tab by path { string parenttabname = ""; if (!String.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent"))) { parenttabname = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent") + "/"; } if (hTabs[parenttabname + strName] != null) { tab = TabController.Instance.GetTab(Convert.ToInt32(hTabs[parenttabname + strName]), portalId, false); } } if (tab == null || isNewPortal) { tab = TabController.DeserializeTab(nodeTab, null, hTabs, portalId, isAdminTemplate, mergeTabs, hModules); } //when processing the template we should try and identify the Admin tab var logType = "AdminTab"; if (tab.TabName == "Admin") { portal.AdminTabId = tab.TabID; } //when processing the template we can find: hometab, usertab, logintab switch (XmlUtils.GetNodeValue(nodeTab, "tabtype", "").ToLowerInvariant()) { case "splashtab": portal.SplashTabId = tab.TabID; logType = "SplashTab"; break; case "hometab": portal.HomeTabId = tab.TabID; logType = "HomeTab"; break; case "logintab": portal.LoginTabId = tab.TabID; logType = "LoginTab"; break; case "usertab": portal.UserTabId = tab.TabID; logType = "UserTab"; break; case "searchtab": portal.SearchTabId = tab.TabID; logType = "SearchTab"; break; case "404tab": portal.Custom404TabId = tab.TabID; logType = "Custom404Tab"; break; case "500tab": portal.Custom500TabId = tab.TabID; logType = "Custom500Tab"; break; } UpdatePortalSetup(portalId, portal.AdministratorId, portal.AdministratorRoleId, portal.RegisteredRoleId, portal.SplashTabId, portal.HomeTabId, portal.LoginTabId, portal.RegisterTabId, portal.UserTabId, portal.SearchTabId, portal.Custom404TabId, portal.Custom500TabId, portal.TermsTabId, portal.PrivacyTabId, portal.AdminTabId, GetActivePortalLanguage(portalId)); EventLogController.Instance.AddLog(logType, tab.TabID.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_UPDATED); } } private void ParseTabs(XmlNode nodeTabs, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { //used to control if modules are true modules or instances //will hold module ID from template / new module ID so new instances can reference right moduleid //only first one from the template will be create as a true module, //others will be moduleinstances (tabmodules) Hashtable hModules = new Hashtable(); Hashtable hTabs = new Hashtable(); //if running from wizard we need to pre populate htabs with existing tabs so ParseTab //can find all existing ones if (!isNewPortal) { Hashtable hTabNames = new Hashtable(); foreach (KeyValuePair<int, TabInfo> tabPair in TabController.Instance.GetTabsByPortal(portalId)) { TabInfo objTab = tabPair.Value; if (!objTab.IsDeleted) { var tabname = objTab.TabName; if (!Null.IsNull(objTab.ParentId)) { tabname = Convert.ToString(hTabNames[objTab.ParentId]) + "/" + objTab.TabName; } hTabNames.Add(objTab.TabID, tabname); } } //when parsing tabs we will need tabid given tabname foreach (int i in hTabNames.Keys) { if (hTabs[hTabNames[i]] == null) { hTabs.Add(hTabNames[i], i); } } hTabNames.Clear(); } foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab")) { HtmlUtils.WriteKeepAlive(); ParseTab(nodeTab, portalId, isAdminTemplate, mergeTabs, ref hModules, ref hTabs, isNewPortal); } //Process tabs that are linked to tabs foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab[url/@type = 'Tab']")) { HtmlUtils.WriteKeepAlive(); int tabId = XmlUtils.GetNodeValueInt(nodeTab, "tabid", Null.NullInteger); string tabPath = XmlUtils.GetNodeValue(nodeTab, "url", Null.NullString); if (tabId > Null.NullInteger) { TabInfo objTab = TabController.Instance.GetTab(tabId, portalId, false); objTab.Url = TabController.GetTabByTabPath(portalId, tabPath, Null.NullString).ToString(); TabController.Instance.UpdateTab(objTab); } } var folderManager = FolderManager.Instance; var fileManager = FileManager.Instance; //Process tabs that are linked to files foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab[url/@type = 'File']")) { HtmlUtils.WriteKeepAlive(); var tabId = XmlUtils.GetNodeValueInt(nodeTab, "tabid", Null.NullInteger); var filePath = XmlUtils.GetNodeValue(nodeTab, "url", Null.NullString); if (tabId > Null.NullInteger) { var objTab = TabController.Instance.GetTab(tabId, portalId, false); var fileName = Path.GetFileName(filePath); var folderPath = filePath.Substring(0, filePath.LastIndexOf(fileName)); var folder = folderManager.GetFolder(portalId, folderPath); var file = fileManager.GetFile(folder, fileName); objTab.Url = "FileID=" + file.FileId; TabController.Instance.UpdateTab(objTab); } } } private void ParseTemplateInternal(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { LocaleCollection localeCollection; ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal, out localeCollection); } private void ParseTemplateInternal(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal, out LocaleCollection localeCollection) { CachingProvider.DisableCacheExpiration(); var xmlPortal = new XmlDocument { XmlResolver = null }; IFolderInfo objFolder; try { xmlPortal.Load(Path.Combine(templatePath, templateFile)); } catch (Exception ex) { Logger.Error(ex); } var node = xmlPortal.SelectSingleNode("//portal/settings"); if (node != null && isNewPortal) { HtmlUtils.WriteKeepAlive(); ParsePortalSettings(node, portalId); } node = xmlPortal.SelectSingleNode("//locales"); if (node != null && isNewPortal) { HtmlUtils.WriteKeepAlive(); localeCollection = ParseEnabledLocales(node, portalId); } else { var portalInfo = Instance.GetPortal(portalId); var defaultLocale = LocaleController.Instance.GetLocale(portalInfo.DefaultLanguage); if (defaultLocale == null) { defaultLocale = new Locale { Code = portalInfo.DefaultLanguage, Fallback = Localization.SystemLocale, Text = CultureInfo.GetCultureInfo(portalInfo.DefaultLanguage).NativeName }; Localization.SaveLanguage(defaultLocale, false); } localeCollection = new LocaleCollection { { defaultLocale.Code, defaultLocale } }; } node = xmlPortal.SelectSingleNode("//portal/rolegroups"); if (node != null) { ParseRoleGroups(node.CreateNavigator(), portalId, administratorId); } node = xmlPortal.SelectSingleNode("//portal/roles"); if (node != null) { ParseRoles(node.CreateNavigator(), portalId, administratorId); } node = xmlPortal.SelectSingleNode("//portal/portalDesktopModules"); if (node != null) { ParsePortalDesktopModules(node.CreateNavigator(), portalId); } node = xmlPortal.SelectSingleNode("//portal/folders"); if (node != null) { ParseFolders(node, portalId); } node = xmlPortal.SelectSingleNode("//portal/extensionUrlProviders"); if (node != null) { ParseExtensionUrlProviders(node.CreateNavigator(), portalId); } var defaultFolderMapping = FolderMappingController.Instance.GetDefaultFolderMapping(portalId); if (FolderManager.Instance.GetFolder(portalId, "") == null) { objFolder = FolderManager.Instance.AddFolder(defaultFolderMapping, ""); objFolder.IsProtected = true; FolderManager.Instance.UpdateFolder(objFolder); AddFolderPermissions(portalId, objFolder.FolderID); } if (FolderManager.Instance.GetFolder(portalId, "Templates/") == null) { var folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, "Templates/") ?? defaultFolderMapping; objFolder = FolderManager.Instance.AddFolder(folderMapping, "Templates/"); objFolder.IsProtected = true; FolderManager.Instance.UpdateFolder(objFolder); //AddFolderPermissions(PortalId, objFolder.FolderID); } // force creation of users folder if not present on template if (FolderManager.Instance.GetFolder(portalId, "Users/") == null) { var folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, "Users/") ?? defaultFolderMapping; objFolder = FolderManager.Instance.AddFolder(folderMapping, "Users/"); objFolder.IsProtected = true; FolderManager.Instance.UpdateFolder(objFolder); //AddFolderPermissions(PortalId, objFolder.FolderID); } if (mergeTabs == PortalTemplateModuleAction.Replace) { foreach (KeyValuePair<int, TabInfo> tabPair in TabController.Instance.GetTabsByPortal(portalId)) { var objTab = tabPair.Value; objTab.TabName = objTab.TabName + "_old"; objTab.TabPath = Globals.GenerateTabPath(objTab.ParentId, objTab.TabName); objTab.IsDeleted = true; TabController.Instance.UpdateTab(objTab); foreach (KeyValuePair<int, ModuleInfo> modulePair in ModuleController.Instance.GetTabModules(objTab.TabID)) { var objModule = modulePair.Value; ModuleController.Instance.DeleteTabModule(objModule.TabID, objModule.ModuleID, false); } } } node = xmlPortal.SelectSingleNode("//portal/tabs"); if (node != null) { string version = xmlPortal.DocumentElement.GetAttribute("version"); if (version != "5.0") { XmlDocument xmlAdmin = new XmlDocument { XmlResolver = null }; try { string path = Path.Combine(templatePath, "admin.template"); if (!File.Exists(path)) { //if the template is a merged copy of a localized templte the //admin.template may be one director up path = Path.Combine(templatePath, "..\admin.template"); } xmlAdmin.Load(path); XmlNode adminNode = xmlAdmin.SelectSingleNode("//portal/tabs"); foreach (XmlNode adminTabNode in adminNode.ChildNodes) { node.AppendChild(xmlPortal.ImportNode(adminTabNode, true)); } } catch (Exception ex) { Logger.Error(ex); } } ParseTabs(node, portalId, false, mergeTabs, isNewPortal); } CachingProvider.EnableCacheExpiration(); } private void PrepareLocalizedPortalTemplate(PortalTemplateInfo template, out string templatePath, out string templateFile) { if (string.IsNullOrEmpty(template.LanguageFilePath)) { //no language to merge templatePath = Path.GetDirectoryName(template.TemplateFilePath) + @"\"; templateFile = Path.GetFileName(template.TemplateFilePath); return; } templatePath = Path.Combine(TestableGlobals.Instance.HostMapPath, "MergedTemplate"); Directory.CreateDirectory(templatePath); var buffer = new StringBuilder(File.ReadAllText(template.TemplateFilePath)); XDocument languageDoc; using (var reader = PortalTemplateIO.Instance.OpenTextReader(template.LanguageFilePath)) { languageDoc = XDocument.Load(reader); } var localizedData = languageDoc.Descendants("data"); foreach (var item in localizedData) { var nameAttribute = item.Attribute("name"); if (nameAttribute != null) { string name = nameAttribute.Value; var valueElement = item.Descendants("value").FirstOrDefault(); if (valueElement != null) { string value = valueElement.Value; buffer = buffer.Replace(string.Format("[{0}]", name), value); } } } templateFile = string.Format("Merged-{0}-{1}", template.CultureCode, Path.GetFileName(template.TemplateFilePath)); File.WriteAllText(Path.Combine(templatePath, templateFile), buffer.ToString()); } private void UpdatePortalInternal(PortalInfo portal, bool clearCache) { var processorPassword = portal.ProcessorPassword; if (!string.IsNullOrEmpty(processorPassword)) { processorPassword = Security.FIPSCompliant.EncryptAES(processorPassword, Config.GetDecryptionkey(), Host.Host.GUID); } DataProvider.Instance().UpdatePortalInfo(portal.PortalID, portal.PortalGroupID, portal.PortalName, portal.LogoFile, portal.FooterText, portal.ExpiryDate, portal.UserRegistration, portal.BannerAdvertising, portal.Currency, portal.AdministratorId, portal.HostFee, portal.HostSpace, portal.PageQuota, portal.UserQuota, portal.PaymentProcessor, portal.ProcessorUserId, processorPassword, portal.Description, portal.KeyWords, portal.BackgroundFile, 0, //site log history function has been removed. portal.SplashTabId, portal.HomeTabId, portal.LoginTabId, portal.RegisterTabId, portal.UserTabId, portal.SearchTabId, portal.Custom404TabId, portal.Custom500TabId, portal.TermsTabId, portal.PrivacyTabId, portal.DefaultLanguage, portal.HomeDirectory, UserController.Instance.GetCurrentUserInfo().UserID, portal.CultureCode); EventLogController.Instance.AddLog("PortalId", portal.PortalID.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); //ensure a localization item exists (in case a new default language has been set) DataProvider.Instance().EnsureLocalizationExists(portal.PortalID, portal.DefaultLanguage); //clear portal cache if (clearCache) { DataCache.ClearHostCache(true); } } private static void UpdatePortalSettingInternal(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) { string currentSetting = GetPortalSetting(settingName, portalID, string.Empty, cultureCode); if (currentSetting != settingValue) { if (isSecure && !string.IsNullOrEmpty(settingName) && !string.IsNullOrEmpty(settingValue)) { settingValue = Security.FIPSCompliant.EncryptAES(settingValue, Config.GetDecryptionkey(), Host.Host.GUID); } DataProvider.Instance().UpdatePortalSetting(portalID, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID, cultureCode, isSecure); EventLogController.Instance.AddLog(settingName + ((cultureCode == Null.NullString) ? String.Empty : " (" + cultureCode + ")"), settingValue, GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_UPDATED); if (clearCache) { DataCache.ClearPortalCache(portalID, false); DataCache.RemoveCache(DataCache.PortalDictionaryCacheKey); var httpContext = HttpContext.Current; if (httpContext != null) { var cultureCodeForKey = GetActivePortalLanguageFromHttpContext(httpContext, portalID); var dictionaryKey = String.Format(HttpContextKeyPortalSettingsDictionary, portalID, cultureCodeForKey); httpContext.Items[dictionaryKey] = null; } } EventManager.Instance.OnPortalSettingUpdated(new PortalSettingUpdatedEventArgs { PortalId = portalID, SettingName = settingName, SettingValue = settingValue }); } } private void UpdatePortalSetup(int portalId, int administratorId, int administratorRoleId, int registeredRoleId, int splashTabId, int homeTabId, int loginTabId, int registerTabId, int userTabId, int searchTabId, int custom404TabId, int custom500TabId, int termsTabId, int privacyTabId, int adminTabId, string cultureCode) { DataProvider.Instance().UpdatePortalSetup(portalId, administratorId, administratorRoleId, registeredRoleId, splashTabId, homeTabId, loginTabId, registerTabId, userTabId, searchTabId, custom404TabId, custom500TabId, termsTabId, privacyTabId, adminTabId, cultureCode); EventLogController.Instance.AddLog("PortalId", portalId.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); DataCache.ClearHostCache(true); } #endregion #region Public Methods /// <summary> /// Creates a new portal alias /// </summary> /// <param name="portalId">Id of the portal</param> /// <param name="portalAlias">Portal Alias to be created</param> public void AddPortalAlias(int portalId, string portalAlias) { //Check if the Alias exists PortalAliasInfo portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias, portalId); //If alias does not exist add new if (portalAliasInfo == null) { portalAliasInfo = new PortalAliasInfo {PortalID = portalId, HTTPAlias = portalAlias, IsPrimary = true}; PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); } } /// <summary> /// Copies the page template. /// </summary> /// <param name="templateFile">The template file.</param> /// <param name="mappedHomeDirectory">The mapped home directory.</param> public void CopyPageTemplate(string templateFile, string mappedHomeDirectory) { string hostTemplateFile = string.Format("{0}Templates\\{1}", Globals.HostMapPath, templateFile); if (File.Exists(hostTemplateFile)) { string portalTemplateFolder = string.Format("{0}Templates\\", mappedHomeDirectory); if (!Directory.Exists(portalTemplateFolder)) { //Create Portal Templates folder Directory.CreateDirectory(portalTemplateFolder); } string portalTemplateFile = portalTemplateFolder + templateFile; if (!File.Exists(portalTemplateFile)) { File.Copy(hostTemplateFile, portalTemplateFile); } } } /// <summary> /// Creates the portal. /// </summary> /// <param name="portalName">Name of the portal.</param> /// <param name="adminUserId">The obj admin user.</param> /// <param name="description">The description.</param> /// <param name="keyWords">The key words.</param> /// <param name="template"> </param> /// <param name="homeDirectory">The home directory.</param> /// <param name="portalAlias">The portal alias.</param> /// <param name="serverPath">The server path.</param> /// <param name="childPath">The child path.</param> /// <param name="isChildPortal">if set to <c>true</c> means the portal is child portal.</param> /// <returns>Portal id.</returns> public int CreatePortal(string portalName, int adminUserId, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { //Attempt to create a new portal int portalId = CreatePortal(portalName, homeDirectory, template.CultureCode); //Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. if (HttpContext.Current != null) { HttpContext.Current.Items.Add("CreatingPortalId", portalId); } string message = Null.NullString; if (portalId != -1) { //add administrator int administratorId = adminUserId; var adminUser = new UserInfo(); //add userportal record UserController.AddUserPortal(portalId, administratorId); //retrieve existing administrator try { adminUser = UserController.GetUserById(portalId, administratorId); } catch (Exception Exc) { Logger.Error(Exc); } if (administratorId > 0) { CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); } } else { message += Localization.GetString("CreatePortal.Error"); throw new Exception(message); } try { EnsureRequiredEventLogTypesExist(); } catch (Exception) { //should be no exception, but suppress just in case } //remove the portal id from http context as there is no exception. if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CreatingPortalId")) { HttpContext.Current.Items.Remove("CreatingPortalId"); } return portalId; } /// <summary> /// Creates the portal. /// </summary> /// <param name="portalName">Name of the portal.</param> /// <param name="adminUser">The obj admin user.</param> /// <param name="description">The description.</param> /// <param name="keyWords">The key words.</param> /// <param name="template"> </param> /// <param name="homeDirectory">The home directory.</param> /// <param name="portalAlias">The portal alias.</param> /// <param name="serverPath">The server path.</param> /// <param name="childPath">The child path.</param> /// <param name="isChildPortal">if set to <c>true</c> means the portal is child portal.</param> /// <returns>Portal id.</returns> public int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { //Attempt to create a new portal int portalId = CreatePortal(portalName, homeDirectory, template.CultureCode); //Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. if (HttpContext.Current != null) { HttpContext.Current.Items.Add("CreatingPortalId", portalId); } string message = Null.NullString; if (portalId != -1) { //add administrator int administratorId = Null.NullInteger; adminUser.PortalID = portalId; try { UserCreateStatus createStatus = UserController.CreateUser(ref adminUser); if (createStatus == UserCreateStatus.Success) { administratorId = adminUser.UserID; //reload the UserInfo as when it was first created, it had no portal id and therefore //used host profile definitions adminUser = UserController.GetUserById(adminUser.PortalID, adminUser.UserID); } else { message += UserController.GetUserCreateStatus(createStatus); } } catch (Exception Exc) { Logger.Error(Exc); message += Localization.GetString("CreateAdminUser.Error") + Exc.Message + Exc.StackTrace; } if (administratorId > 0) { CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); } } else { message += Localization.GetString("CreatePortal.Error"); throw new Exception(message); } try { EnsureRequiredEventLogTypesExist(); } catch (Exception) { //should be no exception, but suppress just in case } //remove the portal id from http context as there is no exception. if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CreatingPortalId")) { HttpContext.Current.Items.Remove("CreatingPortalId"); } return portalId; } /// <summary> /// Get all the available portal templates grouped by culture /// </summary> /// <returns>List of PortalTemplateInfo objects</returns> public IList<PortalTemplateInfo> GetAvailablePortalTemplates() { var list = new List<PortalTemplateInfo>(); var templateFilePaths = PortalTemplateIO.Instance.EnumerateTemplates(); var languageFileNames = PortalTemplateIO.Instance.EnumerateLanguageFiles().Select(Path.GetFileName).ToList(); foreach (string templateFilePath in templateFilePaths) { var currentFileName = Path.GetFileName(templateFilePath); var langs = languageFileNames.Where(x => GetTemplateName(x).Equals(currentFileName, StringComparison.InvariantCultureIgnoreCase)).Select(x => GetCultureCode(x)).Distinct().ToList(); if (langs.Any()) { langs.ForEach(x => list.Add(new PortalTemplateInfo(templateFilePath, x))); } else { //DNN-6544 portal creation requires valid culture, if template has no culture defined, then use portal's default language. var portalSettings = PortalSettings.Current; var cultureCode = portalSettings != null ? GetPortalDefaultLanguage(portalSettings.PortalId) : Localization.SystemLocale; list.Add(new PortalTemplateInfo(templateFilePath, cultureCode)); } } return list; } /// <summary> /// Gets the current portal settings. /// </summary> /// <returns>portal settings.</returns> PortalSettings IPortalController.GetCurrentPortalSettings() { return GetCurrentPortalSettingsInternal(); } IAbPortalSettings IPortalController.GetCurrentSettings() { return GetCurrentPortalSettingsInternal(); } /// <summary> /// Gets information of a portal /// </summary> /// <param name = "portalId">Id of the portal</param> /// <returns>PortalInfo object with portal definition</returns> public PortalInfo GetPortal(int portalId) { if (portalId == -1) { return null; } string defaultLanguage = GetActivePortalLanguage(portalId); PortalInfo portal = GetPortal(portalId, defaultLanguage); if (portal == null) { //Active language may not be valid, so fallback to default language defaultLanguage = GetPortalDefaultLanguage(portalId); portal = GetPortal(portalId, defaultLanguage); } return portal; } /// <summary> /// Gets information of a portal /// </summary> /// <param name = "portalId">Id of the portal</param> /// <param name="cultureCode">The culture code.</param> public PortalInfo GetPortal(int portalId, string cultureCode) { if (portalId == -1) { return null; } PortalInfo portal = GetPortalInternal(portalId, cultureCode); if (Localization.ActiveLanguagesByPortalID(portalId) > 1) { if (portal == null) { //Get Fallback language string fallbackLanguage = string.Empty; if (string.IsNullOrEmpty(cultureCode)) cultureCode = GetPortalDefaultLanguage(portalId); Locale userLocale = LocaleController.Instance.GetLocale(cultureCode); if (userLocale != null && !string.IsNullOrEmpty(userLocale.Fallback)) { fallbackLanguage = userLocale.Fallback; } if (String.IsNullOrEmpty(fallbackLanguage)) { fallbackLanguage = Localization.SystemLocale; } portal = GetPortalInternal(portalId, fallbackLanguage); //if we cannot find any fallback, it mean's it's a non portal default langauge if (portal == null) { DataProvider.Instance().EnsureLocalizationExists(portalId, GetActivePortalLanguage(portalId)); DataCache.ClearHostCache(true); portal = GetPortalInternal(portalId, GetActivePortalLanguage(portalId)); } } } return portal; } /// <summary> /// Gets the portal. /// </summary> /// <param name="uniqueId">The unique id.</param> /// <returns>Portal info.</returns> public PortalInfo GetPortal(Guid uniqueId) { return GetPortalList(Null.NullString).SingleOrDefault(p => p.GUID == uniqueId); } /// <summary> /// Gets information from all portals /// </summary> /// <returns>ArrayList of PortalInfo objects</returns> public ArrayList GetPortals() { return new ArrayList(GetPortalList(Null.NullString)); } /// <summary> /// Get portals in specific culture. /// </summary> /// <param name="cultureCode">The culture code.</param> /// <returns></returns> public List<PortalInfo> GetPortalList(string cultureCode) { string cacheKey = String.Format(DataCache.PortalCacheKey, Null.NullInteger, cultureCode); return CBO.GetCachedObject<List<PortalInfo>>(new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, cultureCode), c => CBO.FillCollection<PortalInfo>(DataProvider.Instance().GetPortals(cultureCode)) ); } /// <summary> /// Gets the portal settings dictionary. /// </summary> /// <param name="portalId">The portal ID.</param> /// <returns>portal settings.</returns> public Dictionary<string, string> GetPortalSettings(int portalId) { return GetPortalSettingsDictionary(portalId, string.Empty); } /// <summary> /// Gets the portal settings dictionary. /// </summary> /// <param name="portalId">The portal ID.</param> /// <param name="cultureCode">The culture code</param> /// <returns>portal settings.</returns> public Dictionary<string, string> GetPortalSettings(int portalId, string cultureCode) { return GetPortalSettingsDictionary(portalId, cultureCode); } /// <summary> /// Load info for a portal template /// </summary> /// <param name="templatePath">Full path to the portal template</param> /// <param name="cultureCode">the culture code if any for the localization of the portal template</param> /// <returns>A portal template</returns> public PortalTemplateInfo GetPortalTemplate(string templatePath, string cultureCode) { var template = new PortalTemplateInfo(templatePath, cultureCode); if (!string.IsNullOrEmpty(cultureCode) && template.CultureCode != cultureCode) { return null; } return template; } /// <summary> /// Gets the portal space used bytes. /// </summary> /// <param name="portalId">The portal id.</param> /// <returns>Space used in bytes</returns> public long GetPortalSpaceUsedBytes(int portalId) { long size = 0; IDataReader dr = DataProvider.Instance().GetPortalSpaceUsed(portalId); try { if (dr.Read()) { if (dr["SpaceUsed"] != DBNull.Value) { size = Convert.ToInt64(dr["SpaceUsed"]); } } } catch (Exception ex) { Exceptions.LogException(ex); } finally { CBO.CloseDataReader(dr, true); } return size; } /// <summary> /// Verifies if there's enough space to upload a new file on the given portal /// </summary> /// <param name="portalId">Id of the portal</param> /// <param name="fileSizeBytes">Size of the file being uploaded</param> /// <returns>True if there's enough space available to upload the file</returns> public bool HasSpaceAvailable(int portalId, long fileSizeBytes) { int hostSpace; if (portalId == -1) { hostSpace = 0; } else { PortalSettings ps = GetCurrentPortalSettingsInternal(); if (ps != null && ps.PortalId == portalId) { hostSpace = ps.HostSpace; } else { PortalInfo portal = GetPortal(portalId); hostSpace = portal.HostSpace; } } return (((GetPortalSpaceUsedBytes(portalId) + fileSizeBytes) / Math.Pow(1024, 2)) <= hostSpace) || hostSpace == 0; } /// <summary> /// Remaps the Special Pages such as Home, Profile, Search /// to their localized versions /// </summary> /// <remarks> /// </remarks> public void MapLocalizedSpecialPages(int portalId, string cultureCode) { DataCache.ClearHostCache(true); DataProvider.Instance().EnsureLocalizationExists(portalId, cultureCode); PortalInfo defaultPortal = GetPortal(portalId, GetPortalDefaultLanguage(portalId)); PortalInfo targetPortal = GetPortal(portalId, cultureCode); Locale targetLocale = LocaleController.Instance.GetLocale(cultureCode); TabInfo tempTab; if (defaultPortal.HomeTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.HomeTabId, portalId, targetLocale); if (tempTab != null) { targetPortal.HomeTabId = tempTab.TabID; } } if (defaultPortal.LoginTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.LoginTabId, portalId, targetLocale); if (tempTab != null) { targetPortal.LoginTabId = tempTab.TabID; } } if (defaultPortal.RegisterTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.RegisterTabId, portalId, targetLocale); if (tempTab != null) { targetPortal.RegisterTabId = tempTab.TabID; } } if (defaultPortal.SplashTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.SplashTabId, portalId, targetLocale); if (tempTab != null) { targetPortal.SplashTabId = tempTab.TabID; } } if (defaultPortal.UserTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.UserTabId, portalId, targetLocale); if (tempTab != null) { targetPortal.UserTabId = tempTab.TabID; } } if (defaultPortal.SearchTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.SearchTabId, portalId, targetLocale); if (tempTab != null) { targetPortal.SearchTabId = tempTab.TabID; } } if (defaultPortal.Custom404TabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.Custom404TabId, portalId, targetLocale); if (tempTab != null) { targetPortal.Custom404TabId = tempTab.TabID; } } if (defaultPortal.Custom500TabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.Custom500TabId, portalId, targetLocale); if (tempTab != null) { targetPortal.Custom500TabId = tempTab.TabID; } } if (defaultPortal.TermsTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.TermsTabId, portalId, targetLocale); if (tempTab != null) { targetPortal.TermsTabId = tempTab.TabID; } } if (defaultPortal.PrivacyTabId != Null.NullInteger) { tempTab = TabController.Instance.GetTabByCulture(defaultPortal.PrivacyTabId, portalId, targetLocale); if (tempTab != null) { targetPortal.PrivacyTabId = tempTab.TabID; } } UpdatePortalInternal(targetPortal, false); } /// <summary> /// Removes the related PortalLocalization record from the database, adds optional clear cache /// </summary> /// <param name="portalId"></param> /// <param name="cultureCode"></param> /// <param name="clearCache"></param> public void RemovePortalLocalization(int portalId, string cultureCode, bool clearCache = true) { DataProvider.Instance().RemovePortalLocalization(portalId, cultureCode); if (clearCache) { DataCache.ClearPortalCache(portalId, false); } } /// <summary> /// Processess a template file for the new portal. /// </summary> /// <param name="portalId">PortalId of the new portal</param> /// <param name="template">The template</param> /// <param name="administratorId">UserId for the portal administrator. This is used to assign roles to this user</param> /// <param name="mergeTabs">Flag to determine whether Module content is merged.</param> /// <param name="isNewPortal">Flag to determine is the template is applied to an existing portal or a new one.</param> /// <remarks> /// The roles and settings nodes will only be processed on the portal template file. /// </remarks> public void ParseTemplate(int portalId, PortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { string templatePath, templateFile; PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal); } /// <summary> /// Processes the resource file for the template file selected /// </summary> /// <param name="portalPath">New portal's folder</param> /// <param name="resoureceFile">full path to the resource file</param> /// <remarks> /// The resource file is a zip file with the same name as the selected template file and with /// an extension of .resources (to disable this file being downloaded). /// For example: for template file "portal.template" a resource file "portal.template.resources" can be defined. /// </remarks> public void ProcessResourceFileExplicit(string portalPath, string resoureceFile) { try { FileSystemUtils.UnzipResources(new ZipInputStream(new FileStream(resoureceFile, FileMode.Open, FileAccess.Read)), portalPath); } catch (Exception exc) { Logger.Error(exc); } } /// <summary> /// Updates the portal expiry. /// </summary> /// <param name="portalId">The portal id.</param> /// <param name="cultureCode">The culture code.</param> public void UpdatePortalExpiry(int portalId, string cultureCode) { var portal = GetPortal(portalId, cultureCode); if (portal.ExpiryDate == Null.NullDate) { portal.ExpiryDate = DateTime.Now; } portal.ExpiryDate = portal.ExpiryDate.AddMonths(1); UpdatePortalInfo(portal); } /// <summary> /// Updates basic portal information /// </summary> /// <param name="portal"></param> public void UpdatePortalInfo(PortalInfo portal) { UpdatePortalInternal(portal, true); } [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] void IPortalController.UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode) { UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, false); } /// <summary> /// Adds or Updates or Deletes a portal setting value. /// </summary> void IPortalController.UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) { UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); } #endregion #region Public Static Methods /// <summary> /// Adds the portal dictionary. /// </summary> /// <param name="portalId">The portal id.</param> /// <param name="tabId">The tab id.</param> public static void AddPortalDictionary(int portalId, int tabId) { var portalDic = GetPortalDictionary(); portalDic[tabId] = portalId; DataCache.SetCache(DataCache.PortalDictionaryCacheKey, portalDic); } /// <summary> /// Creates the root folder for a child portal. /// </summary> /// <remarks> /// If call this method, it will create the specific folder if the folder doesn't exist; /// and will copy subhost.aspx to the folder if there is no 'Default.aspx'; /// </remarks> /// <param name="ChildPath">The child path.</param> /// <returns> /// If the method executed successful, it will return NullString, otherwise return error message. /// </returns> /// <example> /// <code lang="C#"> /// string childPhysicalPath = Server.MapPath(childPath); /// message = PortalController.CreateChildPortalFolder(childPhysicalPath); /// </code> /// </example> public static string CreateChildPortalFolder(string ChildPath) { string message = Null.NullString; //Set up Child Portal try { // create the subdirectory for the new portal if (!Directory.Exists(ChildPath)) { Directory.CreateDirectory(ChildPath); } // create the subhost default.aspx file if (!File.Exists(ChildPath + "\\" + Globals.glbDefaultPage)) { File.Copy(Globals.HostMapPath + "subhost.aspx", ChildPath + "\\" + Globals.glbDefaultPage); } } catch (Exception Exc) { Logger.Error(Exc); message += Localization.GetString("ChildPortal.Error") + Exc.Message + Exc.StackTrace; } return message; } /// <summary> /// Deletes all expired portals. /// </summary> /// <param name="serverPath">The server path.</param> public static void DeleteExpiredPortals(string serverPath) { foreach (PortalInfo portal in GetExpiredPortals()) { DeletePortal(portal, serverPath); } } /// <summary> /// Deletes the portal. /// </summary> /// <param name="portal">The portal.</param> /// <param name="serverPath">The server path.</param> /// <returns>If the method executed successful, it will return NullString, otherwise return error message.</returns> public static string DeletePortal(PortalInfo portal, string serverPath) { string message = string.Empty; //check if this is the last portal var portals = Instance.GetPortals(); if (portals.Count > 1) { if (portal != null) { //delete custom resource files Globals.DeleteFilesRecursive(serverPath, ".Portal-" + portal.PortalID + ".resx"); //If child portal delete child folder var arr = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); if (arr.Count > 0) { var portalAliasInfo = arr[0]; string portalName = Globals.GetPortalDomainName(portalAliasInfo.HTTPAlias, null, true); if (portalAliasInfo.HTTPAlias.IndexOf("/", StringComparison.Ordinal) > -1) { portalName = GetPortalFolder(portalAliasInfo.HTTPAlias); } if (!String.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) { DeletePortalFolder(serverPath, portalName); } } //delete upload directory if (!string.IsNullOrEmpty(portal.HomeDirectory)) { var homeDirectory = portal.HomeDirectoryMapPath; // check whether home directory is not used by other portal // it happens when new portal creation failed, but home directory defined by user is already in use with other portal var homeDirectoryInUse = portals.OfType<PortalInfo>().Any(x => x.PortalID != portal.PortalID && x.HomeDirectoryMapPath.Equals(homeDirectory, StringComparison.OrdinalIgnoreCase)); if (!homeDirectoryInUse) { if (Directory.Exists(homeDirectory)) { Globals.DeleteFolderRecursive(homeDirectory); } } } //remove database references DeletePortalInternal(portal.PortalID); } } else { message = Localization.GetString("LastPortal"); } return message; } /// <summary> /// Get the portal folder froma child portal alias. /// </summary> /// <param name="alias">portal alias.</param> /// <returns>folder path of the child portal.</returns> public static string GetPortalFolder(string alias) { alias = alias.ToLowerInvariant().Replace("http://", string.Empty).Replace("https://", string.Empty); var appPath = Globals.ApplicationPath + "/"; if (string.IsNullOrEmpty(Globals.ApplicationPath) || alias.IndexOf(appPath, StringComparison.InvariantCultureIgnoreCase) == Null.NullInteger) { return alias.Contains("/") ? alias.Substring(alias.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) + 1) : string.Empty; } return alias.Substring(alias.IndexOf(appPath, StringComparison.InvariantCultureIgnoreCase) + appPath.Length); } /// <summary>Delete the child portal folder and try to remove its parent when parent folder is empty.</summary> /// <param name="serverPath">the server path.</param> /// <param name="portalFolder">the child folder path.</param> public static void DeletePortalFolder(string serverPath, string portalFolder) { var physicalPath = serverPath + portalFolder; Globals.DeleteFolderRecursive(physicalPath); //remove parent folder if its empty. var parentFolder = Directory.GetParent(physicalPath); while (parentFolder != null && !parentFolder.FullName.Equals(serverPath.TrimEnd('\\'), StringComparison.InvariantCultureIgnoreCase)) { if (parentFolder.GetDirectories().Length + parentFolder.GetFiles().Length == 0) { parentFolder.Delete(); parentFolder = parentFolder.Parent; } else { break; } } } /// <summary> /// Gets the portal dictionary. /// </summary> /// <returns>portal dictionary. the dictionary's Key -> Value is: TabId -> PortalId.</returns> public static Dictionary<int, int> GetPortalDictionary() { string cacheKey = string.Format(DataCache.PortalDictionaryCacheKey); return CBO.GetCachedObject<Dictionary<int, int>>(new CacheItemArgs(cacheKey, DataCache.PortalDictionaryTimeOut, DataCache.PortalDictionaryCachePriority), GetPortalDictionaryCallback); } /// ----------------------------------------------------------------------------- /// <summary> /// GetPortalsByName gets all the portals whose name matches a provided filter expression /// </summary> /// <remarks> /// </remarks> /// <param name="nameToMatch">The email address to use to find a match.</param> /// <param name="pageIndex">The page of records to return.</param> /// <param name="pageSize">The size of the page</param> /// <param name="totalRecords">The total no of records that satisfy the criteria.</param> /// <returns>An ArrayList of PortalInfo objects.</returns> /// ----------------------------------------------------------------------------- public static ArrayList GetPortalsByName(string nameToMatch, int pageIndex, int pageSize, ref int totalRecords) { if (pageIndex == -1) { pageIndex = 0; pageSize = int.MaxValue; } Type type = typeof(PortalInfo); return CBO.FillCollection(DataProvider.Instance().GetPortalsByName(nameToMatch, pageIndex, pageSize), ref type, ref totalRecords); } public static ArrayList GetPortalsByUser(int userId) { Type type = typeof(PortalInfo); return CBO.FillCollection(DataProvider.Instance().GetPortalsByUser(userId), type); } public static int GetEffectivePortalId(int portalId) { if (portalId > Null.NullInteger && Globals.Status != Globals.UpgradeStatus.Upgrade) { var portal = Instance.GetPortal(portalId); var portalGroup = (from p in PortalGroupController.Instance.GetPortalGroups() where p.PortalGroupId == portal.PortalGroupID select p) .SingleOrDefault(); if (portalGroup != null) { portalId = portalGroup.MasterPortalId; } } return portalId; } /// <summary> /// Gets all expired portals. /// </summary> /// <returns>all expired portals as array list.</returns> public static ArrayList GetExpiredPortals() { return CBO.FillCollection(DataProvider.Instance().GetExpiredPortals(), typeof(PortalInfo)); } /// <summary> /// Determines whether the portal is child portal. /// </summary> /// <param name="portal">The portal.</param> /// <param name="serverPath">The server path.</param> /// <returns> /// <c>true</c> if the portal is child portal; otherwise, <c>false</c>. /// </returns> public static bool IsChildPortal(PortalInfo portal, string serverPath) { bool isChild = Null.NullBoolean; var arr = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); if (arr.Count > 0) { PortalAliasInfo portalAlias = arr[0]; var portalName = Globals.GetPortalDomainName(portalAlias.HTTPAlias, null, true); if (portalAlias.HTTPAlias.IndexOf("/") > -1) { portalName = GetPortalFolder(portalAlias.HTTPAlias); } if (!String.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) { isChild = true; } } return isChild; } public static bool IsMemberOfPortalGroup(int portalId) { var portal = Instance.GetPortal(portalId); return portal != null && portal.PortalGroupID > Null.NullInteger; } /// <summary> /// Deletes the portal setting (neutral and for all languages). /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="settingName">Name of the setting.</param> public static void DeletePortalSetting(int portalID, string settingName) { DeletePortalSetting(portalID, settingName, Null.NullString); } /// <summary> /// Deletes the portal setting in this language. /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="settingName">Name of the setting.</param> /// <param name="cultureCode">The culture code.</param> public static void DeletePortalSetting(int portalID, string settingName, string cultureCode) { DataProvider.Instance().DeletePortalSetting(portalID, settingName, cultureCode.ToLowerInvariant()); EventLogController.Instance.AddLog("SettingName", settingName + ((cultureCode == Null.NullString) ? String.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); DataCache.ClearHostCache(true); } /// <summary> /// Deletes all portal settings by portal id. /// </summary> /// <param name="portalID">The portal ID.</param> public static void DeletePortalSettings(int portalID) { DeletePortalSettings(portalID, Null.NullString); } /// <summary> /// Deletes all portal settings by portal id and for a given language (Null: all languages and neutral settings). /// </summary> /// <param name="portalID">The portal ID.</param> public static void DeletePortalSettings(int portalID, string cultureCode) { DataProvider.Instance().DeletePortalSettings(portalID, cultureCode); EventLogController.Instance.AddLog("PortalID", portalID.ToString() + ((cultureCode == Null.NullString) ? String.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); DataCache.ClearHostCache(true); } /// <summary> /// takes in a text value, decrypts it with a FIPS compliant algorithm and returns the value /// </summary> /// <param name="settingName">the setting to read</param> /// <param name="passPhrase">the pass phrase used for encryption/decryption</param> /// <returns></returns> public static string GetEncryptedString(string settingName, int portalID, string passPhrase) { Requires.NotNullOrEmpty("key", settingName); Requires.NotNullOrEmpty("passPhrase", passPhrase); var cipherText = GetPortalSetting(settingName, portalID, string.Empty); return Security.FIPSCompliant.DecryptAES(cipherText, passPhrase, Host.Host.GUID); } /// <summary> /// Gets the portal setting. /// </summary> /// <param name="settingName">Name of the setting.</param> /// <param name="portalID">The portal ID.</param> /// <param name="defaultValue">The default value.</param> /// <returns>Returns setting's value if portal contains the specific setting, otherwise return defaultValue.</returns> public static string GetPortalSetting(string settingName, int portalID, string defaultValue) { var retValue = Null.NullString; try { string setting; Instance.GetPortalSettings(portalID).TryGetValue(settingName, out setting); retValue = string.IsNullOrEmpty(setting) ? defaultValue : setting; } catch (Exception exc) { Logger.Error(exc); } return retValue; } /// <summary> /// Gets the portal setting for a specific language (or neutral). /// </summary> /// <param name="settingName">Name of the setting.</param> /// <param name="portalID">The portal ID.</param> /// <param name="defaultValue">The default value.</param> /// <param name="cultureCode">culture code of the language to retrieve (not empty)</param> /// <returns>Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue.</returns> public static string GetPortalSetting(string settingName, int portalID, string defaultValue, string cultureCode) { var retValue = Null.NullString; try { string setting; Instance.GetPortalSettings(portalID, cultureCode).TryGetValue(settingName, out setting); retValue = string.IsNullOrEmpty(setting) ? defaultValue : setting; } catch (Exception exc) { Logger.Error(exc); } return retValue; } /// <summary> /// Gets the portal setting as boolean. /// </summary> /// <param name="key">The key.</param> /// <param name="portalID">The portal ID.</param> /// <param name="defaultValue">default value.</param> /// <returns>Returns setting's value if portal contains the specific setting, otherwise return defaultValue.</returns> public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defaultValue) { bool retValue = Null.NullBoolean; try { string setting; Instance.GetPortalSettings(portalID).TryGetValue(key, out setting); if (string.IsNullOrEmpty(setting)) { retValue = defaultValue; } else { retValue = (setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)); } } catch (Exception exc) { Logger.Error(exc); } return retValue; } /// <summary> /// Gets the portal setting as boolean for a specific language (or neutral). /// </summary> /// <param name="key">The key.</param> /// <param name="portalID">The portal ID.</param> /// <param name="defaultValue">default value.</param> /// <param name="cultureCode">culture code of the language to retrieve (not empty)</param> /// <returns>Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue.</returns> public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defaultValue, string cultureCode) { bool retValue = Null.NullBoolean; try { string setting; GetPortalSettingsDictionary(portalID, cultureCode).TryGetValue(key, out setting); if (string.IsNullOrEmpty(setting)) { retValue = defaultValue; } else { retValue = (setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)); } } catch (Exception exc) { Logger.Error(exc); } return retValue; } /// <summary> /// Gets the portal setting as integer. /// </summary> /// <param name="key">The key.</param> /// <param name="portalID">The portal ID.</param> /// <param name="defaultValue">The default value.</param> /// <returns>Returns setting's value if portal contains the specific setting, otherwise return defaultValue.</returns> public static int GetPortalSettingAsInteger(string key, int portalID, int defaultValue) { int retValue = Null.NullInteger; try { string setting; Instance.GetPortalSettings(portalID).TryGetValue(key, out setting); if (string.IsNullOrEmpty(setting)) { retValue = defaultValue; } else { retValue = Convert.ToInt32(setting); } } catch (Exception exc) { Logger.Error(exc); } return retValue; } /// <summary> /// Gets the portal setting as double. /// </summary> /// <param name="key">The key.</param> /// <param name="portalId">The portal Id.</param> /// <param name="defaultValue">The default value.</param> /// <returns>Returns setting's value if portal contains the specific setting, otherwise return defaultValue.</returns> public static double GetPortalSettingAsDouble(string key, int portalId, double defaultValue) { double retValue = Null.NullDouble; try { string setting; Instance.GetPortalSettings(portalId).TryGetValue(key, out setting); if (string.IsNullOrEmpty(setting)) { retValue = defaultValue; } else { retValue = Convert.ToDouble(setting); } } catch (Exception exc) { Logger.Error(exc); } return retValue; } /// <summary> /// Gets the portal setting as integer for a specific language (or neutral). /// </summary> /// <param name="key">The key.</param> /// <param name="portalID">The portal ID.</param> /// <param name="defaultValue">The default value.</param> /// <param name="cultureCode">culture code of the language to retrieve (not empty)</param> /// <returns>Returns setting's value if portal contains the specific setting (for specified lang, otherwise return defaultValue.</returns> public static int GetPortalSettingAsInteger(string key, int portalID, int defaultValue, string cultureCode) { int retValue = Null.NullInteger; try { string setting; GetPortalSettingsDictionary(portalID, cultureCode).TryGetValue(key, out setting); if (string.IsNullOrEmpty(setting)) { retValue = defaultValue; } else { retValue = Convert.ToInt32(setting); } } catch (Exception exc) { Logger.Error(exc); } return retValue; } /// <summary> /// takes in a text value, encrypts it with a FIPS compliant algorithm and stores /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="settingName">host settings key</param> /// <param name="settingValue">host settings value</param> /// <param name="passPhrase">pass phrase to allow encryption/decryption</param> public static void UpdateEncryptedString(int portalID, string settingName, string settingValue, string passPhrase) { Requires.NotNullOrEmpty("key", settingName); Requires.PropertyNotNull("value", settingValue); Requires.NotNullOrEmpty("passPhrase", passPhrase); var cipherText = Security.FIPSCompliant.EncryptAES(settingValue, passPhrase, Host.Host.GUID); UpdatePortalSetting(portalID, settingName, cipherText); } /// <summary> /// Updates a single neutral (not language specific) portal setting and clears it from the cache. /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="settingName">Name of the setting.</param> /// <param name="settingValue">The setting value.</param> public static void UpdatePortalSetting(int portalID, string settingName, string settingValue) { UpdatePortalSetting(portalID, settingName, settingValue, true); } /// <summary> /// Updates a single neutral (not language specific) portal setting, optionally without clearing the cache. /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="settingName">Name of the setting.</param> /// <param name="settingValue">The setting value.</param> /// <param name="clearCache">if set to <c>true</c> [clear cache].</param> public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache) { UpdatePortalSetting(portalID, settingName, settingValue, clearCache, Null.NullString, false); } /// <summary> /// Updates a language specific or neutral portal setting and clears it from the cache. /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="settingName">Name of the setting.</param> /// <param name="settingValue">The setting value.</param> /// <param name="cultureCode">culture code for language specific settings, null string ontherwise.</param> [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, string cultureCode) { UpdatePortalSetting(portalID, settingName, settingValue, true, cultureCode, false); } /// <summary> /// Updates a language specific or neutral portal setting and optionally clears it from the cache. /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="settingName">Name of the setting.</param> /// <param name="settingValue">The setting value.</param> /// <param name="clearCache">if set to <c>true</c> [clear cache].</param> /// <param name="cultureCode">culture code for language specific settings, null string ontherwise.</param> public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode) { UpdatePortalSetting(portalID, settingName, settingValue, clearCache, cultureCode, false); } /// <summary> /// Updates a language specific or neutral portal setting and optionally clears it from the cache. /// All overloaded methors will not encrypt the setting value. Therefore, call this method whenever /// there is a need to encrypt the setting value before storing it in the datanbase. /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="settingName">Name of the setting.</param> /// <param name="settingValue">The setting value.</param> /// <param name="clearCache">if set to <c>true</c> [clear cache].</param> /// <param name="cultureCode">culture code for language specific settings, null string ontherwise.</param> /// <param name="isSecure">When true it encrypt the value before storing it in the database</param> public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) { Instance.UpdatePortalSetting(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); } /// <summary> /// Checks the desktop modules whether is installed. /// </summary> /// <param name="nav">The nav.</param> /// <returns>Empty string if the module hasn't been installed, otherwise return the frind name.</returns> public static string CheckDesktopModulesInstalled(XPathNavigator nav) { string friendlyName; DesktopModuleInfo desktopModule; StringBuilder modulesNotInstalled = new StringBuilder(); foreach (XPathNavigator desktopModuleNav in nav.Select("portalDesktopModule")) { friendlyName = XmlUtils.GetNodeValue(desktopModuleNav, "friendlyname"); if (!string.IsNullOrEmpty(friendlyName)) { desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); if (desktopModule == null) { //PE and EE templates have HTML as friendly name so check to make sure //there is really no HTML module installed if (friendlyName == "HTML") { desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName("HTML Pro"); if (desktopModule == null) { modulesNotInstalled.Append(friendlyName); modulesNotInstalled.Append("<br/>"); } } else { modulesNotInstalled.Append(friendlyName); modulesNotInstalled.Append("<br/>"); } } } } return modulesNotInstalled.ToString(); } /// <summary> /// function provides the language for portalinfo requests /// in case where language has not been installed yet, will return the core install default of en-us /// </summary> /// <param name = "portalID"></param> /// <returns></returns> /// <remarks> /// </remarks> public static string GetActivePortalLanguage(int portalID) { // get Language string Language = Localization.SystemLocale; string tmpLanguage = GetPortalDefaultLanguage(portalID); var isDefaultLanguage = false; if (!String.IsNullOrEmpty(tmpLanguage)) { Language = tmpLanguage; isDefaultLanguage = true; } //handles case where portalcontroller methods invoked before a language is installed if (portalID > Null.NullInteger && Globals.Status == Globals.UpgradeStatus.None && Localization.ActiveLanguagesByPortalID(portalID) == 1) { return Language; } if (HttpContext.Current != null && Globals.Status == Globals.UpgradeStatus.None) { if ((HttpContext.Current.Request.QueryString["language"] != null)) { Language = HttpContext.Current.Request.QueryString["language"]; } else { PortalSettings _PortalSettings = GetCurrentPortalSettingsInternal(); if (_PortalSettings != null && _PortalSettings.ActiveTab != null && !String.IsNullOrEmpty(_PortalSettings.ActiveTab.CultureCode)) { Language = _PortalSettings.ActiveTab.CultureCode; } else { //PortalSettings IS Nothing - probably means we haven't set it yet (in Begin Request) //so try detecting the user's cookie if (HttpContext.Current.Request["language"] != null) { Language = HttpContext.Current.Request["language"]; isDefaultLanguage = false; } //if no cookie - try detecting browser if ((String.IsNullOrEmpty(Language) || isDefaultLanguage) && EnableBrowserLanguageInDefault(portalID)) { CultureInfo Culture = Localization.GetBrowserCulture(portalID); if (Culture != null) { Language = Culture.Name; } } } } } return Language; } /// <summary> /// return the current DefaultLanguage value from the Portals table for the requested Portalid /// </summary> /// <param name = "portalID"></param> /// <returns></returns> /// <remarks> /// </remarks> public static string GetPortalDefaultLanguage(int portalID) { string cacheKey = String.Format("PortalDefaultLanguage_{0}", portalID); return CBO.GetCachedObject<string>(new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, portalID), GetPortalDefaultLanguageCallBack); } /// <summary> /// set the required DefaultLanguage in the Portals table for a particular portal /// saves having to update an entire PortalInfo object /// </summary> /// <param name = "portalID"></param> /// <param name = "CultureCode"></param> /// <remarks> /// </remarks> public static void UpdatePortalDefaultLanguage(int portalID, string CultureCode) { DataProvider.Instance().UpdatePortalDefaultLanguage(portalID, CultureCode); //ensure localization record exists as new portal default language may be relying on fallback chain //of which it is now the final part DataProvider.Instance().EnsureLocalizationExists(portalID, CultureCode); } public static void IncrementCrmVersion(int portalID) { int currentVersion; var versionSetting = GetPortalSetting(ClientResourceSettings.VersionKey, portalID, "1"); if (int.TryParse(versionSetting, out currentVersion)) { var newVersion = currentVersion + 1; UpdatePortalSetting(portalID, ClientResourceSettings.VersionKey, newVersion.ToString(CultureInfo.InvariantCulture), true); } } public static void IncrementOverridingPortalsCrmVersion() { foreach (PortalInfo portal in Instance.GetPortals()) { string setting = GetPortalSetting(ClientResourceSettings.OverrideDefaultSettingsKey, portal.PortalID, "False"); bool overriden; // if this portal is overriding the host level... if (bool.TryParse(setting, out overriden) && overriden) { // increment its version IncrementCrmVersion(portal.PortalID); } } } #endregion public class PortalTemplateInfo { private string _resourceFilePath; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalController)); public PortalTemplateInfo(string templateFilePath, string cultureCode) { TemplateFilePath = templateFilePath; InitLocalizationFields(cultureCode); InitNameAndDescription(); } private void InitNameAndDescription() { if (!String.IsNullOrEmpty(LanguageFilePath)) { LoadNameAndDescriptionFromLanguageFile(); } if (String.IsNullOrEmpty(Name)) { Name = Path.GetFileNameWithoutExtension(TemplateFilePath); } if (String.IsNullOrEmpty(Description)) { LoadDescriptionFromTemplateFile(); } } private void LoadDescriptionFromTemplateFile() { try { XDocument xmlDoc; using (var reader = PortalTemplateIO.Instance.OpenTextReader(TemplateFilePath)) { xmlDoc = XDocument.Load(reader); } Description = xmlDoc.Elements("portal").Elements("description").SingleOrDefault().Value; } catch (Exception e) { Logger.Error("Error while parsing: " + TemplateFilePath, e); } } private void LoadNameAndDescriptionFromLanguageFile() { try { using (var reader = PortalTemplateIO.Instance.OpenTextReader(LanguageFilePath)) { var xmlDoc = XDocument.Load(reader); Name = ReadLanguageFileValue(xmlDoc, "LocalizedTemplateName.Text"); Description = ReadLanguageFileValue(xmlDoc, "PortalDescription.Text"); } } catch (Exception e) { Logger.Error("Error while parsing: " + TemplateFilePath, e); } } static string ReadLanguageFileValue(XDocument xmlDoc, string name) { return (from f in xmlDoc.Descendants("data") where (string)f.Attribute("name") == name select (string)f.Element("value")).SingleOrDefault(); } private void InitLocalizationFields(string cultureCode) { LanguageFilePath = PortalTemplateIO.Instance.GetLanguageFilePath(TemplateFilePath, cultureCode); if (!String.IsNullOrEmpty(LanguageFilePath)) { CultureCode = cultureCode; } else { var portalSettings = PortalSettings.Current; //DNN-6544 portal creation requires valid culture, if template has no culture defined, then use default language. CultureCode = portalSettings != null ? GetPortalDefaultLanguage(portalSettings.PortalId) : Localization.SystemLocale; } } public string Name { get; private set; } public string CultureCode { get; private set; } public string TemplateFilePath { get; private set; } public string LanguageFilePath { get; private set; } public string Description { get; private set; } public string ResourceFilePath { get { if (_resourceFilePath == null) { _resourceFilePath = PortalTemplateIO.Instance.GetResourceFilePath(TemplateFilePath); } return _resourceFilePath; } } } } }
46.560297
303
0.534123
[ "MIT" ]
Persian-DnnSoftware/Dnn.Platform
DNN Platform/Library/Entities/Portals/PortalController.cs
169,110
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using Azure; using Management; using DataLake; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for FileSystemOperations. /// </summary> public static partial class FileSystemOperationsExtensions { /// <summary> /// Appends to the specified file, optionally first creating the file if it /// does not yet exist. This method supports multiple concurrent appends to the /// file. NOTE: The target must not contain data added by Create or normal /// (serial) Append. ConcurrentAppend and Append cannot be used /// interchangeably; once a target file has been modified using either of these /// append options, the other append option cannot be used on the target file. /// ConcurrentAppend does not guarantee order and can result in duplicated data /// landing in the target file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='filePath'> /// The Data Lake Store path (starting with '/') of the file to which to append /// using concurrent append. /// </param> /// <param name='streamContents'> /// The file contents to include when appending to the file. /// </param> /// <param name='appendMode'> /// Indicates the concurrent append call should create the file if it doesn't /// exist or just open the existing file for append. Possible values include: /// 'autocreate' /// </param> /// <param name='syncFlag'> /// Optionally indicates what to do after completion of the concurrent append. /// DATA indicates more data is coming so no sync takes place, METADATA /// indicates a sync should be done to refresh metadata of the file only. CLOSE /// indicates that both the stream and metadata should be refreshed upon append /// completion. Possible values include: 'DATA', 'METADATA', 'CLOSE' /// </param> public static void ConcurrentAppend(this IFileSystemOperations operations, string accountName, string filePath, Stream streamContents, AppendModeType? appendMode = default(AppendModeType?), SyncFlag? syncFlag = default(SyncFlag?)) { operations.ConcurrentAppendAsync(accountName, filePath, streamContents, appendMode, syncFlag).GetAwaiter().GetResult(); } /// <summary> /// Appends to the specified file, optionally first creating the file if it /// does not yet exist. This method supports multiple concurrent appends to the /// file. NOTE: The target must not contain data added by Create or normal /// (serial) Append. ConcurrentAppend and Append cannot be used /// interchangeably; once a target file has been modified using either of these /// append options, the other append option cannot be used on the target file. /// ConcurrentAppend does not guarantee order and can result in duplicated data /// landing in the target file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='filePath'> /// The Data Lake Store path (starting with '/') of the file to which to append /// using concurrent append. /// </param> /// <param name='streamContents'> /// The file contents to include when appending to the file. /// </param> /// <param name='appendMode'> /// Indicates the concurrent append call should create the file if it doesn't /// exist or just open the existing file for append. Possible values include: /// 'autocreate' /// </param> /// <param name='syncFlag'> /// Optionally indicates what to do after completion of the concurrent append. /// DATA indicates more data is coming so no sync takes place, METADATA /// indicates a sync should be done to refresh metadata of the file only. CLOSE /// indicates that both the stream and metadata should be refreshed upon append /// completion. Possible values include: 'DATA', 'METADATA', 'CLOSE' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ConcurrentAppendAsync(this IFileSystemOperations operations, string accountName, string filePath, Stream streamContents, AppendModeType? appendMode = default(AppendModeType?), SyncFlag? syncFlag = default(SyncFlag?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.ConcurrentAppendWithHttpMessagesAsync(accountName, filePath, streamContents, appendMode, syncFlag, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Sets or removes the expiration time on the specified file. This operation /// can only be executed against files. Folders are not supported. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='filePath'> /// The Data Lake Store path (starting with '/') of the file on which to set or /// remove the expiration time. /// </param> /// <param name='expiryOption'> /// Indicates the type of expiration to use for the file: 1. NeverExpire: /// ExpireTime is ignored. 2. RelativeToNow: ExpireTime is an integer in /// milliseconds representing the expiration date relative to when file /// expiration is updated. 3. RelativeToCreationDate: ExpireTime is an integer /// in milliseconds representing the expiration date relative to file creation. /// 4. Absolute: ExpireTime is an integer in milliseconds, as a Unix timestamp /// relative to 1/1/1970 00:00:00. Possible values include: 'NeverExpire', /// 'RelativeToNow', 'RelativeToCreationDate', 'Absolute' /// </param> /// <param name='expireTime'> /// The time that the file will expire, corresponding to the ExpiryOption that /// was set. /// </param> public static void SetFileExpiry(this IFileSystemOperations operations, string accountName, string filePath, ExpiryOptionType expiryOption, long? expireTime = default(long?)) { operations.SetFileExpiryAsync(accountName, filePath, expiryOption, expireTime).GetAwaiter().GetResult(); } /// <summary> /// Sets or removes the expiration time on the specified file. This operation /// can only be executed against files. Folders are not supported. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='filePath'> /// The Data Lake Store path (starting with '/') of the file on which to set or /// remove the expiration time. /// </param> /// <param name='expiryOption'> /// Indicates the type of expiration to use for the file: 1. NeverExpire: /// ExpireTime is ignored. 2. RelativeToNow: ExpireTime is an integer in /// milliseconds representing the expiration date relative to when file /// expiration is updated. 3. RelativeToCreationDate: ExpireTime is an integer /// in milliseconds representing the expiration date relative to file creation. /// 4. Absolute: ExpireTime is an integer in milliseconds, as a Unix timestamp /// relative to 1/1/1970 00:00:00. Possible values include: 'NeverExpire', /// 'RelativeToNow', 'RelativeToCreationDate', 'Absolute' /// </param> /// <param name='expireTime'> /// The time that the file will expire, corresponding to the ExpiryOption that /// was set. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task SetFileExpiryAsync(this IFileSystemOperations operations, string accountName, string filePath, ExpiryOptionType expiryOption, long? expireTime = default(long?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.SetFileExpiryWithHttpMessagesAsync(accountName, filePath, expiryOption, expireTime, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Checks if the specified access is available at the given path. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='path'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to check access. /// </param> /// <param name='fsaction'> /// File system operation read/write/execute in string form, matching regex /// pattern '[rwx-]{3}' /// </param> public static void CheckAccess(this IFileSystemOperations operations, string accountName, string path, string fsaction = default(string)) { operations.CheckAccessAsync(accountName, path, fsaction).GetAwaiter().GetResult(); } /// <summary> /// Checks if the specified access is available at the given path. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='path'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to check access. /// </param> /// <param name='fsaction'> /// File system operation read/write/execute in string form, matching regex /// pattern '[rwx-]{3}' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CheckAccessAsync(this IFileSystemOperations operations, string accountName, string path, string fsaction = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CheckAccessWithHttpMessagesAsync(accountName, path, fsaction, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates a directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='path'> /// The Data Lake Store path (starting with '/') of the directory to create. /// </param> public static FileOperationResult Mkdirs(this IFileSystemOperations operations, string accountName, string path) { return operations.MkdirsAsync(accountName, path).GetAwaiter().GetResult(); } /// <summary> /// Creates a directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='path'> /// The Data Lake Store path (starting with '/') of the directory to create. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FileOperationResult> MkdirsAsync(this IFileSystemOperations operations, string accountName, string path, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.MkdirsWithHttpMessagesAsync(accountName, path, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Concatenates the list of source files into the destination file, removing /// all source files upon success. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='destinationPath'> /// The Data Lake Store path (starting with '/') of the destination file /// resulting from the concatenation. /// </param> /// <param name='sources'> /// A list of comma seperated Data Lake Store paths (starting with '/') of the /// files to concatenate, in the order in which they should be concatenated. /// </param> public static void Concat(this IFileSystemOperations operations, string accountName, string destinationPath, IList<string> sources) { operations.ConcatAsync(accountName, destinationPath, sources).GetAwaiter().GetResult(); } /// <summary> /// Concatenates the list of source files into the destination file, removing /// all source files upon success. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='destinationPath'> /// The Data Lake Store path (starting with '/') of the destination file /// resulting from the concatenation. /// </param> /// <param name='sources'> /// A list of comma seperated Data Lake Store paths (starting with '/') of the /// files to concatenate, in the order in which they should be concatenated. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ConcatAsync(this IFileSystemOperations operations, string accountName, string destinationPath, IList<string> sources, CancellationToken cancellationToken = default(CancellationToken)) { await operations.ConcatWithHttpMessagesAsync(accountName, destinationPath, sources, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Concatenates the list of source files into the destination file, deleting /// all source files upon success. This method accepts more source file paths /// than the Concat method. This method and the parameters it accepts are /// subject to change for usability in an upcoming version. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='msConcatDestinationPath'> /// The Data Lake Store path (starting with '/') of the destination file /// resulting from the concatenation. /// </param> /// <param name='streamContents'> /// A list of Data Lake Store paths (starting with '/') of the source files. /// Must be a comma-separated path list in the format: /// sources=/file/path/1.txt,/file/path/2.txt,/file/path/lastfile.csv /// </param> /// <param name='deleteSourceDirectory'> /// Indicates that as an optimization instead of deleting each individual /// source stream, delete the source stream folder if all streams are in the /// same folder instead. This results in a substantial performance improvement /// when the only streams in the folder are part of the concatenation /// operation. WARNING: This includes the deletion of any other files that are /// not source files. Only set this to true when source files are the only /// files in the source directory. /// </param> public static void MsConcat(this IFileSystemOperations operations, string accountName, string msConcatDestinationPath, Stream streamContents, bool? deleteSourceDirectory = default(bool?)) { operations.MsConcatAsync(accountName, msConcatDestinationPath, streamContents, deleteSourceDirectory).GetAwaiter().GetResult(); } /// <summary> /// Concatenates the list of source files into the destination file, deleting /// all source files upon success. This method accepts more source file paths /// than the Concat method. This method and the parameters it accepts are /// subject to change for usability in an upcoming version. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='msConcatDestinationPath'> /// The Data Lake Store path (starting with '/') of the destination file /// resulting from the concatenation. /// </param> /// <param name='streamContents'> /// A list of Data Lake Store paths (starting with '/') of the source files. /// Must be a comma-separated path list in the format: /// sources=/file/path/1.txt,/file/path/2.txt,/file/path/lastfile.csv /// </param> /// <param name='deleteSourceDirectory'> /// Indicates that as an optimization instead of deleting each individual /// source stream, delete the source stream folder if all streams are in the /// same folder instead. This results in a substantial performance improvement /// when the only streams in the folder are part of the concatenation /// operation. WARNING: This includes the deletion of any other files that are /// not source files. Only set this to true when source files are the only /// files in the source directory. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task MsConcatAsync(this IFileSystemOperations operations, string accountName, string msConcatDestinationPath, Stream streamContents, bool? deleteSourceDirectory = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.MsConcatWithHttpMessagesAsync(accountName, msConcatDestinationPath, streamContents, deleteSourceDirectory, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get the list of file status objects specified by the file path, with /// optional pagination parameters /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='listFilePath'> /// The Data Lake Store path (starting with '/') of the directory to list. /// </param> /// <param name='listSize'> /// Gets or sets the number of items to return. Optional. /// </param> /// <param name='listAfter'> /// Gets or sets the item or lexographical index after which to begin returning /// results. For example, a file list of 'a','b','d' and listAfter='b' will /// return 'd', and a listAfter='c' will also return 'd'. Optional. /// </param> /// <param name='listBefore'> /// Gets or sets the item or lexographical index before which to begin /// returning results. For example, a file list of 'a','b','d' and /// listBefore='d' will return 'a','b', and a listBefore='c' will also return /// 'a','b'. Optional. /// </param> public static FileStatusesResult ListFileStatus(this IFileSystemOperations operations, string accountName, string listFilePath, int? listSize = default(int?), string listAfter = default(string), string listBefore = default(string)) { return operations.ListFileStatusAsync(accountName, listFilePath, listSize, listAfter, listBefore).GetAwaiter().GetResult(); } /// <summary> /// Get the list of file status objects specified by the file path, with /// optional pagination parameters /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='listFilePath'> /// The Data Lake Store path (starting with '/') of the directory to list. /// </param> /// <param name='listSize'> /// Gets or sets the number of items to return. Optional. /// </param> /// <param name='listAfter'> /// Gets or sets the item or lexographical index after which to begin returning /// results. For example, a file list of 'a','b','d' and listAfter='b' will /// return 'd', and a listAfter='c' will also return 'd'. Optional. /// </param> /// <param name='listBefore'> /// Gets or sets the item or lexographical index before which to begin /// returning results. For example, a file list of 'a','b','d' and /// listBefore='d' will return 'a','b', and a listBefore='c' will also return /// 'a','b'. Optional. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FileStatusesResult> ListFileStatusAsync(this IFileSystemOperations operations, string accountName, string listFilePath, int? listSize = default(int?), string listAfter = default(string), string listBefore = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListFileStatusWithHttpMessagesAsync(accountName, listFilePath, listSize, listAfter, listBefore, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the file content summary object specified by the file path. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='getContentSummaryFilePath'> /// The Data Lake Store path (starting with '/') of the file for which to /// retrieve the summary. /// </param> public static ContentSummaryResult GetContentSummary(this IFileSystemOperations operations, string accountName, string getContentSummaryFilePath) { return operations.GetContentSummaryAsync(accountName, getContentSummaryFilePath).GetAwaiter().GetResult(); } /// <summary> /// Gets the file content summary object specified by the file path. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='getContentSummaryFilePath'> /// The Data Lake Store path (starting with '/') of the file for which to /// retrieve the summary. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ContentSummaryResult> GetContentSummaryAsync(this IFileSystemOperations operations, string accountName, string getContentSummaryFilePath, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetContentSummaryWithHttpMessagesAsync(accountName, getContentSummaryFilePath, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get the file status object specified by the file path. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='getFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to retrieve the status. /// </param> public static FileStatusResult GetFileStatus(this IFileSystemOperations operations, string accountName, string getFilePath) { return operations.GetFileStatusAsync(accountName, getFilePath).GetAwaiter().GetResult(); } /// <summary> /// Get the file status object specified by the file path. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='getFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to retrieve the status. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FileStatusResult> GetFileStatusAsync(this IFileSystemOperations operations, string accountName, string getFilePath, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetFileStatusWithHttpMessagesAsync(accountName, getFilePath, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Appends to the specified file. NOTE: The target must not contain data added /// by ConcurrentAppend. ConcurrentAppend and Append cannot be used /// interchangeably; once a target file has been modified using either of these /// append options, the other append option cannot be used on the target file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='directFilePath'> /// The Data Lake Store path (starting with '/') of the file to which to /// append. /// </param> /// <param name='streamContents'> /// The file contents to include when appending to the file. /// </param> /// <param name='offset'> /// The optional offset in the stream to begin the append operation. Default is /// to append at the end of the stream. /// </param> /// <param name='syncFlag'> /// Optionally indicates what to do after completion of the append. DATA /// indicates more data is coming so no sync takes place, METADATA indicates a /// sync should be done to refresh metadata of the file only. CLOSE indicates /// that both the stream and metadata should be refreshed upon append /// completion. Possible values include: 'DATA', 'METADATA', 'CLOSE' /// </param> public static void Append(this IFileSystemOperations operations, string accountName, string directFilePath, Stream streamContents, long? offset = default(long?), SyncFlag? syncFlag = default(SyncFlag?)) { operations.AppendAsync(accountName, directFilePath, streamContents, offset, syncFlag).GetAwaiter().GetResult(); } /// <summary> /// Appends to the specified file. NOTE: The target must not contain data added /// by ConcurrentAppend. ConcurrentAppend and Append cannot be used /// interchangeably; once a target file has been modified using either of these /// append options, the other append option cannot be used on the target file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='directFilePath'> /// The Data Lake Store path (starting with '/') of the file to which to /// append. /// </param> /// <param name='streamContents'> /// The file contents to include when appending to the file. /// </param> /// <param name='offset'> /// The optional offset in the stream to begin the append operation. Default is /// to append at the end of the stream. /// </param> /// <param name='syncFlag'> /// Optionally indicates what to do after completion of the append. DATA /// indicates more data is coming so no sync takes place, METADATA indicates a /// sync should be done to refresh metadata of the file only. CLOSE indicates /// that both the stream and metadata should be refreshed upon append /// completion. Possible values include: 'DATA', 'METADATA', 'CLOSE' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AppendAsync(this IFileSystemOperations operations, string accountName, string directFilePath, Stream streamContents, long? offset = default(long?), SyncFlag? syncFlag = default(SyncFlag?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.AppendWithHttpMessagesAsync(accountName, directFilePath, streamContents, offset, syncFlag, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates a file with optionally specified content. NOTE: If content is /// provided, the resulting file cannot be modified using ConcurrentAppend. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='directFilePath'> /// The Data Lake Store path (starting with '/') of the file to create. /// </param> /// <param name='streamContents'> /// The file contents to include when creating the file. This parameter is /// optional, resulting in an empty file if not specified. /// </param> /// <param name='overwrite'> /// The indication of if the file should be overwritten. /// </param> /// <param name='syncFlag'> /// Optionally indicates what to do after completion of the append. DATA /// indicates more data is coming so no sync takes place, METADATA indicates a /// sync should be done to refresh metadata of the file only. CLOSE indicates /// that both the stream and metadata should be refreshed upon append /// completion. Possible values include: 'DATA', 'METADATA', 'CLOSE' /// </param> public static void Create(this IFileSystemOperations operations, string accountName, string directFilePath, Stream streamContents = default(Stream), bool? overwrite = default(bool?), SyncFlag? syncFlag = default(SyncFlag?)) { operations.CreateAsync(accountName, directFilePath, streamContents, overwrite, syncFlag).GetAwaiter().GetResult(); } /// <summary> /// Creates a file with optionally specified content. NOTE: If content is /// provided, the resulting file cannot be modified using ConcurrentAppend. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='directFilePath'> /// The Data Lake Store path (starting with '/') of the file to create. /// </param> /// <param name='streamContents'> /// The file contents to include when creating the file. This parameter is /// optional, resulting in an empty file if not specified. /// </param> /// <param name='overwrite'> /// The indication of if the file should be overwritten. /// </param> /// <param name='syncFlag'> /// Optionally indicates what to do after completion of the append. DATA /// indicates more data is coming so no sync takes place, METADATA indicates a /// sync should be done to refresh metadata of the file only. CLOSE indicates /// that both the stream and metadata should be refreshed upon append /// completion. Possible values include: 'DATA', 'METADATA', 'CLOSE' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateAsync(this IFileSystemOperations operations, string accountName, string directFilePath, Stream streamContents = default(Stream), bool? overwrite = default(bool?), SyncFlag? syncFlag = default(SyncFlag?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateWithHttpMessagesAsync(accountName, directFilePath, streamContents, overwrite, syncFlag, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Opens and reads from the specified file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='directFilePath'> /// The Data Lake Store path (starting with '/') of the file to open. /// </param> /// <param name='length'> /// The number of bytes that the server will attempt to retrieve. It will /// retrieve &lt;= length bytes. /// </param> /// <param name='offset'> /// The byte offset to start reading data from. /// </param> public static Stream Open(this IFileSystemOperations operations, string accountName, string directFilePath, long? length = default(long?), long? offset = default(long?)) { return operations.OpenAsync(accountName, directFilePath, length, offset).GetAwaiter().GetResult(); } /// <summary> /// Opens and reads from the specified file. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='directFilePath'> /// The Data Lake Store path (starting with '/') of the file to open. /// </param> /// <param name='length'> /// The number of bytes that the server will attempt to retrieve. It will /// retrieve &lt;= length bytes. /// </param> /// <param name='offset'> /// The byte offset to start reading data from. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Stream> OpenAsync(this IFileSystemOperations operations, string accountName, string directFilePath, long? length = default(long?), long? offset = default(long?), CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.OpenWithHttpMessagesAsync(accountName, directFilePath, length, offset, null, cancellationToken).ConfigureAwait(false); _result.Request.Dispose(); return _result.Body; } /// <summary> /// Sets the Access Control List (ACL) for a file or folder. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='setAclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory on /// which to set the ACL. /// </param> /// <param name='aclspec'> /// The ACL spec included in ACL creation operations in the format /// '[default:]user|group|other::r|-w|-x|-' /// </param> public static void SetAcl(this IFileSystemOperations operations, string accountName, string setAclFilePath, string aclspec) { operations.SetAclAsync(accountName, setAclFilePath, aclspec).GetAwaiter().GetResult(); } /// <summary> /// Sets the Access Control List (ACL) for a file or folder. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='setAclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory on /// which to set the ACL. /// </param> /// <param name='aclspec'> /// The ACL spec included in ACL creation operations in the format /// '[default:]user|group|other::r|-w|-x|-' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task SetAclAsync(this IFileSystemOperations operations, string accountName, string setAclFilePath, string aclspec, CancellationToken cancellationToken = default(CancellationToken)) { await operations.SetAclWithHttpMessagesAsync(accountName, setAclFilePath, aclspec, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Modifies existing Access Control List (ACL) entries on a file or folder. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='modifyAclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory with /// the ACL being modified. /// </param> /// <param name='aclspec'> /// The ACL specification included in ACL modification operations in the format /// '[default:]user|group|other::r|-w|-x|-' /// </param> public static void ModifyAclEntries(this IFileSystemOperations operations, string accountName, string modifyAclFilePath, string aclspec) { operations.ModifyAclEntriesAsync(accountName, modifyAclFilePath, aclspec).GetAwaiter().GetResult(); } /// <summary> /// Modifies existing Access Control List (ACL) entries on a file or folder. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='modifyAclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory with /// the ACL being modified. /// </param> /// <param name='aclspec'> /// The ACL specification included in ACL modification operations in the format /// '[default:]user|group|other::r|-w|-x|-' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ModifyAclEntriesAsync(this IFileSystemOperations operations, string accountName, string modifyAclFilePath, string aclspec, CancellationToken cancellationToken = default(CancellationToken)) { await operations.ModifyAclEntriesWithHttpMessagesAsync(accountName, modifyAclFilePath, aclspec, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Removes existing Access Control List (ACL) entries for a file or folder. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='removeAclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory with /// the ACL being removed. /// </param> /// <param name='aclspec'> /// The ACL spec included in ACL removal operations in the format /// '[default:]user|group|other' /// </param> public static void RemoveAclEntries(this IFileSystemOperations operations, string accountName, string removeAclFilePath, string aclspec) { operations.RemoveAclEntriesAsync(accountName, removeAclFilePath, aclspec).GetAwaiter().GetResult(); } /// <summary> /// Removes existing Access Control List (ACL) entries for a file or folder. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='removeAclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory with /// the ACL being removed. /// </param> /// <param name='aclspec'> /// The ACL spec included in ACL removal operations in the format /// '[default:]user|group|other' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task RemoveAclEntriesAsync(this IFileSystemOperations operations, string accountName, string removeAclFilePath, string aclspec, CancellationToken cancellationToken = default(CancellationToken)) { await operations.RemoveAclEntriesWithHttpMessagesAsync(accountName, removeAclFilePath, aclspec, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Removes the existing Default Access Control List (ACL) of the specified /// directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='defaultAclFilePath'> /// The Data Lake Store path (starting with '/') of the directory with the /// default ACL being removed. /// </param> public static void RemoveDefaultAcl(this IFileSystemOperations operations, string accountName, string defaultAclFilePath) { operations.RemoveDefaultAclAsync(accountName, defaultAclFilePath).GetAwaiter().GetResult(); } /// <summary> /// Removes the existing Default Access Control List (ACL) of the specified /// directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='defaultAclFilePath'> /// The Data Lake Store path (starting with '/') of the directory with the /// default ACL being removed. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task RemoveDefaultAclAsync(this IFileSystemOperations operations, string accountName, string defaultAclFilePath, CancellationToken cancellationToken = default(CancellationToken)) { await operations.RemoveDefaultAclWithHttpMessagesAsync(accountName, defaultAclFilePath, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Removes the existing Access Control List (ACL) of the specified file or /// directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='aclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory with /// the ACL being removed. /// </param> public static void RemoveAcl(this IFileSystemOperations operations, string accountName, string aclFilePath) { operations.RemoveAclAsync(accountName, aclFilePath).GetAwaiter().GetResult(); } /// <summary> /// Removes the existing Access Control List (ACL) of the specified file or /// directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='aclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory with /// the ACL being removed. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task RemoveAclAsync(this IFileSystemOperations operations, string accountName, string aclFilePath, CancellationToken cancellationToken = default(CancellationToken)) { await operations.RemoveAclWithHttpMessagesAsync(accountName, aclFilePath, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets Access Control List (ACL) entries for the specified file or directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='aclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to get the ACL. /// </param> public static AclStatusResult GetAclStatus(this IFileSystemOperations operations, string accountName, string aclFilePath) { return operations.GetAclStatusAsync(accountName, aclFilePath).GetAwaiter().GetResult(); } /// <summary> /// Gets Access Control List (ACL) entries for the specified file or directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='aclFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to get the ACL. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AclStatusResult> GetAclStatusAsync(this IFileSystemOperations operations, string accountName, string aclFilePath, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAclStatusWithHttpMessagesAsync(accountName, aclFilePath, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the requested file or directory, optionally recursively. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='filePath'> /// The Data Lake Store path (starting with '/') of the file or directory to /// delete. /// </param> /// <param name='recursive'> /// The optional switch indicating if the delete should be recursive /// </param> public static FileOperationResult Delete(this IFileSystemOperations operations, string accountName, string filePath, bool? recursive = default(bool?)) { return operations.DeleteAsync(accountName, filePath, recursive).GetAwaiter().GetResult(); } /// <summary> /// Deletes the requested file or directory, optionally recursively. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='filePath'> /// The Data Lake Store path (starting with '/') of the file or directory to /// delete. /// </param> /// <param name='recursive'> /// The optional switch indicating if the delete should be recursive /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FileOperationResult> DeleteAsync(this IFileSystemOperations operations, string accountName, string filePath, bool? recursive = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(accountName, filePath, recursive, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Rename a file or directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='renameFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory to /// move/rename. /// </param> /// <param name='destination'> /// The path to move/rename the file or folder to /// </param> public static FileOperationResult Rename(this IFileSystemOperations operations, string accountName, string renameFilePath, string destination) { return operations.RenameAsync(accountName, renameFilePath, destination).GetAwaiter().GetResult(); } /// <summary> /// Rename a file or directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='renameFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory to /// move/rename. /// </param> /// <param name='destination'> /// The path to move/rename the file or folder to /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FileOperationResult> RenameAsync(this IFileSystemOperations operations, string accountName, string renameFilePath, string destination, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RenameWithHttpMessagesAsync(accountName, renameFilePath, destination, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Sets the owner of a file or directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='setOwnerFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to set the owner. /// </param> /// <param name='owner'> /// The AAD Object ID of the user owner of the file or directory. If empty, the /// property will remain unchanged. /// </param> /// <param name='group'> /// The AAD Object ID of the group owner of the file or directory. If empty, /// the property will remain unchanged. /// </param> public static void SetOwner(this IFileSystemOperations operations, string accountName, string setOwnerFilePath, string owner = default(string), string group = default(string)) { operations.SetOwnerAsync(accountName, setOwnerFilePath, owner, group).GetAwaiter().GetResult(); } /// <summary> /// Sets the owner of a file or directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='setOwnerFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to set the owner. /// </param> /// <param name='owner'> /// The AAD Object ID of the user owner of the file or directory. If empty, the /// property will remain unchanged. /// </param> /// <param name='group'> /// The AAD Object ID of the group owner of the file or directory. If empty, /// the property will remain unchanged. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task SetOwnerAsync(this IFileSystemOperations operations, string accountName, string setOwnerFilePath, string owner = default(string), string group = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.SetOwnerWithHttpMessagesAsync(accountName, setOwnerFilePath, owner, group, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Sets the permission of the file or folder. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='setPermissionFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to set the permission. /// </param> /// <param name='permission'> /// A string representation of the permission (i.e 'rwx'). If empty, this /// property remains unchanged. /// </param> public static void SetPermission(this IFileSystemOperations operations, string accountName, string setPermissionFilePath, string permission = default(string)) { operations.SetPermissionAsync(accountName, setPermissionFilePath, permission).GetAwaiter().GetResult(); } /// <summary> /// Sets the permission of the file or folder. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The Azure Data Lake Store account to execute filesystem operations on. /// </param> /// <param name='setPermissionFilePath'> /// The Data Lake Store path (starting with '/') of the file or directory for /// which to set the permission. /// </param> /// <param name='permission'> /// A string representation of the permission (i.e 'rwx'). If empty, this /// property remains unchanged. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task SetPermissionAsync(this IFileSystemOperations operations, string accountName, string setPermissionFilePath, string permission = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.SetPermissionWithHttpMessagesAsync(accountName, setPermissionFilePath, permission, null, cancellationToken).ConfigureAwait(false); } } }
54.235441
326
0.579006
[ "MIT" ]
dnelly/azure-sdk-for-net
src/ResourceManagement/DataLake.Store/Microsoft.Azure.Management.DataLake.Store/Generated/FileSystemOperationsExtensions.cs
65,193
C#
using Orchestra.Networking.Rtmp.Serialization; namespace Orchestra.Networking.Rtmp.Messages.Commands { [RtmpCommand(Name = "receiveAudio")] public class ReceiveAudioCommandMessage : CommandMessage { [OptionalArgument] public bool IsReceive { get; set; } public ReceiveAudioCommandMessage(AmfEncodingVersion encoding) : base(encoding) { } } }
25.0625
87
0.693267
[ "MIT" ]
CloudConstruct/Orchestra
Orchestra/Networking/Rtmp/Messages/Commands/ReceiveAudioCommandMessage.cs
403
C#
/* * eZmax API Definition (Full) * * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.7 * Contact: support-api@ezmax.ca * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = eZmaxApi.Client.OpenAPIDateConverter; namespace eZmaxApi.Model { /// <summary> /// Request for PUT /1/object/ezsigntemplate/{pkiEzsigntemplateID} /// </summary> [DataContract(Name = "ezsigntemplate-editObject-v1-Request")] public partial class EzsigntemplateEditObjectV1Request : IEquatable<EzsigntemplateEditObjectV1Request>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="EzsigntemplateEditObjectV1Request" /> class. /// </summary> [JsonConstructorAttribute] protected EzsigntemplateEditObjectV1Request() { } /// <summary> /// Initializes a new instance of the <see cref="EzsigntemplateEditObjectV1Request" /> class. /// </summary> /// <param name="objEzsigntemplate">objEzsigntemplate (required).</param> public EzsigntemplateEditObjectV1Request(EzsigntemplateRequestCompound objEzsigntemplate = default(EzsigntemplateRequestCompound)) { // to ensure "objEzsigntemplate" is required (not null) if (objEzsigntemplate == null) { throw new ArgumentNullException("objEzsigntemplate is a required property for EzsigntemplateEditObjectV1Request and cannot be null"); } this.ObjEzsigntemplate = objEzsigntemplate; } /// <summary> /// Gets or Sets ObjEzsigntemplate /// </summary> [DataMember(Name = "objEzsigntemplate", IsRequired = true, EmitDefaultValue = false)] public EzsigntemplateRequestCompound ObjEzsigntemplate { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class EzsigntemplateEditObjectV1Request {\n"); sb.Append(" ObjEzsigntemplate: ").Append(ObjEzsigntemplate).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 Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.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 EzsigntemplateEditObjectV1Request); } /// <summary> /// Returns true if EzsigntemplateEditObjectV1Request instances are equal /// </summary> /// <param name="input">Instance of EzsigntemplateEditObjectV1Request to be compared</param> /// <returns>Boolean</returns> public bool Equals(EzsigntemplateEditObjectV1Request input) { if (input == null) { return false; } return ( this.ObjEzsigntemplate == input.ObjEzsigntemplate || (this.ObjEzsigntemplate != null && this.ObjEzsigntemplate.Equals(input.ObjEzsigntemplate)) ); } /// <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.ObjEzsigntemplate != null) { hashCode = (hashCode * 59) + this.ObjEzsigntemplate.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
36.335714
149
0.617653
[ "MIT" ]
ezmaxinc/eZmax-SDK-csharp-netcore
src/eZmaxApi/Model/EzsigntemplateEditObjectV1Request.cs
5,087
C#
using BTCPayServer.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BTCPayServer.Data { public class InvoiceData { public string StoreDataId { get; set; } public StoreData StoreData { get; set; } public string Id { get; set; } public DateTimeOffset Created { get; set; } public List<PaymentData> Payments { get; set; } public List<InvoiceEventData> Events { get; set; } public List<RefundAddressesData> RefundAddresses { get; set; } public List<HistoricalAddressInvoiceData> HistoricalAddressInvoices { get; set; } public byte[] Blob { get; set; } public string ItemCode { get; set; } public string OrderId { get; set; } public string Status { get; set; } public string ExceptionStatus { get; set; } public string CustomerEmail { get; set; } public List<AddressInvoiceData> AddressInvoices { get; set; } public List<PendingInvoiceData> PendingInvoices { get; set; } public Services.Invoices.InvoiceState GetInvoiceState() { return new Services.Invoices.InvoiceState(Status, ExceptionStatus); } } }
19.010989
79
0.472832
[ "MIT" ]
2pac1/btcpayserver
BTCPayServer/Data/InvoiceData.cs
1,732
C#
namespace Stripe { using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; /// <summary> /// Source objects allow you to accept a variety of payment methods. They represent a customer's payment instrument and can be used with the Source API just like a card object: once chargeable, they can be charged, or attached to customers. /// </summary> public class Source : StripeEntity<Source>, IHasId, IHasMetadata, IHasObject, IPaymentSource { /// <summary> /// Unique identifier for the object. /// </summary> [JsonProperty("id")] public string Id { get; set; } /// <summary> /// String representing the object's type. Objects of the same type share the same value. /// </summary> [JsonProperty("object")] public string Object { get; set; } [JsonProperty("ach_credit_transfer")] public SourceAchCreditTransfer AchCreditTransfer { get; set; } [JsonProperty("ach_debit")] public SourceAchDebit AchDebit { get; set; } [JsonProperty("acss_debit")] public SourceAcssDebit AcssDebit { get; set; } [JsonProperty("alipay")] public SourceAlipay Alipay { get; set; } /// <summary> /// Amount associated with the source. This is the amount for which the source will be chargeable once ready. Required for single-use sources. /// </summary> [JsonProperty("amount")] public long? Amount { get; set; } [JsonProperty("au_becs_debit")] public SourceAuBecsDebit AuBecsDebit { get; set; } [JsonProperty("bancontact")] public SourceBancontact Bancontact { get; set; } [JsonProperty("bitcoin")] public SourceBitcoin Bitcoin { get; set; } [JsonProperty("card")] public SourceCard Card { get; set; } [JsonProperty("card_present")] public SourceCardPresent CardPresent { get; set; } /// <summary> /// The client secret of the source. Used for client-side polling using a publishable key. /// </summary> [JsonProperty("client_secret")] public string ClientSecret { get; set; } /// <summary> /// Information related to the code verification flow. Present if the source is authenticated by a verification code (flow is code_verification). /// </summary> [JsonProperty("code_verification")] public SourceCodeVerification CodeVerification { get; set; } [JsonProperty("created")] [JsonConverter(typeof(DateTimeConverter))] public DateTime Created { get; set; } /// <summary> /// The currency associated with the source. This is the currency for which the source will be chargeable once ready. Required for single-use sources. /// </summary> [JsonProperty("currency")] public string Currency { get; set; } /// <summary> /// The customer to which the source is attached, if any. /// </summary> [JsonProperty("customer")] public string Customer { get; set; } [JsonProperty("eps")] public SourceEps Eps { get; set; } /// <summary> /// The authentication flow of the source. Flow is one of redirect, receiver, code_verification, none. /// </summary> [JsonProperty("flow")] public string Flow { get; set; } [JsonProperty("giropay")] public SourceGiropay Giropay { get; set; } [JsonProperty("ideal")] public SourceIdeal Ideal { get; set; } [JsonProperty("klarna")] public SourceKlarna Klarna { get; set; } /// <summary> /// Has the value <c>true</c> if the object exists in live mode or the value /// <c>false</c> if the object exists in test mode. /// </summary> [JsonProperty("livemode")] public bool Livemode { get; set; } /// <summary> /// A set of key/value pairs that you can attach to an order object. It can be useful for /// storing additional information about the order in a structured format. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } [JsonProperty("multibanco")] public SourceMultibanco Multibanco { get; set; } /// <summary> /// Information about the owner of the payment instrument that may be used or required by particular source types. /// </summary> [JsonProperty("owner")] public SourceOwner Owner { get; set; } [JsonProperty("p24")] public SourceP24 P24 { get; set; } /// <summary> /// Information related to the receiver flow. Present if the source is a receiver (flow is receiver). /// </summary> [JsonProperty("receiver")] public SourceReceiver Receiver { get; set; } /// <summary> /// Information related to the redirect flow. Present if the source is authenticated by a redirect (flow is redirect). /// </summary> [JsonProperty("redirect")] public SourceRedirect Redirect { get; set; } [JsonProperty("sepa_credit_transfer")] public SourceSepaCreditTransfer SepaCreditTransfer { get; set; } [JsonProperty("sepa_debit")] public SourceSepaDebit SepaDebit { get; set; } [JsonProperty("sofort")] public SourceSofort Sofort { get; set; } /// <summary> /// Information about the items and shipping associated with the source. /// Required for transactional credit (for example Klarna) sources /// before you can charge it. /// </summary> [JsonProperty("source_order")] public SourceSourceOrder SourceOrder { get; set; } /// <summary> /// Extra information about a source. This will appear on your customer's statement every time you charge the source. /// </summary> [JsonProperty("statement_descriptor")] public string StatementDescriptor { get; set; } /// <summary> /// The status of the charge, one of canceled, chargeable, consumed, failed, or pending. Only chargeable source objects can be used to create a charge. /// </summary> [JsonProperty("status")] public string Status { get; set; } [JsonProperty("three_d_secure")] public SourceThreeDSecure ThreeDSecure { get; set; } /// <summary> /// The type of the source. The type is a payment method, one of card, three_d_secure, giropay, sepa_debit, ideal, klarna, sofort, or bancontact. /// </summary> [JsonProperty("type")] public string Type { get; set; } /// <summary> /// One of reusable, single-use. Whether this source should be reusable or not. Some source types may or may not be reusable by construction, while other may leave the option at creation. If an incompatible value is passed, an error will be returned. /// </summary> [JsonProperty("usage")] public string Usage { get; set; } [JsonProperty("wechat")] public SourceWechat Wechat { get; set; } } }
38.294737
258
0.616822
[ "Apache-2.0" ]
PaitoAnderson/stripe-dotnet
src/Stripe.net/Entities/Sources/Source.cs
7,276
C#
namespace BumblesBikesLibrary.BicycleComponents; public interface IBicycleComponent { public string Name { get; set; } public float Weight { get; set; } public float Cost { get; set; } }
25
49
0.715
[ "MIT" ]
Kpackt/Real-World-Implementation-of-C-Design-Patterns
chapter-3/BumbleBikesLibrary/BicycleComponents/IBicycleComponent.cs
202
C#
using Alex.API.Utils; using Alex.Networking.Java.Packets.Play; using Alex.Worlds; using NLog; namespace Alex.Entities.Passive { public class Sheep : PassiveMob { private static readonly Logger Log = LogManager.GetCurrentClassLogger(typeof(Sheep)); private static readonly DyeColor[] SheepColors = new DyeColor[] { DyeColor.WhiteDye, DyeColor.OrangeDye, DyeColor.MagentaDye, DyeColor.LightBlueDye, DyeColor.YellowDye, DyeColor.LimeDye, DyeColor.PinkDye, DyeColor.GrayDye, DyeColor.LightGrayDye, DyeColor.CyanDye, DyeColor.PurpleDye, DyeColor.BlueDye, DyeColor.BrownDye, DyeColor.GreenDye, DyeColor.RedDye, DyeColor.BlackDye }; private DyeColor _color = DyeColor.WhiteDye; public DyeColor Color { get { return _color; } set { _color = value; ModelRenderer.EntityColor = value.Color.ToVector3(); } } public Sheep(World level) : base((EntityType)13, level) { Height = 1.3; Width = 0.9; } protected override void HandleJavaMeta(MetaDataEntry entry) { base.HandleJavaMeta(entry); if (entry.Index == 16 && entry is MetadataByte meta) { SetSheared((meta.Value & 0x10) != 0); SetColor(meta.Value & 0x0F); } } public void SetColor(int value) { if (value < 0 || value > 19) { Log.Warn($"Invalid sheep color: {value}"); return; } Color = SheepColors[value % SheepColors.Length]; } public void SetSheared(bool value) { TryUpdateGeometry("minecraft:sheep", value ? "sheared" : "default"); IsSheared = value; } } }
19.654321
87
0.668342
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
lvyitian1/Alex
src/Alex/Entities/Passive/Sheep.cs
1,592
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Azure.MSSql { /// <summary> /// Manages a Database Vulnerability Assessment Rule Baseline. /// /// &gt; **NOTE** Database Vulnerability Assessment is currently only available for MS SQL databases. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Azure = Pulumi.Azure; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var exampleResourceGroup = new Azure.Core.ResourceGroup("exampleResourceGroup", new Azure.Core.ResourceGroupArgs /// { /// Location = "West US", /// }); /// var exampleSqlServer = new Azure.Sql.SqlServer("exampleSqlServer", new Azure.Sql.SqlServerArgs /// { /// ResourceGroupName = exampleResourceGroup.Name, /// Location = exampleResourceGroup.Location, /// Version = "12.0", /// AdministratorLogin = "4dm1n157r470r", /// AdministratorLoginPassword = "4-v3ry-53cr37-p455w0rd", /// }); /// var exampleAccount = new Azure.Storage.Account("exampleAccount", new Azure.Storage.AccountArgs /// { /// ResourceGroupName = exampleResourceGroup.Name, /// Location = exampleResourceGroup.Location, /// AccountTier = "Standard", /// AccountReplicationType = "GRS", /// }); /// var exampleContainer = new Azure.Storage.Container("exampleContainer", new Azure.Storage.ContainerArgs /// { /// StorageAccountName = exampleAccount.Name, /// ContainerAccessType = "private", /// }); /// var exampleServerSecurityAlertPolicy = new Azure.MSSql.ServerSecurityAlertPolicy("exampleServerSecurityAlertPolicy", new Azure.MSSql.ServerSecurityAlertPolicyArgs /// { /// ResourceGroupName = exampleResourceGroup.Name, /// ServerName = exampleSqlServer.Name, /// State = "Enabled", /// }); /// var exampleDatabase = new Azure.Sql.Database("exampleDatabase", new Azure.Sql.DatabaseArgs /// { /// ResourceGroupName = exampleResourceGroup.Name, /// ServerName = exampleSqlServer.Name, /// Location = exampleResourceGroup.Location, /// Edition = "Standard", /// }); /// var exampleServerVulnerabilityAssessment = new Azure.MSSql.ServerVulnerabilityAssessment("exampleServerVulnerabilityAssessment", new Azure.MSSql.ServerVulnerabilityAssessmentArgs /// { /// ServerSecurityAlertPolicyId = exampleServerSecurityAlertPolicy.Id, /// StorageContainerPath = Output.Tuple(exampleAccount.PrimaryBlobEndpoint, exampleContainer.Name).Apply(values =&gt; /// { /// var primaryBlobEndpoint = values.Item1; /// var name = values.Item2; /// return $"{primaryBlobEndpoint}{name}/"; /// }), /// StorageAccountAccessKey = exampleAccount.PrimaryAccessKey, /// }); /// var exampleDatabaseVulnerabilityAssessmentRuleBaseline = new Azure.MSSql.DatabaseVulnerabilityAssessmentRuleBaseline("exampleDatabaseVulnerabilityAssessmentRuleBaseline", new Azure.MSSql.DatabaseVulnerabilityAssessmentRuleBaselineArgs /// { /// ServerVulnerabilityAssessmentId = exampleServerVulnerabilityAssessment.Id, /// DatabaseName = exampleDatabase.Name, /// RuleId = "VA2065", /// BaselineName = "master", /// BaselineResults = /// { /// new Azure.MSSql.Inputs.DatabaseVulnerabilityAssessmentRuleBaselineBaselineResultArgs /// { /// Results = /// { /// "allowedip1", /// "123.123.123.123", /// "123.123.123.123", /// }, /// }, /// new Azure.MSSql.Inputs.DatabaseVulnerabilityAssessmentRuleBaselineBaselineResultArgs /// { /// Results = /// { /// "allowedip2", /// "255.255.255.255", /// "255.255.255.255", /// }, /// }, /// }, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// Database Vulnerability Assessment Rule Baseline can be imported using the `resource id`, e.g. /// /// ```sh /// $ pulumi import azure:mssql/databaseVulnerabilityAssessmentRuleBaseline:DatabaseVulnerabilityAssessmentRuleBaseline example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/acceptanceTestResourceGroup1/providers/Microsoft.Sql/servers/mssqlserver/databases/mysqldatabase/vulnerabilityAssessments/Default/rules/VA2065/baselines/master /// ``` /// </summary> public partial class DatabaseVulnerabilityAssessmentRuleBaseline : Pulumi.CustomResource { /// <summary> /// The name of the vulnerability assessment rule baseline. Valid options are `default` and `master`. `default` implies a baseline on a database level rule and `master` for server level rule. Defaults to `default`. Changing this forces a new resource to be created. /// </summary> [Output("baselineName")] public Output<string?> BaselineName { get; private set; } = null!; /// <summary> /// A `baseline_result` block as documented below. Multiple blocks can be defined. /// </summary> [Output("baselineResults")] public Output<ImmutableArray<Outputs.DatabaseVulnerabilityAssessmentRuleBaselineBaselineResult>> BaselineResults { get; private set; } = null!; /// <summary> /// Specifies the name of the MS SQL Database. Changing this forces a new resource to be created. /// </summary> [Output("databaseName")] public Output<string> DatabaseName { get; private set; } = null!; /// <summary> /// The vulnerability assessment rule ID. Changing this forces a new resource to be created. /// </summary> [Output("ruleId")] public Output<string> RuleId { get; private set; } = null!; /// <summary> /// The Vulnerability Assessment ID of the MS SQL Server. Changing this forces a new resource to be created. /// </summary> [Output("serverVulnerabilityAssessmentId")] public Output<string> ServerVulnerabilityAssessmentId { get; private set; } = null!; /// <summary> /// Create a DatabaseVulnerabilityAssessmentRuleBaseline resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public DatabaseVulnerabilityAssessmentRuleBaseline(string name, DatabaseVulnerabilityAssessmentRuleBaselineArgs args, CustomResourceOptions? options = null) : base("azure:mssql/databaseVulnerabilityAssessmentRuleBaseline:DatabaseVulnerabilityAssessmentRuleBaseline", name, args ?? new DatabaseVulnerabilityAssessmentRuleBaselineArgs(), MakeResourceOptions(options, "")) { } private DatabaseVulnerabilityAssessmentRuleBaseline(string name, Input<string> id, DatabaseVulnerabilityAssessmentRuleBaselineState? state = null, CustomResourceOptions? options = null) : base("azure:mssql/databaseVulnerabilityAssessmentRuleBaseline:DatabaseVulnerabilityAssessmentRuleBaseline", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing DatabaseVulnerabilityAssessmentRuleBaseline resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static DatabaseVulnerabilityAssessmentRuleBaseline Get(string name, Input<string> id, DatabaseVulnerabilityAssessmentRuleBaselineState? state = null, CustomResourceOptions? options = null) { return new DatabaseVulnerabilityAssessmentRuleBaseline(name, id, state, options); } } public sealed class DatabaseVulnerabilityAssessmentRuleBaselineArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the vulnerability assessment rule baseline. Valid options are `default` and `master`. `default` implies a baseline on a database level rule and `master` for server level rule. Defaults to `default`. Changing this forces a new resource to be created. /// </summary> [Input("baselineName")] public Input<string>? BaselineName { get; set; } [Input("baselineResults", required: true)] private InputList<Inputs.DatabaseVulnerabilityAssessmentRuleBaselineBaselineResultArgs>? _baselineResults; /// <summary> /// A `baseline_result` block as documented below. Multiple blocks can be defined. /// </summary> public InputList<Inputs.DatabaseVulnerabilityAssessmentRuleBaselineBaselineResultArgs> BaselineResults { get => _baselineResults ?? (_baselineResults = new InputList<Inputs.DatabaseVulnerabilityAssessmentRuleBaselineBaselineResultArgs>()); set => _baselineResults = value; } /// <summary> /// Specifies the name of the MS SQL Database. Changing this forces a new resource to be created. /// </summary> [Input("databaseName", required: true)] public Input<string> DatabaseName { get; set; } = null!; /// <summary> /// The vulnerability assessment rule ID. Changing this forces a new resource to be created. /// </summary> [Input("ruleId", required: true)] public Input<string> RuleId { get; set; } = null!; /// <summary> /// The Vulnerability Assessment ID of the MS SQL Server. Changing this forces a new resource to be created. /// </summary> [Input("serverVulnerabilityAssessmentId", required: true)] public Input<string> ServerVulnerabilityAssessmentId { get; set; } = null!; public DatabaseVulnerabilityAssessmentRuleBaselineArgs() { } } public sealed class DatabaseVulnerabilityAssessmentRuleBaselineState : Pulumi.ResourceArgs { /// <summary> /// The name of the vulnerability assessment rule baseline. Valid options are `default` and `master`. `default` implies a baseline on a database level rule and `master` for server level rule. Defaults to `default`. Changing this forces a new resource to be created. /// </summary> [Input("baselineName")] public Input<string>? BaselineName { get; set; } [Input("baselineResults")] private InputList<Inputs.DatabaseVulnerabilityAssessmentRuleBaselineBaselineResultGetArgs>? _baselineResults; /// <summary> /// A `baseline_result` block as documented below. Multiple blocks can be defined. /// </summary> public InputList<Inputs.DatabaseVulnerabilityAssessmentRuleBaselineBaselineResultGetArgs> BaselineResults { get => _baselineResults ?? (_baselineResults = new InputList<Inputs.DatabaseVulnerabilityAssessmentRuleBaselineBaselineResultGetArgs>()); set => _baselineResults = value; } /// <summary> /// Specifies the name of the MS SQL Database. Changing this forces a new resource to be created. /// </summary> [Input("databaseName")] public Input<string>? DatabaseName { get; set; } /// <summary> /// The vulnerability assessment rule ID. Changing this forces a new resource to be created. /// </summary> [Input("ruleId")] public Input<string>? RuleId { get; set; } /// <summary> /// The Vulnerability Assessment ID of the MS SQL Server. Changing this forces a new resource to be created. /// </summary> [Input("serverVulnerabilityAssessmentId")] public Input<string>? ServerVulnerabilityAssessmentId { get; set; } public DatabaseVulnerabilityAssessmentRuleBaselineState() { } } }
50.219424
359
0.620872
[ "ECL-2.0", "Apache-2.0" ]
suresh198526/pulumi-azure
sdk/dotnet/MSSql/DatabaseVulnerabilityAssessmentRuleBaseline.cs
13,961
C#
using System; using System.ComponentModel; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Text; using System.Runtime; using System.Collections; using NetOffice.Tools; namespace NetOffice.OfficeApi.Tools.Contribution { /// <summary> /// Represents a tray menu item /// </summary> [ItemType(TrayMenuItemType.Item)] public class TrayMenuItem { #region Fields private TrayMenu _owner; private string _text; private bool _visible; private string _toolTipText; private Image _image; private Color _backColor = Color.FromKnownColor(KnownColor.Control); private Color _foreColor = Color.FromKnownColor(KnownColor.ControlText); private Font _font; private bool _enabled = true; private ContentAlignment _textAlign; private ContentAlignment _imageAlign; private Padding _padding; private TrayMenuItems _items; private object _itemsLock = new object(); #endregion #region Ctor /// <summary> /// Creates an instance of the class /// </summary> /// <param name="owner">item owner</param> /// <param name="text">shown caption</param> internal TrayMenuItem(TrayMenu owner, string text) { if (null == owner) throw new ArgumentNullException("owner"); _owner = owner; Text = text; } /// <summary> /// Creates an instance of the class /// </summary> /// <param name="owner">item owner</param> /// <param name="text">shown caption</param> /// <param name="visible">item visibility</param> internal TrayMenuItem(TrayMenu owner, string text, bool visible) { if (null == owner) throw new ArgumentNullException("owner"); _owner = owner; Text = text; Visible = visible; } #endregion #region Properties /// <summary> /// Owner Menu /// </summary> protected internal TrayMenu Owner { get { return _owner; } } /// <summary> /// Optional Child Items /// </summary> public virtual TrayMenuItems Items { get { lock (_itemsLock) { if (null == _items) _items = OnCreateMenuItems(); } return _items; } } /// <summary> /// Background color /// </summary> public virtual Color BackColor { get { return _backColor; } set { if (value != _backColor) { _backColor = value; _owner.OnItemBackColorChanged(this); } } } /// <summary> /// Fore/Font color /// </summary> public virtual Color ForeColor { get { return _foreColor; } set { if (value != _foreColor) { _foreColor = value; _owner.OnItemForeColorChanged(this); } } } /// <summary> /// Item Font /// </summary> public virtual Font Font { get { return _font; } set { if (value != _font) { _font = value; _owner.OnItemFontChanged(this); } } } /// <summary> /// Get or set item visibility /// </summary> public virtual bool Visible { get { return _visible; } set { if (value != _visible) { _visible = value; _owner.OnItemVisibleChanged(this); } } } /// <summary> /// Item Enabled State /// </summary> public virtual bool Enabled { get { return _enabled; } set { if (value != _enabled) { _enabled = value; _owner.OnItemEnabledChanged(this); } } } /// <summary> /// Shown caption /// </summary> public virtual string Text { get { return _text; } set { if (value != _text) { _text = value; _owner.OnItemTextChanged(this); } } } /// <summary> /// Shown Text Alignment /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public virtual ContentAlignment TextAlign { get { return _textAlign; } set { if (value != _textAlign) { _textAlign = value; _owner.OnItemTextAlignChanged(this); } } } /// <summary> /// Shown Tooltip /// </summary> public virtual string ToolTipText { get { return _toolTipText; } set { if (value != _toolTipText) { _toolTipText = value; _owner.OnItemToolTipTextChanged(this); } } } /// <summary> /// Shown Image /// </summary> public virtual Image Image { get { return _image; } set { if (value != _image) { _image = value; _owner.OnItemImageChanged(this); } } } /// <summary> /// Shown Image Alignment /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public virtual ContentAlignment ImageAlign { get { return _imageAlign; } set { if (value != _imageAlign) { _imageAlign = value; _owner.OnItemImageAlignChanged(this); } } } /// <summary> /// Padding Space /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public virtual Padding Padding { get { return _padding; } set { if (value != _padding) { _padding = value; _owner.OnItemPaddingChanged(this); } } } /// <summary> /// Instance Category Type /// </summary> public TrayMenuItemType ItemType { get; protected internal set; } /// <summary> /// Well known any tag /// </summary> public object Tag { get; set; } /// <summary> /// Same as Tag /// </summary> public object Extender { get; set; } #endregion #region Methods /// <summary> /// Initialize values from ui element /// </summary> /// <param name="font">element font</param> /// <param name="textAlign">text align</param> /// <param name="imageAlign">image align</param> /// <param name="padding">padding space</param> internal void SetupElements(Font font, ContentAlignment textAlign, ContentAlignment imageAlign, Padding padding) { _font = font; _textAlign = textAlign; _imageAlign = imageAlign; _padding = padding; } /// <summary> /// Creates an instance of TrayMenuItems /// </summary> /// <returns>TrayMenuItems instance</returns> protected internal virtual TrayMenuItems OnCreateMenuItems() { return new TrayMenuItems(Owner, this); } #endregion } }
24.096774
120
0.428938
[ "MIT" ]
DominikPalo/NetOffice
Source/Office/Tools/Contribution/TrayMenuUtils/TrayMenuItem.cs
8,966
C#
/* Copyright 2015 MongoDB Inc. * * 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.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using MongoDB.Driver.Linq.Expressions; using MongoDB.Driver.Linq.Expressions.ResultOperators; namespace MongoDB.Driver.Linq.Processors.Pipeline.MethodCallBinders { internal sealed class SingleBinder : IMethodCallBinder<PipelineBindingContext> { public static IEnumerable<MethodInfo> GetSupportedMethods() { return MethodHelper.GetEnumerableAndQueryableMethodDefinitions("Single") .Concat(MethodHelper.GetEnumerableAndQueryableMethodDefinitions("SingleOrDefault")); } public Expression Bind(PipelineExpression pipeline, PipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable<Expression> arguments) { var source = pipeline.Source; if (arguments.Any()) { source = BinderHelper.BindWhere( pipeline, bindingContext, ExpressionHelper.GetLambda(arguments.Single())); } source = new TakeExpression(source, Expression.Constant(2)); return new PipelineExpression( source, pipeline.Projector, new SingleResultOperator( node.Type, pipeline.Projector.Serializer, node.Method.Name == nameof(Enumerable.SingleOrDefault))); } } }
37
160
0.67471
[ "MIT" ]
594270461/LandlordsCore
Server/ThirdParty/MongodbDriver/MongoDB.Driver/Linq/Processors/Pipeline/MethodCallBinders/SingleBinder.cs
2,074
C#
// This file was generated. Do not modify. using System; using System.Linq; using System.Collections.Generic; using System.Collections.Immutable; namespace cilspirv.Spirv.Ops { public sealed record OpBitwiseXor : BitInstruction { public ID ResultType { get; init; } public ID Result { get; init; } public ID Operand1 { get; init; } public ID Operand2 { get; init; } public override OpCode OpCode => OpCode.OpBitwiseXor; public override int WordCount => 1 + 1 + 1 + 1 + 1 + ExtraWordCount; public override ID? ResultID => Result; public override ID? ResultTypeID => ResultType; public override IEnumerable<ID> AllIDs => new[] { ResultType, Result, Operand1, Operand2 }.Concat(ExtraIDs); public OpBitwiseXor() {} private OpBitwiseXor(IReadOnlyList<uint> codes, Range range) { var (start, end) = range.GetOffsetAndLength(codes.Count); end += start; var i = start; ResultType = new ID(codes[i++]); Result = new ID(codes[i++]); Operand1 = new ID(codes[i++]); Operand2 = new ID(codes[i++]); ExtraOperands = codes.Skip(i).Take(end - i) .Select(x => new ExtraOperand(x)) .ToImmutableArray(); } public override void Write(Span<uint> codes, Func<ID, uint> mapID) { if (codes.Length < WordCount) throw new ArgumentException("Output span too small", nameof(codes)); var i = 0; codes[i++] = InstructionCode; codes[i++] = mapID(ResultType); codes[i++] = mapID(Result); codes[i++] = mapID(Operand1); codes[i++] = mapID(Operand2); if (!ExtraOperands.IsDefaultOrEmpty) foreach (var o in ExtraOperands) o.Write(codes, ref i, mapID); } } }
34.714286
116
0.565329
[ "MIT" ]
Helco/cilspirv
cilspirv.transpiler/Spirv/Ops/Bit/OpBitwiseXor.cs
1,944
C#
using System.Diagnostics.CodeAnalysis; namespace AdventOfCode.Common.Internal; internal class MergedIndexable2D<TValue> : IIndexable2D<TValue> { private readonly IIndexable2D<IIndexable2D<TValue>> _blocks; public MergedIndexable2D(IIndexable<IIndexable<IIndexable2D<TValue>>> source) : this(new IndexableOfIndexableAsIndexable2D<IIndexable2D<TValue>>(source)) { } public MergedIndexable2D(IIndexable2D<IIndexable2D<TValue>> source) { Length0 = 0; Length1 = 0; for (int i = 0; i < source.Length0; i++) { int rowHeight = 0; int currentRowLength = 0; for (int j = 0; j < source.Length1; j++) { IIndexable2D<TValue> block = source[i, j]; if (rowHeight == 0) rowHeight = block.Length0; currentRowLength += block.Length1; if (block.Length0 != rowHeight) throw new FormatException("Variable block height in block row."); } Length0 += rowHeight; if (Length1 == 0) Length1 = currentRowLength; if (currentRowLength != Length1) throw new FormatException("Variable block length."); } _blocks = source; } public int Length0 { get; } public int Length1 { get; } public TValue this[int x, int y] { get { GetComposedIndex(x, y, out int ox, out int ix, out int oy, out int iy); return _blocks[ox, oy][ix, iy]; } set { GetComposedIndex(x, y, out int ox, out int ix, out int oy, out int iy); _blocks[ox, oy][ix, iy] = value; } } public bool TryGetValue(int x, int y, [MaybeNullWhen(false)] out TValue value) { GetComposedIndex(x, y, out int ox, out int ix, out int oy, out int iy); if (_blocks.TryGetValue((ox, oy), out var values)) return values.TryGetValue((ix, iy), out value); value = default; return false; } private void GetComposedIndex(int x, int y, out int outerX, out int innerX, out int outerY, out int innerY) { int sum; outerX = 0; for (sum = _blocks[outerX, 0].Length0; x >= sum; sum += _blocks[outerX, 0].Length0) outerX++; innerX = x - (sum - _blocks[outerX, 0].Length0); outerY = 0; for (sum = _blocks[outerX, outerY].Length1; y >= sum; sum += _blocks[outerX, outerY].Length1) outerY++; innerY = y - (sum - _blocks[outerX, outerY].Length1); } }
23.763441
108
0.666063
[ "MIT" ]
andreibsk/AdventOfCode
src/AdventOfCode.Common/Internal/MergedIndexable2D.cs
2,210
C#
using System; using System.Security.Cryptography; using DeviceId.Components; using DeviceId.Encoders; using DeviceId.Formatters; using FluentAssertions; using Xunit; namespace DeviceId.Tests.Formatters { public class StringDeviceIdFormatterTests { [Fact] public void Constructor_EncoderIsNull_ThrowsArgumentNullException() { Action act = () => new StringDeviceIdFormatter(null); act.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\r\nParameter name: encoder"); } [Fact] public void GetDeviceId_ComponentsIsNull_ThrowsArgumentNullException() { var formatter = new StringDeviceIdFormatter(new HashDeviceIdComponentEncoder(() => MD5.Create(), new HexByteArrayEncoder())); Action act = () => formatter.GetDeviceId(null); act.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\r\nParameter name: components"); } [Fact] public void GetDeviceId_ComponentsIsEmpty_ReturnsEmptyString() { var formatter = new StringDeviceIdFormatter(new HashDeviceIdComponentEncoder(() => MD5.Create(), new HexByteArrayEncoder())); var deviceId = formatter.GetDeviceId(new IDeviceIdComponent[] { }); deviceId.Should().Be(String.Empty); } [Fact] public void GetDeviceId_ComponentsAreValid_ReturnsDeviceId() { var formatter = new StringDeviceIdFormatter(new HashDeviceIdComponentEncoder(() => MD5.Create(), new HexByteArrayEncoder())); var deviceId = formatter.GetDeviceId(new IDeviceIdComponent[] { new DeviceIdComponent("Test1", "Test1"), new DeviceIdComponent("Test2", "Test2"), }); deviceId.Should().Be("e1b849f9631ffc1829b2e31402373e3c.c454552d52d55d3ef56408742887362b"); } [Fact] public void GetDeviceId_ComponentReturnsNull_ReturnsDeviceId() { var formatter = new StringDeviceIdFormatter(new HashDeviceIdComponentEncoder(() => MD5.Create(), new HexByteArrayEncoder())); var deviceId = formatter.GetDeviceId(new IDeviceIdComponent[] { new DeviceIdComponent("Test1", default(string)), }); deviceId.Should().Be("d41d8cd98f00b204e9800998ecf8427e"); } } }
35.144928
137
0.654021
[ "MIT" ]
Twistie/DeviceId
test/DeviceId.Tests/Formatters/StringDeviceIdFormatterTests.cs
2,427
C#
/* Copyright (c) 2012 <a href="http://www.gutgames.com">James Craig</a> 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.*/ #region Usings using System.Drawing; using System.Drawing.Imaging; using Utilities.DataTypes.ExtensionMethods; using Utilities.Media.Image.ExtensionMethods; #endregion namespace Utilities.Media.Image.Procedural { /// <summary> /// Cellular texture helper /// </summary> public static class CellularTexture { #region Functions /// <summary> /// Generates a cellular texture image /// </summary> /// <param name="Width">Width</param> /// <param name="Height">Height</param> /// <param name="NumberOfPoints">Number of points</param> /// <param name="Seed">Random seed</param> /// <returns>Returns an image of a cellular texture</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Body")] public static Bitmap Generate(int Width, int Height, int NumberOfPoints, int Seed) { float[,] DistanceBuffer = new float[Width, Height]; float MinimumDistance = float.MaxValue; float MaxDistance = float.MinValue; CellularMap Map = new CellularMap(Seed, Width, Height, NumberOfPoints); MaxDistance = Map.MaxDistance; MinimumDistance = Map.MinDistance; DistanceBuffer = Map.Distances; Bitmap ReturnValue = new Bitmap(Width, Height); BitmapData ImageData = ReturnValue.LockImage(); int ImagePixelSize = ImageData.GetPixelSize(); for (int x = 0; x < Width; ++x) { for (int y = 0; y < Height; ++y) { float Value = GetHeight(x, y, DistanceBuffer, MinimumDistance, MaxDistance); Value *= 255; int RGBValue = ((int)Value).Clamp(255, 0); ImageData.SetPixel(x, y, Color.FromArgb(RGBValue, RGBValue, RGBValue), ImagePixelSize); } } ReturnValue.UnlockImage(ImageData); return ReturnValue; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "2#")] private static float GetHeight(float X, float Y, float[,] DistanceBuffer, float MinimumDistance, float MaxDistance) { return (DistanceBuffer[(int)X,(int)Y] - MinimumDistance) / (MaxDistance - MinimumDistance); } #endregion } }
46.719512
272
0.658575
[ "MIT" ]
JoySky/Craig-s-Utility-Library
Utilities.Media/Media/Image/Procedural/CellularTexture.cs
3,833
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BookTube.Web.Areas.Administration.Models { public class PublisherIputModel { [Required] [StringLength(90, MinimumLength = 5)] public string Name { get; set; } [Required] [StringLength(90, MinimumLength = 5)] public string Contacts { get; set; } } }
20.95
50
0.749403
[ "MIT" ]
georgieff1288/BookTube
src/BookTube/Web/BookTube.Web/Areas/Administration/Models/PublisherIputModel.cs
421
C#
using System; using System.Collections.Generic; using System.Text; using b2xtranslator.CommonTranslatorLib; using System.Xml; using b2xtranslator.DocFileFormat; using b2xtranslator.OpenXmlLib; using System.IO; using b2xtranslator.Tools; using System.Globalization; using b2xtranslator.OfficeDrawing; using b2xtranslator.OfficeDrawing.Shapetypes; namespace b2xtranslator.WordprocessingMLMapping { public class VMLPictureMapping : PropertiesMapping, IMapping<PictureDescriptor> { ContentPart _targetPart; bool _olePreview; private XmlElement _imageData = null; public VMLPictureMapping(XmlWriter writer, ContentPart targetPart, bool olePreview) : base(writer) { this._targetPart = targetPart; this._olePreview = olePreview; this._imageData = this._nodeFactory.CreateElement("v", "imageData", OpenXmlNamespaces.VectorML); } public void Apply(PictureDescriptor pict) { var imgPart = copyPicture(pict.BlipStoreEntry); if (imgPart != null) { var shape = (Shape)pict.ShapeContainer.Children[0]; var options = pict.ShapeContainer.ExtractOptions(); //v:shapetype var type = new PictureFrameType(); type.Convert(new VMLShapeTypeMapping(this._writer)); //v:shape this._writer.WriteStartElement("v", "shape", OpenXmlNamespaces.VectorML); this._writer.WriteAttributeString("type", "#" + VMLShapeTypeMapping.GenerateTypeId(type)); var style = new StringBuilder(); double xScaling = pict.mx / 1000.0; double yScaling = pict.my / 1000.0; var width = new TwipsValue(pict.dxaGoal * xScaling); var height = new TwipsValue(pict.dyaGoal * yScaling); string widthString = Convert.ToString(width.ToPoints(), CultureInfo.GetCultureInfo("en-US")); string heightString = Convert.ToString(height.ToPoints(), CultureInfo.GetCultureInfo("en-US")); style.Append("width:").Append(widthString).Append("pt;"); style.Append("height:").Append(heightString).Append("pt;"); this._writer.WriteAttributeString("style", style.ToString()); this._writer.WriteAttributeString("id", pict.ShapeContainer.GetHashCode().ToString()); if (this._olePreview) { this._writer.WriteAttributeString("o", "ole", OpenXmlNamespaces.Office, ""); } foreach (var entry in options) { switch (entry.pid) { //BORDERS case ShapeOptions.PropertyId.borderBottomColor: var bottomColor = new RGBColor((int)entry.op, RGBColor.ByteOrder.RedFirst); this._writer.WriteAttributeString("o", "borderbottomcolor", OpenXmlNamespaces.Office, "#" + bottomColor.SixDigitHexCode); break; case ShapeOptions.PropertyId.borderLeftColor: var leftColor = new RGBColor((int)entry.op, RGBColor.ByteOrder.RedFirst); this._writer.WriteAttributeString("o", "borderleftcolor", OpenXmlNamespaces.Office, "#" + leftColor.SixDigitHexCode); break; case ShapeOptions.PropertyId.borderRightColor: var rightColor = new RGBColor((int)entry.op, RGBColor.ByteOrder.RedFirst); this._writer.WriteAttributeString("o", "borderrightcolor", OpenXmlNamespaces.Office, "#" + rightColor.SixDigitHexCode); break; case ShapeOptions.PropertyId.borderTopColor: var topColor = new RGBColor((int)entry.op, RGBColor.ByteOrder.RedFirst); this._writer.WriteAttributeString("o", "bordertopcolor", OpenXmlNamespaces.Office, "#" + topColor.SixDigitHexCode); break; //CROPPING case ShapeOptions.PropertyId.cropFromBottom: //cast to signed integer int cropBottom = (int)entry.op; appendValueAttribute(this._imageData, null, "cropbottom", cropBottom + "f", null); break; case ShapeOptions.PropertyId.cropFromLeft: //cast to signed integer int cropLeft = (int)entry.op; appendValueAttribute(this._imageData, null, "cropleft", cropLeft + "f", null); break; case ShapeOptions.PropertyId.cropFromRight: //cast to signed integer int cropRight = (int)entry.op; appendValueAttribute(this._imageData, null, "cropright", cropRight + "f", null); break; case ShapeOptions.PropertyId.cropFromTop: //cast to signed integer int cropTop = (int)entry.op; appendValueAttribute(this._imageData, null, "croptop", cropTop + "f", null); break; } } //v:imageData appendValueAttribute(this._imageData, "r", "id", imgPart.RelIdToString, OpenXmlNamespaces.Relationships); appendValueAttribute(this._imageData, "o", "title", "", OpenXmlNamespaces.Office); this._imageData.WriteTo(this._writer); //borders writePictureBorder("bordertop", pict.brcTop); writePictureBorder("borderleft", pict.brcLeft); writePictureBorder("borderbottom", pict.brcBottom); writePictureBorder("borderright", pict.brcRight); //close v:shape this._writer.WriteEndElement(); } } /// <summary> /// Writes a border element /// </summary> /// <param name="name">The name of the element</param> /// <param name="brc">The BorderCode object</param> private void writePictureBorder(string name, BorderCode brc) { this._writer.WriteStartElement("w10", name, OpenXmlNamespaces.OfficeWord); this._writer.WriteAttributeString("type", getBorderType(brc.brcType)); this._writer.WriteAttributeString("width", brc.dptLineWidth.ToString()); this._writer.WriteEndElement(); } /// <summary> /// Copies the picture from the binary stream to the zip archive /// and creates the relationships for the image. /// </summary> /// <param name="pict">The PictureDescriptor</param> /// <returns>The created ImagePart</returns> protected ImagePart copyPicture(BlipStoreEntry bse) { //create the image part ImagePart imgPart = null; if(bse != null) { switch (bse.btWin32) { case BlipStoreEntry.BlipType.msoblipEMF: imgPart = this._targetPart.AddImagePart(ImagePart.ImageType.Emf); break; case BlipStoreEntry.BlipType.msoblipWMF: imgPart = this._targetPart.AddImagePart(ImagePart.ImageType.Wmf); break; case BlipStoreEntry.BlipType.msoblipJPEG: case BlipStoreEntry.BlipType.msoblipCMYKJPEG: imgPart = this._targetPart.AddImagePart(ImagePart.ImageType.Jpeg); break; case BlipStoreEntry.BlipType.msoblipPNG: imgPart = this._targetPart.AddImagePart(ImagePart.ImageType.Png); break; case BlipStoreEntry.BlipType.msoblipTIFF: imgPart = this._targetPart.AddImagePart(ImagePart.ImageType.Tiff); break; case BlipStoreEntry.BlipType.msoblipPICT: case BlipStoreEntry.BlipType.msoblipERROR: case BlipStoreEntry.BlipType.msoblipUNKNOWN: case BlipStoreEntry.BlipType.msoblipLastClient: case BlipStoreEntry.BlipType.msoblipFirstClient: case BlipStoreEntry.BlipType.msoblipDIB: //throw new MappingException("Cannot convert picture of type " + bse.btWin32); break; } if (imgPart != null) { var outStream = imgPart.GetStream(); //write the blip if (bse.Blip != null) { switch (bse.btWin32) { case BlipStoreEntry.BlipType.msoblipEMF: case BlipStoreEntry.BlipType.msoblipWMF: //it's a meta image var metaBlip = (MetafilePictBlip)bse.Blip; //meta images can be compressed var decompressed = metaBlip.Decrompress(); outStream.Write(decompressed, 0, decompressed.Length); break; case BlipStoreEntry.BlipType.msoblipJPEG: case BlipStoreEntry.BlipType.msoblipCMYKJPEG: case BlipStoreEntry.BlipType.msoblipPNG: case BlipStoreEntry.BlipType.msoblipTIFF: //it's a bitmap image var bitBlip = (BitmapBlip)bse.Blip; outStream.Write(bitBlip.m_pvBits, 0, bitBlip.m_pvBits.Length); break; } } } } return imgPart; } } }
47.013514
149
0.529942
[ "BSD-3-Clause" ]
EvolutionJobs/b2xtranslator
Doc/WordprocessingMLMapping/VMLPictureMapping.cs
10,437
C#
using Xunit; namespace IxMilia.Erlang.Test { public class TestBase { public static void ArrayEquals<T>(T[] expected, T[] actual) { if (expected == null && actual == null) { return; } Assert.False(expected == null || actual == null); Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual[i]); } } } }
23.304348
67
0.466418
[ "MIT" ]
ixmilia/erlang
src/IxMilia.Erlang.Test/TestBase.cs
538
C#
using RhythmCodex.Infrastructure; namespace RhythmCodex.Xbox.Model { [Model] public class XboxIsoFileEntry { public int StartSector { get; set; } public int FileSize { get; set; } public XboxIsoFileAttributes Attributes { get; set; } public string FileName { get; set; } public override string ToString() { return $"\"{FileName}\" sector={StartSector} size={FileSize} attr={Attributes}"; } } }
26.611111
92
0.613779
[ "MIT" ]
SaxxonPike/RhythmCodex
Source/RhythmCodex.Lib/Xbox/Model/XboxIsoFileEntry.cs
479
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 grafana-2020-08-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ManagedGrafana.Model { /// <summary> /// Contains the instructions for one Grafana role permission update in a <a href="https://docs.aws.amazon.com/grafana/latest/APIReference/API_UpdatePermissions.html">UpdatePermissions</a> /// operation. /// </summary> public partial class UpdateInstruction { private UpdateAction _action; private Role _role; private List<User> _users = new List<User>(); /// <summary> /// Gets and sets the property Action. /// <para> /// Specifies whether this update is to add or revoke role permissions. /// </para> /// </summary> [AWSProperty(Required=true)] public UpdateAction Action { get { return this._action; } set { this._action = value; } } // Check to see if Action property is set internal bool IsSetAction() { return this._action != null; } /// <summary> /// Gets and sets the property Role. /// <para> /// The role to add or revoke for the user or the group specified in <code>users</code>. /// </para> /// </summary> [AWSProperty(Required=true)] public Role Role { get { return this._role; } set { this._role = value; } } // Check to see if Role property is set internal bool IsSetRole() { return this._role != null; } /// <summary> /// Gets and sets the property Users. /// <para> /// A structure that specifies the user or group to add or revoke the role for. /// </para> /// </summary> [AWSProperty(Required=true)] public List<User> Users { get { return this._users; } set { this._users = value; } } // Check to see if Users property is set internal bool IsSetUsers() { return this._users != null && this._users.Count > 0; } } }
30.050505
192
0.595294
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/ManagedGrafana/Generated/Model/UpdateInstruction.cs
2,975
C#
using System; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Threading; using WBrush = System.Windows.Media.Brush; namespace Microsoft.Maui.Controls.Compatibility.Platform.WPF { /// <summary> /// An intermediate class for injecting bindings for things the default /// textbox doesn't allow us to bind/modify /// </summary> public class FormsTextBox : TextBox { const char ObfuscationCharacter = '●'; public static readonly DependencyProperty PlaceholderTextProperty = DependencyProperty.Register("PlaceholderText", typeof(string), typeof(FormsTextBox), new PropertyMetadata(string.Empty)); public static readonly DependencyProperty PlaceholderForegroundBrushProperty = DependencyProperty.Register("PlaceholderForegroundBrush", typeof(WBrush), typeof(FormsTextBox), new PropertyMetadata(default(WBrush))); public static readonly DependencyProperty IsPasswordProperty = DependencyProperty.Register("IsPassword", typeof(bool), typeof(FormsTextBox), new PropertyMetadata(default(bool), OnIsPasswordChanged)); public new static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(FormsTextBox), new PropertyMetadata("", TextPropertyChanged)); protected internal static readonly DependencyProperty DisabledTextProperty = DependencyProperty.Register("DisabledText", typeof(string), typeof(FormsTextBox), new PropertyMetadata("")); static InputScope s_passwordInputScope; InputScope _cachedInputScope; CancellationTokenSource _cts; bool _internalChangeFlag; int _cachedSelectionLength; public FormsTextBox() { TextChanged += OnTextChanged; SelectionChanged += OnSelectionChanged; } public bool IsPassword { get { return (bool)GetValue(IsPasswordProperty); } set { SetValue(IsPasswordProperty, value); } } public string PlaceholderText { get { return (string)GetValue(PlaceholderTextProperty); } set { SetValue(PlaceholderTextProperty, value); } } public WBrush PlaceholderForegroundBrush { get { return (WBrush)GetValue(PlaceholderForegroundBrushProperty); } set { SetValue(PlaceholderForegroundBrushProperty, value); } } public new string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } protected internal string DisabledText { get { return (string)GetValue(DisabledTextProperty); } set { SetValue(DisabledTextProperty, value); } } static InputScope PasswordInputScope { get { if (s_passwordInputScope != null) return s_passwordInputScope; s_passwordInputScope = new InputScope(); var name = new InputScopeName { NameValue = InputScopeNameValue.Default }; s_passwordInputScope.Names.Add(name); return s_passwordInputScope; } } void DelayObfuscation() { int lengthDifference = base.Text.Length - Text.Length; var savedSelectionStart = SelectionStart; string updatedRealText = DetermineTextFromPassword(Text, SelectionStart, base.Text); if (Text == updatedRealText) { // Nothing to do return; } _internalChangeFlag = true; Text = updatedRealText; _internalChangeFlag = false; // Cancel any pending delayed obfuscation _cts?.Cancel(); _cts = null; string newText; if (lengthDifference != 1) { // Either More than one character got added in this text change (e.g., a paste operation) // Or characters were removed. Either way, we don't need to do the delayed obfuscation dance newText = Obfuscate(Text); } else { // Only one character was added; we need to leave it visible for a brief time period // Obfuscate all but the character added for now newText = Obfuscate(Text, savedSelectionStart - 1); // Leave the added character visible until a new character is added // or sufficient time has passed if (_cts == null) { _cts = new CancellationTokenSource(); } Task.Run(async () => { await Task.Delay(TimeSpan.FromSeconds(0.5), _cts.Token); _cts.Token.ThrowIfCancellationRequested(); await Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { var ss = SelectionStart; var sl = SelectionLength; base.Text = Obfuscate(Text); SelectionStart = ss; SelectionLength = sl; })); }, _cts.Token); } if (base.Text != newText) { base.Text = newText; } SelectionStart = savedSelectionStart; } static string DetermineTextFromPassword(string realText, int start, string passwordText) { var lengthDifference = passwordText.Length - realText.Length; if (lengthDifference > 0) realText = realText.Insert(start - lengthDifference, new string(ObfuscationCharacter, lengthDifference)); else if (lengthDifference < 0) realText = realText.Remove(start, -lengthDifference); var sb = new System.Text.StringBuilder(passwordText.Length); for (int i = 0; i < passwordText.Length; i++) sb.Append(passwordText[i] == ObfuscationCharacter ? realText[i] : passwordText[i]); return sb.ToString(); } string Obfuscate(string text, int visibleSymbolIndex = -1) { if (visibleSymbolIndex == -1) return new string(ObfuscationCharacter, text?.Length ?? 0); if (text == null || text.Length == 1) return text; var prefix = visibleSymbolIndex > 0 ? new string(ObfuscationCharacter, visibleSymbolIndex) : string.Empty; var suffix = visibleSymbolIndex == text.Length - 1 ? string.Empty : new string(ObfuscationCharacter, text.Length - visibleSymbolIndex - 1); return prefix + text.Substring(visibleSymbolIndex, 1) + suffix; } static void OnIsPasswordChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var textBox = (FormsTextBox)dependencyObject; textBox.UpdateInputScope(); textBox.SyncBaseText(); } void OnSelectionChanged(object sender, RoutedEventArgs routedEventArgs) { // Cache this value for later use as explained in OnKeyDown below _cachedSelectionLength = SelectionLength; } // Because the implementation of a password entry is based around inheriting from TextBox (via FormsTextBox), there // are some inaccuracies in the behavior. OnKeyDown is what needs to be used for a workaround in this case because // there's no easy way to disable specific keyboard shortcuts in a TextBox, so key presses are being intercepted and // handled accordingly. protected override void OnKeyDown(KeyEventArgs e) { if (IsPassword) { // The ctrlDown flag is used to track if the Ctrl key is pressed; if it's actively being used and the most recent // key to trigger OnKeyDown, then treat it as handled. var ctrlDown = (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl) && e.IsDown; // The shift, tab, and directional (Home/End/PgUp/PgDown included) keys can be used to select text and should otherwise // be ignored. if ( e.Key == Key.LeftShift || e.Key == Key.RightShift || e.Key == Key.Tab || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Down || e.Key == Key.Home || e.Key == Key.End || e.Key == Key.PageUp || e.Key == Key.PageDown) { base.OnKeyDown(e); return; } // For anything else, continue on (calling base.OnKeyDown) and then if Ctrl is still being pressed, do nothing about it. // The tricky part here is that the SelectionLength value needs to be cached because in an example where the user entered // '123' into the field and selects all of it, the moment that any character key is pressed to replace the entire string, // the SelectionLength is equal to zero, which is not what's desired. Entering a key will thus remove the selected number // of characters from the Text value. OnKeyDown is fortunately called before OnSelectionChanged which enables this. else { // If the C or X keys (copy/cut) are pressed while Ctrl is active, ignore handing them at all. Undo and Redo (Z/Y) should // be ignored as well as this emulates the regular behavior of a PasswordBox. if ((e.Key == Key.C || e.Key == Key.X || e.Key == Key.Z || e.Key == Key.Y) && ctrlDown) { e.Handled = false; return; } base.OnKeyDown(e); if (_cachedSelectionLength > 0 && !ctrlDown) { var savedSelectionStart = SelectionStart; Text = Text.Remove(SelectionStart, _cachedSelectionLength); SelectionStart = savedSelectionStart; } } } else base.OnKeyDown(e); } void OnTextChanged(object sender, System.Windows.Controls.TextChangedEventArgs textChangedEventArgs) { if (IsPassword) { DelayObfuscation(); } else if (base.Text != Text) { // Not in password mode, so we just need to make the "real" Text match // what's in the textbox; the internalChange flag keeps the TextProperty // synchronization from happening _internalChangeFlag = true; Text = base.Text; _internalChangeFlag = false; } } void SyncBaseText() { if (_internalChangeFlag) return; var savedSelectionStart = SelectionStart; base.Text = IsPassword ? Obfuscate(Text) : Text; DisabledText = base.Text; var len = base.Text.Length; SelectionStart = savedSelectionStart > len ? len : savedSelectionStart; } static void TextPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var textBox = (FormsTextBox)dependencyObject; textBox.SyncBaseText(); } void UpdateInputScope() { if (IsPassword) { _cachedInputScope = InputScope; InputScope = PasswordInputScope; // We don't want suggestions turned on if we're in password mode } else InputScope = _cachedInputScope; } } }
33.066225
176
0.710194
[ "MIT" ]
10088/maui
src/Compatibility/Core/src/WPF/FormsTextBox.cs
9,988
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("06.ExtractSongsLINQ")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("06.ExtractSongsLINQ")] [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("5453562c-29f0-4aa4-b725-2d411430b5ab")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.135135
84
0.746279
[ "MIT" ]
zvet80/TelerikAcademy
11.Databases/02.XMLProcessingIn.NET/06.ExtractSongsLINQ/Properties/AssemblyInfo.cs
1,414
C#
namespace Minions.Services.Implementations { using Data; using Minions.Models; using Models; using System; using System.Collections.Generic; using System.Linq; public class TownService : ITownService { private readonly MinionsDbContext db; public TownService(MinionsDbContext db) { this.db = db; } public int ChangeTownNamesToUppercase(string countryName) { var country = this.db .Countries .Where(c => c.Name == countryName) .Select(c => new CountryModel { Name = c.Name, Towns = c.Towns }) .FirstOrDefault(); if (country == null) { throw new InvalidOperationException($"Invalid country {countryName}"); } var changedTowns = 0; foreach (var town in country.Towns) { town.Name = town.Name.ToUpper(); changedTowns++; } return changedTowns; } public IEnumerable<Town> TownsByCountryName(string countryName) { return this.db.Towns.Where(c => c.Country.Name == countryName).ToList(); } } }
25.5
86
0.507541
[ "MIT" ]
thelad43/Databases-Advanced-Entity-Framework-SoftUni
01. Introduction to DB Apps/Minions.Services/Implementations/TownService.cs
1,328
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Http.Headers; using Xunit; namespace System.Net.Http.Tests { public class RangeConditionHeaderValueTest { [Fact] public void Ctor_EntityTagOverload_MatchExpectation() { RangeConditionHeaderValue rangeCondition = new RangeConditionHeaderValue( new EntityTagHeaderValue("\"x\"") ); Assert.Equal(new EntityTagHeaderValue("\"x\""), rangeCondition.EntityTag); Assert.Null(rangeCondition.Date); EntityTagHeaderValue input = null; Assert.Throws<ArgumentNullException>( () => { new RangeConditionHeaderValue(input); } ); } [Fact] public void Ctor_EntityTagStringOverload_MatchExpectation() { RangeConditionHeaderValue rangeCondition = new RangeConditionHeaderValue("\"y\""); Assert.Equal(new EntityTagHeaderValue("\"y\""), rangeCondition.EntityTag); Assert.Null(rangeCondition.Date); AssertExtensions.Throws<ArgumentException>( "tag", () => { new RangeConditionHeaderValue((string)null); } ); } [Fact] public void Ctor_DateOverload_MatchExpectation() { RangeConditionHeaderValue rangeCondition = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero) ); Assert.Null(rangeCondition.EntityTag); Assert.Equal( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero), rangeCondition.Date ); } [Fact] public void ToString_UseDifferentrangeConditions_AllSerializedCorrectly() { RangeConditionHeaderValue rangeCondition = new RangeConditionHeaderValue( new EntityTagHeaderValue("\"x\"") ); Assert.Equal("\"x\"", rangeCondition.ToString()); rangeCondition = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero) ); Assert.Equal("Thu, 15 Jul 2010 12:33:57 GMT", rangeCondition.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentrangeConditions_SameOrDifferentHashCodes() { RangeConditionHeaderValue rangeCondition1 = new RangeConditionHeaderValue("\"x\""); RangeConditionHeaderValue rangeCondition2 = new RangeConditionHeaderValue( new EntityTagHeaderValue("\"x\"") ); RangeConditionHeaderValue rangeCondition3 = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero) ); RangeConditionHeaderValue rangeCondition4 = new RangeConditionHeaderValue( new DateTimeOffset(2008, 8, 16, 13, 44, 10, TimeSpan.Zero) ); RangeConditionHeaderValue rangeCondition5 = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero) ); RangeConditionHeaderValue rangeCondition6 = new RangeConditionHeaderValue( new EntityTagHeaderValue("\"x\"", true) ); Assert.Equal(rangeCondition1.GetHashCode(), rangeCondition2.GetHashCode()); Assert.NotEqual(rangeCondition1.GetHashCode(), rangeCondition3.GetHashCode()); Assert.NotEqual(rangeCondition3.GetHashCode(), rangeCondition4.GetHashCode()); Assert.Equal(rangeCondition3.GetHashCode(), rangeCondition5.GetHashCode()); Assert.NotEqual(rangeCondition1.GetHashCode(), rangeCondition6.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { RangeConditionHeaderValue rangeCondition1 = new RangeConditionHeaderValue("\"x\""); RangeConditionHeaderValue rangeCondition2 = new RangeConditionHeaderValue( new EntityTagHeaderValue("\"x\"") ); RangeConditionHeaderValue rangeCondition3 = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero) ); RangeConditionHeaderValue rangeCondition4 = new RangeConditionHeaderValue( new DateTimeOffset(2008, 8, 16, 13, 44, 10, TimeSpan.Zero) ); RangeConditionHeaderValue rangeCondition5 = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero) ); RangeConditionHeaderValue rangeCondition6 = new RangeConditionHeaderValue( new EntityTagHeaderValue("\"x\"", true) ); Assert.False(rangeCondition1.Equals(null), "\"x\" vs. <null>"); Assert.True(rangeCondition1.Equals(rangeCondition2), "\"x\" vs. \"x\""); Assert.False(rangeCondition1.Equals(rangeCondition3), "\"x\" vs. date"); Assert.False(rangeCondition3.Equals(rangeCondition1), "date vs. \"x\""); Assert.False(rangeCondition3.Equals(rangeCondition4), "date vs. different date"); Assert.True(rangeCondition3.Equals(rangeCondition5), "date vs. date"); Assert.False(rangeCondition1.Equals(rangeCondition6), "\"x\" vs. W/\"x\""); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { RangeConditionHeaderValue source = new RangeConditionHeaderValue( new EntityTagHeaderValue("\"x\"") ); RangeConditionHeaderValue clone = (RangeConditionHeaderValue)( (ICloneable)source ).Clone(); Assert.Equal(source.EntityTag, clone.EntityTag); Assert.Null(clone.Date); source = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero) ); clone = (RangeConditionHeaderValue)((ICloneable)source).Clone(); Assert.Null(clone.EntityTag); Assert.Equal(source.Date, clone.Date); } [Fact] public void GetRangeConditionLength_DifferentValidScenarios_AllReturnNonZero() { RangeConditionHeaderValue result = null; CallGetRangeConditionLength(" W/ \"tag\" ", 1, 9, out result); Assert.Equal(new EntityTagHeaderValue("\"tag\"", true), result.EntityTag); Assert.Null(result.Date); CallGetRangeConditionLength(" w/\"tag\"", 1, 7, out result); Assert.Equal(new EntityTagHeaderValue("\"tag\"", true), result.EntityTag); Assert.Null(result.Date); CallGetRangeConditionLength("\"tag\"", 0, 5, out result); Assert.Equal(new EntityTagHeaderValue("\"tag\""), result.EntityTag); Assert.Null(result.Date); CallGetRangeConditionLength("Wed, 09 Nov 1994 08:49:37 GMT", 0, 29, out result); Assert.Null(result.EntityTag); Assert.Equal(new DateTimeOffset(1994, 11, 9, 8, 49, 37, TimeSpan.Zero), result.Date); CallGetRangeConditionLength("Sun, 06 Nov 1994 08:49:37 GMT", 0, 29, out result); Assert.Null(result.EntityTag); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), result.Date); } [Fact] public void GetRangeConditionLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetRangeConditionLength(" \"x\"", 0); // no leading whitespace allowed CheckInvalidGetRangeConditionLength(" Wed 09 Nov 1994 08:49:37 GMT", 0); CheckInvalidGetRangeConditionLength("\"x", 0); CheckInvalidGetRangeConditionLength("Wed, 09 Nov", 0); CheckInvalidGetRangeConditionLength("W/Wed 09 Nov 1994 08:49:37 GMT", 0); CheckInvalidGetRangeConditionLength("\"x\",", 0); CheckInvalidGetRangeConditionLength("Wed 09 Nov 1994 08:49:37 GMT,", 0); CheckInvalidGetRangeConditionLength("", 0); CheckInvalidGetRangeConditionLength(null, 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse(" \"x\" ", new RangeConditionHeaderValue("\"x\"")); CheckValidParse( " Sun, 06 Nov 1994 08:49:37 GMT ", new RangeConditionHeaderValue( new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) ) ); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("\"x\" ,"); // no delimiter allowed CheckInvalidParse("Sun, 06 Nov 1994 08:49:37 GMT ,"); // no delimiter allowed CheckInvalidParse("\"x\" Sun, 06 Nov 1994 08:49:37 GMT"); CheckInvalidParse("Sun, 06 Nov 1994 08:49:37 GMT \"x\""); CheckInvalidParse(null); CheckInvalidParse(string.Empty); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidTryParse(" \"x\" ", new RangeConditionHeaderValue("\"x\"")); CheckValidTryParse( " Sun, 06 Nov 1994 08:49:37 GMT ", new RangeConditionHeaderValue( new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) ) ); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("\"x\" ,"); // no delimiter allowed CheckInvalidTryParse("Sun, 06 Nov 1994 08:49:37 GMT ,"); // no delimiter allowed CheckInvalidTryParse("\"x\" Sun, 06 Nov 1994 08:49:37 GMT"); CheckInvalidTryParse("Sun, 06 Nov 1994 08:49:37 GMT \"x\""); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); } #region Helper methods private void CheckValidParse(string input, RangeConditionHeaderValue expectedResult) { RangeConditionHeaderValue result = RangeConditionHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>( () => { RangeConditionHeaderValue.Parse(input); } ); } private void CheckValidTryParse(string input, RangeConditionHeaderValue expectedResult) { RangeConditionHeaderValue result = null; Assert.True(RangeConditionHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { RangeConditionHeaderValue result = null; Assert.False(RangeConditionHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CallGetRangeConditionLength( string input, int startIndex, int expectedLength, out RangeConditionHeaderValue result ) { object temp = null; Assert.Equal( expectedLength, RangeConditionHeaderValue.GetRangeConditionLength(input, startIndex, out temp) ); result = temp as RangeConditionHeaderValue; } private static void CheckInvalidGetRangeConditionLength(string input, int startIndex) { object result = null; Assert.Equal( 0, RangeConditionHeaderValue.GetRangeConditionLength(input, startIndex, out result) ); Assert.Null(result); } #endregion } }
41.057239
97
0.596359
[ "MIT" ]
belav/runtime
src/libraries/System.Net.Http/tests/UnitTests/Headers/RangeConditionHeaderValueTest.cs
12,194
C#
using System; using System.ComponentModel; [Serializable] [Description("gold")] public class Gold { public int gold; public static Gold actualGold; public Gold(int gold) { this.gold = gold; } public string Print() { return string.Format("{0}", gold); } }
14
42
0.603896
[ "Apache-2.0" ]
Playyer96/rpg-clientF
Assets/Scripts/REST/Gold.cs
310
C#