foreach statement error GetEnumerator - c#

I am attempting to build a blog based on a tutorial from VS 2010, and using VS 2013 I am getting errors. Any help would be appreciated. My Foreach statement will not execute.. I am getting an error stating Foreach statement cannot operate on variables of type 'blog.Models.Tag' because blog.Models.Tag does not contain a public definition for Get Enumerator...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using blog.Models;
using System.Text;
namespace blog.Controllers
{
public class PostsController : Controller
{
private BlogModel model = new BlogModel();
private const int PostsPerPage = 4;
public ActionResult Index(int? id)
{
int pageNumber = id ?? 0;
IEnumerable<Post> posts =
(from post in model.Posts
where post.DateTime < DateTime.Now
orderby post.DateTime descending
select post).Skip(pageNumber * PostsPerPage).Take(PostsPerPage + 1);
ViewBag.IsPreviousLinkVisible = pageNumber > 0;
ViewBag.IsNextLinkVisible = posts.Count() > PostsPerPage;
ViewBag.PageNumber = pageNumber;
ViewBag.IsAdmin = IsAdmin;
return View(posts.Take(PostsPerPage));
}
public ActionResult Details(int id)
{
Post post = GetPost(id);
ViewBag.IsAdmin = IsAdmin;
return View(post);
}
[ValidateInput(false)]
public ActionResult Comment(int id, string name, string email, string body)
{
Post post = GetPost(id);
Comment comment = new Comment();
comment.Post = post;
comment.Time = DateTime.Now;
comment.Name = name;
comment.Email = email;
comment.Body = body;
model.Comments.Add(comment);
model.SaveChanges();
return RedirectToAction("Details", new { id = id });
}
public ActionResult Tags(string id)
{
Tag Tag = (dynamic)GetTag(id);
ViewBag.IsAdmin = IsAdmin;
return View("Index", Tag.Posts);
}
[ValidateInput(false)]
public ActionResult Update(int? id, string title, string body, DateTime dateTime, string tags)
{
if(!IsAdmin)
{
return RedirectToAction("Index");
}
Post post = GetPost(id);
post.Title = title;
post.Body = body;
post.DateTime = dateTime;
post.Tags.Clear();
tags = tags ?? string.Empty;
string[] tagNames = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string tagName in tagNames)
{
post.Tags.Add(GetTag(tagName));
}
if(!id.HasValue)
{
model.Posts.Add(post);
}
model.SaveChanges();
return RedirectToAction("Details", new { id = post.Id });
}
public ActionResult Edit(int? id)
{
Post post = GetPost(id);
StringBuilder tagList = new StringBuilder();
foreach(Tag tag in post.Tags)
{
tagList.AppendFormat("{0} ", tag.Name);
}
ViewBag.Tags = tagList.ToString();
return View(post);
}
private object GetTag(string tagName)
{
return model.Tags.Where(x => x.Name == tagName).FirstOrDefault() ?? new Tag() {Name = tagName};
}
private Post GetPost(int? id)
{
return id.HasValue ? model.Posts.Where(x => x.Id == id).First() : new Post() { Id = -1 };
}
//TODO: Fix this later
public bool IsAdmin { get { return true; } }
}
}
Here is my Tag.cs
namespace blog.Models
{
using System;
using System.Collections.Generic;
public partial class Tag
{
public Tag()
{
this.Posts = new HashSet<Post>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Post> Posts { get; set; }
internal void Clear()
{
//throw new NotImplementedException();
}
internal void Add(object p)
{
//throw new NotImplementedException();
}
}
}
Here is my Posts.cs
namespace blog.Models
{
using System;
using System.Collections.Generic;
public partial class Post
{
public Post()
{
this.Comments = new HashSet<Comment>();
}
public int Id { get; set; }
public string Title { get; set; }
public System.DateTime DateTime { get; set; }
public string Body { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual Tag Tags { get; set; }
}
}

Foreach can only be done on a collection implementing the GetEnumerator, because it uses this function to get the "next" item to foreach on. Apparently this function is not present.

Related

How to loop API pages and compare values for changing markers on map using xamarin.forms.maps iOS C#

I want to check each page values from the API and against the values to change the color of the map marker.
This is my API: http://194.141.118.43:3001/?id=0 where id is from 0 to 16
I want:
if from ?id=0 AL = 1 the marker should be green
if from ?id=0 AL = 2 the marker should be yellow
if from ?id=0 AL = 3 the marker should be orange
if from ?id=0 AL = 4 the marker should be red
So I want to check for all 17 stations (from ?id=0 to ?id=16)
I am currently checking the property Alertlevelwebsite in this method with this API: http://194.141.118.43:3001/stations, But now I have to check all the values from this address for each pin and I have to put a color for the largest value for each pin.
http://194.141.118.43:3001/?id=0 (from 0 to 16)
I use this example from xamarin.forms.maps - https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithmaps/ and in CustomMapRenderer class I try to change the colors in this method:
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
//Get Value
c_annotation = annotation;
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
annotationView.CalloutOffset = new CGPoint(0, 0);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
((CustomMKAnnotationView)annotationView).Address = customPin.Address;
//Add First Line
((CustomMKAnnotationView)annotationView).AlertLevel = customPin.AlertLevel;
if (customPin.AlertLevel == 1)
{
annotationView.Image = UIImage.FromFile("green.png");
}
else if (customPin.AlertLevel == 2)
{
annotationView.Image = UIImage.FromFile("yellow.png");
}
else if (customPin.AlertLevel == 3)
{
annotationView.Image = UIImage.FromFile("orange.png");
}
else if (customPin.AlertLevel == 4)
{
annotationView.Image = UIImage.FromFile("red.png");
}
//Add Second Line
((CustomMKAnnotationView)annotationView).CodeNum = customPin.CodeNum;
((CustomMKAnnotationView)annotationView).MapCode = customPin.MapCode;
//Here I add the RequestUri for stations
string GenerateRequestUriStations(string endpoint)
{
string requestUri = endpoint;
requestUri += $"stations";
return requestUri;
}
//Here I need the loop from 0 to 16 every page and change the pin icons like above if statement
string GenerateRequestUri(string endpoint)
{
string requestUri = endpoint;
requestUri += $"?id=0";
return requestUri;
}
//This is the value who I need to compare result.WaterData.Ardaforecast but does not allow me to write result.WaterData.Ardaforecast and does not allow me to foreach here .. I don't know why ?
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
}
annotationView.CanShowCallout = true;
configureDetailView(annotationView);
return annotationView;
}
In the comments above the code I mean that when I write:
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var item in IAsyncResult)
{
}
When I try to write result. automatic puts me IAsyncResult.. I don't know why.. ?
Can I get an example of how to loop all the pages and change colors on the markers ?
My GetDataFromAPI look like this:
public IEnumerable<AlertLevel> GetDataFromAPI(int mapCode)
{
var listAlert = new List<AlertLevel>();
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint, mapCode));
foreach (var item in reusult.WaterData.Ardaforecast[0].Items)
{
var currentData = new AlertLevel()
{
dateForecast = item.DateTimeForecast,
levelForecast = item.AlertLevelForecast
};
listAlert.Add(currentData);
}
return listAlert;
}
My GetWaterDataForecast look like this:
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using MaritsaTundzhaForecast.Models;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Services
{
public class RestServiceData
{
HttpClient _client1;
HttpClient _client2;
public RestServiceData()
{
_client1 = new HttpClient();
_client2 = new HttpClient();
}
public WaterBindingData GetWaterDataForecast(string query, string query2)
{
WaterDataJson waterData = new WaterDataJson();
WaterStationsJson waterStations = new WaterStationsJson();
WaterBindingData result = new WaterBindingData();
try
{
var task = Task.Run(() => _client1.GetAsync(query));
task.Wait();
var response = task.Result;
var task2 = Task.Run(() => _client2.GetAsync(query2));
task2.Wait();
var response2 = task2.Result;
if (response.IsSuccessStatusCode && response2.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
var content2 = response2.Content.ReadAsStringAsync().Result;
var json = content2.Replace("\"ardaforecast\":[[", "\"ardaforecast\":[ {\"items\": [")
.Replace("}],{\"fieldCount\"", "}],\"details\":{\"fieldCount\"")
.Replace("}]}", "}}]}");
waterData = JsonConvert.DeserializeObject<WaterDataJson>(json);
waterStations = JsonConvert.DeserializeObject<WaterStationsJson>(content);
result.WaterData = waterData;
result.WaterStation = waterStations;
}
}
catch (Exception ex)
{
Debug.WriteLine("\t\tERROR {0}", ex.Message);
}
return result;
}
}
}
My WaterBindingData look like:
using System;
namespace MaritsaTundzhaForecast.Models
{
public class WaterBindingData
{
public WaterDataJson WaterData { get; set; }
public WaterStationsJson WaterStation { get; set; }
}
}
My WaterDataJson and WaterStations look like:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast
{
public class WaterDataJson
{
public List<ForecastBody> Ardaforecast { get; set; }
}
public class ForecastBody
{
public ForecastItem[] Items { get; set; }
public ForecastDetails Details { get; set; }
}
public class ForecastItem
{
[JsonProperty("Dt")]
public DateTime DateTimeForecast { get; set; }
[JsonProperty("AL")]
public int AlertLevelForecast { get; set; }
}
public class ForecastDetails
{
public int fieldCount { get; set; }
public int affectedRows { get; set; }
public int insertId { get; set; }
public int serverStatus { get; set; }
public int warningCount { get; set; }
public int changedRows { get; set; }
public string message { get; set; }
public bool protocol41 { get; set; }
}
}
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Models
{
public class WaterStationsJson
{
public List<ForecastStations> Stations { get; set; }
}
public class ForecastStations
{
[JsonProperty("Map_code")]
public int MapCode { get; set; }
[JsonProperty("NAME_IME")]
public string NameEN { get; set; }
[JsonProperty("NAME_CYR")]
public string NameBG { get; set; }
[JsonProperty("Alertlevelwebsite")]
public int AlertLevelStation { get; set; }
[JsonProperty("CODENUM")]
public int CodeNum { get; set; }
}
}

Get Newly Created DB ID to pass to Quote Method

EDIT: I have the Quote working on EDIT, but it's not working on Create. I've adjusted my method from my original post. So my issue is I cannot figure out to pass the ID of a newly created record to the quote method.
Student here!
Creating an MVC app and I cannot figure out I'm missing. I thought I had it working and then I moved on, but when I went back to test, I realized it wasn't working and am getting a bunch of errors. I know the reason is because the values I think I'm passing aren't actually being passed.
I have the two scenarios, Create and Edit and when the DB entry is created it should redirect to my quote method, but that is where I'm getting errors. I can't figure out how to pass the values that were just created to the quote method. Any suggestions as to what I'm missing would be appreciated!
This is my controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CarInsurance.Models;
using CarInsurance.View_Models;
namespace CarInsurance.Controllers
{
public class InsureeController : Controller
{
private InsuranceEntities db = new InsuranceEntities();
// GET: Insuree/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Insuree insuree = db.Insurees.Find(id);
if (insuree == null)
{
return HttpNotFound();
}
return View(insuree);
}
// GET: Insuree/Create
public ActionResult Create()
{
return View();
}
// POST: Insuree/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "FirstName,LastName,EmailAddress,DateOfBirth,CarYear,CarMake,CarModel,DUI,SpeedingTickets,CoverageType")] Insuree insuree)
{
if (ModelState.IsValid)
{
db.Insurees.Add(insuree);
db.SaveChanges();
}
return RedirectToAction("Quote", insuree);
}
// GET: Insuree/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Insuree insuree = db.Insurees.Find(id);
if (insuree == null)
{
return HttpNotFound();
}
return View(insuree);
}
// POST: Insuree/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,EmailAddress,DateOfBirth,CarYear,CarMake,CarModel,DUI,SpeedingTickets,CoverageType")] Insuree insuree)
{
if (ModelState.IsValid)
{
db.Entry(insuree).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Quote", insuree);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
// GET: Quote
public ActionResult Quote(int? id)
{
Insuree insuree = db.Insurees.Find(id);
Quote quote = new Quote();
quote.FirstName = insuree.FirstName;
quote.LastName = insuree.LastName;
quote.EmailAddress = insuree.EmailAddress;
quote.DateOfBirth = insuree.DateOfBirth;
quote.CarYear = insuree.CarYear;
quote.CarMake = insuree.CarMake;
quote.CarModel = insuree.CarModel.ToLower();
quote.DUI = Convert.ToBoolean(insuree.DUI);
quote.SpeedingTickets = insuree.SpeedingTickets;
quote.CoverageType = Convert.ToBoolean(insuree.CoverageType);
var age = DateTime.Now.Year - insuree.DateOfBirth.Year;
decimal totalQuote = 50;
// Age Constraints
if (age <= 18)
{
totalQuote += 100;
quote.quoteAge = 100;
}
if (age >= 19 && age <= 25)
{
totalQuote += 50;
quote.quoteAge = 50;
}
if (age > 25)
{
totalQuote += 25;
quote.quoteAge = 25;
}
// Car Constraints
if (quote.CarYear < 2000 || quote.CarYear > 2015)
{
totalQuote += 25;
quote.quoteCar = 25;
}
if (quote.CarMake == "porsche")
{
totalQuote += 25;
quote.quoteCar += 25;
}
if (quote.CarModel == "911 carrera")
{
totalQuote += 25;
quote.quoteCar += 25;
}
// Driving History Constraints
if (quote.SpeedingTickets > 0)
{
totalQuote += quote.SpeedingTickets * 10;
quote.quoteTickets = quote.SpeedingTickets * 10;
}
if (quote.DUI)
{
totalQuote *= Convert.ToDecimal(1.25);
quote.quoteDUI = totalQuote * Convert.ToDecimal(.25);
}
// Coverage Requested
if (quote.CoverageType)
{
totalQuote *= Convert.ToDecimal(1.50);
}
ViewBag.Quote = Math.Round(totalQuote, 2);
return View(quote);
}
}
}
And my quote class if needed:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CarInsurance.View_Models
{
public class Quote
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public DateTime DateOfBirth { get; set; }
public int CarYear { get; set; }
public string CarMake { get; set; }
public string CarModel { get; set; }
public bool DUI { get; set; }
public int SpeedingTickets { get; set; }
public bool CoverageType { get; set; }
public decimal quoteAge { get; set; }
public decimal quoteCar { get; set; }
public decimal quoteTickets { get; set; }
public decimal quoteDUI { get; set; }
}
}

How to check if duplicate data is present in the database using asp.net mvc

I want to show a message saying that the JourneyID already exists in the database.
The model is :
using System.Web.Mvc;
namespace Project_Final.Models
{
using System;
public partial class sp_FMS_Group6_Module3_ViewBonusMilesRequesttt_Result
{
public int RequestID { get; set; }
public Nullable<long> CustomerID { get; set; }
[Remote("Check", "Home", ErrorMessage = "Bonus Miles Request has already been sent!")]
public Nullable<int> JourneyID { get; set; }
public Nullable<System.DateTime> RequestDate { get; set; }
public string Status { get; set; }
}
}
The following are the actions in my controller :
[HttpPost]
public ActionResult Index(string Create)
{
FMS_Group6_Module3_BonusMilesRequestt objProd = new FMS_Group6_Module3_BonusMilesRequestt();
objProd.CustomerID = int.Parse(Request.Form["CustomerID"].ToString());
objProd.JourneyID = int.Parse(Request.Form["JourneyID"].ToString());
objProd.RequestDate = DateTime.Parse(Request.Form["RequestDate"].ToString());
objProd.Status = "Pending";
objDB.FMS_Group6_Module3_BonusMilesRequestt.Add(objProd);
int i = objDB.SaveChanges();
if (i > 0)
ViewBag.Message = "Product details saved successfully";
return Content("<script language='javascript' type='text/javascript'>alert('Your Bonus Miles Request has been successfully sent!');window.location='/Home/GetID'</script>");
//return Redirect("GetID");
}
public ActionResult Check(string Crreate)
{
FMS_Group6_Module3_BonusMilesRequestt objProd = new FMS_Group6_Module3_BonusMilesRequestt();
bool ifJourneyIDExist = false;
try
{
ifJourneyIDExist = Crreate.Equals(objProd.JourneyID) ? true : false;
return Json(!ifJourneyIDExist, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
Any kind of help would be greatly appreciated. Thanks.
Before you insert, you can check in the DB, if the JourneyID is exists.
if (objDB.FMS_Group6_Module3_BonusMilesRequestt.Any(x => x.JourneyID == objProd.JourneyID))
{
// Exists
}
LINQ query to make sure all values (ex enumerable) are not duplicated
var noDuplicationVariable = enumerableValues.GroupBy(a => a.Key).All(b => b.Count() == 1);
use it as an assertion condition before your function

mvc 4 access variables stored with session in model class after form submits

I stored some values into a model class using session variables and want to access them after the form submits. The values are stored in the ReportChooser Model and I would like to access the values in the View.
Report Controller
List<ReportEntryInfo> reiList = new List<ReportEntryInfo>();
foreach (string s in Request["ReportPeriodEntries"].ToString().Split(','))
{
string[] reportPeriodEntries = s.ToString().Split('_');
string reportPeriodID = reportPeriodEntries[0];
string entryID = reportPeriodEntries[1];
ReportEntryInfo rei = new ReportEntryInfo();
rei.EntryID = Convert.ToInt16(entryID);
rei.ReportPeriodID = Convert.ToInt16(reportPeriodID);
rei.ReportPeriodName = (from rp in db.ReportPeriods where rp.ReportPeriodID == rei.ReportPeriodID select rp.ReportPeriodName).FirstOrDefault();
reiList.Add(rei);
}
rc.ReportPeriodEntries = reiList;
List<ReportSchoolInfo> rsiList = new List<ReportSchoolInfo>();
foreach (string s in Request["Schools"].ToString().Split(','))
{
ReportSchoolInfo rsi = new ReportSchoolInfo();
rsi.SchoolID = Convert.ToInt16(s);
List<School> sList = db.Schools.Where(sc => sc.SchoolID == rsi.SchoolID && sc.IsActive == true).ToList();
foreach (School sl in sList)
{
rsi.SchoolName = sl.SchoolName;
rsi.SchoolLevelID = sl.SchoolLevelID;
rsi.DistID = sl.DistID;
rsi.DistName = sl.District.DistName;
}
rsiList.Add(rsi);
}
rc.Schools = rsiList;
rc.IndicatorID = indicatorID;
if (form["ComparisonSideBySide"] == "School")
rc.ComparisonSideBySide = ComparisonSideBySideValue.School;
else
rc.ComparisonSideBySide = ComparisonSideBySideValue.Entry;
rc.IncludeNarrative = Convert.ToBoolean(form["IncludeNarrative"]);
if (ModelState.IsValid)
{
if (indicatorID == 1)
{
if (rc.ComparisonSideBySide == ComparisonSideBySideValue.School)
return RedirectToAction("Leadership_sch");
else
return RedirectToAction("Leadership_entry");
}
else
{
ViewBag.ReportChooser = rc;
return View();
}
}
else
{
ViewBag.ReportChooser = rc;
return View();
}
View
#model IEnumerable<ImpactIndicator.Models.ReportDataModel>
#{
ViewBag.Title = "Report";
ImpactIndicator.Models.ReportChooser reportChooser = ViewBag.ReportChooser;
}
<hgroup class="title">
<h2>Report: Leadership</h2>
</hgroup>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
}
ReportChooser Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace ImpactIndicator.Models
{
public enum ComparisonSideBySideValue { School, Entry };
public class ReportChooser
{
public int IndicatorID
{
get
{
if (HttpContext.Current.Session["ReportChooser_IndicatorID"] != null)
return Convert.ToInt16(HttpContext.Current.Session["ReportChoose_IndicatorID"]);
else
return 0;
}
set
{
HttpContext.Current.Session["ReportChooser_IndicatorID"] = value;
}
}
public List<ReportSchoolInfo> Schools
{
get
{
if (HttpContext.Current.Session["ReportChooser_SchoolInfo"] != null)
{
List<ReportSchoolInfo> schools=(List<ReportSchoolInfo>)HttpContext.Current.Session["ReportChooser_SchoolInfo"];
schools.OrderBy(t=>t.DistName).ThenBy(t=>t.SchoolName);
return schools;
}
else
return null;
}
set
{
HttpContext.Current.Session["ReportChooser_SchoolInfo"] = value;
}
}
public int SchoolLevelID
{
get
{
if (HttpContext.Current.Session["ReportChooser_SchoolLevelID"] != null)
return Convert.ToInt16(HttpContext.Current.Session["ReportChoose_SchoolLevelID"]);
else
return 0;
}
set
{
HttpContext.Current.Session["ReportChooser_SchoolLevelID"] = value;
}
}
public List<ReportEntryInfo> ReportPeriodEntries
{
get
{
if (HttpContext.Current.Session["ReportChooser_ReportPeriodEntries"] != null)
return (List<ReportEntryInfo>)HttpContext.Current.Session["ReportChooser_ReportPeriodEntries"];
else
return null;
}
set
{
HttpContext.Current.Session["ReportChooser_ReportPeriodEntries"] = value;
}
}
public bool IncludeNarrative
{
get
{
if (HttpContext.Current.Session["ReportChooser_IncludeNarrative"] != null)
return Convert.ToBoolean(HttpContext.Current.Session["ReportChooser_IncludeNarrative"]);
else
return false;
}
set
{
HttpContext.Current.Session["ReportChooser_IncludeNarrative"] = value;
}
}
public ComparisonSideBySideValue ComparisonSideBySide
{
get
{
if (HttpContext.Current.Session["ReportChooser_ComparisonSideBySide"] != null)
return (ComparisonSideBySideValue)HttpContext.Current.Session["ReportChooser_ComparisonSideBySide"];
else
return ComparisonSideBySideValue.Entry;
}
set
{
HttpContext.Current.Session["ReportChooser_ComparisonSideBySide"] = value;
}
}
public ReportChooser()
{
}
}
}
ReportDataModel Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ImpactIndicator.Models
{
public class ReportDataModel
{
public int IndicatorID { get; set; }
public int ReportPeriodID { get; set; }
public int EntryID { get; set; }
public int SchoolID {get; set;}
public bool IsSchoolRequiredToReport { get; set; }
public int? SchoolEntryID { get; set; }
public int? IndDomainID {get; set;}
public int? IndLevelID {get; set;}
public int? IndQuestionID {get; set;}
public string Response { get; set; }
public ReportDataModel()
{
}
}
}
You can access to variables stored in session using this
var variable = (Cast the type of variable)HttpContext.Current.Session["the key"];

Serialization woes

I have an issue with serialization. I understand that methods can not be serialized for good reason, so I created a factory class to convert my existing class into a more manageable class.
This is the original class:
using Assets.Components;
using Assets.Data;
using IO.Components;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Assets
{
[Serializable]
public class Asset
{
#region Fields
Metadata _metadata;
string _fileName;
string _companyId;
#endregion
#region Properties
[Required]
public string DisplayName { get; set; }
public string Description { get; set; }
public string Tags { get; set; }
public int Id { get; set; }
public int CategoryId { get; set; }
public AssetType Type { get; set; }
public int LanguageId { get; set; }
public int StatusId { get; set; }
public DateTime DateCreated { get; set; }
public long DateCreatedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public int Views { get; set; }
public int Downloads { get; set; }
public string ThumbNail { get; set; }
public string Filename
{
set { _fileName = value; }
}
[Required]
public string CompanyId
{
set { _companyId = value; }
}
public string GetBaseDirectory
{
get { return "/Public/Uploads/" + this._companyId + "/0"; }
}
public double Rating
{
get
{
List<int> Score = new List<int>();
foreach (IRating oRating in this.Ratings())
{
Score.Add(oRating.Score);
}
return (Score.Count > 0) ? Score.Average() : 0;
}
}
public Metadata Metadata
{
get
{
if (_metadata == null)
{
_metadata = new Metadata(this.Id);
if (_metadata.AssetId == 0)
{
try
{
if (GetFilename() != null)
{
string path = System.IO.Path.Combine(HttpContext.Current.Server.MapPath(this.GetBaseDirectory), GetFilename());
if (!System.IO.File.Exists(path))
_metadata = new Metadata();
else
{
_metadata = MetadataExtractor.Create(path, this.Id);
_metadata.save();
}
}
else
{
_metadata = new Metadata();
}
}
catch
{
_metadata = new Metadata();
}
}
}
return _metadata;
}
}
public bool IsConverted { get; set; }
public string UserId { get; set; }
public DateTime DateModified { get; set; }
public long DateModifiedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public string Culture { get; set; }
public string Language { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public int CategoryCount { get; set; }
public int AssetCount { get; set; }
public bool IgnoreRights { get; set; }
#endregion
#region Contructors
/// <summary>
/// Default constructor
/// </summary>
public Asset()
{
}
/// <summary>
/// Get's the asset from the database, but set's the status to the profiles Requires Approval state.
/// </summary>
/// <param name="Id">Asset Id</param>
/// <param name="IsViewing">Boolean to update the reports table</param>
/// <param name="IsDownloading">Boolean to update the reports table</param>
public Asset(int Id, string UserId, string CompanyId, bool IsViewing, bool IsDownloading)
{
try
{
Asset oAsset = AssetData.GetAsset(Id, IsViewing, IsDownloading, UserId, CompanyId);
// Assign the values to this class
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.IsConverted = oAsset.IsConverted;
this.StatusId = oAsset.StatusId;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.UserName = oAsset.UserName;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
catch (Exception ex)
{
Stars.BLL.Error.Handling.LogError("Skipstone", "Asset", "Asset", ex.Message, ex.ToString()); // Record our error
}
}
/// <summary>
/// Used for executing some of the public methods
/// </summary>
/// <param name="Id">Id of the asset to retrieve</param>
/// <param name="CompanyId">The CompanyId of the company for the User</param>
public Asset(int Id, string CompanyId)
{
this.Id = Id;
this.CompanyId = CompanyId;
}
#endregion
#region Public methods
public string GetCompanyId()
{
return _companyId;
}
public string GetFilename()
{
return _fileName;
}
public string GetThumbnail()
{
return this.GetBaseDirectory + "/" + this.ThumbNail;
}
public string GetSmallThumbnail()
{
return this.GetBaseDirectory + "/sml_" + this.ThumbNail;
}
public Collection<IRating> Ratings()
{
Collection<IRating> oRatings = new Collection<IRating>();
try
{
oRatings = RatingData.get(this.Id);
}
catch
{
// record our error
}
return oRatings;
}
public Collection<IComment> Comments()
{
Collection<IComment> oComments = new Collection<IComment>();
try
{
oComments = CommentData.getAssetComments(this.Id);
}
catch (Exception ex)
{
// record our error
}
return oComments;
}
public void SaveMetadata()
{
}
public Collection<GenericType> Categories()
{
return MiscellaneousManager.AssetCategories(this.Id, GetCompanyId());
}
public void Save()
{
if (this.Id > 0)
{
AssetData.update(this);
}
else
{
Asset oAsset = AssetData.create(this);
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
}
public void delete()
{
AssetData.delete(this.Id);
AssetManager.RemoveFromCache(this);
}
#endregion
}
}
and this is my factory method:
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
which is part of my audittrailmanager class:
using Assets;
using Core;
using Reports.Objects;
using System;
using System.IO;
using System.Xml.Serialization;
namespace Reports.Components
{
public static class AuditTrailManager
{
#region Public methods
public static Audit AuditTrailFactory(Profile Profile, Object Object, Event Event)
{
Audit Audit = new Audit(SerializeObject(Object))
{
UserId = Profile.UserId,
UserName = Profile.UserName,
CompanyId = Profile.CompanyId,
ObjectName = GetObjectNameFromType(Object.GetType().ToString()),
Event = Event
};
return Audit;
}
#endregion
#region Private methods
private static string GetObjectNameFromType(string Type)
{
switch (Type)
{
case "Assets.Asset": return "Asset";
case "Core.SiteSetting": return "CompanySettings";
}
return "";
}
private static string SerializeObject(Object Object)
{
string ObjectType = Object.GetType().ToString();
switch (ObjectType)
{
case "Assets.Asset": return Serialize(AssetFactory((Asset)Object));
}
return ""; // If we fail
}
private static string Serialize(Object Object)
{
XmlSerializer ser = new XmlSerializer(Object.GetType());
using (StringWriter Xml = new StringWriter())
{
ser.Serialize(Xml, Object);
return (Xml.ToString());
}
}
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
#endregion
}
}
What I am trying to do is create an audit trail which records the object I am working on (in this case an asset) and I am serializing the class and inserting it into the database for use in reporting, etc.
My question is; is this the way to do it. Is there a better way?

Categories

Resources