Code Examples
It is a well-known fact that programmers spend 80% of their time reading code and only 20% writing it. At AltexSoft we understand the importance of well written and high quality source code, as the code may be shared between different team members, integrated to other systems and reviewed after many years since the first release date. Below are some sample codes written by AltexSoft software engineers for various projects.
Code examples written in C# programming language
BaseLinqRepository.cs (Download entire file)
using System.Linq;
using Organization.Project.Common.Dal;
using System.Data.Linq;
namespace Organization.Project.Dal
{
/// <summary>
/// Base L2S repository for different types of entities
/// </summary>
/// <typeparam name="IEntity">entity interface</typeparam>
/// <typeparam name="TEntity">entity type</typeparam>
public class BaseLinqRepository<IEntity, TEntity> : IRepository<IEntity> where TEntity : class, IEntity, new()
{
#region User Defined Variables
private readonly DataContext context;
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="context">L2S context</param>
public BaseLinqRepository(DataContext context)
{
this.context = context;
}
#endregion
#region Public Methods
/// <summary>
/// Gets IQueryable of all the entities of some type from the database (with possibility
/// to add some additional filters, sortings, etc. before the query really executes)
/// </summary>
/// <returns>IQueryable of all the entities of some type</returns>
public IQueryable<IEntity> GetAll()
{
return context.GetTable<TEntity>().Select(e => (IEntity)e);
}
/// <summary>
/// Adds a new entity to the context so it will be added to the database on submit
/// </summary>
/// <param name="entity">entity object</param>
/// <returns>if result of the operation is successful</returns>
public bool Add(IEntity entity)
{
var cEnt = entity as TEntity;
if (cEnt != null)
{
context.GetTable<TEntity>().InsertOnSubmit(cEnt);
return true;
}
return false;
}
/// <summary>
/// Deletes a new entity from the context so it will be removed from the database on submit
/// </summary>
/// <param name="entity">entity object</param>
/// <returns>if result of the operation is successful</returns>
public bool Delete(IEntity entity)
{
var cEnt = entity as TEntity;
if (cEnt != null)
{
context.GetTable<TEntity>().DeleteOnSubmit(cEnt);
return true;
}
return false;
}
/// <summary>
/// Creates an empty entity
/// </summary>
/// <returns>an entity through its common interface</returns>
public IEntity CreateEmpty()
{
return new TEntity();
}
/// <summary>
/// Refresh an entity by values from database
/// </summary>
/// <param name="entity">an entity to refresh</param>
public void Refresh(IEntity entity)
{
context.Refresh(RefreshMode.OverwriteCurrentValues, entity);
}
#endregion
}
}
BuyStuffController.cs (Download entire file)
using System;
using System.Linq;
using System.Web.Mvc;
using Organization.Project.Common;
using Organization.Project.Common.Authentication;
using Organization.Project.Common.Bll;
using Organization.Project.Common.Bll.Objects;
using Organization.Project.Common.Configuration;
using Organization.Project.Common.Enums.Bll;
using Organization.Project.Common.Enums.UI;
using Organization.Project.Web.Authentication;
using Organization.Project.Web.Extensions;
using Organization.Project.Web.Helpers;
using Organization.Project.Web.Models;
using Organization.Project.Web.Models.BuyStuff;
using Organization.Project.Web.ViewData;
namespace Organization.Project.Web.Controllers
{
/// <summary>
/// Controller for buy stuff operations
/// </summary>
public class BuyStuffController : BaseController
{
#region User Defined Variables
private readonly ICreditsManager creditsManager;
private readonly IReferenceBookManager referenceBookManager;
private readonly IErrorLogManager errorLog;
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="auth">authentication instance</param>
/// <param name="authManager">account manager instance</param>
/// <param name="cart">shopping cart instance</param>
/// <param name="config">configuration instance</param>
/// <param name="creditsManager">credits manager instance</param>
/// <param name="errorLogManager">error log manager</param>
/// <param name="referenceBookManager">reference book manager instance</param>
public BuyStuffController(IAuthentication auth, IAccountManager authManager, IProjectCart cart, IProjectConfiguration config, ICreditsManager creditsManager, IErrorLogManager errorLogManager, IReferenceBookManager referenceBookManager)
: base(auth, authManager, cart, config)
{
this.creditsManager = creditsManager;
this.errorLog = errorLogManager;
this.referenceBookManager = referenceBookManager;
}
#endregion
#region Public Methods
/// <summary>
/// Gets basic BuyStuff view
/// </summary>
/// <returns>BuyStuff page</returns>
[ForceNoCache]
public ActionResult Index(string loadAction)
{
var items = Cart.GetItems(CurrentUser, 0, Constants.BuyStuffPageSize);
var model = CreateBuyStuffViewData(Cart.GetItemsCost(CurrentUser), items, 0);
return View(model);
}
/// <summary>
/// Gets cart items list view (control)
/// </summary>
/// <param name="page">cart items current page</param>
/// <returns>cart items partial view</returns>
[ProjectAuthorize]
public ActionResult GetCartItemsView(int page)
{
var items = Cart.GetItems(CurrentUser, page * Constants.BuyStuffPageSize, Constants.BuyStuffPageSize);
int pagesCount = GetPagesCount(items.Total, Constants.BuyStuffPageSize);
// if no items on page (deleted last item on page) show last page
if (page >= pagesCount)
{
page = pagesCount - 1;
items = Cart.GetItems(CurrentUser, page * Constants.BuyStuffPageSize, Constants.BuyStuffPageSize);
}
return PartialView("Cart/CartItemsList", CreateBuyStuffViewData(Cart.GetItemsCost(CurrentUser), items, page));
}
/// <summary>
/// Gets bought items list view (control)
/// </summary>
/// <returns>bought items partial view</returns>
[ProjectAuthorize]
public ActionResult GetBoughtItemsView()
{
return PartialView("Cart/BoughtItemsList", CreateBoughtStuffListModel());
}
/// <summary>
/// Downloads chitchat or application (add to cart and redirect to BuyStuff)
/// </summary>
/// <param name="id">chitchat or application id</param>
/// <param name="isApplication">true if item is application</param>
/// <returns>redirect to page with user's cart</returns>
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult DownloadItem(int id, bool isApplication)
{
try
{
Cart.AddItem(CurrentUser, id, !isApplication);
return Json(new { isSuccessful = true });
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json( new { isSuccessful = false, message = "InvalidOperation" });
}
}
/// <summary>
/// Adds content items to user's cart
/// </summary>
/// <param name="id">chitchat or application id</param>
/// <param name="isApplication">true if item is application</param>
/// <returns>json data</returns>
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult AddItemToCart(int id, bool isApplication)
{
try
{
Cart.AddItem(this.CurrentUser, id, !isApplication);
return Json(new { isSuccessful = true, totalCount = Cart.GetItemsCount(this.CurrentUser) });
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json(new { isSuccessful = false, message = "InvalidOperation" });
}
}
/// <summary>
/// Removes content items from user's cart
/// </summary>
/// <param name="id">chitchat or application id</param>
/// <param name="isApplication">true if item is application</param>
/// <returns>json data</returns>
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult DeleteItemFromCart(int id, bool isApplication)
{
try
{
if (isApplication)
Cart.DeleteApplication(this.CurrentUser, id);
else
Cart.DeleteChitchat(this.CurrentUser, id);
return Json(new { isSuccessful = true, totalCount = Cart.GetItemsCount(this.CurrentUser) });
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json(new { isSuccessful = false, message = "InvalidOperation" });
}
}
/// <summary>
/// Deletes item (chitchat or application) from cart
/// </summary>
/// <param name="id">cart item id</param>
/// <param name="page">current page number</param>
/// <returns>List of cart items view + total items count</returns>
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult DeleteCartItem(int id, int page)
{
try
{
Cart.DeleteItem(CurrentUser, id);
return Json(new { isSuccessful = true, cartItemsView = ((PartialViewResult)GetCartItemsView(page)).GenerateMarkup(ControllerContext), totalCount = Cart.GetItemsCount(this.CurrentUser) }, "text/html");
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json(new { isSuccessful = false, message = "InvalidOperation" });
}
}
/// <summary>
/// Clears all the items from the cart
/// </summary>
/// <param name="page">current page number</param>
/// <returns>List of cart items view</returns>
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult ClearCart(int page)
{
try
{
Cart.Clear(CurrentUser);
return Json(new { isSuccessful = true, cartItemsView = ((PartialViewResult)GetCartItemsView(page)).GenerateMarkup(ControllerContext), totalCount = Cart.GetItemsCount(this.CurrentUser) }, "text/html");
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json(new { isSuccessful = false, message = "InvalidOperation" });
}
}
/// <summary>
/// Buys all the items from the cart
/// </summary>
/// <returns>List of bought items</returns>
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult BuyItems()
{
JsonViewData viewData;
try
{
BuyStuffTransactionResult res = creditsManager.BuyStuff(CurrentUser, Cart);
if (res == BuyStuffTransactionResult.Ok)
viewData = new JsonViewData { isSuccessful = true, message = res.ToString() };
else
viewData = new JsonViewData { isSuccessful = false, message = res.ToString() };
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
viewData = new JsonViewData { isSuccessful = false, message = e.Message };
}
return Json(viewData);
}
/// <summary>
/// Gets number of items in the user's cart
/// </summary>
/// <returns>json data</returns>
public ActionResult GetItemsCount()
{
return Json(new { isSuccessful = true, totalCount = Cart.GetItemsCount(this.CurrentUser) });
}
#endregion
#region Private Methods
/// <summary>
/// Creates Buy Stuff page viewdata
/// </summary>
/// <param name="totalCost">cost of all items in cart</param>
/// <param name="selectedItems">paged list of items in cart</param>
/// <param name="currentPage">current pager page</param>
/// <returns>Buy stuff viewdata instance</returns>
protected BuyStuffViewData CreateBuyStuffViewData(int totalCost, PagedResult<ICartItem<int>> selectedItems, int currentPage)
{
var data = CreateViewData<BuyStuffViewData>(ProjectWebPage.BuyStuff);
data.MyCredits = this.Auth.IsAuthenticated ? this.CurrentUser.TotalCredits : 0;
data.TotalCost = totalCost;
data.SelectedStuff = CreateCartItemsModel(selectedItems);
data.ListTotalPages = GetPagesCount(selectedItems.Total, Constants.BuyStuffPageSize);
data.ListCurrentPage = currentPage;
data.User = CurrentUser;
data.PaymentCompleteModel = BuyCreditsHelper.CreateModel(this.CurrentUser, this.Request,
ProjectWebPage.BuyStuff);
return data;
}
/// <summary>
/// Creates Bought stuff list model
/// </summary>
/// <returns>Bought stuff list model</returns>
protected BoughtStuffListModel CreateBoughtStuffListModel()
{
return new BoughtStuffListModel()
{
BoughtItems = Cart.RecentlyDownloadedItems,
BoughtApplications = Cart.RecentlyDownloadedApplications.Select(app => new ApplicationModel
{
Application = app,
CategoryPath = referenceBookManager.GetAppCategoriesImagePath(u => Url.Content(u), app.AppCategoryImpl),
})
.ToList()
};
}
/// <summary>
/// Creates cart items model
/// </summary>
/// <param name="items">paged list of items in cart</param>
/// <returns></returns>
protected PagedResult<CartItemModel> CreateCartItemsModel(PagedResult<ICartItem<int>> items)
{
return new PagedResult<CartItemModel>(
items.Total,
items.Result.Select(i => i.IsApplication
? new CartItemModel(i.CartItemId, new ApplicationModel
{ Application = i.Application,
CategoryPath = referenceBookManager.GetAppCategoriesImagePath(u => Url.Content(u), i.Application.AppCategoryImpl),
}, i.IsAlreadyPurchased)
: new CartItemModel(i.CartItemId, new itemModel { item = i.item }, i.IsAlreadyPurchased)).ToArray());
}
#endregion
}
}
StoresController.cs (Download entire file)
using System.Linq;
using System.Web.Mvc;
using Organization.Project.Common.Dal.Objects;
using Organization.Project.Common.Enums.Bll;
using Organization.Project.Common.Enums.UI;
using Organization.Project.Common.Authentication;
using Organization.Project.Common.Bll;
using Organization.Project.Common.Configuration;
using Organization.Project.Web.Helpers;
using Organization.Project.Web.Models.Popups;
using Organization.Project.Web.Models.Stores;
using Organization.Project.Web.ViewData;
using Organization.Project.Web.Extensions;
using System.Collections.Generic;
namespace Organization.Project.Web.Controllers
{
/// <summary>
/// Controller for stores-related operations
/// </summary>
public class StoresController : BaseController
{
#region User Defined Variables
private readonly IStoresManager storesManager;
private readonly IReferenceBookManager referenceBookManager;
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="auth">authentication instance</param>
/// <param name="authManager">account manager instance</param>
/// <param name="cart">cart instance</param>
/// <param name="config">Project configuration instance</param>
/// <param name="referenceBookManager">reference books instance</param>
/// <param name="storesManager">stores manager instance</param>
public StoresController(IAuthentication auth, IAccountManager authManager, IProjectCart cart, IProjectConfiguration config, IReferenceBookManager referenceBookManager, IStoresManager storesManager)
: base(auth, authManager, cart, config)
{
this.storesManager = storesManager;
this.referenceBookManager = referenceBookManager;
}
#endregion
#region Public Methods
/// <summary>
/// Shows view for searching of stores
/// </summary>
/// <returns>view for stores search</returns>
[ForceNoCache]
public ActionResult Index()
{
var viewData = CreateViewData<StoresViewData>(ProjectWebPage.Where2Buy);
var countries = referenceBookManager.GetAllCountries().ToArray();
ICountry firstCountry = countries.FirstOrDefault();
viewData.StoresModel = new StoresModel
{
Countries = countries.Select(c => new KeyValuePair<object, string>(c.Id, c.Name)),
CountriesCodes = countries.Select(c => new KeyValuePair<object, string>(c.Id, c.Abbreviation)),
CountriesStatesModel = CreateCountriesStatesModel(),
DefaultCountryId = firstCountry != null ? (int?)firstCountry.Id : null,
Config = viewData.Config
};
return View(viewData);
}
/// <summary>
/// Shows view with list of found stores
/// </summary>
/// <param name="countryId">country id</param>
/// <param name="zip">zip code</param>
/// <param name="stateId">state id</param>
/// <param name="searchProduct">search product type</param>
/// <returns>view with list of found stores</returns>
public ActionResult GetSearchResults(int countryId, string zip, int? stateId, StoresSearchProductType searchProduct)
{
return PartialView("StoresList", storesManager.GetStores(countryId, stateId, zip, searchProduct));
}
/// <summary>
/// Gets external part of map dialog view
/// </summary>
/// <returns>map dialog view frame</returns>
public ActionResult GetMapExtView()
{
var model = new GeneralPopupModel("", null)
{
IconFile = "icoStoreMap.gif",
TitleText = "<h2 style=\"display:inline;\"><img height=\"31\" width=\"187\" src=\"" + Url.Image("hStoreMap.gif") + "\" style=\"float:left\" /><span class=\"SelectedStoreName\" /></h2>",
InHeight = 230,
InWidth = 721
};
return View("PopupsExt/GeneralPopup", model);
}
#endregion
#region Private Methods
private IEnumerable<CountryStatesModel> CreateCountriesStatesModel()
{
return from state in referenceBookManager.GetAllCountriesStates()
group state by state.CountryId
into grouping
select
new CountryStatesModel
{
CountryId = grouping.Key,
CountryStates =
grouping.OrderBy(g => g.Ordinal).Select(
g => new KeyValuePair<object, string>(g.Id, g.LongName))
};
}
#endregion
}
}
StoresManager.cs (Download entire file)
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Organization.Project.Common.Bll;
using Organization.Project.Common.Bll.Geocode;
using Organization.Project.Common.Bll.Geocode.Providers;
using Organization.Project.Common.Dal.Objects;
using Organization.Project.Common.Dal;
using Organization.Project.Common.Enums.Bll;
using Organization.Project.Bll.Managers.Extensions;
namespace Organization.Project.Bll.Managers
{
/// <summary>
/// Handles store management activities
/// </summary>
public class StoresManager : IStoresManager
{
#region User Defined Variables
private readonly IRepository<IStore> storesRepository;
private readonly IRepository<ICountryState> countryStateRepository;
private readonly IGeocodeProvider geocodeProvider;
private readonly IRepository<ICountry> countryRepository;
private readonly IErrorLogManager errorLog;
#endregion
#region Constructors
/// <summary>
/// Contstructor
/// </summary>
/// <param name="repositoriesFactory">factory for resolving different repositories</param>
/// <param name="geocodeProvider">geocode provider for indirect search</param>
/// <param name="errorLogManager">error log manager</param>
public StoresManager(IRepositoriesFactory repositoriesFactory, IGeocodeProvider geocodeProvider, IErrorLogManager errorLogManager)
{
this.storesRepository = repositoriesFactory.GetStoresRepository();
this.countryRepository = repositoriesFactory.GetCountriesRepository();
this.countryStateRepository = repositoriesFactory.GetCountriesStatesRepository();
this.geocodeProvider = geocodeProvider;
this.errorLog = errorLogManager;
}
#endregion
#region Public Methods
/// <summary>
/// Gets list of stores
/// </summary>
/// <param name="countryId">country id</param>
/// <param name="stateId">country state id</param>
/// <param name="zip">country zip code</param>
/// <param name="searchType">search type</param>
/// <returns>list of stores</returns>
public IEnumerable<IStore> GetStores(int countryId, int? stateId, string zip, StoresSearchProductType searchType)
{
IEnumerable<IStore> result;
IEnumerable<string> states = GetStateNames(stateId);
IEnumerable<IStore> offlineStores = GetOfflineStores(countryId, states, zip, null, searchType);
if (string.IsNullOrEmpty(zip))
{
//search without zip
IEnumerable<IStore> onlineStores = GetOnlineStores(countryId, searchType);
result = StoresManagerExtensions.GetMergedStores(offlineStores, onlineStores);
}
else
{
//search with zip
IEnumerable<int> excludeId = offlineStores.Select(s => s.Id).ToArray();
IEnumerable<IStore> indirectStores = GetGeocodeIndirectStores(countryId, states, zip, searchType, excludeId);
//if there are no direct and indirect results => remove zip term
if (offlineStores.Count() == 0 && indirectStores.Count() == 0)
{
result = GetStores(countryId, stateId, null, searchType);
}
else
{
//merge direct, online, indirect results
IEnumerable<IStore> onlineStores = GetOnlineStores(countryId, searchType);
result = offlineStores.Union(StoresManagerExtensions.GetMergedStores(indirectStores, onlineStores));
}
}
return result;
}
#endregion
#region Private Methods
/// <summary>
/// Gets list of online stores
/// </summary>
/// <param name="countryId">country id</param>
/// <param name="searchType">search type</param>
/// <returns>list of online stores</returns>
private IQueryable<IStore> GetOnlineStores(int countryId, StoresSearchProductType searchType)
{
return storesRepository.GetAll()
.Where(s => s.CountryId == countryId && s.IsOnline)
.ApplySearchTypeFilter(searchType)
.OrderByDescending(s => s.Weight);
}
/// <summary>
/// Gets list of offline stores
/// </summary>
/// <param name="countryId">country id</param>
/// <param name="states">country state id</param>
/// <param name="zip">country zip code</param>
/// <param name="cities">list of cities</param>
/// <param name="searchType">search type</param>
/// <returns>list of offline stores</returns>
private IQueryable<IStore> GetOfflineStores(int countryId, IEnumerable<string> states, string zip, IEnumerable<string> cities, StoresSearchProductType searchType)
{
return storesRepository.GetAll()
.Where(s => s.CountryId == countryId && !s.IsOnline)
.ApplyZipFilter(zip)
.ApplyCityFilter(cities)
.ApplyStatesFilter(states)
.ApplySearchTypeFilter(searchType)
.OrderByDescending(s => s.Weight);
}
private IEnumerable<IStore> GetGeocodeIndirectStores(int countryId, IEnumerable<string> states, string zip, StoresSearchProductType searchType, IEnumerable<int> excludeId)
{
ICountry country = countryRepository.GetAll().SingleOrDefault(c => c.Id == countryId);
if (country == null) return null;
IGeocodeSearchResult result = geocodeProvider.GetSearchResult(country.Abbreviation, country.Name, zip);
if (result.Status == GeocodeSearchStatus.Success)
{
//filter by country
IEnumerable<IGeocodeSearchItem> resultItems = result.SearchItems.Where(si => si.CountryCode.ToLower() == country.Abbreviation.ToLower());
//if states exists apply state filter
IEnumerable<string> indirectStates = (states != null) ? resultItems.Select(si => si.AdministrativeArea).ToArray() : null;
IEnumerable<string> indirectCities = resultItems.Select(si => si.Locality).ToArray();
//if after filter by country we have empty list -> return empty list
return (indirectCities.Count() == 0)
? new IStore[0]
: (IEnumerable<IStore>)GetOfflineStores(countryId,
indirectStates,
null,
indirectCities,
searchType)
.ApplyExcludeIdFilter(excludeId);
}
else
{
errorLog.LogMessage(string.Format("Geocode search error: {0} - {1}", result.Status, result.StatusCode));
return new IStore[0];
}
}
/// <summary>
/// Gets short and long names of state as enumerable sequence
/// </summary>
/// <param name="stateId">country state id</param>
/// <returns>enumerable sequence of state names</returns>
private IEnumerable<string> GetStateNames(int? stateId)
{
if (stateId == null) return null;
ICountryState state = countryStateRepository.GetAll().Where(s => s.Id == stateId).SingleOrDefault();
if (state == null) return null;
return Enumerable.Repeat(state.ShortName.ToLower(), 1).Concat(Enumerable.Repeat(state.LongName.ToLower(), 1));
}
#endregion
}
}
GoogleMapsGeocodeParser.cs (Download entire file)
using System;
using System.Linq;
using Organization.Project.Common.Bll.Geocode;
using System.Web.Script.Serialization;
namespace Organization.Project.Bll.Geocode.Providers
{
/// <summary>
/// Parser of google geocode result (json)
/// </summary>
internal class GoogleMapsGeocodeParser
{
#region Public Methods
/// <summary>
/// Extract geocode search item entities from google maps json result
/// </summary>
/// <param name="inputJson">input json result</param>
/// <returns>list of geocode search items</returns>
public IGeocodeSearchResult ExtractGeocodeSearchItems(string inputJson)
{
GeocodeSearchResult result = new GeocodeSearchResult();
try
{
GoogleGeocodeResult items = new JavaScriptSerializer().Deserialize<GoogleGeocodeResult>(inputJson);
result.Status = this.ConvertStatusCode(items.Status.Code.ToString());
result.StatusCode = items.Status.Code.ToString();
if (result.Status == GeocodeSearchStatus.Success)
{
result.SearchItems = items.Placemark
.Where(i => i.AddressDetails != null)
.Select(i => (IGeocodeSearchItem) new GeocodeSearchItem
{
Country = this.GetCountryName(i.AddressDetails),
CountryCode = this.GetCountryNameCode(i.AddressDetails),
AdministrativeArea = this.GetAdministrativeAreaName(i.AddressDetails),
SubAdministrativeArea = this.GetSubAdministrativeAreaName(i.AddressDetails),
Locality = this.GetLocalityName(i.AddressDetails),
Thoroughfare = this.GetThoroughfareName(i.AddressDetails),
PostalCode = this.GetPostalCode(i.AddressDetails),
Coordinates = new GeocodeCoordinates
{
Latitude = i.Point.Coordinates[0],
Longitude = i.Point.Coordinates[1],
Unbounded = i.Point.Coordinates[2] == 1 ? true : false
}
});
}
else
{
result.SearchItems = new GeocodeSearchItem[0];
}
return result;
}
catch (Exception e)
{
result.Status = GeocodeSearchStatus.InternalError;
result.StatusCode = e.Message;
result.SearchItems = new GeocodeSearchItem[0];
return result;
}
}
#endregion
#region Private Methods
/// <summary>
/// Converts google result code to result status
/// </summary>
/// <param name="statusCode">google status code</param>
/// <returns>result status</returns>
private GeocodeSearchStatus ConvertStatusCode(string statusCode)
{
switch (statusCode)
{
case "200":
return GeocodeSearchStatus.Success;
case "602":
case "603":
return GeocodeSearchStatus.NotFound;
case "500":
return GeocodeSearchStatus.ServerError;
case "610":
case "620":
return GeocodeSearchStatus.ServiceForbidden;
case "601":
return GeocodeSearchStatus.InternalError;
default:
return GeocodeSearchStatus.UnknownError;
}
}
/// <summary>
/// Extracts country name
/// </summary>
/// <param name="address">address entity</param>
/// <returns>country name</returns>
private string GetCountryName(GoogleGeocodeAddressDetails address)
{
return (address.Country != null)
? address.Country.CountryName
: String.Empty;
}
/// <summary>
/// Extracts country abbreviation
/// </summary>
/// <param name="address">address entity</param>
/// <returns>country abbreviation</returns>
private string GetCountryNameCode(GoogleGeocodeAddressDetails address)
{
return (address.Country != null)
? address.Country.CountryNameCode
: String.Empty;
}
/// <summary>
/// Extracts administrative area name
/// </summary>
/// <param name="address">address entity</param>
/// <returns>administrative area name</returns>
private string GetAdministrativeAreaName(GoogleGeocodeAddressDetails address)
{
return (address.Country != null && address.Country.AdministrativeArea != null)
? address.Country.AdministrativeArea.AdministrativeAreaName
: String.Empty;
}
/// <summary>
/// Extracts subadministrative area name
/// </summary>
/// <param name="address">address entity</param>
/// <returns>subadministrative area name</returns>
private string GetSubAdministrativeAreaName(GoogleGeocodeAddressDetails address)
{
return (address.Country != null && address.Country.AdministrativeArea != null
&& address.Country.AdministrativeArea.SubAdministrativeArea != null)
? address.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName
: String.Empty;
}
/// <summary>
/// Extracts locality entity
/// </summary>
/// <param name="address">address entity</param>
/// <returns>locality entity</returns>
private GoogleGeocodeLocality GetLocality(GoogleGeocodeAddressDetails address)
{
GoogleGeocodeCountry country = address.Country;
GoogleGeocodeAdministrativeArea administrativeArea = country != null ? country.AdministrativeArea : null;
GoogleGeocodeSubAdministrativeArea subAdministrativeArea = administrativeArea != null ? administrativeArea.SubAdministrativeArea : null;
if (country != null && country.Locality != null)
{
return country.Locality;
}
else if (administrativeArea != null && administrativeArea.Locality != null)
{
return administrativeArea.Locality;
}
else if (subAdministrativeArea != null && subAdministrativeArea.Locality != null)
{
return subAdministrativeArea.Locality;
}
else
{
return null;
}
}
/// <summary>
/// Extracts locality name
/// </summary>
/// <param name="address">address entity</param>
/// <returns>locality entity name</returns>
private string GetLocalityName(GoogleGeocodeAddressDetails address)
{
GoogleGeocodeLocality locality = this.GetLocality(address);
return locality == null ? String.Empty : locality.LocalityName;
}
/// <summary>
/// Extracts thoroughfare entity
/// </summary>
/// <param name="address">address entity</param>
/// <returns>thoroughfare entity</returns>
private GoogleGeocodeThoroughfare GetThoroughfare(GoogleGeocodeAddressDetails address)
{
GoogleGeocodeCountry country = address.Country;
GoogleGeocodeAdministrativeArea administrativeArea = country != null ? country.AdministrativeArea : null;
GoogleGeocodeSubAdministrativeArea subAdministrativeArea = administrativeArea != null ? administrativeArea.SubAdministrativeArea : null;
GoogleGeocodeLocality locality = this.GetLocality(address);
if (country != null && country.Thoroughfare != null)
{
return country.Thoroughfare;
}
else if (administrativeArea != null && administrativeArea.Thoroughfare != null)
{
return administrativeArea.Thoroughfare;
}
else if (subAdministrativeArea != null && subAdministrativeArea.Thoroughfare != null)
{
return subAdministrativeArea.Thoroughfare;
}
else if (locality != null && locality.Thoroughfare != null)
{
return locality.Thoroughfare;
}
else
{
return null;
}
}
/// <summary>
/// Extracts thoroughfare name
/// </summary>
/// <param name="address">address entity</param>
/// <returns>thoroughfare name</returns>
private string GetThoroughfareName(GoogleGeocodeAddressDetails address)
{
GoogleGeocodeThoroughfare thoroughfare = this.GetThoroughfare(address);
return thoroughfare == null ? String.Empty : thoroughfare.ThoroughfareName;
}
/// <summary>
/// Extracts postal code
/// </summary>
/// <param name="address">address entity</param>
/// <returns>postal code</returns>
private string GetPostalCode(GoogleGeocodeAddressDetails address)
{
GoogleGeocodeCountry country = address.Country;
GoogleGeocodeAdministrativeArea administrativeArea = country != null ? country.AdministrativeArea : null;
GoogleGeocodeSubAdministrativeArea subAdministrativeArea = administrativeArea != null ? administrativeArea.SubAdministrativeArea : null;
GoogleGeocodeLocality locality = this.GetLocality(address);
GoogleGeocodeThoroughfare thoroughfare = this.GetThoroughfare(address);
if (administrativeArea != null && administrativeArea.PostalCode != null)
{
return administrativeArea.PostalCode.PostalCodeNumber;
}
else if (subAdministrativeArea != null && subAdministrativeArea.PostalCode != null)
{
return subAdministrativeArea.PostalCode.PostalCodeNumber;
}
else if (locality != null && locality.PostalCode != null)
{
return locality.PostalCode.PostalCodeNumber;
}
else if (thoroughfare != null && thoroughfare.PostalCode != null)
{
return thoroughfare.PostalCode.PostalCodeNumber;
}
else
{
return String.Empty;
}
}
#endregion
#region Google Maps Geocode Result Memebers
/// <summary>
/// Class presents google geocode json result (it's necessary for parsing)
/// </summary>
private class GoogleGeocodeResult
{
public GoogleGeocodeStatus Status { get; set; }
public GoogleGeocodePlacemark[] Placemark { get; set; }
}
private class GoogleGeocodeStatus
{
public int Code { get; set; }
}
private class GoogleGeocodePlacemark
{
public GoogleGeocodeAddressDetails AddressDetails { get; set; }
public GoogleGeocodeCoordinates Point { get; set; }
}
private class GoogleGeocodeAddressDetails
{
public GoogleGeocodeCountry Country { get; set; }
}
private class GoogleGeocodeCountry
{
public string CountryName { get; set; }
public string CountryNameCode { get; set; }
public GoogleGeocodeAdministrativeArea AdministrativeArea { get; set; }
public GoogleGeocodeLocality Locality { get; set; }
public GoogleGeocodeThoroughfare Thoroughfare { get; set; }
}
private class GoogleGeocodeAdministrativeArea
{
public string AdministrativeAreaName { get; set; }
public GoogleGeocodeSubAdministrativeArea SubAdministrativeArea { get; set; }
public GoogleGeocodeLocality Locality { get; set; }
public GoogleGeocodeThoroughfare Thoroughfare { get; set; }
public GoogleGeocodePostalCode PostalCode { get; set; }
}
private class GoogleGeocodeSubAdministrativeArea
{
public string SubAdministrativeAreaName { get; set; }
public GoogleGeocodeLocality Locality { get; set; }
public GoogleGeocodeThoroughfare Thoroughfare { get; set; }
public GoogleGeocodePostalCode PostalCode { get; set; }
}
private class GoogleGeocodeLocality
{
public string LocalityName { get; set; }
public GoogleGeocodeThoroughfare Thoroughfare { get; set; }
public GoogleGeocodePostalCode PostalCode { get; set; }
}
private class GoogleGeocodeThoroughfare
{
public string ThoroughfareName { get; set; }
public GoogleGeocodePostalCode PostalCode { get; set; }
}
private class GoogleGeocodePostalCode
{
public string PostalCodeNumber { get; set; }
}
private class GoogleGeocodeCoordinates
{
public double[] Coordinates { get; set; }
}
#endregion
}
}