برچسب: same

  • How to open the same URL on different environments with PowerShell | Code4IT


    Revise PowerShell basics with a simple script that opens a browser for each specified URL. We’re gonna cover how to declare variables, define arrays, concatenate strings and run CMD commands.

    Table of Contents

    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    Say that your project is already deployed on multiple environments: dev, UAT, and production; now you want to open the same page from all the environments.

    You could do it manually, by composing the URL on a notepad. Or you could create a PowerShell script that opens them for you.

    In this article, I’m going to share with you a simple script to open multiple browsers with predefined URLs. First of all, I’ll show you the completed script, then I’ll break it down to understand what’s going on and to brush up on some basic syntax for PowerShell.

    Understanding the problem: the full script

    I have a website deployed on 3 environments: dev, UAT, and production, and I want to open all of them under the same page, in this case under “/Image?w=60”.

    So, here’s the script that opens 3 instances of my default browser, each with the URL of one of the environments:

    $baseUrls =
    "https://am-imagegenerator-dev.azurewebsites.net",
    "https://am-imagegenerator-uat.azurewebsites.net",
    "https://am-imagegenerator-prd.azurewebsites.net";
    
    $path = "/Image?w=600";
    
    foreach($baseUrl in $baseUrls)
    {
        $fullUrl = "$($baseUrl)$($path)";
        Invoke-Expression "cmd.exe /C start $($fullUrl)"
    }
    

    Let’s analyze the script step by step to brush up on some basic notions about PowerShell.

    Variables in PowerShell

    The first thing to notice is the way to declare variables:

    There’s not so much to say, except that variables have no type declaration and that each variable name must start with the “$” symbol.

    Arrays in PowerShell

    Talking about arrays, we can see that there is no [] syntax:

    $baseUrls =
        "https://am-imagegenerator-dev.azurewebsites.net",
        "https://am-imagegenerator-uat.azurewebsites.net",
        "https://am-imagegenerator-prd.azurewebsites.net";
    

    In fact, to declare an array you must simply separate each string with ,.

    Foreach loops in PowerShell

    Among the other loops (while, do-while, for), the foreach loop is probably the most used.

    Even here, it’s really simple:

    foreach($baseUrl in $baseUrls)
    {
    
    }
    

    As we’ve already seen before, there is no type declaration for the current item.

    Just like C#, the keyword used in the body of the loop definition is in.

    foreach (var item in collection)
    {
        // In C# we use the `var` keyword to declare the variable
    }
    

    String concatenation in PowerShell

    The $fullUrl variable is the concatenation of 2 string variables: $baseUrl and $path.

    $fullUrl = "$($baseUrl)$($path)";
    

    We can see that to declare this new string we must wrap it between "...".

    More important, every variable that must be interpolated is wrapped in a $() block.

    How to run a command with PowerShell

    The key part of this script is for sure this line:

    Invoke-Expression "cmd.exe /C start $($fullUrl)"
    

    The Invoke-Expression cmdlet evaluates and runs the specified string in your local machine.

    The command cmd.exe /C start $($fullUrl) just tells the CMD to open the link stored in the $fullUrl variable with the default browser.

    Wrapping up

    We learned how to open multiple browser instances with PowerShell. As you can understand, this was just an excuse to revise some basic concepts of PowerShell.

    I think that many of us are too focused on our main language (C#, Java, JavaScript, and so on) that we forget to learn something different that may help us with our day-to-day job.

    Happy coding!



    Source link

  • use the same name for the same concept | Code4IT


    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    As I always say, naming things is hard. We’ve already talked about this in a previous article.

    By creating a simple and coherent dictionary, your classes will have better names because you are representing the same idea with the same name. This improves code readability and searchability. Also, by simply looking at the names of your classes you can grasp the meaning of them.

    Say that we have 3 objects that perform similar operations: they download some content from external sources.

    class YouTubeDownloader {    }
    
    class TwitterDownloadManager {    }
    
    class FacebookDownloadHandler {    }
    

    Here we are using 3 words to use the same concept: Downloader, DownloadManager, DownloadHandler. Why??

    So, if you want to see similar classes, you can’t even search for “Downloader” on your IDE.

    The solution? Use the same name to indicate the same concept!

    class YouTubeDownloader {    }
    
    class TwitterDownloader {    }
    
    class FacebookDownloader {    }
    

    It’s as simple as that! Just a small change can drastically improve the readability and usability of your code!

    So, consider also this small kind of issue when reviewing PRs.

    Conclusion

    A common dictionary helps to understand the code without misunderstandings. Of course, this tip does not refer only to class names, but to variables too. Avoid using synonyms for objects (eg: video and clip). Instead of synonyms, use more specific names (YouTubeVideo instead of Video).

    Any other ideas?

    👉 Let’s discuss it on Twitter or on the comment section below!

    🐧





    Source link

  • IFormattable interface, to define different string formats for the same object | Code4IT

    IFormattable interface, to define different string formats for the same object | Code4IT


    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    Even when the internal data is the same, sometimes you can represent it in different ways. Think of the DateTime structure: by using different modifiers, you can represent the same date in different formats.

    DateTime dt = new DateTime(2024, 1, 1, 8, 53, 14);
    
    Console.WriteLine(dt.ToString("yyyy-MM-dddd")); //2024-01-Monday
    Console.WriteLine(dt.ToString("Y")); //January 2024
    

    Same datetime, different formats.

    You can further customise it by adding the CultureInfo:

    System.Globalization.CultureInfo italianCulture = new System.Globalization.CultureInfo("it-IT");
    
    Console.WriteLine(dt.ToString("yyyy-MM-dddd", italianCulture)); //2024-01-lunedì
    Console.WriteLine(dt.ToString("Y", italianCulture)); //gennaio 2024
    

    Now, how can we use this behaviour in our custom classes?

    IFormattable interface for custom ToString definition

    Take this simple POCO class:

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime BirthDate { get; set; }
    }
    

    We can make this class implement the IFormattable interface so that we can define and use the advanced ToString:

    public class Person : IFormattable
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime BirthDate { get; set; }
    
        public string ToString(string? format, IFormatProvider? formatProvider)
        {
            // Here, you define how to work with different formats
        }
    }
    

    Now, we can define the different formats. Since I like to keep the available formats close to the main class, I added a nested class that only exposes the names of the formats.

    public class Person : IFormattable
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime BirthDate { get; set; }
    
        public string ToString(string? format, IFormatProvider? formatProvider)
        {
            // Here, you define how to work with different formats
        }
    
        public static class StringFormats
        {
            public const string FirstAndLastName = "FL";
            public const string Mini = "Mini";
            public const string Full = "Full";
        }
    }
    

    Finally, we can implement the ToString(string? format, IFormatProvider? formatProvider) method, taking care of all the different formats we support (remember to handle the case when the format is not recognised!)

    public string ToString(string? format, IFormatProvider? formatProvider)
    {
        switch (format)
        {
            case StringFormats.FirstAndLastName:
                return string.Format("{0} {1}", FirstName, LastName);
            case StringFormats.Full:
            {
                FormattableString fs = $"{FirstName} {LastName} ({BirthDate:D})";
                return fs.ToString(formatProvider);
            }
            case StringFormats.Mini:
                return $"{FirstName.Substring(0, 1)}.{LastName.Substring(0, 1)}";
            default:
                return this.ToString();
        }
    }
    

    A few things to notice:

    1. I use a switch statement based on the values defined in the StringFormats subclass. If the format is empty or unrecognised, this method returns the default implementation of ToString.
    2. You can use whichever way to generate a string, like string interpolation, or more complex ways;
    3. In the StringFormats.Full branch, I stored the string format in a FormattableString instance to apply the input formatProvider to the final result.

    Getting a custom string representation of an object

    We can try the different formatting options now that we have implemented them all.

    Look at how the behaviour changes based on the formatting and input culture (Hint: venerdí is the Italian for Friday.).

    Person person = new Person
    {
        FirstName = "Albert",
        LastName = "Einstein",
        BirthDate = new DateTime(1879, 3, 14)
    };
    
    System.Globalization.CultureInfo italianCulture = new System.Globalization.CultureInfo("it-IT");
    
    Console.WriteLine(person.ToString(Person.StringFormats.FirstAndLastName, italianCulture)); //Albert Einstein
    
    Console.WriteLine(person.ToString(Person.StringFormats.Mini, italianCulture)); //A.E
    
    Console.WriteLine(person.ToString(Person.StringFormats.Full, italianCulture)); //Albert Einstein (venerdì 14 marzo 1879)
    
    Console.WriteLine(person.ToString(Person.StringFormats.Full, null)); //Albert Einstein (Friday, March 14, 1879)
    
    Console.WriteLine(person.ToString(Person.StringFormats.Full, CultureInfo.InvariantCulture)); //Albert Einstein (Friday, 14 March 1879)
    
    Console.WriteLine(person.ToString("INVALID FORMAT", CultureInfo.InvariantCulture)); //Scripts.General.IFormattableTest+Person
    
    Console.WriteLine(string.Format("I am {0:Mini}", person)); //I am A.E
    
    Console.WriteLine($"I am not {person:Full}"); //I am not Albert Einstein (Friday, March 14, 1879)
    

    Not only that, but now the result can also depend on the Culture related to the current thread:

    using (new TemporaryThreadCulture(italianCulture))
    {
        Console.WriteLine(person.ToString(Person.StringFormats.Full, CultureInfo.CurrentCulture)); // Albert Einstein (venerdì 14 marzo 1879)
    }
    
    using (new TemporaryThreadCulture(germanCulture))
    {
        Console.WriteLine(person.ToString(Person.StringFormats.Full, CultureInfo.CurrentCulture)); //Albert Einstein (Freitag, 14. März 1879)
    }
    

    (note: TemporaryThreadCulture is a custom class that I explained in a previous article – see below)

    Further readings

    You might be thinking «wow, somebody still uses String.Format? Weird!»

    Well, even though it seems an old-style method to generate strings, it’s still valid, as I explain here:

    🔗How to use String.Format – and why you should care about it | Code4IT

    Also, how did I temporarily change the culture of the thread? Here’s how:
    🔗 C# Tip: How to temporarily change the CurrentCulture | Code4IT

    This article first appeared on Code4IT 🐧

    Wrapping up

    I hope you enjoyed this article! Let’s keep in touch on Twitter or LinkedIn! 🤜🤛

    Happy coding!

    🐧





    Source link