function setMenu(param1, param2){ if(param2 === undefined){ param2 = -1; } //Code }You can call this function in multiple ways:
setMenu(0, 5); setMenu(0); //Param2 will be set to '-1' by the functionAnd both will work.
function setMenu(param1, param2){ if(param2 === undefined){ param2 = -1; } //Code }You can call this function in multiple ways:
setMenu(0, 5); setMenu(0); //Param2 will be set to '-1' by the functionAnd both will work.
<Grid.Resources> <Style x:Key="CategoryLegendItem" TargetType="toolkit:LegendItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="toolkit:LegendItem"> <StackPanel Orientation="Horizontal"> <Rectangle Width="8" Height="8" Fill="{Binding Background}" Stroke="{Binding BorderBrush}" StrokeThickness="1" Margin="0,0,3,0" /> <HyperlinkButton Content="{TemplateBinding Content}" Click="HyperlinkButton_Click" /> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </Grid.Resources>Notice how I replaced the default Title element that displays the legend item text by a HyperlinkButton. That way it actually looks like something that can be clicked. This button also triggers the click event.
series.LegendItemStyle = (Style)LayoutRoot.Resources["CategoryLegendItem"]Finally there's the HyperlinkButtons click handler.
private void HyperlinkButton_Click(object sender, RoutedEventArgs e) { RowPrestation row = (RowPrestation)((sender as HyperlinkButton) .DataContext as PieDataPoint).DataContext; PieSeries series = (PieSeries)(Chart.Child as Chart).Series[0]; series.SelectedItem = row; }Notice that the DataContext of the HyperlinkButton contains the PieDataPoint — in case of a pie chart — that goes with the legend item in question. And if you cast it, that points DataContext contains the bound object that was used as ItemsSource. Mine was a List<RowPrestation>.
ViewBag.DataFilter = new JavaScriptSerializer().Serialize(filter);Where filter is the object.
//Parse parser = document.createElement('div'); parser.innerHTML = '@(ViewBag.DataFilter)'; var DataFilter = $.parseJSON(parser.innerHTML); //Test alert(DataFilter.Fields[0].FieldName);And that's all there's to it.
[WebMethod] public WebServiceResponse CallService(string name, string url, string method, string contentType, string postData) { WebServiceResponse result = new WebServiceResponse(); try{ //Convert the post data into a byte array //The post data is a string like "username=EGS&password=305" byte[] data = null; if (!string.IsNullOrEmpty(postData)) data = Encoding.UTF8.GetBytes(postData); //Create the request and write the post data to it if any WebRequest request = WebRequest.Create(url); if (!string.IsNullOrEmpty(method)) request.Method = method; if (!string.IsNullOrEmpty(contentType)) request.ContentType = contentType; if (data != null) { request.ContentLength = (long)data.Length; using (Stream stream = request.GetRequestStream()) stream.Write(data, 0, data.Length); } else request.ContentLength = 0L; //Get the response from the web service using (WebResponse response = request.GetResponse()) using (StreamReader reader = new StreamReader(response.GetResponseStream())) { result.StatusCode = (int)(response as HttpWebResponse).StatusCode; result.StatusDescription = (response as HttpWebResponse).StatusDescription; result.Content = reader.ReadToEnd(); } } catch (Exception ex) { result.Error = "Error: [DashboardService.CallService] " + ex.Message; } return result; }WebServiceResponse is a custom class with the properties StatusCode, StatusDescription, Content and Error.
List<Customer> list = (from r in dataTable.AsEnumerable() select new Customer { Id = r.Field<int>("Id"), Name = r.Field<string>("Name"), Created = r.Field<datetime>("Created") }).ToList();
List<string> columnNames = (from c in dataTable.Columns.Cast<datacolumn>() select c.ColumnName).ToList();
public class BindableColumnHeader : BehaviorIt needs that .dll from before.{ public object Header { get { return GetValue(HeaderProperty); } set { SetValue(HeaderProperty, value); } } public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header", typeof(object), typeof(BindableColumnHeader), new PropertyMetadata( new PropertyChangedCallback(HeaderBindingChangedHandler))); private static void HeaderBindingChangedHandler( DependencyObject o, DependencyPropertyChangedEventArgs e) { var behave = o as BindableColumnHeader; if (behave != null && behave.AssociatedObject != null) behave.AssociatedObject.Header = e.NewValue; } protected override void OnAttached() { if (this.AssociatedObject != null) this.AssociatedObject.Header = this.Header; base.OnAttached(); } }
<data:datagridtextcolumn binding="{Binding Customer}"> <i:interaction.behaviors> <synbus:bindablecolumnheader header="{Binding Whatever}" /> </i:interaction.behaviors> </data:datagridtextcolumn>
renameWnd.Ok += new RenameWindow.OkEventHandler(delegate(object sender, EventArgs e) { //Whatever needs to be done });Or shorter:
renameWnd.Ok += (object sender, EventArgs e) => { //Whatever needs to be done };And even shorter:
renameWnd.Ok += delegate { //Whatever needs to be done };How much shorter can it get?
renameWnd.Ok += (sender, e) => DoOneThing();Not much to it once you know.
using System.Drawing; using System.Drawing.Drawing2D; ... Image image = Image.FromFile(filePath); if (image.Width > App.MAX_UPLOAD_IMAGE_SIZE || image.Height > App.MAX_UPLOAD_IMAGE_SIZE) { int w = image.Width; int h = image.Height; if (w > h) { w = App.MAX_UPLOAD_IMAGE_SIZE; h = image.Height * w / image.Width; } else { w = image.Width * h / image.Height; h = App.MAX_UPLOAD_IMAGE_SIZE; } Bitmap bitmap = new Bitmap(w, h); Graphics g = Graphics.FromImage((Image)bitmap); g.InterpolationMode = InterpolationMode.HighQualityBilinear; g.DrawImage(image, 0, 0, w, h); g.Dispose(); image.Dispose(); (bitmap as Image).Save(filePath); }
public class TabJustifyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return 0; } else if (!(value is TabControl)) { throw new Exception(@"The TabJustifyConverter must be supplied a TabControl."); } else { TabControl tab = value as TabControl; int count = 0; foreach (TabItem item in tab.Items) if (item.Visibility == Visibility.Visible) count++; return (tab.ActualWidth / count) - 2; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
<controls:TabItem x:Name="tabCustomer" Header="Customer" Width="{Binding ElementName=tabControl, Converter={StaticResource TabJustifyConverter}}">I tried putting that in a resource, but kept getting a "cannot set read-only property"-exception.
var objects = document.getElementsByTagName("object"); for (var i = 0; i < objects.length; i++) { objects[i].outerHTML = objects[i].outerHTML; }Then, at the bottom of any HTML page containing embedded objects, include this file like so:
<script src="FixActivate.js" type="text/javascript"></script>Now when the page is loaded, the embedded objects are immediately active.
public BindingListProductList { get; private set; }
<DataTemplate> <this:ComboBox ItemsSource="{Binding ProductList, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type this:ucStoreVisit}}}" /> </DataTemplate>
Often when outputting an exception message, you get "see inner exception" or "one or more errors occured" for an aggregate exception. It would be convenient to, when outputting error messages, you get those attached. This extension does that. It keeps going down the inner exceptions until there are no more, and outputs them line by line:
/// <summary> /// Returns a string that contains the message and inner messages. /// </summary> public static string GetFullMessage(this Exception source) { var result = new StringBuilder(); var ex = source; try { while (ex != null) { if (result.Length > 0) result.Append(Environment.NewLine); result.Append(ex.Message); //It's handy to get the actual errors when these errors occur. if (ex is ReflectionTypeLoadException) { result.AppendLine("Loader exceptions:"); var typeErrors = (ex as ReflectionTypeLoadException)?.LoaderExceptions; if (typeErrors != null) foreach (var typeError in typeErrors) result.AppendLine(typeError?.Message); } else if (ex is AggregateException) { result.AppendLine("Aggregate exceptions:"); var inner = ex.InnerException; while (inner != null) { result.AppendLine(inner.Message); inner = inner.InnerException; } } ex = ex.InnerException; } } catch (Exception ex2) { result.AppendLine("The following error occured in GetFullMessage:"); result.AppendLine(ex2?.Message); } return result.ToString(); }
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null || value.GetType() != targetType) return null; else return value; }I've put the resource for it in the resources of the App-class, so I don't have to do that in every XAML-file that needs it:
<this:NullObjectConverter x:Key="convNull" />
<toolkit:DataGridComboBoxColumn Header="Store" SelectedValueBinding="{Binding Store, Converter={StaticResource convNull}}"> <toolkit:DataGridComboBoxColumn.ItemsSource> <CompositeCollection> <ListBoxItem>(none)</ListBoxItem> <CollectionContainer x:Name="cboStoreCollection" /> </CompositeCollection> </toolkit:DataGridComboBoxColumn.ItemsSource> </toolkit:DataGridComboBoxColumn>The none-option will arrive in the converter as a ListBoxItem while the target type will be the type of the bound object, and therefore the converter will send NULL to the bindings' source when it's selected.
cboStoreCollection.Collection = mStores;
function stopPropagation(e){ var e = e || event; //Because of IE e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true; //Cancel the event }
e.stopImmediatePropagation();
function findPos(element){ var left = top = 0; if(element.offsetParent){ do{ left += element.offsetLeft; top += element.offsetTop; } while(element = element.offsetParent); } return [left, top]; }
var pos = element.offset(); alert(pos.left + ';' + pos.top);
public enum Language { Dutch = 0, English = 1, French = 2 }
public static class Dictionary { public static Language Language { get; set; } public static string Book { get { return GetEntry("Boek", "Book", "Livre"); } } private static string GetEntry(params string[] entries) { if (entries.Length > (int)Language) return entries[(int)Language]; else return string.Empty; } }
Dictionary.Language = theUsersLanguage;
this.Title = Dictionary.Book;
Version version = Assembly.GetExecutingAssembly().GetName().Version; string formattedVersion = version.GetFormattedString();This extension would then be the following:
public static string Format(this Version version) { var result = new StringBuilder(); result.Append(version.Major).Append('.').Append(version.Minor); if (version.Build > 0 || version.Revision > 0) result.Append('.').Append(version.Build); if (version.Revision > 0) result.Append('.').Append(version.Revision); return result.ToString(); }
return View("Edit");This view will be found in either:
return View("~\\Views\\Administration\\CategoryEdit.cshtml");
<!--[if gte IE 7]> <style type="text/css"> #SearchButton{ height:23px; } </style> <![endif]-->This CSS rule would be applied only by IE7 and later.
unselectable="on"to it.
private Dictionary<int, Customer> DataSupport { get; set; } foreach (KeyValuePair<int, Customer> customer in DataSupport) { int key = customer.Key; Customer value = customer.Value; }
if (File.Exists(App.CUSTOMERS_FILE_NAME)) { using (var reader = new StreamReader(App.CUSTOMERS_FILE_NAME)) { string line = string.Empty; while ((line = reader.ReadLine()) != null) { //Process the line } } }
using (var writer = new StreamWriter(App.CUSTOMERS_FILE_NAME, false, Encoding.Unicode)) { writer.WriteLine("Whatever value"); }The file will be automatically created if it doesn't exist yet.
The version of SQL Server in use does not support datatype ‘datetime2′.The solution is changing a setting in the Entity Framework to target SQL Server 2005 instead of 2008. This setting is not available through the IDE, so:
function synGetCaret(editor) { if(document.selection){ editor.focus(); var range = document.selection.createRange(); var range2 = range.duplicate(); range2.moveToElementText(editor); range2.setEndPoint('EndToEnd', range); var selStart = range2.text.length - range.text.length; return new Array(selStart, selStart + range.text.length); } }The return value is an array with 0 = start and 1 = end.
function synSetCaret(editor, selection) { if (document.selection) { if (selection[0] == NaN) selection[0] = 0; if (selection[1] == NaN) selection[1] = selection[0]; if (editor.setSelectionRange) { editor.setSelectionRange(selection[0], selection[1]); } else if (editor.createTextRange) { var range = editor.createTextRange(); range.collapse(true); range.moveEnd('character', selection[1]); range.moveStart('character', selection[0]); range.select(); } } }
<Grid.RowDefinitions> <Rowdefinition Height="32"> <Rowdefinition Height="7*" x:Name="rowDefTables"> <Rowdefinition Height="3*"> </Grid.RowDefinition>
mSettings.SplitterTablesColumnsPosition = Convert.ToInt32(rowdefTables.Height.Value); mSettings.SaveSettings(); //To a .ini file
mSettings.LoadSettings(); //From the .ini file if (mSettings.SplitterTablesColumnsPosition > 0) rowdefTables.Height = new GridLength( (double)mSettings.SplitterTablesColumnsPosition, GridUnitType.Pixel);
public static void Store(HttpFileCollectionBase files, EntityCollectionlist) { List attachments = new List (); Attachment attachment = null; HttpPostedFileBase file = null; FileStream stream = null; string fullName = string.Empty; byte[] buffer = null; int length = 0; if (files != null && files.Count > 0) { foreach (string inputName in files) { if (!string.IsNullOrEmpty(inputName)) { file = files[inputName] as HttpPostedFileBase; if (file != null && !string.IsNullOrEmpty(file.FileName)) { //Generate file name fullName = Guid.NewGuid().ToString() + '-' + file.FileName; //Store the actual file using (stream = File.Create( HttpContext.Current.Server.MapPath( App.FOLDER_ATTACHMENTS + '/' + fullName))) { buffer = new byte[file.ContentLength]; length = file.InputStream.Read(buffer, 0, file.ContentLength); stream.Write(buffer, 0, length); } //Create and attach to the entities attachment = new Attachment() { Name = fullName, Size = file.ContentLength }; list.Add(attachment); } } } } }
public const string DECIMAL_FORMAT = "0.##"; public static string ToFormattedSize(int size) { float KB = 1024f; float MB = 1024f * KB; float GB = 1024f * MB; if (!size.HasValue) return "-"; else if ((float)size.Value > GB) return ((float)size.Value / GB).ToString(DECIMAL_FORMAT) + " GB"; else if ((float)size.Value > MB) return ((float)size.Value / MB).ToString(DECIMAL_FORMAT) + " MB"; else if ((float)size.Value > KB) return ((float)size.Value / KB).ToString(DECIMAL_FORMAT) + " KB"; else return ((float)size).Value.ToString(DECIMAL_FORMAT) + " B"; }
private static readonly byte[] KEY = { 15, 85, 64, 52, 131, 86, 216, 44 }; private static readonly byte[] IV = { 5, 44, 19, 95, 129, 164, 9, 108 };
public static string Encrypt(this string source) { try { if (string.IsNullOrEmpty(source)) return source; else { using (var des = new DESCryptoServiceProvider()) using (var ms = new MemoryStream()) using (var cs = new CryptoStream(ms, des.CreateEncryptor(KEY, IV), CryptoStreamMode.Write)) using (var sw = new StreamWriter(cs)) { sw.Write(source); sw.Flush(); cs.FlushFinalBlock(); sw.Flush(); return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); } } } catch { return string.Empty; } }
public static string Decrypt(this string source) { try { if (string.IsNullOrEmpty(source)) return source; else { using (var des = new DESCryptoServiceProvider()) using (var ms = new MemoryStream(Convert.FromBase64String(source))) using (var cs = new CryptoStream(ms, des.CreateDecryptor(KEY, IV), CryptoStreamMode.Read)) using (var sr = new StreamReader(cs)) { return sr.ReadToEnd(); } } } catch { return string.Empty; } }
public class GridFilter { public string GroupOp { get; set; } public IEnumerableRules { get; set; } } public class GridFilterRule { public string Field { get; set; } public string Op { get; set; } public string Data { get; set; } }
GridFilter filter = new JavaScriptSerializer().Deserialize(filters);
[Flags] public enum Role{ AuxCreator = 1, AuxEditor = 2, AuxDeletor = 4 }
int roles = Role.AuxCreator | Role.AuxDeletor; //roles = 5
bool isAuxDeletor = (roles & Role.AuxDeletor) == Role.AuxDeletor; //isAuxDeletor = true
int roles = Role.AuxCreator & (~Role.AuxDeletor); //roles = 1
@Html.RouteLink("Nederlands", new { Controller = "Home", Action = "Language", culture = "nl-BE" })
public ActionResult Language(string culture) { App.SetCulture(culture); return RedirectToAction("Index"); }
public static void Store(string key, object value) { if (HttpContext.Current.Session != null) HttpContext.Current.Session[key] = value; } public static object Retrieve(string key) { return HttpContext.Current.Session == null ? null : HttpContext.Current.Session[key]; } public static void SetCulture(string cultureName) { Store("culture", cultureName); Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(cultureName); }
App.SetCulture((string)App.Retrieve("culture") ?? "nl-BE");
string color = "#FF00FF"; //This would be a parameter if (color.StartsWith("#")) color = color.Remove(0, 1); byte r, g, b; if (color.Length == 3) { r = Convert.ToByte(color[0] + "" + color[0], 16); g = Convert.ToByte(color[1] + "" + color[1], 16); b = Convert.ToByte(color[2] + "" + color[2], 16); } else if (color.Length == 6) { r = Convert.ToByte(color[0] + "" + color[1], 16); g = Convert.ToByte(color[2] + "" + color[3], 16); b = Convert.ToByte(color[4] + "" + color[5], 16); } else { throw new ArgumentException("Hex color " + color + " is invalid."); } return new Color.FromArgb(255, r, g, b);
using (MemoryStream stream = new MemoryStream()) { XmlTextWriter xml = new XmlTextWriter(stream, Encoding.UTF8); xml.WriteStartDocument(); xml.WriteStartElement("output"); string value = string.Empty; foreach (DataRow row in data.Rows) { xml.WriteStartElement("row"); foreach (DataColumn col in data.Columns) { value = row[col].ToString(); xml.WriteElementString(col.ColumnName, value); } xml.WriteEndElement(); } xml.WriteEndElement(); xml.WriteEndDocument(); xml.Flush(); byte[] bytes = stream.ToArray(); Response.Clear(); Response.AppendHeader("Content-Disposition", "filename=Output.xml"); Response.AppendHeader("Content-Length", bytes.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.BinaryWrite(bytes); xml.Close(); }
TableServiceContext tableContext = tableClient.GetDataServiceContext(); tableContext.AddObject("Products", new Product() { PartitionKey = "SynProd", RowKey = Guid.NewGuid().ToString(), Name = "EGS Database Tool 1.0.2.0", PurchasePrice = 1400.50m }); tableContext.SaveChanges();
One of the request inputs is not validbecause of the decimal value in the object. Those are not yet supported in tables.
ADO.NET CLR Detail Edm.Binary byte[] Max. 64 kB Edm.Boolean bool Edm.DateTime DateTime 64-bit UTC 01 jan 1601 0:00 - 31 dec 9999 Edm.Double double 64-bit Edm.Guid Guid 128-bit Edm.Int32 int 32-bit Edm.Int64 Int64 64-bit Edm.String string Max. 64 kB, UTF-16 encoded
App.Current.Host.Content.IsFullScreen = true;And just set it to false to reverse it.
Foreground="{x:Static SystemColors.HighlightBrush}"
<Image Source="Help.png" Margin="4 2" Cursor="Hand" Stretch="None"> <Image.ToolTip> <Border CornerRadius="4" Padding="2"> <StackPanel Orientation="Vertical"> <TextBlock x:Name="txtTitle" Margin="1" FontWeight="Bold" /> <TextBlock x:Name="txtText" Margin="1" /> </StackPanel> </Border> </Image.ToolTip> </Image>
ToolTipService.ShowDuration="60000"to the control owning the tooltip, the tooltip will be displayed a whole minute instead of the default 5 seconds.
public partial class HelpUserControl : UserControl { public static readonly DependencyProperty HelpTextProperty = DependencyProperty.Register("HelpText", typeof(string), typeof(HelpUserControl), new PropertyMetadata(OnHelpTextChanged)); public string HelpText { get { return (string)this.GetValue(HelpTextProperty); } set { this.SetValue(HelpTextProperty, value); } } private static void OnHelpTextChanged( DependencyObject target, DependencyPropertyChangedEventArgs e) { (target as HelpUserControl).imgIcon.ToolTip = e.NewValue.ToString(); } }
using System.IO.IsolatedStorage; using(IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForSite()){ if (storage.FileExists(IS_FILE_NAME)) { using(IsolatedStorageFileStream stream = new IsolatedStorageFileStream(IS_FILE_NAME, FileMode.Open, storage)){ //Read the stream } } }
using(IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForSite()){ using(IsolatedStorageFileStream stream = new IsolatedStorageFileStream(IS_FILE_NAME, FileMode.OpenOrCreate, storage)){ stream.WriteLine("EGS rules!"); } }
In XAML, you can use value converters to convert a bound business data value into a GUI-usable value using a class like this one:
public class CurrencyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => ((double)value).ToString("C"); public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => double.Parse((string)value); }
A converter must be put in the resources like so:
<this:CurrencyConverter x:Key="CurrencyConverter" />
You can put it in App.xaml for project-wide usage.
To be then included in a binding like this.
You can also pass it a parameter if you like:
{Binding Amount, Converter={StaticResource CurrencyConverter}} {Binding Amount, Converter={StaticResource CurrencyConverter}, ConverterParameter=EUR}
The parameter is passed as a string.
If you want to pass something else, you can use a markup extension.
<ObjectDataProvider x:Key="Lan" ObjectType="{x:Type this:Culture}" MethodName="GetCulture" />
Culture.Set(culture); ((ObjectDataProvider)App.Current.FindResource("Lan")).Refresh();
{Binding Path=Options, Source={StaticResource Lan}}
<trust level="WSS_Minimal" originUrl="" />
<SecurityClass Name="OdbcPermission" Description="System.Data.Odbc.OdbcPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<IPermission class="OdbcPermission" version="1" Unrestricted="true" />
Microsoft SharePoint Foundation version 3 templates are not supported in this version of the product
C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\ClientI suppose it's a nice feature in some cases, but it rather annoyed me, so I wanted to get rid of them. So I deleted all the localized sub folders in the SDK (de, fr, za-Hans, etc.) and yes!, at the next build localized dll's were no longer generated.
using System; using System.ServiceModel; using System.ServiceModel.Channels; using System.Windows; using EGS.KeyGen.QueryService; namespace EGS.KeyGen { internal class DynamicServiceClient { internal static QueryServiceSoapClient GetClient() { BasicHttpSecurityMode securityMode = Application.Current.Host.Source.Scheme.Equals("https") ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None; BasicHttpBinding binding = new BasicHttpBinding(securityMode); binding.MaxReceivedMessageSize = int.MaxValue; binding.MaxBufferSize = int.MaxValue; return new QueryServiceSoapClient(binding, new EndpointAddress(new Uri(App.ServiceUrl))); } } }
<param name="initParams" value="ServiceUrl=http://www.EGS.be/QueryService.asmx" />and sets it like so:
private void Application_Startup(object sender, StartupEventArgs e) { if (e.InitParams.ContainsKey("ServiceUrl")) ServiceUrl = e.InitParams["ServiceUrl"]; ...
<input type="text" onkeypress="if(event.keyCode==13) document.getElementById('btnToTrigger').click()" />
protected string EncodeStrToHex(string str) { if (string.IsNullOrEmpty(str)) return str; byte[] chars = Encoding.UTF8.GetBytes(str); StringBuilder result = new StringBuilder(chars.Length); foreach (byte c in chars) { result.Append(c.ToString("X2")); } return result.ToString(); } protected string EncodeHexToStr(string hex) { if (string.IsNullOrEmpty(hex)) return hex; byte[] chars = new byte[hex.Length / 2]; string c = string.Empty; for (int i = 0, j = 0; i < chars.Length; i++, j += 2) { c = new string(new char[] { hex[j], hex[j + 1] }); chars[i] = byte.Parse(c, NumberStyles.HexNumber); } return Encoding.UTF8.GetString(chars); }
<httpRuntime requestValidationMode="2.0" />to the
<system.web>section.
Convert.ChangeType(value, type)
else if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (string.IsNullOrEmpty(value)) { return defaultValue; //Commonly 'null' } else { NullableConverter nullConv = new NullableConverter(type); return Convert.ChangeType(value, nullConv.UnderlyingType); } }
public IEnumerableGetStatements(string query) { string[] parts = query.Split(new string[] { ";\r\n" }, StringSplitOptions.RemoveEmptyEntries); return from p in parts select p.Trim(new char[] { ' ', ';', '\t' }); }
Clipboard.SetData(DataFormats.Text, text);
txtQuery.Paste();
xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"
<toolkit:Viewbox Stretch="Uniform">
</toolkit:Viewbox>
Sometimes you need to throw your own custom event with custom arguments. The arguments can be passed directly or by implementing a custom class that inherits from EventArgs. The latter is needed when adding handlers on the event in for instance XAML. The event can be e.g.:
public delegate void ValidationEventHandler(object sender, ValidationEventArgs e); public event ValidationEventHandler Validation; protected virtual void OnValidation(string propertyName, bool isValid, string message) { if (Validation != null) Validation(this, new ValidationEventArgs(propertyName, isValid, message)); }
Which can then be raised by:
OnValidation("Code", false, "Value must not be empty.");
Or you skip the helper method. Make sure the event is not null, meaning there are no listeners:
Validation?.Invoke(this, new ValidationEventArgs(nameof(Code), false, "Value must not be empty."));
You can also use the generic delegate. It can be invoked the same way.
public event EventHandler<ValidationEventArgs> Validation;
private void NotifyPropertyChanged([CallerMemberName]string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
NotifyPropertyChanged();
function startsWith($Text, $Value){ return strpos($Text, $Value) === 0; } function endsWith($Text, $Value){ return strrpos($Text, $Value) === strlen($Text) - strlen($Value); }
<Style x:Key="Button" TargetType="Button">
<Style.Resources>
<LinearGradientBrush x:Key="lgbNormal" StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="{x:Static SystemColors.ControlLightLightColor}" />
<GradientStop Offset="0.5" Color="{x:Static SystemColors.ControlLightColor}" />
<GradientStop Offset="0.5" Color="{x:Static SystemColors.ControlDarkDarkColor}" />
<GradientStop Offset="1" Color="{x:Static SystemColors.ControlDarkDarkColor}" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="lgbMouseOver" StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="{x:Static SystemColors.ControlLightLightColor}" />
<GradientStop Offset="0.5" Color="#083B80" />
<GradientStop Offset="0.5" Color="{x:Static SystemColors.ControlDarkDarkColor}" />
<GradientStop Offset="1" Color="{x:Static SystemColors.ControlDarkDarkColor}" />
</LinearGradientBrush>
</Style.Resources>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="border" BorderThickness="1" BorderBrush="#3E3E3E" CornerRadius="2">
<Grid>
<Rectangle x:Name="rect" RadiusX="2" RadiusY="2" Fill="{StaticResource lgbNormal}" />
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="rect" Property="Fill" Value="{StaticResource lgbMouseOver}" />
<Setter TargetName="border" Property="BorderBrush" Value="#083B80" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="border" Property="Opacity" Value="0.5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
svg2xaml D:\Projects\ArrowUp.svg