Posts

Showing posts with the label C#

CA1062: ValidateArgumentsOfPublicMethods On Co-constructor Calls

Answer : Like this? public MyClass(SomeOtherClass source) : this(source, source == null ? null : source.Name) { } public MyClass(SomeOtherClass source, string name) { /* ... */ }

AutoEllipsis=true Affects The Vertical Positioning Of The Text

Answer : I see it. This looks like a limitation in the underlying winapi, DrawTextEx(). Which doesn't get a lot of help from the Label class, it doesn't turn on the DT_SINGLELINE option (aka TextFormatFlags.SingleLine) since it is capable of rendering multiple lines. DrawTextEx() documents that this is required to get vertically centered text (DT_VCENTER). So the real bug is that it shouldn't be centered at all :) Do note that you do get centered text when you grow the label vertically. The simplest way to work around it is by setting the label's UseCompatibleTextRendering property to True.

C#: Looping Through Lines Of Multiline String

Answer : I suggest using a combination of StringReader and my LineReader class, which is part of MiscUtil but also available in this StackOverflow answer - you can easily copy just that class into your own utility project. You'd use it like this: string text = @"First line second line third line"; foreach (string line in new LineReader(() => new StringReader(text))) { Console.WriteLine(line); } Looping over all the lines in a body of string data (whether that's a file or whatever) is so common that it shouldn't require the calling code to be testing for null etc :) Having said that, if you do want to do a manual loop, this is the form that I typically prefer over Fredrik's: using (StringReader reader = new StringReader(input)) { string line; while ((line = reader.ReadLine()) != null) { // Do something with the line } } This way you only have to test for nullity once, and you don't have to think about a do/while...

Collapse All #regions Only(!) In C# (Visual Studio)

Answer : in Visual Studio 2017 I have to activate 'Collapse #regions when collapsing to definitions' in Tools -> Options -> Text Editor -> C# -> Advanced explicitly to collapse all when pressing Ctrl + M + O Ctrl + M + O will collapse all. Ctrl + M + L will expand all. (in VS 2013 - Toggle All outlining) Ctrl + M + P will expand all and disable outlining. Ctrl + M + M will collapse/expand the current section. These options are also in the context menu under Outlining. Right click in editor -> Outlining to find all options. (After disabling outlining, use same steps to enable outlinging.) The Visual Studio extension Productivity Power Tools 2015 from Microsoft has a feature called Quick Launch Tasks that adds new commands to the Quick Launch menu. One of them is CollapseRegions and it does exactly that. The opposite command is ExpandRegions and it expands all regions for quick browsing of the entire file. These commands can be used pre...

Assign Null To A SqlParameter

Answer : The problem is that the ?: operator cannot determine the return type because you are either returning an int value or a DBNull type value, which are not compatible. You can of course cast the instance of AgeIndex to be type object which would satisfy the ?: requirement. You can use the ?? null-coalescing operator as follows SqlParameter[] parameters = new SqlParameter[1]; SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int); planIndexParameter.Value = (object)AgeItem.AgeIndex ?? DBNull.Value; parameters[0] = planIndexParameter; Here is a quote from the MSDN documentation for the ?: operator that explains the problem Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other. The accepted answer suggests making use of a cast. However, most of the SQL types have a special Null field which can be used to avoid this cast. For example...

Collapse Grid Row In WPF

Answer : All you need is something to cache the height(s) of the visible row. After that, you no longer need converters or to toggle visibility of contained controls. CollapsibleRow public class CollapsibleRow : RowDefinition { #region Fields private GridLength cachedHeight; private double cachedMinHeight; #endregion #region Dependency Properties public static readonly DependencyProperty CollapsedProperty = DependencyProperty.Register("Collapsed", typeof(bool), typeof(CollapsibleRow), new PropertyMetadata(false, OnCollapsedChanged)); private static void OnCollapsedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is CollapsibleRow row && e.NewValue is bool collapsed) { if(collapsed) { if(row.MinHeight != 0) { row.cachedMinHeight = row.MinHeight; row.MinHeight = 0; } ...

C# WPF - ScrollViewer + TextBlock Troubles

Answer : This works: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Name="Scroller"> <TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="100" Width="{Binding ElementName=Scroller, Path=ViewportWidth}" TextWrapping="Wrap" Text="Some really long text that should probably wordwrap when you resize the window." /> </ScrollViewer> </Window> Without more detail, the best I can do is provide the standard way of doing this. Basically, host your element (which has a minimum size) in a scroll viewer; when th...

C# Parameterized Query MySQL With `in` Clause

Answer : This is not possible in MySQL. You can create a required number of parameters and do UPDATE ... IN (?,?,?,?). This prevents injection attacks (but still requires you to rebuild the query for each parameter count). Other way is to pass a comma-separated string and parse it. You could build up the parametrised query "on the fly" based on the (presumably) variable number of parameters, and iterate over that to pass them in. So, something like: List foo; // assuming you have a List of items, in reality, it may be a List<int> or a List<myObject> with an id property, etc. StringBuilder query = new StringBuilder( "UPDATE TABLE_1 SET STATUS = ? WHERE ID IN ( ?") for( int i = 1; i++; i < foo.Count ) { // Bit naive query.Append( ", ?" ); } query.Append( " );" ); MySqlCommand m = new MySqlCommand(query.ToString()); for( int i = 1; i++; i < foo.Count ) { m.Parameters.Add(new MySqlParameter(...)); } You cann...

"Build Failed" On Database First Scaffold-DbContext

Answer : Two most important tips: [1] - Make sure that your project builds completely before you run a new scaffold command. Otherwise... You'll start writing a line of code. You'll realize a required DB column is missing from your model. You'll go to try to scaffold it. Twenty minutes later you'll realize the reason your build (and scaffold command) is failing is because you literally have a half written line of code. Oops! [2] - Check into source control or make a copy: Allows you to easily verify what changed. Allows rollback if needed. You can get some very annoying 'chicken and egg' problems if you get unlucky or make a mistake. Other problems: If you have multiple DLLs make sure you aren't generating into the wrong project . A 'Build failed' message can occur for many reasons, but the dumbest would be if you don't have EFCore installed in the project you're scaffolding into. In the package manager console there is ...

AES Encryption Error: The Input Data Is Not A Complete Block?

Answer : StreamWriter writes UTF8 text characters to a stream. You're writing plaintext.ToString() as text for the ciphertext. This returns "System.Byte[]" , which does not translate into 16 bytes of UTF8. I believe the problem to be padding mode. Unless your text to be encrypted is for sure divisible by BlockSize (in bits, or BlockSize / 8 in bytes), you should specify a PaddingMode other than None. see the post here for example code I changed the function to this: public static byte[] Encrypt(byte[] plaintext, byte[] key) { using (var aes = Aes.Create()) { aes.BlockSize = 128; aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.None; var encryptor = aes.CreateEncryptor(key, new byte[16]); using(var target = new MemoryStream()) using (var cs = new CryptoStream(target, encryptor, CryptoStreamMode.Write)) { cs.Write(plaintext, 0, plaintext.Length); return target.ToArray...

Click Event For WPF Image

Answer : Just add a MouseDown (or MouseLeftButtonDown as suggested) event to your image like so <Image x:Name=aPicture Source="mypic.jpg" MouseDown="aPicture_MouseDown"/> // or <Image x:Name=aPicture Source="mypic.jpg" MouseLeftButtonDown="aPicture_MouseDown"/> which should add this to your code behind private void aPicture_MouseDown(object sender, MouseEventArgs e) { //do something here } In WPF each control has its default template (how it looks) but you can easily change these templates and make controls look like you want. This makes it easier to pick control by its functionality and make it look like you want. In your case you want Click so you choose Button and change its Template <Window ...> <Window.Resources> <Style TargetType="{x:Type Button}" x:Key="ImageButtonStyle"> <Setter Property="Template"> <Setter.Value...

Check If A String Is A Valid Date Using DateTime.TryParse

Answer : If you want your dates to conform a particular format or formats then use DateTime.TryParseExact otherwise that is the default behaviour of DateTime.TryParse DateTime.TryParse This method tries to ignore unrecognized data , if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored. If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload. Example from the same link: string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", "MM...

C# Bootstrap Pagination In ASP.NET Gridview Pager Style?

Image
Answer : I know this is old, But I found something, which is a css style, simple easy and fast https://sufiawan.wordpress.com/2014/09/26/asp-net-use-bootstrap-pagination-on-gridview/ I hope it will save someone sometime. update: *In case the link is down: You add the CSS .pagination-ys { /*display: inline-block;*/ padding-left: 0; margin: 20px 0; border-radius: 4px; } .pagination-ys table > tbody > tr > td { display: inline; } .pagination-ys table > tbody > tr > td > a, .pagination-ys table > tbody > tr > td > span { position: relative; float: left; padding: 8px 12px; line-height: 1.42857143; text-decoration: none; color: #dd4814; background-color: #ffffff; border: 1px solid #dddddd; margin-left: -1px; } .pagination-ys table > tbody > tr > td > span { position: relative; float: left; padding: 8px 12px; line-height: 1.42857143; text-decoration: non...

Change Image Source In Code Behind - Wpf

Answer : None of the above solutions worked for me. But this did: myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative)); You just need one line: ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png")); The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system. You simply want to pass the actual path to the UriSource: logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");

C# Regex For Guid

Answer : This one is quite simple and does not require a delegate as you say. resultString = Regex.Replace(subjectString, @"(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$", "'$0'"); This matches the following styles, which are all equivalent and acceptable formats for a GUID. ca761232ed4211cebacd00aa0057b223 CA761232-ED42-11CE-BACD-00AA0057B223 {CA761232-ED42-11CE-BACD-00AA0057B223} (CA761232-ED42-11CE-BACD-00AA0057B223) Update 1 @NonStatic makes the point in the comments that the above regex will match false positives which have a wrong closing delimiter. This can be avoided by regex conditionals which are broadly supported. Conditionals are supported by the JGsoft engine, Perl, PCRE, Python, and the .NET framework. Ruby supports them starting with version 2.0. Languages such as Delphi, PHP, and R that have regex features based on PCRE also support conditionals. (source http://www.regular-expressions.info/c...

Catch Vs Catch (Exception E) And Throw Vs Throw E

Answer : I think there are two questions here. What is the difference between throw and throw e; ? I don't think there is ever a good reason to write catch (Exception e) { throw e; } . This loses the original stacktrace. When you use throw; the original stacktrace is preserved. This is good because it means that the cause of the error is easier to find. What is the difference between catch and catch (Exception e) ? Both of your examples are the same and equally useless - they just catch an exception and then rethrow it. One minor difference is that the first example will generate a compiler warning. The variable 'e' is declared but never used It makes more sense to ask this question if you had some other code in your catch block that actually does something useful. For example you might want to log the exception: try { int value = 1 / int.Parse("0"); } catch (Exception e) { LogException(e); throw; } Now it's necessary ...

ASP Core WebApi Test File Upload Using Postman

Image
Answer : Thanks to @rmjoia's comment I got it working! Here is what I had to do in Postman: The complete solution for uploading file or files is shown below: This action use for uploading multiple files : // Of course this action exist in microsoft docs and you can read it. HttpPost("UploadMultipleFiles")] public async Task<IActionResult> Post(List<IFormFile> files) { long size = files.Sum(f => f.Length); // Full path to file in temp location var filePath = Path.GetTempFileName(); foreach (var formFile in files) { if (formFile.Length > 0) using (var stream = new FileStream(filePath, FileMode.Create)) await formFile.CopyToAsync(stream); } // Process uploaded files return Ok(new { count = files.Count, path = filePath}); } The postman picture shows how you can send files to this endpoint for uploading multiple files: This action use for uploading single file : [Http...

Are There Any Drawbacks To Relying On The System.Guid.NewGuid() Function When Looking For Unique IDs For Data?

Answer : I'm looking to generate unique ids for identifying some data in my system. I'd recommend a GUID then, since they are by definition globally unique identifiers . I'm using an elaborate system which concatenates some (non unique, relevant) meta-data with System.Guid.NewGuid(). Are there any drawbacks to this approach, or am I in the clear? Well, since we do not know what you would consider a drawback, it is hard to say. A number of possible drawbacks come to mind: GUIDs are big: 128 bits is a lot of bits. GUIDs are not guaranteed to have any particular distribution; it is perfectly legal for GUIDs to be generated sequentially, and it is perfectly legal for the to be distributed uniformly over their 124 bit space (128 bits minus the four bits that are the version number of course.) This can have serious impacts on database performance if the GUID is being used as a primary key on a database that is indexed into sorted order by the GUID; insertion...

Associate A Private Key With The X509Certificate2 Class In .net

Answer : You can save yourself the hassle of copy-pasting all that code and store the private key next to the certificate in a pfx / pkcs#12 file: openssl pkcs12 -export -in my.cer -inkey my.key -out mycert.pfx You'll have to supply a password, which you have to pass to the constructor of X509Certificate2 : X509Certificate2 cert = new X509Certificate2("mycert.pfx","password"); For everyone else with the same problem, I found a neat little piece of code that let's you do exactly that: http://www.codeproject.com/Articles/162194/Certificates-to-DB-and-Back byte[] certBuffer = Helpers.GetBytesFromPEM(publicCert, PemStringType.Certificate); byte[] keyBuffer = Helpers.GetBytesFromPEM(privateKey, PemStringType.RsaPrivateKey); X509Certificate2 certificate = new X509Certificate2(certBuffer, password); RSACryptoServiceProvider prov = Crypto.DecodeRsaPrivateKey(keyBuffer); certificate.PrivateKey = prov; EDIT: The code for the Helper method (which ot...

Cast Datagrid.SelectedItems Collection To List

Answer : Make sure to use the System.Linq namespace then : You should be able to use : List<Foo> SelectedItemsList = DataGrid.SelectedItems.Cast<Foo>().ToList(); or if you're not quite sure what DataGrid.SelectedItems contains : List<Foo> SelectedItemsList = DataGrid.SelectedItems.OfType<Foo>().ToList() Try this: DataGrid.SelectedItems.OfType<Foo>().ToList()