Author: Sudi

  • Quick and easy way to use USERNAME() to extract the name of the logged-in user in Power BI – Part 1

    Quick and easy way to use USERNAME() to extract the name of the logged-in user in Power BI – Part 1

    USERNAME() and USERPRINCIPALNAME() can be used in various ways.

    However, In this post, we will look at two Power BI functions, USERNAME() and USERPRINCIPALNAME(), to extract either the first name or the user’s last name see how they differ when using Power BI Desktop and Power BI Service.

    For this to work, we will need to make use of various string manipulation functions such as LEFT(), RIGHT(), LEN(), and FIND(). Apart from that, you will need to install the Power BI desktop.

    Let us first go over these functions that we will be using to get to our result. If you want to go over the code directly, then please free to go over it at the end of this post.

    Let us begin.

    Username(): Returns the domain name and user name of the current connection with the format of domain-name\user-name. This function does not take any parameter. It returns the username from the credentials given to the system at connection time.

    Left(): Returns the specified number of characters from the start of a text string. This returns a text string containing the specified right-most characters.

    This function fetches the number of characters starting from left.

    Right(): Returns the specified number of characters from the end of a text string. This returns a text string containing the specified right-most characters. Think of this as an equal and opposite of the LEFT() function.

    This function fetches the number of characters starting from right.

    LEN(): Returns the number of characters in a text string. This returns the number of characters in the text string.

    Personally speaking, this is my favorite function as once I know the length of any string, we then have the power to manipulate and extract the data as we see fit.

    FIND(): Returns the starting position of one text string within another text string. FIND is case-sensitive and accent-sensitive. This returns the starting position of the text string that we want to find. There are a few other functions that we can use, which can get us the same result as FIND(). But that is a topic for some other time.

    Now that we have these functions handy, let us begin.

    When we use USERNAME() in the Power BI desktop, it will return the domain name and username from the system’s credentials at connection time. One point to be noted here is that this function DOES NOT take any parameters. For example, if I was to use this function on the Power BI desktop, I will see Domain\username. However, when I publish the report, I will see a fully qualifies username such as username@domain.com.

    So here is a thought, how does one extract just the username when the position of username changes depending on the tool (Desktop vs. Service).

    The trick lies in the fact that we will use Find() within the IF function to check for either “\” or “@” and then, based on the position of this separator( “\ or @”), we will be able to get the right result.

    In the next post, I will go over this formula in detail as this can then modified to use in case when our usernames are abc.def@xyz.com or lastname.firstname@domain.com or LFname@domail.com.

    Regardless of how your company uses the username, using this code and some fancy manipulations, you will extract the information you need.

    USERNAME() Power BI Desktop

    The entire code is as follows and we will go over this logic in the next post.

    MyUsername =
    VAR myusername =
    USERNAME ()
    VAR findmyatrate = "@"
    VAR findmyslash = "\"
    VAR totallen =
    LEN ( USERNAME () )
    VAR myname =
    IF (
    FIND ( findmyatrate, myusername, 1, 0 ) = 0,
    RIGHT ( myusername, totallen - FIND ( findmyslash, myusername, 1 ) ),
    LEFT ( myusername, FIND ( findmyatrate, myusername, 1 ) - 1 )
    )
    VAR capfirstchar =
    UPPER ( LEFT ( myname, 1 ) )
    VAR addremchar =
    LOWER ( RIGHT ( myname, LEN ( myname ) - 1 ) )
    VAR comboth = capfirstchar & addremchar
    RETURN
    "Welcome : " & comboth

    We followed this:

    1. We checked for the @ or \ in the name. (Why?? explanation is in the next post).
    2. Based on our find (FIND()), we extracted the name.
    3. We capitalized the First character of the last name and concatenated the rest.

    Power BI USERNAME() is a function that can get the logged-in username. However, the result of this function varies depending on the tool/component of Power BI. In Power BI Desktop, the result is different than what we will see in the Power BI Service.

    Stay tuned for a detailed explanation for this code. Hope you liked it.

  • Demystifying Date Dimension Part 3

    Demystifying Date Dimension Part 3

    Hello All, let us take a deep dive into Date Dimension Part 3


    However, for the next few blog posts, we will focus on M Query, and we will first work with static values and then modify the M Query to make it more dynamic.

    Steps that you can follow along with me are as follows: 

    We are using the sample data from the previous post. You can download the sample file and have a look at the first 2 parts of this series here and here.

    Click on the edit queries/transform data.

    Click on the new source and click on a blank query.

    This should look something like this.

    In the formula bar type in = List.Dates(#date(2020,1,1), 365, #duration(1,0,0,0)) and press enter.

    This should have given you something like this.

    I hope you recall the three main components that I spoke about, StartDate, EndDate, and the Duration from previous posts. Once again, I will reiterate that this is all that we need for any date table. We get this is all about manipulating the code, but eventually, that is all we need to create a date table.

    Based on this let us break this formula and understand each component of it.

    • The List.Date function takes in three parameters, start as date, count as the number, and duration as the increment.
    • The start is the beginning date or the date when my calendar should start. In this example, I am using the beginning of this year as the start.
    • The count is the number or how many such date instances you want to have on this list. I am choosing 365 as my count. Be careful that this count is the number of days. It is for several instances. If in the duration we choose hours, then this instance will mean 365 such hour instance.
    • The step is the last parameter, and it simply means what the duration or increment of each instance is. I am calling the function #duration and saying that I need an increment of a day, #duration(1,0,0,0).
    • Since we have used the function List.Date, this Query1 is a list.

    Next, click on Transform and convert into a table and rename this as a query as MyCal. 

    When you are prompted for the To Table dialog box, you can hit ok as there is no delimiter we need to worry about.

    Next, rename this column to Date by double-clicking it and type in the word Date. Alternatively, you can also right click this column and rename it. While you are at it, click on the small icon ABC/123 to change the data type to Date. 

    At this point, you have a column called Date in the table called MyCal and the date ranges from 01/01/2020 to 12/30/2020.

    But wait, what happened to 31st??? Remember, we chose the count as 365 earlier. Hence it took 365 days from the StartDate of 01/01/2020.

    Do not worry as we will modify the code in a short while to include the last day of the year.

    Let us continue expanding this table.

    • Click on Add Column in the ribbon.
    • Click on the down arrow under the Date icon.
    • Click on Year, and this will add a new column called Year.
    • Similarly, we can add Month, Quarter, Week, and Day columns in our table. 

    At this point, we should have a decent date table. However, this is very static, and we still have not taken care of the 31st of this year. To take care of that, change the count to 366, and you should have all the days of this year.
    But this is very brutish (because in the Year 2021, we will have 365 days instead of 366). In the next blog, we will make this table more dynamic.

    The complete M code is as follows, to get the same result as above, click on the new blank query and click on the advanced editor, and past the following.

    let
    Source = List.Dates(#date(2020,1,1), 366, #duration(1,0,0,0)),
    #”Converted to Table” = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #”Renamed Columns” = Table.RenameColumns(#”Converted to Table”,{{“Column1”, “Date”}}),
    #”Changed Type” = Table.TransformColumnTypes(#”Renamed Columns”,{{“Date”, type date}}),
    #”Inserted Year” = Table.AddColumn(#”Changed Type”, “Year”, each Date.Year([Date]), Int64.Type),
    #”Inserted Month” = Table.AddColumn(#”Inserted Year”, “Month”, each Date.Month([Date]), Int64.Type),
    #”Inserted Quarter” = Table.AddColumn(#”Inserted Month”, “Quarter”, each Date.QuarterOfYear([Date]), Int64.Type),
    #”Inserted Week of Year” = Table.AddColumn(#”Inserted Quarter”, “Week of Year”, each Date.WeekOfYear([Date]), Int64.Type),
    #”Inserted Day of Year” = Table.AddColumn(#”Inserted Week of Year”, “Day of Year”, each Date.DayOfYear([Date]), Int64.Type)
    in
    #”Inserted Day of Year”

    This should give you a final result like below.

    In the next post, we will continue with the same date table to make it dynamic. If you have questions/queries/comments, please do not hesitate to reach out to me.

  • Demystifying Date Dimension Part 4

    Demystifying Date Dimension Part 4

    Hi all, in this post, let us make a dynamic date dimension.

    If you followed me every step of the way, you should already have this on your table. If not, click on the blank query and paste the following code to speed up and read about the previous post here, and download the sample file below.

    let
    Source = List.Dates(#date(2020,1,1), 366, #duration(1,0,0,0)),
    #"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #"Renamed Columns" = Table.RenameColumns(#"Converted to Table",{{"Column1", "Date"}}),
    #"Changed Type" = Table.TransformColumnTypes(#"Renamed Columns",{{"Date", type date}})
    in
    #"Changed Type"

    Now that we are on the same page, let us begin!!!
    I hope you still remember the three main requirements for a date table. I know I have said this over and over, but once again I will reiterate this that to have a date table, we need StartDate, EndDate, and Duration.

    Now with this in mind, let us begin. First, we need to find the StartDate. In this case, it is 01/01/2020.

    Click on the function icon (fx) and insert a new step.

    By default, you should see that this new step is called Custom 1 and that it is referencing the previous step, as shown below. In my case, it is referencing the step called Inserted Day of Year; for you, it could be different. But the main point here is whenever we add a new step, then by default, it will always refer to the immediate prior step.

    Delete everything including the ‘=’ sign and type in 01/01/2020 and while you are at it, rename this step (right-click on the Custom 1) to StartDate.

    This will fetch us the StartDate. Since now we have StartDate, go ahead and replace #date(2020, 1, 1) in the source step with StartDate. 

    Now we need a count of days. For this let us dynamically get the count of days from 01/01/2020 till today. 

    Create a new step and input this DateTime.Date(DateTime.LocalNow()) in this formula bar and rename this step as EndDate.

    This nested function first fetches the local/current date in DateTime format, then we extract just the date component from it. 

    Insert another step, and this time we will invoke Duration. Days function and wrap it around EndDate minus StartDate. This time we are subtracting the StartDate from EndDate and fetching the number of days from it. (If you want to include today, then we must add 1 to it so we can have today counted as well). Let us rename this new step as Count.

    At this point, we have StartDate and Count. Let us navigate back to the source step and replace the hardcoded 366 with Count. 

    Now insert another step and reference it back to the Changed Type step in the applied steps as shown below. By default, every new step references the immediate prior step, but we want to reference another step hence, the need to manually tell M query where to look for. 

    Once we have the above step, all that is needed is to extract relevant date parts as we did in the previous blog. 

    At this point, our Date Table is ready. We can use this code and just by changing the StartDate we can generate all the dates till today. I changed my StartDate to 01/01/2010 and I can now see all the dates from 01/01/2010 till today.

    If you noticed, we had to enter the StartDate manually, but what if we wanted to use the earliest date present in our model. Well, it is straightforward to do so.

    In our sample, we have an Orders table. Let us say that we wanted to use the first Order Date as my StartDate.
    We can call another List function called List. Min and pass that to our source. Let us see that in action.

    For the sake of simplicity and comparison, I am going to insert another step right after StartDate. Since we know that every new step in M Query references the immediate prior step, inserting a new step right after StartDate will not break our code.

    Insert a new step after StartDate and rename as MinDate.

    • Since we want the earliest date from Orders Table, call List.Min function on the Order Date column.
    • For the MinDate step, insert this ” = List.Min((Orders[Order Date]))”. This will look for the earliest date in the column called Order Date in the table called Orders. 

    Once we have this, go back to the source and replace StartDate with MinDate. 

    At this point, you should have something like below. Here the date table starts from 01/01/2015 which is the first order date in the Orders table. 

    Lets us now say, that we wanted the EndDate to be the last ship date. This is also equally easy. Follow these steps and you will have a true dynamic date table whose dates are based on the dates in your model.

    1. Insert a new step after EndDate and rename it as MaxDate.
    2.  Since we want the latest date from Orders Table, call List. Max function on the Ship Date column.
    3. For the MaxDate step, insert this ” = List.Max((Orders[Ship Date]))”. This will look for the latest date in the column called Ship Date in the table called Orders. 

    At this point, you should have something like below. Here the date table ends on 07/07/2015 which is the second last ship date in the Orders table. To get the last ship date, just add 1 to the count step as follows. 

    This way we can create a dynamic date table that fetches the StartDate and the EndDate using the data within our model.

    I am including all the variations of the M code for easy reference.

     let
        Source = List.Dates(MinDate, Count, #duration(1,0,0,0)),
        #"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
        #"Renamed Columns" = Table.RenameColumns(#"Converted to Table",{{"Column1", "Date"}}),
        #"Changed Type" = Table.TransformColumnTypes(#"Renamed Columns",{{"Date", type date}}),
        // We can manually choose the Start Date and the rest of calendar will populate based on this value
        StartDate = #date(2010, 1, 1),
        // this is taking the earliest date from Order Date column. 
        MinDate = List.Min((Orders[Order Date])),
        // this is taking end date as today's date
        EndDate = DateTime.Date(DateTime.LocalNow()),
        // this is taking the last Ship Date 
        MaxDate = List.Max((Orders[Ship Date])),
        Count = Duration.Days(MaxDate - MinDate) + 1,
        Custom1 = #"Changed Type",
        #"Inserted Year" = Table.AddColumn(Custom1, "Year", each Date.Year([Date]), Int64.Type),
        #"Inserted Month" = Table.AddColumn(#"Inserted Year", "Month", each Date.Month([Date]), Int64.Type),
        #"Inserted Quarter" = Table.AddColumn(#"Inserted Month", "Quarter", each Date.QuarterOfYear([Date]), Int64.Type),
        #"Inserted Week of Year" = Table.AddColumn(#"Inserted Quarter", "Week of Year", each Date.WeekOfYear([Date]), Int64.Type),
        #"Inserted Day of Year" = Table.AddColumn(#"Inserted Week of Year", "Day of Year", each Date.DayOfYear([Date]), Int64.Type),
        #"Sorted Rows" = Table.Sort(#"Inserted Day of Year",{{"Date", Order.Descending}})
        
    in
        #"Sorted Rows"

    I hope you liked demystifying date dimension series and please do let em know you thoughts on this. If you have a request, please do not hesitate to reach out.

    Till next time !!!