Archive

Archive for the ‘Windows’ Category

ASP.NET MVC With Dapper?

September 24, 2016 Leave a comment

Hello fellow coders.

It’s a while again. I’m a lazy, lazy coder, and I don’t have much time updating this blog.

Let’s get talking.

Entity Framework is a wonderful technology. It rescues us from the burden of creating & managing our business classes and CRUD operations within the data layer. It makes our lives easier. It even generates views including DropDownListFor for foreign key relations. Wonderful!

Or does it?

Okay, I love the framework, but it sucks. It is slow, and even slower at being slow. Also, if you are not using Entity Framework, the foreign key relations within a custom designed class is not seen by Scaffolding engine. It only scaffolds generic fields, skipping Foreign Keys and Relations entirely.

I’m using Dapper Micro-ORM for a while now (over 1 year actually). I have successfully completed several mid-sized projects with it. It is a thin layer over standard ADO.NET and it operates fast, and by that, I mean really, really fast.

One caveat is that, you have to manually code your classes, your annotations (Required, DisplayName..), your relationships, etc., and you have to create your foreign key relations (and also dropdown logic).

Tired of doing these over and over, I have created a model, metadata,  view and controller generator which generates all of these for me.

Let’s have a look.

For the sake of simplicity, I have 4 tables, as shown here.

db1

Next, I have decorated the tables and fields with the names I want to see in my views. This is a wonderful thing for non-English users like me.

db2

These settings are used for generating models and views. Now, I open my generator 🙂

db3

Set the options, and click Start. Easy enough!

The generator then creates this structure under the selected folder

db4:

Here is the generated Order Model:

using System;
using System.Collections.Generic;
using System.Linq;
using Models;
using Dapper;

namespace Models
{
	public partial class Order
	{
		#region Primary Keys
		public int Id { get; set; }
		#endregion

		#region Foreign Keys
		public int CustomerId { get; set; }
		#endregion

		#region Generic Fields
		public string Name { get; set; }
		public DateTime OrderDate { get; set; }
		#endregion

		#region Virtual Fields
		public virtual Lazy<Customer> Customer { get { return new Lazy<Customer>(() => new Customer().FetchById((int)CustomerId)); } }
		public virtual Lazy<IEnumerable<Customer>> CustomerList { get { return new Lazy<IEnumerable<Customer>>(() => new Customer().FetchAll()); } }
		#endregion

		#region Methods

		#region Create Method
		public Order Create(Order order)
		{
			this.Id = Database.Connection.Query<int>("INSERT INTO [dbo].Order(CustomerId, Name, OrderDate) VALUES(@CustomerId, @Name, @OrderDate); SELECT CAST(SCOPE_IDENTITY() as int)", order).Single();
			return order;
		}
		#endregion

		#region Fetch By Primary Keys
		public Order FetchById(int id)
		{
			return Database.Connection.Query<Order>("SELECT * FROM [dbo].Order WHERE Id = @Id", new { Id = id } ).SingleOrDefault();
		}
		#endregion

		#region FetchBy Fields
		public Order FetchByName(string name)
		{
			return Database.Connection.Query<Order>("SELECT * FROM [dbo].Order WHERE Name = @Name", new { Name = name } ).SingleOrDefault();
		}

		public Order FetchByOrderDate(DateTime orderDate)
		{
			return Database.Connection.Query<Order>("SELECT * FROM [dbo].Order WHERE OrderDate = @OrderDate", new { OrderDate = orderDate } ).SingleOrDefault();
		}

		#endregion

		#region FetchAll
		public List<Order> FetchAll()
		{
			return Database.Connection.Query<Order>("SELECT * FROM [dbo].Order").ToList();
		}
		#endregion

		#region FetchAllBy Foreign Keys
		public List<Order> FetchAllByCustomerId(int customerId)
		{
			return Database.Connection.Query < Order > ("SELECT * FROM [dbo].Order WHERE CustomerId = @CustomerId", new { CustomerId = customerId }).ToList();
		}

		#endregion

		#region FetchAllBy Fields
		public List<Order> FetchAllByName(string name)
		{
			return Database.Connection.Query<Order>("SELECT * FROM [dbo].Order WHERE Name = @Name", new { Name = name }).ToList();
		}

		public List<Order> FetchAllByOrderDate(DateTime orderDate)
		{
			return Database.Connection.Query<Order>("SELECT * FROM [dbo].Order WHERE OrderDate = @OrderDate", new { OrderDate = orderDate }).ToList();
		}

		#endregion

		#region Update Method
		public Order Update(Order order)
		{
			Database.Connection.Execute("UPDATE [dbo].Order SET CustomerId = @CustomerId, Name = @Name, OrderDate = @OrderDate WHERE Id = @Id", order);
			return order;
		}
		#endregion

		#region Delete By Primary Keys
		public void DeleteById(int id)
		{
			var modelOrderDetails = new OrderDetails();
			modelOrderDetails.DeleteAllByOrderId(id);
			Database.Connection.Execute("DELETE FROM [dbo].Order WHERE Id = @Id", new { Id = id } );
		}
		#endregion

		#region DeleteAllBy Foreign Keys
		public void DeleteAllByCustomerId(int customerId)
		{
			Database.Connection.Execute("DELETE FROM [dbo].Order WHERE CustomerId = @CustomerId", new { CustomerId = customerId });
		}

		#endregion

		#region DeleteAllBy Fields
		public void DeleteAllByName(string name)
		{
			Database.Connection.Execute("DELETE FROM [dbo].Order WHERE Name = @Name", new { Name = name });
		}

		public void DeleteAllByOrderDate(DateTime orderDate)
		{
			Database.Connection.Execute("DELETE FROM [dbo].Order WHERE OrderDate = @OrderDate", new { OrderDate = orderDate });
		}

		#endregion

		#endregion
	}
}

Metadata class:

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Models
{
	[MetadataType(typeof(OrderMetadata))]
	public partial class Order
	{
	}

	public class OrderMetadata
	{
		#region Primary Keys
		[Key]
		[ScaffoldColumn(false)]
		public int Id { get; set; }
		#endregion

		#region Foreign Keys
		[DisplayName("Customer")]
		[Required(ErrorMessage="Customer is required.")]
		public int CustomerId { get; set; }
		#endregion

		#region Generic Fields
		[DisplayName("Order Name")]
		[StringLength(100)]
		[Required(ErrorMessage="Order Name is required.")]
		public string Name { get; set; }
		[DisplayName("Order Date")]
		[DataType(DataType.Date)]
		[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
		[Required(ErrorMessage="Order Date is required.")]
		public DateTime OrderDate { get; set; }
		#endregion

	}
}

And the controller for Order:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Web.Mvc;
using Models;

namespace Test.Controllers
{
	public partial class OrderController: Controller
	{
		#region Methods

		#region Helper: SetDependencies Method
		public void SetDependencies(int customerId = -1)
		{
			ViewBag.customerList = new SelectList(new Customer().FetchAll(), "Id", "CustomerName", customerId != -1 ? customerId : (int?)null);
		}
		#endregion

		#region Index: GET Method
		public ViewResult Index()
		{
			var model = new Order().FetchAll();
			return View(model);
		}
		#endregion

		#region Details: GET Method
		public ActionResult Details(int? id)
		{
			if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
			var model = new Order().FetchById((int)id);
			if (model == null) return HttpNotFound();
			return View(model);
		}

		#endregion

		#region New: GET Method
		public ActionResult New()
		{
			SetDependencies();
			return View();
		}

		#endregion

		#region New: POST Method
		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult New(Order model)
		{
			if (!ModelState.IsValid) { SetDependencies(); return View(model); }
			model.Create(model);
			return RedirectToAction("Index");
		}
		#endregion

		#region Edit: GET Method
		public ActionResult Edit(int? id)
		{
			if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
			var model = new Order().FetchById((int)id);
			if (model == null) return HttpNotFound();
			SetDependencies(model.CustomerId);
			return View(model);
		}

		#endregion

		#region Edit: POST Method
		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult Edit(Order model)
		{
			if (!ModelState.IsValid) { SetDependencies(); return View(model); }
			model.Update(model);
			return RedirectToAction("Index");
		}
		#endregion

		#region Delete: GET Method
		public ActionResult Delete(int? id)
		{
			if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
			var model = new Order().FetchById((int)id);
			if (model == null) return HttpNotFound();
			return View(model);
		}

		#endregion

		#region DeleteConfirmed: POST Method
		[HttpPost, ActionName("Delete")]
		[ValidateAntiForgeryToken]
		public ActionResult DeleteConfirmed(int? id)
		{
			var model = new Order();
			model.DeleteById((int)id);
			return RedirectToAction("Index");
		}
		#endregion

		#endregion
	}
}

And the view (Create)

@model Models.Order
@{
	ViewBag.Title = "New Order";
}

<div class="row st">
	<div class="col-md-12">
		@using (Html.BeginForm())
		{
			@Html.AntiForgeryToken()
			<div class="panel panel-default panel-default">
				<div class="panel-heading"><strong>New Order</strong><input type="submit" class="pull-right SubmitButton" value="Save" /><span class="pull-right">&nbsp;&nbsp;</span><button onclick="location.href = '@Url.Action("Index", "Order")'; return false;" class="SubmitButton pull-right">Back</button></div>
				<div class="panel-body pbcolor">
					<div class="row">
						<div class="col-xs-12">
							<p>Please enter the details of new Order.</p>
						</div>
					</div>
				</div>
				<div class="panel-body">
					<div class="form-horizontal">
						@Html.ValidationSummary(true, "", new { @class = "text-danger" })
						<div class="form-group">
							@Html.LabelFor(model => model.CustomerId, new { @class = "control-label col-md-2" })
							<div class="col-md-10">
								@Html.DropDownListFor(model => model.CustomerId, (IEnumerable<SelectListItem>)ViewBag.customerList, new { @class = "form-control input-sm" })
								@Html.ValidationMessageFor(model => model.CustomerId, "", new { @class = "text-danger" })
							</div>
						</div>
						<div class="form-group">
							@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
							<div class="col-md-10">
								@Html.EditorFor(model => model.Name, new { htmlAttributes =  new { @class = "form-control input-sm" }})
								@Html.ValidationMessageFor(model => model.Name,"", new { @class = "text-danger" })
							</div>
						</div>
						<div class="form-group">
							@Html.LabelFor(model => model.OrderDate, htmlAttributes: new { @class = "control-label col-md-2" })
							<div class="col-md-10">
								@Html.EditorFor(model => model.OrderDate, new { htmlAttributes =  new { @class = "form-control input-sm" }})
								@Html.ValidationMessageFor(model => model.OrderDate,"", new { @class = "text-danger" })
							</div>
						</div>
					</div>
				</div>
			</div>
		}
	</div>
</div>

And voila! The project’s dependencies are generated without a single line of code. It still has plenty of room for adding more features, but hey, I have to do some coding, otherwise every project will be boring 🙂

Have a very nice day!

Advertisements

SyncFusion Essential Studio. For free?

November 22, 2015 Leave a comment

Hello everybody!

After a long silence (again), I’m here to say that I’m alive and still coding. It’s time to add another post, and this is important.

syncfusion-logo

The wonderful guys at Syncfusion made an unbelievable move. They made their $10,000 worth of Essential Studio Enterprise Edition, which consists of hundreds high quality components and tools for ASP.NET, MVC, WPF and more, available for free, with the exception of being an individual or a small company.

As a developer, I have worked with several component packages in the past. For almost 1.5 years, I’m using Syncfusion Essential Studio and never looked back.

The tools and components are the best of the any bundle you can find. The ease of use, the overall quality and the support is definitely unmatched across vendors.

Hurry and grab your license for free. You won’t regret it.

Frank Borland: Welcome back sherrif

December 23, 2012 4 comments

I always have a soft spot for developer tools which has Borland® Logo on it. Although I’m now making money using Microsoft products, Borland products was always first to prefer for me. I know that I am not alone with these feelings.

 

Recently, Borland released a video about the return of Frank Borland, which made me feel like I was still living in the good old times.

Here is the snippet from production agency:

Working together with integrated B2B marketing agency, True, Irresistible Films have produced an introductory film to re-establish Borland Software Corporation as leaders in software development, through awareness generated around the character Frank Borland.

Borland recognises that developers and developmental organisations need to define, manage and measure software delivery processes based on unique needs, tools and preferences, working to identify the requirements, test and change solutions that help companies build better software, faster.

Frank first appeared in advertisements during the 80s, helping to shape Borland as a dynamic company that tackled the biggest of software companies, promoting software such as Sidekick and Turbo Pascal.

Usage of the film will be geared towards targeting Borland’s CRM system of 40,000+ software developers. According to Frank, Borland creates testing software that works together with pre-existing tools in a non-restrictive of forcefully changing manner, offering simple yet powerful functionality.

Frank’s vision is simple: Keep it open, Don’t make it big, make it better. Focus on the user experience. Meet every platform need. Make it affordable. Listen to the community.

Creating, developing aand delivering better software, Frank’s return coincides with some key breakthroughs that will see Borland deliver new releases faster, alongside creating test tools that help deliver smooth engaging consumer experiences.

Borland is focused on extending their web and mobile testing capabilities across a range of platforms, helping to drive testing effort down and minimise time to market. Through application performance testing, Borland aims to bring exciting ideas and new releases to market through a cost effective model, placing affordable, powerful tools in the hands of the user.

Frank, and more directly, Borland’s, intent is to listen to the developers to deliver what’s really needed. On Frank’s return, Borland hope to bring to light some game-changing plans for software in the test environment and enterprise space.

Shot on location in Geneva, Switzerland, the film was captured in real-time, then reversed in Post, meaning Frank pretty much learnt his script in reverse, making for one serious come back!”

Here, watch it and see for yourself:

http://www.meetfrankborland.com/

I love you Borland. I always will.

Goodbye NOD32, Welcome BitDefender.

March 24, 2010 1 comment

For years, I’ve been trusting, using and recommending NOD32 to my customers, and everyone around me. But today, it failed to clean Sality.NAY (Sality.AX for BitDefender) virus. Core system components are infected, so I was unable to delete them. It all begin with flash memory virus detection problems, and it still fails to detect these.

I hvae installed BitDefender, and it did clean every instance of Sality instantly.

I’m leaving NOD32, and will start using BitDefender after now. It has a free version, and I’ll install it to my customers’ computers.

Thank you ESET, for leaving me in the dust. I won’t recommend any of your products after now. If you are into serious IT business, do not recommend it to your customers. You’ll regret it.

The return of a legend: Delphi.

December 28, 2009 2 comments

Just check the screenshot below. The guys at Embarcadero worked really hard, started listening us and this is the result:

Delphi 2010 is a piece of art, a sunshine in the middle of an ocean. It is a gift from heaven, from holy coders at Embarcadero. This time, Delphi is really done right, and backed by a dedicated company. Speed, stability, feature set, everything is perfect.

I personally want to thank everyone who is involved in the process of creating Delphi 2010. You guys rock.

Creating a PostgreSQL Database with TUniScript

August 8, 2009 Leave a comment

Amazing, just amazing. Some software and some developers can not be praised enough. I’m talking about PostgreSQL Database Server, and its excellent features, and its price.

I newly started using PostgreSQL, and believe me, it is one of the most advanced database server in the world.

Combined with a form of fusion (Universal Database Access Components – UniDAC), the Delphi coders found all the energy the would ever need.

I’m to explain how to create a PostgreSQL Database with TUniScript component. I am unable to find a real world example when I first started using UniDAC components.

So here we go. Drop TUniConnection, TPostgreSQLUniProvider and TUniScript components to a form.

Set TUniConnection’s properties, but leave the Database property blank. Set UniScript’s NoPreconnect property to True, and paste this into the SQL property of UniScript component.

DROP DATABASE IF EXISTS "mydatabase";
CREATE DATABASE "mydatabase"
WITH OWNER = postgres
ENCODING = 'UTF8';

Because we didn’t specify a database while setting properties of UniConnection component, we should set it in our code after our database is created:

UniScript1.Execute;
Sleep(5000); // Delay for database creation
UniConnection1.Database := 'mydatabase';

I have added another TUniScript component for adding tables, and it includes table creation data and referential integrity information. After database is created, I’m calling it to create tables:

UniScript2.Execute

And that’s it. We have created a PostgreSQL with Delphi and created tables at runtime. UniDAC is an extremely powerful native component set for Delphi.

A must for a serious programmer.

An update system with an idiotic approach.

June 13, 2009 Leave a comment

Let me introduce you an update approach for disturbing your users, make them suffer and increase potential murder count in your userbase:

1. Make the updates hidden.
2. Require registration for updates. Who cares public usage?
3. Use InstallAware for your software and update distribution platform.
4. Expect all of your users to have broadband internet connection.
5. Force your users to redownload 500 mb’s of update everytime with a new installation. Yes, there are no computers in this world which are part of a development team, and there is nothing called as a network installation.

If a huge company like Embarcadero (CodeGear?) follows this approach, probably it is a right thing, and you should follow them too.

Do anything you want, but stay away from me.