Renaming Project or Solution , Multiple Classes Error

When renaming a project, ensure to empty the /bin/ folder within the project for a clean rebuild.

Old DLL’s from previous builds could cause failures in resolving Controller names as 2 or more instances of the same controller would be found under 2 diff namespaces.

Easiest way: Right click solution -> Clean Solution and then Rebuild.

Repro steps:

1. Create a ASP.NET Web Project with name – App1 and add a controller.

2. Rebuild this project.

3. Rename project to App2 and all namespaces within.

4. Rebuild this project App2.

5. When making a call to a controller method SomeMethod, the routing complains that it cant resolve the controller name due to 2 instances of the controller – one as App1.SomeMethod and another App2.SomeMethod.

— the end —

Creating Bootstrap datepicker

View

<form>

<input type=”text” id=”pickADate” data-bind=”value: dataModel().pickADate” class=”datepicker form-control” readonly name=”pickADate”​ />

<!– id, name can be anything. class is important –>

<script>require[”…., “bootstrap-datepicker”, “bootstrap-datepickerGB”​], function(….,datepicker, datePickerGb) {

                    moment.locale(“en-gb”); // Set Locale for moment (aka moment.locale(“en-gb”))
var vm.mydateDate = moment(data.MyDateDate).format(“L”); // we get dd/mm/yyyy

$(‘.datepicker’).datepicker({ language: “en-GB” });​

}

## requirejs config

        “bootstrap-datepicker”: “bootstrap-datepicker”,
        “bootstrap-datepickerGB”: “locales/bootstrap-datepicker.en-GB.min”,

Thats all..

Posting KnockOut Form data (3 mechanisms)

// MyFormController/PostMyForm

//
   $.ajax({
// Method 1
                    url: “MyForm/MyForm”,
                        method: “POST”,
                        data: self.dataModel(),
                        contentType: ‘application/x-www-form-urlencoded; charset=utf-8’, // ‘application/json’
// Method 2
                        // ## PostBack as FormCollection
                        // data: “myForm”=self.dataModel()
                        // contentType: ‘application/x-www-form-urlencoded; charset=utf-8’,
 // Need to build a JsonValueProvider
// Refer to http://haacked.com/archive/2011/06/30/whatrsquos-the-difference-between-a-value-provider-and-model-binder.aspx/
                      // ## Postback as Json
                        // data: JSON.stringify(self.dataModel())
                        // contentType: ‘application/json’
                        // dataType:”json”,

Model binding Enum back to Object

Whe passing data from client (ko data back to MVC) where the object is an Enum of say 2 values. We need to either setup a Model Binder for that or take a shortcut ​as follows:

<checkbox data-bind=”checked: viewModel.myStatus”>

Enum MyStatus {Complete=1, NotStarted=0}

And if myStatus is of type MyStatus then, we can say in ajax before postback:

postbackObject.myStatus = (viewModel.myStatus ==0) ? “NotStarted” : “Complete”. And the MVC will figure out the Enum string to translate it back to the correct enum and we will get a valid Model in [FromBody].

Thats all

Long Running Task C#

Await and async in .NET 4.5 with C#

public Task<string> RunSlowOperationTask()
        {
            return Task.Factory.StartNew<string>(RunSlowOperation);
        }
OR
var taskData = new CalcTaskData {ForDate = forDate.Value, param2 = Value2};
 Task t = new Task(() => DoCalcAsync(taskData));
 t.Start();
// Long running Task
private async Task DoCalcAsync(CalcTaskData calcTaskData)
{
// long operation
// simulate long wait  (see note below)
}

Note that Thread.Sleep was replaced by Task.Delay(2000).

Thread.Sleep blocks the thread whereas Task.Delay represents a work that will block the thread for two seconds

Task.Run vs RunSynchronously

Task.Run = Tasks are executed asynchronously on a thread pool thread and do not block the calling thread.

​Task.RunSynchronously: Run on the calling thread, Blocks caller.

Both cases need to Wait() to catch exceptions..

TaskScheduler:

Latter: Task gets associated with the current TaskScheduler.

If the target scheduler does not support running this task on the calling thread, the task will be scheduled for execution on the scheduler (? which one), and the calling thread will block until the task has completed execution.

Export Table to Excel – Server side MVC

Excellent blogpost.. Using ClosedXml Nuget pkg..

​http://www.c-sharpcorner.com/UploadFile/rahul4_saxena/export-data-table-to-excel-in-Asp-Net-mvc-4/​

Excerpt:

public ActionResult ExportReportDataPerReport()

DataTable dt = new DataTable(“ReportDataExport”);
// tableName = ReportDataExport (also becomes sheet name in Xlsx)
// Add Columns to the dt. Then add data using dt.NewRow and
dt.AddRow …
// Once dt is populated, run below code..
            using (var wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt);
                wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                wb.Style.Font.Bold = true;
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = “”;
                Response.ContentType = “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”;
                string filenameSuffix = String.Format(“[{0}] [{1} to {2}]”,
                    reportContainer.FuelTypeName,
                    reportContainer.FromDate.Value.ToString(“dd-MMM-yyyy”),
                    reportContainer.ToDate.Value.ToString(“dd-MMM-yyyy”));
                string downloadHeader = String.Format(“attachment;filename= MyReport{0}.xlsx”,
                    filenameSuffix);
                Response.AddHeader(“content-disposition”, downloadHeader);
                using (var myMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(myMemoryStream);
                    myMemoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.End();
                    return new EmptyResult();
                }
            }

} // end of MVC action

NPM and Gulp

NPM is Node Package Manager and similar to Nuget. Uses package.json​ instead of package.config. Allows installation of Javascript based packages from the NPM website (npmjs.org).

INSTALLING NODEJS and NPM:

1. Install Nodejs (x86 or x64 from the NodeJs.Org)

— THIS makes your machine nodejs and npm enabled..

CHECK: Open command line and run node -v and npm -v. We should see a version number.

Gulp: Gulp is a js based task runner to manage and publish your Web Resources/assets such as Javascript js files, CSS files, Image files.

Read more: Common tasks such as minifying, linting, sass -> css compilation, image optimisation etc. are all done by gulp as part of the tasks defined in gulpfile.js. See Quenchjs.com to generate a bog standard gulpfile.js and get started quickly.

INSTALLING GULP:

1. Install Python from Python website (e.g. to C:\Python34\

1.1 Add Python foldername to PATH env. var in System Properties: C:\Python34. This makes sure npm can find python when needed.

2. Open command prompt as Admin.

3. Run npm install -g gulp (to install gulp globally)

4. Check: run gulp -v (will show gulp version installed)

Contd.. Install gulp to Web Resources project: 

1. Chg Dir cd to the project folder. e.g. C:\Projects\MyProject.WebResources\

2. Run npm install –save-dev gulp (or simply npm install gulp)

3. Now gulp is setup.

4. Install required plugins:

npm install jshint gulp-jshint gulp-sass gulp-concat gulp-uglify gulp-rename –save-dev

Now each of the defined gulp tasks can be run to do what we originally wanted – minifying, linting etc.

If we have a default task:

// Default Task
gulp.task(‘default’, [‘lint’, ‘sass’, ‘scripts’, ‘watch’]);

Running gulp​ in that project folder will run all tasks – lint, sass, scripts watch..

To run only one task of all defined ones in gulpfile.js we can run

​gulp sass

See excellent post on further Gulp setup by Travis Maynard.

https://travismaynard.com/writing/getting-started-with-gulp

MISC Package updates:

npm install -g node-gyp

npm install gulp-cssnano

npm install lodash

Misc NPM commands:
npm init
npm link

Issues:

If the default setup doesnt work. Follow steps below.

ISSUE: NPM permission problems
npm config set prefix %APPDATA%\npm
npm config set cache %APPDATA%\npm-cache
OR
npm config set prefix C:\NPM\npm
npm config set cache C:\NPM\npm-cache
ISSUE: ECONRESET errors behind proxy or VPN
npm config set registry http://registry.npmjs.org

Ensure exists Environment variable: NODE_PATH=C:\NPM\npm\node_modules

ISSUE: Cannot find gulp:

Ensure PATH environment variable has C:\NPM\npm at the end. This is where gulp.cmd lives. If we setup the prefix to C:\NPM, we will find gulp.cmd under C:\NPM\npm\gulp.cmd

Angular 2 First Look

Pluralsight course – Angular 2 First Look (John Papa) 

https://app.pluralsight.com/library/courses/angular-2-first-look/table-of-contents

Ready to use / run samples: (edit/run in Plunker online)

http://a2-first-look.azurewebsites.net/

(or http://jpapa.me/a2firstlook)

Further reference n quickstarts:

https://angular.io/docs/ts/latest/guide/

https://angular.io/docs/ts/latest/guide/architecture.html