Category Archives: .NET

TeamCity 10 and ASP.NET MVC

I am new to team city and I read a book about it that describes how to build a java project using maven and use TeamCity to automate the build process.

But I am mainly .NET developer, so I started searching how to automate build and test of an ASP.NET MVC project.

The project was developed using Visual Studio 2015. First to consider when configuring TeamCity build step, is that you should have nuget installer as the first step. For that to work, you should already install nuget tools in TeamCity as below :

teamcity-1

Then in build steps, configure nuget installer:

teamcity-2

For the second step, you have to configure a Visual Studio runner type, so it would build the project:

teamcity-3

But you may encounter an error while trying to build project, cause the teamcity server may not have proper MSIBUID tool, and libraries. So, according to the response in the stackoverflow, first you have to install the proper Build Tool  (you can find 2015 Version from https://www.microsoft.com/en-us/download/details.aspx?id=48159), and then copy the required web application folders for your targeted build.

It works, but if you have Unit test in your project, and it configured to use Visual Studio default Unit Test library, it may will fail cause it cant find appropriate dll.

In another post I will write about how to use NUnit and add it as build step in TeamCity.

Advertisements

ASP.NET MVC with models inheritance and views

Hi

Recently I bumped into a intersing question on stackoverflow.com. The problem was that user had a view but wanted to have some input elements based on variable model. I mean if model passed to view is a, render a Email text input and if it is b then render Name text input. But in mvc you can pass only one model to view. So I suggested have a base model and base view and by checking the type of model in view load the related view using partial as below:

 public ActionResult Base()
        {
            return View(new DerviedOne());
        }

 public class BaseModel
    {
        public int Id { get; set; }
    }

    public class DerviedOne : BaseModel
    {
        public string Email { get; set; }
    }

    public class DerviedTwo : BaseModel
    {
        public string Name { get; set; }
    }
 @using Models
@model Models.BaseModel

@{
    ViewBag.Title = "Base";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<h2>Base</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()


<div class="form-horizontal">

<h4>BaseModel</h4>

        <hr/>
        @Html.ValidationSummary(true, "", new {@class = "text-danger"})

<div class="form-group">

<div class="col-md-offset-2 col-md-10">
                @Html.TextBoxFor(x=>x.Id)
                <input type="submit" value="Create" class="btn btn-default"/>
            </div>

        </div>

    </div>


    if(Model is DerviedOne)
     {
         Html.RenderPartial("DerviedOneView", Model as DerviedOne);
     }

    if (Model is DerviedTwo)
    {
        Html.RenderPartial("DerviedTwoView", Model as DerviedTwo);
    }
}

Alternative forms for an entity based on user ownership

Hi. Long time no post!

In dynamics CRM, according to policies of your business, you can restrict users access to records using security role feature. For example a user can see only opportunities she/he owns. By at some points, some sales people need to have basic information about the business accounts they interact with, they want to know if the account already bought a product from the company or not. The easiest solution is ask the record owner, and the owner would tell the expert/salse person only detiails that is not considered secure.

But this solution causes lot of time waste. There is a feature in Dynamics CRM forms that you can define alternative forms. These forms could be seen by all roles or only specific roles. In out scenario, We want to users see to kind of forms, based on their ownership for the record. If the salesperson own the record she can see all details, if not alternate form is rendered to her. Is it achievable using a code like the following on form load event:

 

   if(CurrentRecordOwner!=CuurentActiveUser)
	   {
		         var currentFormId = Xrm.Page.ui.formSelector.getCurrentItem();

           $.each( Xrm.Page.ui.formSelector.items.get(),function(index,item){
              
                  if (item.getLabel()=="New Form Name" && currentFormId.getLabel()!="New Form Name")
                  {
                           form=item;
                  }
              });
      
          form.navigate();
	   }

It works fine! yes in first load of the form. But when forms redirect tho alternative for, from that moment, if you want to open another record of that type, CRM will use the last loaded form type, I meant if you are the owner you will see the alternate version. I inspected the loaded scripts and saw an amazing behavior. The script I binded to main form event load, was not loaded for the alternative one. Although in alternative form propeties I could see that the scipt bind for load event was there!

So in alternative form properties, I removed the corresponding script and bind it again and it worked! So I could redirect user correctly based on condition.

SSh, .NET and solving timeout issue

I was asked to develop an asp.net mvc solution which gets some data from linux server using ssh. The command I use in ssh client in putty works pretty well, but when I wanted to use those commands using SSH.NET, it took a long time and finally timed out. I finally got an idea to have all my commands in one shell scripting file and call that script with SSH.NET library.

var client = new SshClient(“serveripaddress”, sshport, "user", "pass");
client.Connect();
var cm1 = client.RunCommand("sh shellfilename");

But it was some other issue in shell scripting. As I was new to shell scripting in linux, I did not know how to call to command one after other, because the second command has dependency on first command. I asked a question on stackexchange, and I got what I wanted.

Using Webservices in Dynamics CRM plug-ins

Hi

Sometimes you need calling a web service inside a plugin, like a scenario we encountered. We need a plugin for an activity Status change event, which calls a web service out side of the CRM server. In this situations if you add a web service reference in plug-in code in visual studio and deploying it to CRM server, it would not work using the config items in App.config.

What is the solution ?

You should manually config the web service, I mean hard code it like below :


BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress endpoint = new EndpointAddress("http://webservice?wsdl");
var webserviceClient= new WEbServiceClient(binding, endpoint);

Knockout JS, complex form and asp.net mvc

It is not a week I have got familiar with Knockout.js. First of all let me tell you that currentlyI spend most of my time developing a web application connected to abas ERP system using a java based web service. The web application is an asp.net mvc app, and to make it more like to abas windows client, I am trying my best, and as you know, to make a web app more usable, you HAVE TO use javascript, but use it with caution. Thanks to js libraries developed in last few years, writing a clean and maintainable js code has been more simple than before.

Ok telling story is enough. In my web app, for the first time I decided to use a MVVM js library!. In this phase I have to create a payment form which includes card lines as it items. So to make it easier for user to add items to payment, this time I used knockout to bind invoice items, which are editable. In the past I manually added line item to table and handling edition to any part of line item was a headache, because reflecting the changes made to table containing the items was a lot of hard code.

I am not going to describe the whole solution here, mainly I am going to tell you how to add this line items values to form, to have them as a list in server side (Here server side code is asp.net mvc). Before reading the rest of this article, I recommend reading this tutorial from knockoutjs.

Say our payment model is like below:

public class PayemntModel
{
public string Name{get;set;}
public List Items{get;set;}
}
public class Card
{
public decimal Amount{get;set;}
//... other properties
}

and this is our form handler in server side:

[HttpPost]
public ActionResult Form(PayemntModel model)
{
// handle the data
}

and lets go to client side.

In your clients side code, having form field for “Name” property is easy :

<input type="text" id="Name" name="Name">

but for your card list, can not have something like this:

//first item
<input type="text" id="Amount" value="5600" name="Amount">
//second item
<input type="text" id="Amount" value="2300" name="Amount">

why? first of all modelbinding in mvc side cant detect your list, and also if it find, it can not distingush first item from second.

So every line should have an index and also a unique Id, something like this:

<div data-bind="foreach: Cards">
<input type="hidden" name="Cards.index" value="0">
<inpu value="5600" id="Cards_0__Amount" name="Cards[0].Amount"><input type="hidden" name="Cards.index" value="1">
<inpu value="2300" id="Cards_1__Amount" name="Cards[1].Amount">
</div>

How you achieve this with knockout?! after some googling I found that you can easily change attributes of an HTML tag.!!

Here how it is done :

<div data-bind="foreach: Cards">
<input type="hidden" name="Cards.index" data-bind="value: $index()">
<input data-bind="value: Amount,attr: {'id': 'Cards_' + $index() + '__Amount','name':'Cards['+$index()+'].Amount'}" type="hidden">
</div>

you can use $index() to easily separate item lines and give them unique id. It is a function in knockout that return index of each item in an observablearray.

Thats it!