Auto publishing reports to Tableau Server

Tableau it’s a great tool for data visualization, however if you are using it a lot, you may want to automate some stuff. One of them is publishing/updating reports to Tableau Server. This is when Tableau Utility Command comes in handy, you can install it on your development server and use in the power-shell script. One of the solutions is to use CI server for auto deployments, you only need to give the git/svn access for users changing the reports or adding new ones.

tableau

Following script can be run as build step in TeamCity to detect workbooks that have been changed recently and publish them automatically to Tableau server. Parent folder of each workbook will be used as project name when publishing. In order to run it, just pass in email notification list and server password – of course you need to configure the params (server url, smtp etc.).

param (
[string]$cmddir = "C:\Program Files\Tableau\Tableau Server\8.2\extras\Command Line Utility", #location where tabcmd has been installed
[string]$server = "https://tableau:81", #this is url of the Tableau server 
[string]$currentDir = (split-path -parent $MyInvocation.MyCommand.Definition) +"\", #current script location
[string]$notificationEmailList = "test1@test.com,test2@test.com", #send email notifications if successful
[string]$admin = "user", #admin account for the server
[string]$pass = "" #to be passed in as param
)
 
function SendEmail($emailTo,$title,$body)
{ 
   $smtp=new-object Net.Mail.SmtpClient("my_smtp_server"); $smtp.Send("sentAs@mydomain.com", $emailTo, $title, $body);
}
 
$global:temp_ = "";
 
#login to Tableau
cd  $cmddir
.\tabcmd login -s $server -u $admin -p $pass
 
 get-childitem -Path $currentDir –recurse |  where-object { 
    $_.LastWriteTime -gt (get-date).AddMinutes(-10) -and $_.FullName.EndsWith(".twb")
  } | 
  Foreach-Object {
 
       [string]$projectName = [System.IO.DirectoryInfo]$_.Directory.Name;
        $global:temp_ += [string][System.IO.Path]::GetFileName($_.FullName) + " | ";
 
       #publish or overwrite workbook on the server
       .\tabcmd publish $_.FullName -r $projectName  -o  
  } 
 
 
#more commands
#.\tabcmd publish "workbook.twbx" -r "project name" -n "Workbook Name" --db-user "" --db-password "" -o
 
 
#log out to release the session
.\tabcmd logout
 
if(-not $global:temp_ -eq "")
{
   SendEmail $notificationEmailList "Tableau report published" "Following report(s) has just been successfully published to Tableau Server: $global:temp_"
}

enjoy!

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

TOGAF vs COBIT, PRINCE2 and ITIL – Webinar

TOGAF is currently the most popular open architecture framework that is widely implemented in medium and big organizations. It’s ADM lets us operate within generic, proven framework when defining the Enterprise Architecture.

If you are an Architect or PM, it is very useful to know how TOGAF relates to other frameworks like COBIT, ITIL and PRINCE2.

Digram below shows how those frameworks overlap with each other on the operation, governance and change management level.
togaf_process_change_frameworks
We can clearly see that TOGAF overlaps with COBIT in architecture governance, with ITIL in service/ operation area and with PRINCE2 in change management.

Further interaction is shown on the next diagram:

Togaf_cobit_itil_prince2

Process chain for the above diagrams depicts following image:

process_change_detials

ITIL itself, can be described as follows:

service_level_knowhow_itil

Finally, the last diagram shows how PRINCE2 relates to Architecture within its operational level:

architecture_in_prince2

For more information, please check following video:


1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 4.00 out of 5)
Loading...Loading...

Multiple object bindings on MVC view

Multiple object bindings in MVC are the common requirement when working with more advanced UI. An example of that can be creating order form with multiple order items being added dynamically by the user.

In such a scenario we can create binding for our “Order” model as normal and create partial view with the structure of our “OrderItem” class separately. By doing this, the user will be able to dynamically preload order items using ajax request, appending created html to div container.

When submitting the form, order items will be automatically bound to the nested property list, provided the html control ids and names will follow the convention: name of the list property, index id and property name; id=’OrderItems_ID__Quantity’

For example:

   <input type="number" id='OrderItems_@(Model.OrderItemId)__Quantity' value="@Model.Quantity" name='OrderItems[@Model.OrderItemId].Quantity'/>
 

MVC-order

Lets create our order and order items classes first

   public class Order
    {
        public int OrderId { get; set; }
        [Required]
        [Display(Name = "Order Person")]
        public string OrderPerson { get; set; }
        [Required]
        [Display(Name = "Delivery Address")]
        public string DeliveryAddress { get; set; }
        public string OrderComments { get; set; }
        public DateTime OrderDate { get; set; }
        public double TotalNet { get; set; }
        public double TotalVAT { get; set; }
        public double TotalAmount { get; set; }
        [Required]
        public List<OrderItem> OrderItems { get; set; }
    }

	public class OrderItem
    {
        public int OrderItemId { get; set; }
        [Required]
        public string ItemName { get; set; }
        [Required]
        public int Quantity { get; set; }
        [Required]
        public double? UnitPrice { get; set; }
        public double VATRate { get; set; }
        public double TotalValue { get; set; }
    }
 

Our Order form will look the standard way, plus extra element for dynamically added elements:

  <div class="form-group">
    <b>@Html.ActionLink("Add item", "LoadBlankItemRow", null, new { id = "addOrderItem", @class = "btn btn-warning" })</b>
     <div style="padding-top: 10px;">
         <p class="itemColumn">Quantity</p>
         <p class="itemColumn">Name</p>
         <p class="itemColumn">Unit Price</p>
         <p class="itemColumn">VAT Rate</p>
         <p class="itemColumn">Net Value</p>
         <p class="itemColumn"></p>
       </div>
     <div id="editorRows">
        @foreach (var itemModel in Model.OrderItems)
         {
            @Html.Partial("_OrderItem", itemModel)
         }
       </div>
   </div>
 

When user clicks the Add item link, the controller action is being invoked returning html structure reflecting the list item model.

   [HttpGet]
   public virtual PartialViewResult LoadBlankItemRow(int id)
   {
     var orderItem = new OrderItem { OrderItemId = id, Quantity = 1 };

     return PartialView("_OrderItem", orderItem);
   }
 

We will use jquery to get the current numbers of items already inserted and define the current index. This will be used to create appropriate control names required for nested model bindings:

   $("#addOrderItem").click(function (e) {
        var itemIndex = $("#editorRows input.iHidden").length;
        $.get("@Url.Action("LoadBlankItemRow", "Order")/" + itemIndex, function (data) {
            $("#editorRows").append(data);
        });
        return false;
    });
 

Each dynamically inserted row will have JavaScript logic to remove the current row and recalculate total values:

    $("a.deleteRow").click(function () {
        $(this).parents("#itemRow").remove();
        calculateTotals();
        return false;
    });

    $('#OrderItems_@(Model.OrderItemId)__Quantity').blur(function () {
        updateTotalValue(@Model.OrderItemId);
    });
    $('#OrderItems_@(Model.OrderItemId)__UnitPrice').blur(function () {
        updateTotalValue(@Model.OrderItemId);
    });
    $('#OrderItems_@(Model.OrderItemId)__VATRate').change(function () {
        updateTotalValue(@Model.OrderItemId);
    });

Finally, scripts included on parent model form will calculate and update controls located outside the partial view, providing Total amount for the entire order.

   function updateTotalValue(id) {
        var qnt = $('#OrderItems_' + id + '__Quantity').val();
        var uprc = $('#OrderItems_' + id + '__UnitPrice').val();

        var vat = parseFloat($('#OrderItems_' + id + '__VATRate').val());
        if (vat == 0) { val = (qnt * uprc); } else { val = (qnt * uprc) * (1 + vat / 100); }
        if (qnt == 0 || uprc == 0) { val = 0; }

        $('#OrderItems_' + id + '__TotalValue').val(val.toFixed(2));
        calculateTotals();
    }

    function calculateTotals() {
        var totalNet = 0.0; var totalVat = 0.0;

        $("#editorRows").children().each(function (index) {
            var qnt = $('#OrderItems_' + index + '__Quantity').val();
            var uprc = $('#OrderItems_' + index + '__UnitPrice').val();
            var vat = parseFloat($('#OrderItems_' + index + '__VATRate').val());
            if (qnt != null && qnt != 'NaN') {
                totalNet += qnt * uprc;
                if (vat != 0) {
                    totalVat += parseFloat((qnt * uprc) * (vat / 100));
                }
            }
        });

        $('#TotalNet').val(totalNet.toFixed(2));
        $('#TotalVAT').val(totalVat.toFixed(2));
        $('#TotalAmount').val((totalNet + totalVat).toFixed(2));
    }

I have included working project below. Enjoy!

MVC OrderForm

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...Loading...

C# commonly used coding standards

In this article I will present you with some most commonly used coding standards that I have come across while working in multiple companies.

1. Naming Conversions

1.1 Use Pascal Casing for class and method names and camel Casing for local variables

Pascal Casing:

public class MyClass
{
      public void GetData()
     {
     }
}

Camel Casing

public class MyClass
{
      public void GetData(string productName)
     { 
          var myProduct = GetProductFromDatabase(productName);
     }
}

1.2 Do not use underscores for member names eg.

//correct

public string myVariable;
public int myProduct;

//incorrect

public string my_variable;
public int _ myProduct;

1.3 Do not use shortcuts eg.

//correct
public string databaseConnectionString;

//incorrect
public string dbConnStr;

1.4 Give the function names appropriate to the returning values eg.

//correct
public  string GetProductReferenceNumber()
{
}

//incorrect
public  string GetObjectString()
{
}

1.5 Use predefined type names instead of system names eg.

//correct
int ProductID;
string ProductName;

//incorrect
Int32 ProductID;
String ProductName;

1.6 Use the var name for variable declaration if the type can be easily identified from the right hand side of the equation eg.

//correct
var name = "myname";

//incorrect
var myObject = GetBasicObject();

1.7 Use noun names for classes

//correct
public class Product
{
}

//incorrect
public class UserProduct
{
}

1.8 Use „I” prefix for interface names eg.

public interface IProductCollection

1.9 Declare private variables on the top of the classes starting with statics on the top

public class Product
{
    static string productName;
    static int productCount;

    int currectCount;
    string productLocationName;

    public void Calculate()
    {
    }
}

1.10 Use singular names for enums except bit field enums eg.

//correct
enum ProductType
{
    ProductTypeOne, ProductTypeTwo
}

//incorrect
enum ProductTypes
{
    ProductTypeOne, ProductTypeTwo
}

//correct
enum ProductTypes
{
    ProductTypeOne = 1, 
    ProductTypeTwo =2
}

2. General rules

2.1 Use && and || operands instead of single & Or |. This will avoid unnecessary comparisons eg.

//correct
If(product != null && (product.Id > 0 || product.Name.length > 0))
{
}

//incorrect
If(product != null & (product.Id > 0 | product.Name.length > 0))
{
}

2.2 Always use (vertically aligned) curly brackets eg.

//correct
foreach(var item In myCollection)
{
      var result = item.Result;
}

//incorrect
foreach(var item In myCollection)
        var result = item.Result;

2.3 Use „using” statements for objects that implement IDisposable interface eg.

//correct
using(var connection = new SqlConnection())
{
     using( var reader = command.ExecuteReader())
     {
     }
}

//incorrect
var connection = new SqlConnection();
var reader = command.ExecuteReader();

reader.close();
connection.close();

2.4 Use lambda expressions for events that you do not need have reference to at later stage in you code eg.

//correct 
public MyForm()
{
   this.Click += (s, e) =>   {
       MessageBox.Show(((ClickEventArgs)e).Point.ToString());
  };
}
//not advisable 
public MyForm()
{
      this.Click += new EventHandler(MyFunction_Click);
}

void Form1_Click(object sender, ClickEventArgs e)  
{     
     MessageBox.Show(((ClickEventArgs)e).Point.ToString());
 }

2.5 Use object initializers for creating object eg.

//correct
var product = new Product()
{
   ProductID = 1,
   ProductName = “Test”,
   CreateDate = DateTime.Now
}

//incorrect
 var product = new Product();
 product. ProductID = 1,
 product .ProductName = “Test”,
 product .CreateDate = DateTime.Now

2.6 Each function should only perform one task eg.

//correct
public int CalculatePriceWithVAT(double initPrice, double vatRate)
{
      return initPrice = initPrice * (1- vatRate);
}
//incorrect
public int CalculatePrice ()
{
      var initPrice = GetInitPrice();
      var vatRate = GetVatFromDataBase();

      return initPrice = initPrice * (1- vatRate);
}

2.7 Separate parts of the code into logical groups eg.

//correct
int CalculateStock()
{
     var fakeValue = 12;
      fakeValue += 12;

      var fakeProduct = new Product();
      var result = fakeProduct.Count + fakeValue;

      return result;
}
//avoid
int CalculateStock()
{
     var fakeValue = 12;
      fakeValue += 12;
      var fakeProduct = new Product();
      var result = fakeProduct.Count + fakeValue;
      return result;
}

2.8 In LINQ use following to check bool values eg:

//correct
If(products.Any())
{
}

//incorrect
If(products.Count() > 0 )
{
}
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...Loading...

LINQ basic string and digit operations

Hi, today I want to show you how we can do the basic string and digit operations with the LINQ. If you are not using Linq in your current projects, you may find it very tempting to start with it. Once you learn it you will probably be using it all the time 🙂

Lets start with the function that sums the numbers that contains a given digit. We can do it in just one line of code 🙂

 public static int SumNumbers(int[] numbers, int digit)
 {
     return numbers.Where(i => i.ToString().Contains(digit.ToString())).Sum();
 }

If you want to sum number of words that contain minimum number of letters, this will be useful.

 public static int CountWords(string text, int minNumberOfLetters)
 {
     return text.Split(' ').Count(i => i.Length >= minNumberOfLetters);
 }

If you ever wanted to find the longest word in a text, here is example.

 public static string FindLongestWord(string text)
 {
     return text.Split(' ').OrderByDescending(i => i.Length).ThenBy(i => i).First();
 }

And if you want to count number of distinct words longer than given number, check this

 public static int CountWordsLongerThan(string text, int minimumLetters)
 {
     return text.Split(' ').Where(i => i.Length >= minimumLetters).Distinct().Count();
 }

This function gets list of non unique words in the string (separated by the space) and longer than 5 letters

 public static IEnumerable<string> FindNonUniqueWords(string inputText)
 {
     return inputText.ToLower().Split(' ')
       .OrderBy(i => i).GroupBy(i => i).Where(i => i.Count() > 1)
       .Select(i => i.Key).Where(i => i.Length > 5);
 }

And finally something more sophisticated, similarity calculation between two texts (for words having more than 4 letters)

 public static int CalculateSimilarity(string text1, string text2)
 {
    var words1 = text1.Split(' ').Where(i => i.Length > 4).Distinct();
    var words2 = text2.Split(' ').Where(i => i.Length > 4).Distinct();

     return words1.Intersect(words2).Count();
  }

Don’t forget to use “using System.Linq;” namespace in your project before using this. And of course parameters validation must be added to every function to be fully functional.

That’s it for now.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

Implementing MVC3 Custom Model Binders

MVC model binders simply map Http browser requests to model objects. Normally if action invoker is unable to find the proper binder of the provided type, it uses built-in binder class: DefaultModelBinder. Default model binder is using following sources to bind to model object: Request.Form, RouteData.Values, Request.QueryString, Request.Files. The search for values is also done in same order.

We can include and exclude bindings for some object properties in action method or in class attribute.

 public ActionResult Create([Bind(Include="FirstName, LastName")] Client client) {

 //or in our class
 [Bind(Exclude="IsApproved")]
 public class Client {

In our example we will bind the model manually. This gives us more controls on how the model objects are instantiated and helps if we are using dependency resolver.

 [HttpPost]
  public ActionResult Edit(int id, FormCollection collection)
  {
        try
        {
            // TODO: Add update logic here
            //client client = (client)DependencyResolver.Current.GetService(typeof(client));
            var client = new Client();

            UpdateModel(client, collection);

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

Below is our custom model binder implementation. Please note that the binder class needs to inherit from IModelBinder interface. In the example, we simple check if model exists or use dependency resolver to provide one. Next we are getting prefixes and values from BindingContext.ValueProvider property, that gives us all consolidates value providers we can read from. Please note that we didn’t include any validation logic.

  public class ClientModelBinder : IModelBinder
  {

   public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // check if model to update exists and create one if not
        Client model = (Client)bindingContext.Model ?? (Client)DependencyResolver.Current.GetService(typeof(Client));

        // check if the value provider has the required prefix
        bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);

        string searchPrefix = (hasPrefix && !string.IsNullOrEmpty(bindingContext.ModelName)) ? bindingContext.ModelName + "." : "";

        // populate the fields of the model object
        model.ClientId = int.Parse(GetValue(bindingContext, searchPrefix, "ClientId"));
        model.FirstName = GetValue(bindingContext, searchPrefix, "FirstName");
        model.LastName = GetValue(bindingContext, searchPrefix, "LastName");
        model.BirthDate = DateTime.Parse(GetValue(bindingContext, searchPrefix, "BirthDate"));
        model.IsApproved = GetCheckedValue(bindingContext, searchPrefix, "IsApproved");
        model.Role = (Role)Enum.Parse(typeof(Role), GetValue(bindingContext, searchPrefix, "Role"));

        return model;
    }
 }

Next step is to register our custom binder. We can do it either in the global file or by giving attribute to our Client class.

  protected void Application_Start()
  {
        AreaRegistration.RegisterAllAreas();

        ModelBinders.Binders.Add(typeof(Client), new ClientModelBinder());

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

  //or
  [ModelBinder(typeof(ClientModelBinder))]
  public class Client
   {

You can also implement your own model binder provider which is very useful when handling multiple custom class binders.

 public class CustomModelBinderProvider : IModelBinderProvider 
 {
   public IModelBinder GetBinder(Type modelType) 
   {
      //return or apply the switch with other model type binders
      return modelType == typeof(Client) ? new ClientModelBinder() : null;
   }
 }

 //you can register provider in global app start method
 ModelBinderProviders.BinderProviders.Add(new CustomModelBinderProvider());

I have included application sample, so you can test how it works by setting the break point in the binding function and see how the model values are being retrieved.
CustomModelBinder

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

Polymorphism in practice (C# sample)

One of the main principles of the Object Oriented Programming is the Polymorphism. This term simply means that an class can be used as more than one type through inheritance. It can have it’s own type, the base type or interface type it inherits from. In C# every type is polymorphic as the all types inherit from Object type.

Lets assume we are building an Internet store with the basket functionality. By creating base class and inheriting from it we get all properties from the base class plus the properties of the class that we are creating. By marking class as abstract we specify that this class cannot be instantiated and may serve only as a base class for other classes deeper in the system.

  public abstract class BasketBase
  {

  }

   public class Basket : BasketBase
   {

   }

By marking methods as a virtual in the base class, we can implement our own logic whenever we need it using override keyword in the underlying class.

   public abstract class BasketBase
   {
        public List<ProductItem> ProductList = new List<ProductItem>();
        public double Total = 0;
        public bool IsCheckedOut = false;
        public abstract void Checkout();
    }

    public class Basket : BasketBase
    {
        public override void Checkout()
        {
            if (base.IsCheckedOut) { throw new Exception("Check out has been already done!"); };
            ////////////

            foreach (ProductItem p in base.ProductList)
            {
                base.Total += p.ProductPrice * p.ItemCount;
            }

            base.IsCheckedOut = true;
        }
     }

When building advanced systems, Polymorphism gives you the chance to easily change the logic of existing methods by overriding it. It also makes your application cleaner by reusing amount of code needed to create properties in underlying classes.

I have included sample application of the Internet store with the basket and voucher functionality for you to do some testing.


basket.vouchers
Polymorphism-sample-app

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...