Blog

My blog serves as a way for me to post solutions to problems I solve at work or during the long hours of freelance work.


String.Format

by Ezekiel 12. August 2014 03:56

 

Currency "{0:c}"

Date "{0:MM/dd/yyyy}"

Tags: ,

C# | General | Javascript | MVC | Razor Views

Remove Text from Textbox during OnClick using Razor View

by Ezekiel 7. January 2014 10:49

 

            <div class="editor-field">
                @Html.TextAreaFor(model => model.Product.Description, new
                                {
                                    onfocus="(this.value == 'enter description') && (this.value = '')",
                                    onblur="(this.value == '') && (this.value = 'enter description')"
                                })
                @Html.ValidationMessageFor(model => model.Product.Description)
            </div> 

 

Tags: , ,

Javascript | MVC | Razor Views

ASP.NET C# MVC Unit Testing

by Ezekiel 21. December 2013 03:48

 

[Fact]
public void ListActionReturnsListOfCategories()
{
    // Arrange

    // create the mock
    var mockRepository = new Mock<ICategoryRepository>();

    // create a list of categories to return
    var categories = new[] { new Category {Id = 1, Name = "test"} };

    // tell the mock that when FindAll is called,
    // return the list of categories
    mockRepository.Setup(cr => cr.FindAll()).Returns(categories);

    // pass the mocked instance, not the mock itself, to the category
    // controller using the Object property
    var controller = new CategoryController(mockRepository.Object);

    // Act
    var result = (ViewResult) controller.List();

    // Assert
    var listCategories = Assert.IsAssignableFrom<IEnumerable<Category>>(result.ViewData.Model);
    Assert.Equal(1, listCategories.Count());           
}

 

[Fact]
public void ListActionReturnsListOfCategories()
{
    // Arrange
    var mockService = new Mock<ICategoryService>();
    var categories = new[] { new Category { Id = 1, Name = "test" } };
    mockService.Setup(cr => cr.FindAll()).Returns(categories);
    var controller = new CategoryController(mockService.Object);

    // Act
    var result = (ViewResult) controller.List();

    // Assert
    var listCategories = Assert.IsAssignableFrom<IEnumerable<Category>>(result.ViewData.Model);           
    Assert.Equal(1, listCategories.Count());
}

 [Fact]
public void PriceIsFormattedAsCurrency()
{
    // Arrange
    var product = new Product {Price = 9.22m};
    var presentationProduct = new
        PresentationProductStub(product);

    // Act
    string cost = presentationProduct.DisplayPrice;

    // Assert
    Assert.Equal("$9.22", cost);
}

[Fact]
public void DefaultUrlRoutesToCategoryControllerAndListAction()
{
    // Arrange
    var context = ContextHelper.GetMockHttpContext("~/");
    var routes = new RouteCollection();
    MvcApplication.RegisterRoutes(routes);

    // Act
    RouteData routeData = routes.GetRouteData(context.Object);

    // Assert
    RouteTestingHelper.AssertRouteData(routeData, "Category", "List", "");
}

[Fact]
public void ProductEditUrlRoutesToProductControllerAndListAction()
{
    // Arrange
    var context = ContextHelper.GetMockHttpContext("~/Product/Edit/12");
    var routes = new RouteCollection();
    MvcApplication.RegisterRoutes(routes);

    // Act
    RouteData routeData = routes.GetRouteData(context.Object);

    // Assert
    RouteTestingHelper.AssertRouteData(routeData, "Product", "Edit", "12");
}

[Fact]
public void ListActionReturnsViewResultWithDefaultName()
{
    // Arrange
    var mockService = new Mock<ICategoryService>();
    var controller = new CategoryController(mockService.Object);

    // Act
    var result = controller.List();

    // Assert
    var viewResult = Assert.IsType<ViewResult>(result);           
    Assert.Empty(viewResult.ViewName);
}

   /// <summary>
    ///This is a test class for LibraryCoreTest and is intended
    ///to contain all LibraryCoreTest Unit Tests
    ///</summary>
    [TestClass()]
    public class LibraryCoreTest
    {

        private LibraryCore _target;
        private Mock<IMemberManager> _mock;

        /// <summary>
        ///A test for CalculateMemberShipCost
        ///</summary>
        [TestMethod()]
        public void CalculateMemberShipCostTest()
        {
            _mock = new Mock<IMemberManager>();
            _target = new LibraryCore(_mock.Object);
            Member member = new Member()
            {
                MemberID=1,
                FirstName="Erandika",
                SecondName="Sandaruwan",
                Age=25,
                MaximumBookCanBorrow=4,
            };

            _mock.Setup(x => x.GetMember(It.IsAny<int>())).Returns(member);
   
            int memberID = 1;
            double expected = 12;
            double actual;
            actual = _target.CalculateMemberShipCost(memberID);
            Assert.AreEqual(expected, actual); 
        }
    }

 [TestMethod] // [Fact] for XUnit framework
public async Task YourTestName()

{

     // Arrange

     // mock/stub your async method, use a framework or do it yourself - Task.FromResult() is the key

     // SomeMethodAsync() returns Task<string>

     var fakeRepository = new Mock<ISomeRepository>();

     fakeRepository.Setup(m => m.SomeMethodAsync()).Returns(Task.FromResult("your object to return"));

     // constructor injection, or other technique (e.g. property injection)

     var target = new SomeController(fakeRepository.Object);

     // Act

     // SomeMethodAsync() uses mocked/stubed ISomeRepository inside

     ActionResult result = await target.SomeMethodAsync();

     // Assert

     // your assertion

}

 

Tags: , ,

MVC | Unit Testing

How to Use PageList.MVC

by Ezekiel 6. December 2013 15:53

 

Run the following in Package Manager Console.

PM> Install-Package PagedList.Mvc

 

Controller -

        public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            var products = from s in db.Products
                           select s;

            switch (sortOrder)
            {
                case "name_desc":
                    products = products.OrderByDescending(s => s.Name);
                    break;
                case "Date":
                    products = products.OrderBy(s => s.Price);
                    break;
                case "date_desc":
                    products = products.OrderByDescending(s => s.Price);
                    break;
                default:  // Name ascending
                    products = products.OrderBy(s => s.Name);
                    break;
            }

            int pageSize = 300;
            int pageNumber = (page ?? 1);

            return View(products.ToPagedList(pageNumber, pageSize));
        }

 

 

Front-end -

 

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
 

Tags: ,

MVC

The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.

by Ezekiel 6. December 2013 13:30

 

I received this error when trying to use PageList.MVC without adding sorting to the controller.

Tags: ,

MVC

MVC Data Annotation

by Ezekiel 12. November 2012 17:36

 

[Key]

[Required]

[ComplexType]

[ScaffoldColumn(false)]

[DisplayName("Category")]


[MaxLength(10), MinLength(5)]

[MaxLength(10, ErrorMessage="BloggerName must be 10 characters or less"), MinLength(5)]

[ConcurrencyCheck, MaxLength(10, ErrorMessage="BloggerName must be 10 characters or less"), MinLength(5)]

[Display(Name = "Name", Description = "Enter the name of the product.")]

[HttpPost]

[Timestamp]

[Table("InternalBlogs")]

[Column(“BlogDescription", TypeName="ntext")]

[DatabaseGenerated(DatabaseGenerationOption.Computed)]

[ForeignKey("BlogId")]

[InverseProperty("CreatedBy")]

Tags: , ,

C# | MVC

NuGet TinyMCE Install

by Ezekiel 16. September 2012 07:45

 

Launch Package Manager Console:

Tools > Library Package Manager > Package Manager Console

 

Copy and paste this line below and hit enter:

 PM> Install-Package TinyMCE

Tags: , , ,

MVC | NuGet | TinyMCE

MVC HTTP Post Edit View Model Data Using FormCollection in C#

by Ezekiel 16. June 2012 18:16

 

Model View Class -

    public class ProductViewModel
    {
        public Product Product { get; set; }
        public List<Image> Images { get; set; }
    }

 

Controller Method -

        //
        // POST: /Manager/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection, IEnumerable<HttpPostedFileBase> files)
        {
            if (ModelState.IsValid)
            {
                Product product = db.Products.Single(p => p.ProductId == id);

                UpdateModel(product, "Product");

                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();

                // Insert images
                InsertUploadFiles(product, files);

                return RedirectToAction("Index");
            }

            return Redirect("index");
        } 

 

 UI -

@using (Html.BeginForm("edit", "manager", FormMethod.Post, new { id = Model.Product.ProductId, enctype = "multipart/form-data" }))

 

Tags: , ,

ASP.NET | C# | MVC

How to Install Code First EntityFramework NuGet

by Ezekiel 13. June 2012 15:44

 

In Visual Studio go to -

Tools > Library Package Manager > Package Manager Console

 

At the command prompt copy and paste the code from this site -

http://nuget.org/packages/entityframework

 

Tags: , ,

MVC | Code First

Maximum request length exceeded.

by Ezekiel 10. June 2012 16:27

 

I was getting this error message when uploading more then two image files.

 

Add this to your web.confg -

<httpRuntime requestValidationMode="2.0" maxRequestLength="20192" />

 

 

Tags: , ,

.NET 4.0 | ASP.NET | MVC

RecentPosts