I'm a new in API
I have a c# windows application connected to entity framework now I want to change that I want to connect my app to Asp.net web API (restful) and this service connect with database through entity framework I add my entity framework code to class library and reference it to the service
here my controller code is it correct or need to edit somethings on it? and after this step I need to consume the service in my windows app and then host it right ?
public class BuyAndRechargeController : ApiController
{
public readonly BuyAndRechargeSystemModel _dataBaseEntities = new BuyAndRechargeSystemModel(new DatabaseConfiguration().GetAppConfiguration());
[HttpGet]
[ActionName("phoneNumberChecking")]
public bool CheckExistingPhoneNumber(string phoneNumberChecking)
{
return (_dataBaseEntities.Customers.Count(number => number.PhoneNumber == phoneNumberChecking) != 0);
}
[ActionName("GetCustomers")]
public List<Customer> GetCustomers()
{
List<Customer> customerList = new List<Customer>();
customerList = _dataBaseEntities.Customers.Select(customer => new Customer
{
CustomerName = customer.Name,
CustomerPhoneNumber = customer.PhoneNumber,
CustomerBirthdate = customer.BirthDate,
CustomerPackageName = customer.Packages.Name,
CustomerBalance = (decimal)customer.Balance
}).ToList();
return customerList;
}
[ActionName("GetCustomerInformation")]
public Customer GetCustomerInformation(string phoneNumber)
{
Customer customerInformation;
customerInformation = _dataBaseEntities.Customers
.Where(customer => customer.PhoneNumber.Equals(phoneNumber)).Select(customer => new Customer
{
CustomerName = customer.Name,
CustomerPhoneNumber = customer.PhoneNumber,
CustomerBirthdate = customer.BirthDate,
CustomerPackageName = customer.Packages.Name,
CustomerBalance = (decimal)customer.Balance
}).Single();
return customerInformation;
}
[HttpPut]
[ActionName("RechargeBalance")]
public string RechargeBalance(string phoneNumber, string amount)
{//FirstOrDefault --> single
Customers customer = _dataBaseEntities.Customers.Single(customerPhoneNumber =>
customerPhoneNumber.PhoneNumber.Equals(phoneNumber));
customer.Balance = customer.Balance + Convert.ToDecimal(amount);
IFormatProvider culture = System.Globalization.CultureInfo.CurrentCulture;
customer.ExpireDate = DateTime.ParseExact(DateTime.Now.AddMonths(1).ToString("dd-MM-yyyy"), "dd-MM-yyyy", culture);
_dataBaseEntities.SaveChanges();
return customer.Balance.ToString();
}
[ActionName("GetPackagesList")]
public List<string> GetPackagesList(string packageType)
{
List<string> packagesList = _dataBaseEntities.Packages.Where(package => package.Type.Equals(packageType))
.Select(package => package.Name).ToList();
return packagesList;
}
[ActionName("GetFilteredCustomers")]
public List<Customer> GetFilteredCustomers(string search)
{
List<Customer> customerList = new List<Customer>();
customerList =
_dataBaseEntities.Customers.Where(customer => customer.Name.Contains(search) || customer.PhoneNumber.Contains(search)).Select(customer => new Customer
{
CustomerName = customer.Name,
CustomerPhoneNumber = customer.PhoneNumber,
CustomerBirthdate = customer.BirthDate,
CustomerPackageName = customer.Packages.Name,
CustomerBalance = Convert.ToDecimal(customer.Balance)
}).ToList();
return customerList;
}
[ActionName("DeleteCustomers")]
public bool DeleteCustomers(string[] customerPhoneNumber)
{
bool isDeleted = true;
bool result = false;
List<Customers> deleteQuery = new List<Customers>();
foreach (string phoneNumber in customerPhoneNumber)
{
Customers customerRow = _dataBaseEntities.Customers.Single(customer => customer.PhoneNumber.Equals(phoneNumber));
deleteQuery.Add(customerRow);
if (customerRow != null)
{
isDeleted = true && isDeleted;
}
else
{
isDeleted = false && isDeleted;
break;
}
}
foreach (Customers delete in deleteQuery)
{
if (isDeleted)
{
_dataBaseEntities.Customers.Remove(delete);
_dataBaseEntities.SaveChanges();
result = true;
}
else
{
result = false;
}
}
return result;
}
[HttpPost]
[ActionName("AddPackage")]
public bool AddPackage(string packageType, string packageName, string packagePrice)
{
bool isAdded = false;
try
{
Packages package = new Packages();
package.Name = packageName;
package.Type = packageType;
package.price = Int32.Parse(packagePrice);
_dataBaseEntities.Packages.Add(package);
_dataBaseEntities.SaveChanges();
isAdded = true;
}
catch
{
isAdded = false;
}
return isAdded;
}
[HttpGet]
[ActionName("CheckIfNoCustomers")]
public bool CheckIfNoCustomers()
{
bool isNoCustomer = false;
int countOfCustomers = _dataBaseEntities.Customers.Count();
if (countOfCustomers == 0)
{
isNoCustomer = true;
}
else
{
isNoCustomer = false;
}
return isNoCustomer;
}
[HttpPost]
[ActionName("AddCustomer")]
public bool AddCustomer(string packageName, string phoneNumber, string customerName, string customerBirthDate)
{
bool result = false;
try
{
Customers customer = new Customers();
int packageId = _dataBaseEntities.Packages.Where(package => package.Name.Equals(packageName))
.Select(package => package.ID).Single();
int packagePrice = _dataBaseEntities.Packages.Where(package => package.Name.Equals(packageName))
.Select(package => package.price).Single();
string expireDateADateTime = DateTime.Now.AddMonths(3).ToString("yyyy-MM-dd HH:mm:ss");
DateTime expireDate = DateTime.ParseExact(expireDateADateTime, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture);
customer.Name = customerName;
customer.PhoneNumber = phoneNumber;
customer.BirthDate = customerBirthDate;
customer.PackageID = packageId;
customer.ExpireDate = expireDate;
customer.Balance = packagePrice;
_dataBaseEntities.Customers.Add(customer);
_dataBaseEntities.SaveChanges();
result = true;
}
catch (DbEntityValidationException e)
{
e.EntityValidationErrors.SelectMany(error => error.ValidationErrors).ToList().ForEach(
item => Console.WriteLine("{0} - {1}", item.PropertyName, item.ErrorMessage));
result = false;
WriteToLogFile.WriteToLogErrorFile(e);
}
catch (Exception ex)
{
result = false;
WriteToLogFile.WriteToLogErrorFile(ex);
}
return result;
}
[ActionName("GetPackageTypeFromName")]
public string GetPackageTypeFromName(string packageName)
{
string packageType = _dataBaseEntities.Packages.Where(package => package.Name.Equals(packageName))
.Select(package => package.Type).Single();
return packageType;
}
[ActionName("GetExpireDate")]
public DateTime GetExpireDate(string phoneNumber)
{
DateTime? expireDate = _dataBaseEntities.Customers
.Where(customer => customer.PhoneNumber.Equals(phoneNumber)).Select(customer => customer.ExpireDate)
.Single();
return (DateTime)expireDate;
}
[HttpPut]
[ActionName("EditCustomer")]
public bool EditCustomer(string packageName, string editCustomerName, string editCustomerBirthDate, string phoneNumber)
{
bool isEdited = false;
Customers customer =
_dataBaseEntities.Customers.FirstOrDefault(customerPhone => customerPhone.PhoneNumber.Equals(phoneNumber));
if (customer != null)
{
int packageId = _dataBaseEntities.Packages.Where(package => package.Name.Equals(packageName))
.Select(package => package.ID).Single();
customer.Name = editCustomerName;
customer.BirthDate = editCustomerBirthDate;
customer.PackageID = packageId;
_dataBaseEntities.SaveChanges();
isEdited = true;
}
else
{
isEdited = false;
}
return isEdited;
}
[HttpGet]
[ActionName("CheckExistingPackages")]
public bool CheckExistingPackages(string packageName)
{
bool existPackage = false;
int packages = _dataBaseEntities.Packages.Where(package => package.Name == packageName)
.Select(package => packageName).Count();
if (packages != 0)
{
existPackage = true;
}
return existPackage;
}
}
Related
I have Student and Backpack entities:
internal class Student
{
public Guid Guid { get; set; }
public string Name { get; set; }
ICollection<Backpack> backpacks;
public virtual ICollection<Backpack> Backpacks
{
get
{
if (backpacks == null && LazyLoader != null)
{
backpacks = LazyLoader.Load(this, ref backpacks);
}
return backpacks;
}
set
{
backpacks = value;
}
}
ILazyLoader LazyLoader;
public Student(ILazyLoader lazyLoader)
{
LazyLoader = lazyLoader;
}
public Student()
{
}
}
internal class Backpack
{
public Backpack()
{
}
ILazyLoader LazyLoader;
public Backpack(ILazyLoader lazyLoader)
{
LazyLoader = lazyLoader;
}
public Guid Guid { get; set; }
public string Name { get; set; }
Student student;
public virtual Student Student
{
get
{
if (student == null && LazyLoader != null)
{
student = LazyLoader.Load(this, ref student);
}
return student;
}
set
{
student = value;
}
}
}
When an entity is changed and saved from one context and is used in another context, I want to update them. For example:
Scenario 1: when changing primitive properties and saved, I am updating the entry using reload:
var context1 = new MainContext();
var studentDilshodFromContext1 = context1.Set<Student>().First(s => s.Name == "Mike");
var context2 = new MainContext();
var studentMikeFromContext2 = context2.Set<Student>().First(s => s.Name == "Mike");
studentMikeFromContext1.Name = "Jake";
context1.SaveChanges();
context2.Entry(studentMikeFromContext2).Reload();
Console.WriteLine(studentMikeFromContext2.Name); //Nice! it is Jake after reloading
Scenario 2: now, I want to change the navigation property:
var context1 = new MainContext();
var jakeStudent = context1.Set<Student>().First(s => s.Name == "Jake");
var mikeBackpackFromContext1 = context1.Set<Backpack>().First(s => s.Name == "Mike's Backpack");
mikeBackpackFromContext1.Student = jakeStudent;
var context2 = new MainContext();
var mikeBackpackFromContext2 = context2.Set<Backpack>().First(s => s.Name == "Mike's Backpack");
context1.SaveChanges();
context2.Entry(mikeBackpackFromContext2).Reload();
Console.WriteLine(mikeBackpackFromContext2.Student.Name); //Object reference exception because Student is null. I am expecting Jake
Scenario 3: when the item was added to the navigation collection property, I would like to see it in context2:
var context1 = new MainContext();
var jakeStudentFromContext1 = context1.Set<Student>().First(s => s.Name == "Jake");
var newBackpack = new Backpack() { Student = jakeStudentFromContext1, Guid = Guid.NewGuid(), Name = "New Jake backpack" };
context1.Add(newBackpack);
var context2 = new MainContext();
var jakeStudentFromContext2 = context2.Set<Student>().First(s => s.Name == "Jake");
var backpacks = jakeStudentFromContext2.Backpacks;
context1.SaveChanges();
context2.Entry(jakeStudentFromContext2).Reload();
Console.WriteLine(jakeStudentFromContext2.Backpacks.Any(d => d.Guid == newBackpack.Guid)); //It is false but I am expecting true
As you can see entry.Reload() working fine only with primitive type properties, but not working with navigation properties. I tried NavigationEntry.Load and CollectionEntry.Load but they are not working as well.
So, in these scenarios how can I re-load my navigation properties?
Problem arises in this snippet, but i dont really know why(code is from a tutorial
https://www.youtube.com/watch?v=b0CrSerID1A&list=PLjCTEYO9N-j0wMr_p9j92lfgbY4E9c_Ds&index=16
PICTURE of problem
public string GetCartId(HttpContext context)
{
if (context.Session[CartSessionKey] == null)
{
if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
{
context.Session[CartSessionKey] =
context.User.Identity.Name;
}
else
{
Guid tempCartId = Guid.NewGuid();
context.Session[CartSessionKey] = tempCartId.ToString();
}
}
return context.Session[CartSessionKey].ToString();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Http;
namespace DogSupreme.Models
{
public class ShoppingCart
{
private ContextClass accsess = new ContextClass();
string ShoppingCartId { get; set; }
public const string CartSessionKey = "CartId";
public static ShoppingCart GetCart(HttpContext context)
{
var cart = new ShoppingCart();
cart.ShoppingCartId = cart.GetCartId(context);
return cart;
}
// Helper method to simplify shopping cart calls
public static ShoppingCart GetCart(Microsoft.AspNetCore.Mvc.Controller controller)
{
return GetCart(controller.HttpContext);
}
public void AddToCart(Product item)
{
var cartItem = accsess.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartId
&& c.ItemId == item.ProductId);
if (cartItem == null)
{
cartItem = new Cart
{
ItemId = item.ProductId,
CartId = ShoppingCartId,
Count = 1,
DateCreated = DateTime.Now
};
accsess.Carts.Add(cartItem);
}
else
{
cartItem.Count++;
}
accsess.SaveChanges();
}
public int RemoveFromCart(int id)
{
var cartItem = accsess.Carts.Single(
cart => cart.CartId == ShoppingCartId
&& cart.RecordId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Count > 1)
{
cartItem.Count--;
itemCount = cartItem.Count;
}
else
{
accsess.Carts.Remove(cartItem);
}
accsess.SaveChanges();
}
return itemCount;
}
public void EmptyCart()
{
var cartItems = accsess.Carts.Where(
cart => cart.CartId == ShoppingCartId);
foreach (var cartItem in cartItems)
{
accsess.Carts.Remove(cartItem);
}
accsess.SaveChanges();
}
public List<Cart> GetCartItems()
{
return accsess.Carts.Where(
cart => cart.CartId == ShoppingCartId).ToList();
}
public int GetCount()
{
int? count = (from cartItems in accsess.Carts
where cartItems.CartId == ShoppingCartId
select (int?)cartItems.Count).Sum();
return count ?? 0;
}
public decimal GetTotal()
{
decimal? total = (from cartItems in accsess.Carts
where cartItems.CartId == ShoppingCartId
select (int?)cartItems.Count *
cartItems.Product.Price).Sum();
return total ?? decimal.Zero;
}
public int CreateOrder(Order order)
{
decimal orderTotal = 0;
var cartItems = GetCartItems();
foreach (var item in cartItems)
{
var orderDetail = new OrderDetail
{
ItemId = item.ItemId,
OrderId = order.OrderId,
UnitPrice = item.Product.Price,
Quantity = item.Count
};
orderTotal += (item.Count * item.Product.Price);
accsess.OrderDetails.Add(orderDetail);
}
order.Total = orderTotal;
accsess.SaveChanges();
EmptyCart();
return order.OrderId;
}
public string GetCartId(HttpContext context)
{
if (context.Session[CartSessionKey] == null)
{
if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
{
context.Session[CartSessionKey] =
context.User.Identity.Name;
}
else
{
Guid tempCartId = Guid.NewGuid();
context.Session[CartSessionKey] = tempCartId.ToString();
}
}
return context.Session[CartSessionKey].ToString();
}
public void MigrateCart(string userName)
{
var shoppingCart = accsess.Carts.Where(
c => c.CartId == ShoppingCartId);
foreach (Cart item in shoppingCart)
{
item.CartId = userName;
}
accsess.SaveChanges();
}
}
}
You can use extension methods (Microsoft.AspNetCore.Http.Extensions) to get or set string session keys:
public string GetCartId(HttpContext context)
{
var session = context.Session;
if (!session.Keys.Contains(CartSessionKey))
{
var userName = context.User.Identity.Name;
if (!string.IsNullOrWhiteSpace(userName))
{
session.SetString(CartSessionKey, userName);
}
else
{
Guid tempCartId = Guid.NewGuid();
session.SetString(CartSessionKey, tempCartId.ToString())
}
}
return session.GetString(CartSessionKey);
}
Otherwise you should manually convert strings to and from byte array
Slightly refactored code to split cartId generation from working with session:
public string GetCartId(HttpContext context)
{
var cartId = context.Session.GetString(CartSessionKey);
if (cartId == null)
{
cartId = GetUserCartId(context.User.Identity.Name);
context.Session.SetString(CartSessionKey, cartId);
}
return cartId;
}
private void GetUserCartId(string userName)
{
if (!string.IsNullOrWhiteSpace(userName))
return userName;
var tempCartId = Guid.NewGuid();
return tempCartId.ToString();
}
I am using Pagedlist for Pagination in my MVC project. Pagination is working for most of the cases without ViewModels.
But when I use a ViewModel PagedList generating Pagination links but without any parameter value to querystring page.
Here is my ViewModel
public class SearchResult
{
public int ItemID { get; set; }
public string ItemTitle { get; set; }
public int? AuthorID { get; set; }
public string AuthorName { get; set; }
public int? IssueDate { get; set; }
}
And ActionResult Method
public ActionResult Date(int? page)
{
try
{
string query;
if (Request.RequestContext.RouteData.Values["query"] != null)
{
using (dreposEntities db = new dreposEntities())
{
query = Request.RequestContext.RouteData.Values["query"].ToString();
int issueYear = int.Parse(query);
ViewBag.Query = issueYear;
var dateFilter = db.itemstreams.Where(q => q.issuedate == issueYear).ToList();
List<SearchResult> resultList = new List<SearchResult>();
if (dateFilter.Any())
{
foreach (var c in dateFilter)
{
SearchResult obj = new SearchResult
{
ItemID = c.id,
ItemTitle = c.title,
IssueDate = c.issuedate,
};
resultList.Add(obj);
}
}
ViewBag.SearchQuery = query;
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
else
{
using (dreposEntities db = new dreposEntities())
{
List<SearchResult> resultList = new List<SearchResult>();
var files = db.itemstreams.Where(s=>s.status==1).ToList();
if (files.Any())
{
foreach (var f in files)
{
SearchResult obj = new SearchResult
{
ItemID = f.id,
ItemTitle = f.title,
IssueDate = f.issuedate,
};
resultList.Add(obj);
}
}
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
}
catch (Exception e)
{
return View();
}
}
What above code is showing in View is attached in below email
And in View/Razor
<div class="pull-right">
#Html.PagedListPager(Model, page => Url.Action("Date", new { page }), new PagedListRenderOptions() { Display = PagedListDisplayMode.IfNeeded })
</div>
I am getting value XX is not valid. But I am binding the correct datatype to the Model and I am still getting this error. Please find the error in . My controller is considering all datatype besides string to be not valid. Even the StartData and EndDate is throwing the same exception though I am binding the correct datatype.
I am not sure am I missing anything here. The worse part here is if I try to implement same (file) in another sample project it is working fine.
Following is my Model
public class Dept_User_Link
{
public Dept_User_Link()
{
StartDate = DateTime.Now;
EndDate = DateTime.Now;
}
private List<Dept_User_Link> deptUserLink = new List<Dept_User_Link>();
public int ID { get; set; }
[Required]
public int DeptID { get; set; }
[Required]
public int UserID { get; set; }
[Required]
public Guid Dummy { get; set; }
[Required]
public DateTime StartDate { get; set; }
[Required]
[DateRange(StartDateEditFieldName = "StartDate")]
public DateTime EndDate { get; set; }
}
and following is my controller
public ActionResult GridVwPartial()
{
var model = new Dept_User_Link().GetDeptUsersLink();
ViewData["Departments"] = new Department().GetDepartments().Select(x => new { DeptID = x.ID, Name = x.Name }).ToList();
ViewData["Users"] = new Users().GetUsers().Select(x => new { UserID = x.ID, Name = x.Name }).ToList();
ViewData["GuidVals"] = new GuidVal().GuidValData();
return PartialView("GridVwPartial", model);
}
public ActionResult AddNew(Dept_User_Link data) {
// Add 'data' values to the underlying datasource
// ...
var model = new Dept_User_Link().GetDeptUsersLink();
ViewData["Departments"] = new Department().GetDepartments().Select(x => new { DeptID = x.ID, Name = x.Name }).ToList();
ViewData["Users"] = new Users().GetUsers().Select(x => new { UserID = x.ID, Name = x.Name }).ToList();
return GridVwPartial();
}
and following is my View
#using ROCKtree.CCTVWeb.Models
#model IList<Dept_User_Link>
#{
Html.DevExpress().GridView<Dept_User_Link>(settings =>
{
settings.Name = "cascadingExample";
settings.CallbackRouteValues = new { Controller = "Grid", Action = "GridVwPartial" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Grid", Action = "AddNew" };
settings.CommandColumn.Visible = true;
settings.CommandColumn.ShowNewButtonInHeader = true;
settings.SettingsEditing.Mode = GridViewEditingMode.EditForm;
settings.KeyFieldName = "ID";
settings.Columns.Add(m => m.DeptID, column =>
{
column.EditorProperties().ComboBox(x =>
{
x.TextField = "Name";
x.ValueField = "DeptID";
x.DataSource = ViewData["Departments"];
x.ClientSideEvents.SelectedIndexChanged = "OnSelectedDeptChanges";
x.ValidationSettings.CausesValidation = true;
//x.ClientSideEvents.SelectedIndexChanged = "";
});
});
settings.Columns.Add(m => m.UserID, column =>
{
column.EditorProperties().ComboBox(x =>
{
x.TextField = "Name";
x.ValueField = "UserID";
//x.DataSource = ViewData["Users"];
x.LoadDropDownOnDemand = true;
x.CallbackRouteValues = new { Controller = "Grid", Action = "UserCallback" };
x.ClientSideEvents.BeginCallback = "UserComboBox_BeginCallback";
// x.ClientSideEvents.SelectedIndexChanged = "";
});
});
settings.Columns.Add(m => m.Dummy, column =>
{
column.EditorProperties().ComboBox(cmb =>
{
cmb.TextField = "Name";
cmb.ValueField = "ID";
cmb.DataSource = ViewData["GuidVals"];
});
});
settings.Columns.Add(m => m.StartDate, column =>
{
column.EditorProperties().DateEdit(clm =>
{
clm.TimeSectionProperties.Visible = true;
clm.DisplayFormatString = "dd-MMM-yy HH:mm";
clm.DisplayFormatInEditMode = true;
clm.TimeSectionProperties.TimeEditProperties.EditFormatString = "HH";
clm.TimeSectionProperties.TimeEditProperties.EditFormat = EditFormat.Custom;
clm.UseMaskBehavior = true;
clm.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithTooltip;
clm.ValidationSettings.Display = Display.Dynamic;
clm.ValidationSettings.CausesValidation = true;
clm.ValidationSettings.SetFocusOnError = true;
});
//column.SetEditItemTemplateContent(c =>
//{
// ViewContext.Writer.Write("<div class='form-group'><div class='input-group date' id='datetimepicker1'><input type='text' class=\"form-control\" /><span class=\"input-group-addon\">");
// ViewContext.Writer.Write("<span class=\"glyphicon glyphicon-calendar\"></span></span></div></div>");
//});
});
settings.Columns.Add(m => m.EndDate, column =>
{
column.EditorProperties().DateEdit(clm =>
{
clm.TimeSectionProperties.Visible = true;
clm.DisplayFormatString = "dd-MMM-yy HH:mm";
clm.DisplayFormatInEditMode = true;
clm.TimeSectionProperties.TimeEditProperties.EditFormatString = "HH";
clm.TimeSectionProperties.TimeEditProperties.EditFormat = EditFormat.Custom;
clm.UseMaskBehavior = true;
clm.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithTooltip;
clm.ValidationSettings.Display = Display.Dynamic;
clm.ValidationSettings.CausesValidation = true;
clm.ValidationSettings.SetFocusOnError = true;
});
//column.SetEditItemTemplateContent(c =>
//{
// ViewContext.Writer.Write("<div class='form-group'><div class='input-group date' id='datetimepicker1'><input type='text' class=\"form-control\" /><span class=\"input-group-addon\">");
// ViewContext.Writer.Write("<span class=\"glyphicon glyphicon-calendar\"></span></span></div></div>");
//});
});
}).Bind(Model).GetHtml();
}
Data for the Dummy Property
public IList<GuidVal> GuidValData()
{
if (guidVal == null || guidVal.Count() == 0)
{
//List<Department> deptList = new List<Department>();
List<string> deptValues = File.ReadLines(path).ToList();
foreach (string data in deptValues)
{
if (!string.IsNullOrEmpty(data))
{
string[] str = data.Split(separators, StringSplitOptions.None);
GuidVal deptLnk = new GuidVal();
deptLnk.ID = Guid.Parse(str[0]);
deptLnk.Name = str[1];
this.guidVal.Add(deptLnk);
}
}
}
return guidVal;
}
I have two lists: a list of countries and a list of jobs
public List<Countries> getSharedCountries(string brandName)
{
var items = SharedJobs.Where(a => a.BrandName == brandName);
var items2 = items.OrderBy(a => a.CountryCode);
Countries = new List<Countries>();
string Country = null;
foreach (var item in items2)
{
if (Country != item.CountryCode)
{
Country = item.CountryCode;
Countries.Add(new Countries() { CountryCode = item.CountryCode, JobIDs = getSharedJob(item.CountryCode) });
}
}
return Countries;
}
public void getSharedJob(string Country)
{
var items = SharedJobs.Where(a => a.CountryCode == Country);
JobNetDetails = new List<JobDetail>();
CareerBoardDetails = new List<JobDetail>();
JobSharkDetails = new List<JobDetail>();
JobServeDetails = new List<JobDetail>();
int AusCount = 0;
foreach (var item in items)
{
if (Country == "AUS")
{
AusCount++;
if (AusCount % 4 == 0)
{
JobNetDetails.Add(new JobDetail() { JobPageTitle = item.JobPageTitle, JobID = item.JobID, JobUrl = item.JobUrl });
}
else
{
JobServeDetails.Add(new JobDetail() { JobPageTitle = item.JobPageTitle, JobID = item.JobID, JobUrl = item.JobUrl });
}
}
}
}
On the line where I am accessing the method getSharedJob, it errors and gives me the error, cannot implicitly convert void to system.generic.List?
I am very confused as to why this is happening?
As the signature of your method states, public void getSharedJob(string Country) it's void, so it doesn't return anything, you should change it and return the list you wish.
Edit: As I read in the comments you need to return 4 Lists.
You have several options:
You can return an array of Lists;
You can return a List of Lists;
You can return your own class containing the 4 Lists.
Try below code which returns jobDetails from the method you are calling
public List<Countries> getSharedCountries(string brandName)
{
var items = SharedJobs.Where(a => a.BrandName == brandName);
var items2 = items.OrderBy(a => a.CountryCode);
Countries = new List<Countries>();
string Country = null;
foreach (var item in items2)
{
if (Country != item.CountryCode)
{
Country = item.CountryCode;
foreach (var jobDetail in getSharedJob(item.CountryCode))
{
Countries.Add(new Countries() { CountryCode = item.CountryCode, JobIDs = jobDetail.JobID });
}
}
}
return Countries;
}
public List<JobDetail> getSharedJob(string Country)
{
var items = SharedJobs.Where(a => a.CountryCode == Country);
JobNetDetails = new List<JobDetail>();
CareerBoardDetails = new List<JobDetail>();
JobSharkDetails = new List<JobDetail>();
JobServeDetails = new List<JobDetail>();
int AusCount = 0;
foreach (var item in items)
{
if (Country == "AUS")
{
AusCount++;
if (AusCount % 4 == 0)
{
JobNetDetails.Add(new JobDetail() { JobPageTitle = item.JobPageTitle, JobID = item.JobID, JobUrl = item.JobUrl });
}
else
{
JobServeDetails.Add(new JobDetail() { JobPageTitle = item.JobPageTitle, JobID = item.JobID, JobUrl = item.JobUrl });
}
}
}
return JobServeDetails;
}
Your method signature says take a string variable and return nothing (void).
public void getSharedJob(string country)
JobIDs is expecting a value
JobIDs = getSharedJob(item.CountryCode)
so you need to return a value which matches the JobIDs type which I assume is a List of ints or a List of JobDetails.