Saturday, May 2, 2015

How to use "PetaPoco - A tiny ORM-ish thing for your POCOs"

PetePoco is a tiny, fast, single-file micro-ORM for .NET and Mono.
  • It is a single file that you easily add to any project.
  • It works wit strongly typed POCO's.
  • It supports a close relationship between object and database table.
  • It is fast because it uses dynamic method generations (MSIL) to assign column values to properties. 


And this is how you can use it to insert, update, delete and retrieve the records, it is amazing and easy to use!
  • Add PetePoco package to your project by using Nuget (http://nuget.org/List/Packages/PetaPoco)
  • After installation you will see the PetaPoco class added to your project.
  • It is ready to use and this is how you can use it!


[PetaPoco.TableName("fsCarts")]
[PetaPoco.PrimaryKey("RecordID")]
public class Cart
{
  [Key]
  public int RecordId { get; set; }
  public string CartId { get; set; }
  public Guid ProductId { get; set; }
  public int Count { get; set; }
  public DateTime DateCreated { get; set; }

}

public void AddToCart(Product product)
{
    try
    {
       var cartItem = con.FirstOrDefault<Cart>("SELECT * FROM fsCarts WHERE CartID=@0 AND ProductID=@1", ShoppingCardId, product.ProductId);

        if (cartItem == null)
        {
            cartItem = new Cart
            {
               ProductId = product.ProductId,
               CartId = ShoppingCardId,
               Count = 1,
               DateCreated = DateTime.Now
             };
             con.Insert("fsCarts", "RecordID", cartItem);
         }
         else
         {
              cartItem.Count++;
              con.Update("fsCarts", "RecordID", cartItem);
          }
    }
    catch (Exception ex)
    {
        Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new Exception("Shopping Cart AddToCart: " + ex.ToString())));
    }
}

////////////////////

public int RemoveFromCart(int id)
{
    int itemCount = 0;
    try
    {
        var cartItem = con.FirstOrDefault<Cart>("SELECT * FROM fsCarts WHERE CartID=@0 AND RecordId=@1", ShoppingCardId, id);

        if (cartItem != null)
        {
            if (cartItem.Count > 1)
            {
                cartItem.Count--;
                itemCount = cartItem.Count;
                con.Update("fsCarts", "RecordID", cartItem);
             }
             else
             {
                con.Delete("fsCarts", "RecordID", cartItem);
              }
        }

     }
     catch (Exception ex)
     {
         Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new Exception("Shopping Cart RemoveFromCart: " + ex.ToString())));
      }

    return itemCount;
 }


////////////////////

public List<Cart> GetCartItems()
{
    List<Cart> cartItemList = new List<Cart>();
    try
    {
        cartItemList = con.Query<Cart>("SELECT * FROM fsCarts WHERE CartID=@0", ShoppingCardId).ToList();

    }
    catch (Exception ex)
    {
        Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new Exception("Shopping Cart GetCartItems: " + ex.ToString())));
    }
   return cartItemList;
}

////////////////////

public decimal GetTotal()
{
    decimal? total = null;
    try
    {
        total = con.ExecuteScalar<decimal>("SELECT SUM(ISNULL(p.Price,0)*c.Count) FROM fsCarts c INNER JOIN fsProducts p ON c.ProductID=p.ProductID WHERE c.CartID=@0", ShoppingCardId);

     }
     catch (Exception ex)
     {
        Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new Exception("Shopping Cart GetTotal: " + ex.ToString())));
      }
    return total ?? decimal.Zero;
}

Converting Enum Values to Generic List

Working with Enum values is very useful in so many circumstances and when you need to covert these enum values to List<SelectListItem>, here is how you can do it;


public List<SelectListItem> GetPaymentOptions()
{
    PaymentOptions[] values = (PaymentOptions[])Enum.GetValues(typeof(PaymentOptions));

    var list = from value in values
               select new SelectListItem()
               {
                   Value = ((int)value).ToString(),
                   Text = value.ToString()
                };

    List<SelectListItem> paymentOptions = list.ToList<SelectListItem>();

    return paymentOptions;
}

That is all- nice and simple!

Happy coding!

Tuesday, March 17, 2015

Solution for "DestinationUnreachable" Problem When Using SOAPUI to Test Your Web Service

This error occurs when you try to test one of the web service methods by using SoapUI.

All you need to do is;

  • Check "Add default wsa:To" from WS-A tab as shown below.













That is all!

Happy coding!

Tuesday, March 10, 2015

Solution for Umbraco Mvc Project Error: "Could not load file or assembly 'ClientDependency.Core, Version=1.7.1.2, Culture=neutral, PublicKeyToken=null.' or one of its dependencies"

This error occurs  when trying to add a new controller to a Umbraco Mvc project(Umbraco version is 7.1.x.). This is an Umbraco bug and this is because of umbraco assemblies were built with specific versions.

All you need to do is;
  • Upgrade the umbraco mvc version to 7.2.2 or later by using Nuget Package Manager.
  • If you don't want to upgrade your umbraco mvc version, then you can just copy an existing controller and paste it and change it according to your project needs. This is the other way.
That's all!

Error Message:









Happy coding!

Wednesday, March 4, 2015

Solution for "This configuration section cannot be used at this path. This happens when the section is locked at a parent level..."

This error occurs  when there is a problem reading the configuration file for the Web server or Web application.

All you need to do is;

  • Click "Start" button.
  • Search for "Turn windows features on or off".
  • In the Windows Features window, go to "Internet Information Services\World Wide Web Services\Application Development Features".
  • Check all the features apart from CGI.
  • Restart your IIS.

That's all!

Error Message:
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

Happy coding!

Monday, September 15, 2014

Design Patterns - Abstract Factory Pattern

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern_AbstractFactoryApp
{
   class Program
   {
      static void Main(string[] args)
      {
         /* ABSTRACT FACTORY PATTERN:
          * The abstract factory pattern provides a way to 
          * encapsulate a group of individual factories 
          * that have a common theme without 
          * specifying their concrete classes.
          * Use of this pattern makes it possible to 
          * interchange concrete implementations 
          * without changing the code 
          * that uses them, even at runtime. 
          * However, employment of this pattern, 
          * as with similar design patterns, 
          * may result in unnecessary complexity 
          * and extra work in the initial writing of code
          */

         var samsungSmartPhone = new GenericFactory<SamsungSmartPhone>();
         SmartPhone smartPhone1 = new SamsungSmartPhone();
         samsungSmartPhone.CreateInstance().TestSmartPhone(smartPhone1);

         var appleSmartPhone = new GenericFactory<AppleSmartPhone>();
         SmartPhone smartPhone2 = new SamsungSmartPhone();
         appleSmartPhone.CreateInstance().TestSmartPhone(smartPhone2);

         Console.ReadKey();
      }
   }
}

**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern_AbstractFactoryApp
{
   public class GenericFactory<T>
      where T : new()
   {
      public T CreateInstance()
      {
         return new T();
      }
   }
}


**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern_AbstractFactoryApp
{
   public abstract class PhoneFactory
   {
      public abstract SmartPhone CreateSmartPhone();
      public abstract DummyPhone CreateDummyPhone();
   }
}

**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern_AbstractFactoryApp
{
   public abstract class SmartPhone
   {
      public abstract void TestSmartPhone(SmartPhone phone);
   }
}

**************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern_AbstractFactoryApp
{
   public abstract class DummyPhone
   {
      public abstract void TestDummyPhone(DummyPhone phone);
   }
}

**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern_AbstractFactoryApp
{
   public class AppleFactory : PhoneFactory
   {
      public override SmartPhone CreateSmartPhone()
      {
         return new AppleSmartPhone();
      }

      public override DummyPhone CreateDummyPhone()
      {
         return new AppleDummyPhone();
      }
   }
}

**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern_AbstractFactoryApp
{
   class AppleSmartPhone : SmartPhone
   {
      public override void TestSmartPhone(SmartPhone phone)
      {
         Console.WriteLine("Apple Smart: " + phone.GetType().Name);
      }
   }
}

**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern_AbstractFactoryApp
{
   class AppleDummyPhone : DummyPhone
   {
      public override void TestDummyPhone(DummyPhone phone)
      {
         Console.WriteLine("Apple Dummy: " + phone.GetType().Name);
      }
   }
}

**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern_AbstractFactoryApp
{
   class SamsungFactory:PhoneFactory
   {
      public override SmartPhone CreateSmartPhone()
      {
         return new SamsungSmartPhone();
      }

      public override DummyPhone CreateDummyPhone()
      {
         return new SamsungDummyPhone();
      }
   }
}

**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern_AbstractFactoryApp
{
   class SamsungSmartPhone : SmartPhone
   {
      public override void TestSmartPhone(SmartPhone phone)
      {
         Console.WriteLine("Samsung Smart: " + phone.GetType().Name);
      }
   }
}

**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern_AbstractFactoryApp
{
   class SamsungDummyPhone:DummyPhone
   {
      public override void TestDummyPhone(DummyPhone phone)
      {
         Console.WriteLine("Samsung Dummy: " + phone.GetType().Name);
      }
   }
}