File extension not being detected for file upload - asp.net

Ok I have the following extensions I am checking in my code.
FileAttachments.FileAttachmentTypes fileAttachmentType = FileAttachments.FileAttachmentTypes.None;
The strings below in the conts are helled in a constants file
public const string wordExtensions = "docx;docm;doc";
public const string imageExtensions = "gif;tiff;tif;png;eps;raw;bmp;jpeg;jpg";
public const string excelExtensions = "csv;xml;xls;xlsb;xlsm;xlsx";
Which is then parsed down here
I am getting my extension from the File Info class as such
foreach (var fileAttachments in FormFile) {
if (fileAttachments.Length > 0) {
string filePath = Path.Combine(hostingEnvironment.WebRootPath, "Uploads");
var tennantId = GetCurrentTennantId().Result;
var settings = _context.SystemSetup.FirstOrDefault().UploadFolderPath;
string uniqueFilename = Guid.NewGuid().ToString() + "_" + fileAttachments.FileName;
string savedFileName = Path.Combine(filePath, uniqueFilename);
FileInfo infoFile = new FileInfo(savedFileName);
string extension = infoFile.Extension.Replace(".","");
Here I check the file extension Parameter above in the semi colan separated strings
if (extension.Contains(Constants.imageExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Image;
} else if (extension.Contains("pdf")) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.PDF;
} else if (extension.Contains(Constants.videoFormats)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Video;
} else if (extension.Contains(Constants.excelExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Excel;
} else if (extension.Contains(Constants.wordExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Word;
} else if (extension.Contains(Constants.audioExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Voice;
}
}
Types is just an area for categorizing them into tabs for front end display
public enum FileAttachmentTypes {
[Display(Name = "Microsoft Word")]
Word = 1,
[Display(Name = "Microsoft Excel")]
Excel = 2,
[Display(Name = "Image")]
Image = 3,
[Display(Name = "Voice Recordings")]
Voice = 4,
[Display(Name = "PDF")]
PDF = 5,
[Display(Name = "Video")]
Video = 6,
[Display(Name = "Evidence")]
Evidence = 7,
[Display(Name = "None")]
None = 8,
[Display(Name = "Notes")]
NOTES = 9,
[Display(Name = "Shared Case")]
SharedCase = 10,
[Display(Name = "Created Case")]
CreatedCase = 11
}
My Question is why is it not finding it for a word document of extension docx when its clearly there

Related

How to insert a picture into a word processing document using DocumentFormat.OpenXML Library and AltChunk Class c#

I am using Telerik:RadEditor component for Asp.Net to save openXML and html report, I need to download word file format from this html report using DocumentFormat.OpenXML library from Microsoft, the code i used working successfully but can't see image after download word file.
I tried the below references but image not showing also.
https://learn.microsoft.com/en-us/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document
https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing.altchunk?view=openxml-2.8.1
Add HTML String to OpenXML (*.docx) Document
How to insert a non-inline picture into a word document using VB6?
Adding image in word document
My Code is as follows:
protected void btnsavetoword_Click(object sender, EventArgs e)
{
try
{
clsReportTemplateBO objexist = new clsReportTemplateBO();
objexist.RefNo = hdnRefNo.Value;
objexist.CreatedBy = clsUser.UserName;
List<clsReportTemplateBO> objReport = clsReportTemplateBL.GetSavedReports(objexist);
if (objReport.Count > 0)
{
string ReportText = edrReport.Content;
ReportText = ReportText.Replace(objReport[0].HeaderHTML, "");
ReportText = ReportText.Replace(objReport[0].FooterHTML, "");
objexist.ReportCode = objReport[0].ReportCode;
foreach (clsReportTemplateBO datarow in objReport)
{
if (datarow.ReportFormat == "Word")
{
objexist.PatientReportId = datarow.PatientReportId;
}
}
if (objReport.Count == 2)
{
string PatientReportId = objexist.PatientReportId;
ConverttoWord(objexist.ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
else if (objReport.Count == 1 && objReport[0].ReportFormat == "HTML")
{
objexist.ReportName = objReport[0].ReportName;
objexist.HID = objReport[0].HID;
objexist.CreatedBy = clsUser.UserName;
objexist.ReportFormat = "Word";
objexist.RefNo = hdnRefNo.Value;
if (clsReportTemplateBL.SavePatientReport(objexist))
{
string PatientReportId = objexist.PatientReportId;
ConverttoWord(objexist.ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
}
else if (objReport.Count == 1 && objReport[0].ReportFormat == "Word")
{
string PatientReportId = objexist.PatientReportId;
ConverttoWord(objexist.ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
}
else
{
clsReportTemplateBO obj = new clsReportTemplateBO();
string ReportCode = HttpContext.Current.Session["ReportCode"].ToString();
obj = clsReportTemplateBL.GetReportTemplate(ReportCode);
obj.ReportName = ReportName;
obj.ReportCode = ReportCode;
obj.HID = HID;
obj.CreatedBy = clsUser.UserName;
obj.ReportFormat = "Word";
obj.RefNo = hdnRefNo.Value;
string ReportText = edrReport.Content;
ReportText = ReportText.Replace(obj.HeaderHTML, "");
ReportText = ReportText.Replace(obj.FooterHTML, "");
if (clsReportTemplateBL.SavePatientReport(obj))
{
string PatientReportId = obj.PatientReportId;
ConverttoWord(ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
}
}
catch
{
rdWMngr.RadAlert("Report saved failed", 400, 150, "Report", null, clsConstants.ErrorMessage);
}
}
ConvertToWord method as follows:
protected void ConverttoWord(string ReportCode, string PatientReportId, string ReportText)
{
string domain = HttpContext.Current.Request.Url.Authority;
string RefNo = hdnRefNo.Value;
int PatientReportDetailId = clsReportTemplateBL.SavePatientReportDetail(PatientReportId, RefNo, domain, clsUser.UserName);
string sourceFile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ReportFormatPath"].ToString() + ReportCode + ".docx");
string destFile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["SavedReportPath"].ToString() + RefNo + PatientReportDetailId.ToString() + ".docx");
System.IO.FileInfo file = new System.IO.FileInfo(sourceFile);
System.IO.FileInfo dest = new System.IO.FileInfo(destFile);
if (file.Exists)
{
if (dest.Exists)
{
rdWMngr.RadAlert("File already converted. Try to download from Saved Report", 400, 150, "Saved Report", null, clsConstants.WarningMessage);
}
else
{
File.Copy(sourceFile, destFile);
}
exporttoword(destFile, ReportText);
}
else
{
rdWMngr.RadAlert("File not exist on " + sourceFile, 400, 150, "Saved Report", null, clsConstants.WarningMessage);
}
}
ExportToWord method as follows:
private void exporttoword(string FilePath, string ReportText)
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(FilePath, true))
{
string altChunkId = "AltChunkId1";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart("application/xhtml+xml"/*AlternativeFormatImportPartType.Html*/, altChunkId);
//string stamp = "~/images/Menu/EStamp.png"; //Location of image that I need to insert into word when i save
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
{
using (StreamWriter streamWriter = new StreamWriter(chunkStream))
{
streamWriter.Write(ReportText);
}
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
// this inserts altChunk after the last Paragraph
mainPart.Document.Body
.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
mainPart.Document.Save();
}
//Download
System.IO.FileInfo file = new System.IO.FileInfo(FilePath);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
rdWMngr.RadAlert("Error", 400, 150, "Saved Report", null, clsConstants.WarningMessage);
}
}
How can I insert image to the word file when I need to download it using DocumentFormat.OpenXML library in Asp.Net?

How to prevent duplicate validation while updating the value without any changes?

#RequestMapping(value = "/updateYearMaster", method = RequestMethod.POST)
public String updateYearmaster(#RequestParam(value = "id", required = false) Long id,
#RequestParam(value = "fromyear", required = false) Date fromyear,
#RequestParam(value = "toyear", required = false) Date toyear,
#RequestParam(value = "status", required = false) String status,
#RequestParam(value = "yeardescription", required = false) String yeardescription, Model model) {
Yearmaster yearmaster = new Yearmaster(fromyear, toyear, status, yeardescription);
yearmaster.setId(id);
List val = yearmasterService.duplicateEditYear(fromyear, toyear, id);
if (!val.isEmpty()) {
model.addAttribute("yearmaster", yearmaster);
errorMessage = "fromyear and toyear combination is already exist";
model.addAttribute("errorMessage", errorMessage);
return "edit-year-master";
} else {
yearmasterService.save(yearmaster);
return "redirect:/yearmaster";
}
}

import excel file to database using EPPlus

I am having a hard time understanding what should be a simple task. I am now using EPPlus to help me with this task. However, I am at a point of where I can't track what is going on. (per the comment below and days of google searching) I'm trying to read in an excel file and pass that to my EF model. It breaks down at line 159 where I am trying to put in the values from the excel file but keeps coming across as null. However when looking at the values past line 159 they all have the correct information. I am not sure how to even track a bug like this.
TruckController.cs
// POST: Trucks/Import
[HttpPost]
public ActionResult Import(FormCollection formCollection)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["file"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
file.SaveAs(Server.MapPath("~/" + "test.xlsx"));
//string fileName = file.FileName;
// string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
// var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
var MyImport = new List<string>();
MyImport = ImportDataRecords(new FileInfo(Server.MapPath("~/" ) + "test.xlsx"));
}
}
return View("Import");
}
public List<string> ImportDataRecords(FileInfo file)
{
var resultMessages = new List<string>();
var totalImported = 0;
try
{
using (var excelPackage = new ExcelPackage(file))
{
string DeliveryColumn,
ItemNoColumn,
MaterialColumn,
MaterialDescriptionColumn,
DeliveryQtytoPickColumn,
PickedQuantityColumn,
SalesUoMColumn,
BatchPickedColumn,
BinNoColumn,
BagWeightColumn,
PalletNoColumn,
PalletStackingNoColumn,
StageNoColumn,
SubStopNoColumn,
PickStatusColumn,
PackStatusColumn,
SoldToColumn,
SoldToNameColumn,
ShipToNameColumn;
if (!file.Name.EndsWith("xlsx"))
{
resultMessages.Add("File selected is not an Excel file");
return resultMessages;
}
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null)
{
resultMessages.Add("File was empty");
return resultMessages;
}
using (var headers = worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
{
var expectedHeaders = new[]
{
"Delivery", "Item No.", "Material", "Material Description", "Delivery Qty to Pick",
"Picked Quantity", "Sales UoM", "Batch Picked", "BIN No.", "Bag Weight", "Pallet No.",
"Pallet Stacking No", "Stage No", "Sub Stop No", "Pick Status", "Pack Status", "Sold-To",
"Sold-To Name", "Ship-To Name"
};
if (!expectedHeaders.All(e => headers.Any(h => h.Value.Equals(e))))
{
resultMessages.Add("Some columns are missing from the file");
return resultMessages;
}
DeliveryColumn = headers.First(h => h.Value.Equals("Delivery")).Address[0].ToString();
ItemNoColumn = headers.First(h => h.Value.Equals("Item No.")).Address[0].ToString();
MaterialColumn = headers.First(h => h.Value.Equals("Material")).Address[0].ToString();
MaterialDescriptionColumn = headers.First(h => h.Value.Equals("Material Description")).Address[0].ToString();
DeliveryQtytoPickColumn = headers.First(h => h.Value.Equals("Delivery Qty to Pick")).Address[0].ToString();
PickedQuantityColumn = headers.First(h => h.Value.Equals("Picked Quantity")).Address[0].ToString();
SalesUoMColumn = headers.First(h => h.Value.Equals("Sales UoM")).Address[0].ToString();
BatchPickedColumn = headers.First(h => h.Value.Equals("Batch Picked")).Address[0].ToString();
BinNoColumn = headers.First(h => h.Value.Equals("BIN No.")).Address[0].ToString();
BagWeightColumn = headers.First(h => h.Value.Equals("Bag Weight")).Address[0].ToString();
PalletNoColumn = headers.First(h => h.Value.Equals("Pallet No.")).Address[0].ToString();
PalletStackingNoColumn = headers.First(h => h.Value.Equals("Pallet Stacking No")).Address[0].ToString();
StageNoColumn = headers.First(h => h.Value.Equals("Stage No")).Address[0].ToString();
SubStopNoColumn = headers.First(h => h.Value.Equals("Sub Stop No")).Address[0].ToString();
PickStatusColumn = headers.First(h => h.Value.Equals("Pick Status")).Address[0].ToString();
PackStatusColumn = headers.First(h => h.Value.Equals("Pack Status")).Address[0].ToString();
SoldToColumn = headers.First(h => h.Value.Equals("Sold-To")).Address[0].ToString();
SoldToNameColumn = headers.First(h => h.Value.Equals("Sold-To Name")).Address[0].ToString();
ShipToNameColumn = headers.First(h => h.Value.Equals("Ship-To Name")).Address[0].ToString();
using (var context = new EPPlusTruckContext())
{
var lastRow = worksheet.Dimension.End.Row;
for (var row = 2; row <= lastRow; row++)
{
-----------Line 159-------------> var truck = new Truck()
{
Delivery = worksheet.Cells[DeliveryColumn + row].Value.ToString(),
ItemNo = worksheet.Cells[ItemNoColumn + row].Value.ToString(),
Material = worksheet.Cells[MaterialColumn + row].Value.ToString(),
MaterialDescription = worksheet.Cells[MaterialDescriptionColumn + row].Value.ToString(),
DeliveryQtyToPick = worksheet.Cells[DeliveryQtytoPickColumn + row].Value.ToString(),
PickedQuantity = worksheet.Cells[PickedQuantityColumn + row].Value.ToString(),
SalesUoM = worksheet.Cells[SalesUoMColumn + row].Value.ToString(),
BatchPicked = worksheet.Cells[BatchPickedColumn + row].Value.ToString(),
BinNo = worksheet.Cells[BinNoColumn + row].Value.ToString(),
BagWeight = worksheet.Cells[BagWeightColumn + row].Value.ToString(),
PalletNo = worksheet.Cells[PalletNoColumn + row].Value.ToString(),
PalletStackingNo = worksheet.Cells[PalletStackingNoColumn + row].Value.ToString(),
StageNo = worksheet.Cells[StageNoColumn + row].Value.ToString(),
SubStopNo = worksheet.Cells[SubStopNoColumn + row].Value.ToString(),
PickStatus = worksheet.Cells[PickStatusColumn + row].Value.ToString(),
PackStatus = worksheet.Cells[PackStatusColumn + row].Value.ToString(),
SoldTo = worksheet.Cells[SoldToColumn + row].Value.ToString(),
SoldToName = worksheet.Cells[SoldToNameColumn + row].Value.ToString(),
ShipToName = worksheet.Cells[ShipToNameColumn + row].Value.ToString(),
};
db.Trucks.Add(truck);
try
{
db.SaveChanges();
totalImported++;
}
catch (Exception ex)
{
resultMessages.Add(string.Format("Record on line#{0} failed: {1}\n", row, ex.Message));
}
}
}
}
resultMessages.Insert(0, string.Format("{0} records successfully imported.\n", totalImported));
return resultMessages;
}
}
catch (IOException ex)
{
resultMessages.Add("File still open. Please close Excel file before importing.");
return resultMessages;
}
}
A simple example here:
Reff: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}

MailEnable - Create Account

I'm trying to create an e-mail with MailEnable
based http://www.mailenable.com/developers/NET_SignUp.zip
MailEnable.Administration.Login oLogin = new MailEnable.Administration.Login();
oLogin.Account = iCliente.URL;
oLogin.LastAttempt = -1;
oLogin.LastSuccessfulLogin = -1;
oLogin.LoginAttempts = -1;
oLogin.Password = txt_Senha.Text;
oLogin.Rights = "";
oLogin.Status = -1;
oLogin.UserName = txt_Email + "#" + iCliente.URL;
if (oLogin.GetLogin() != 1)
{
oLogin.LastAttempt = 0;
oLogin.LastSuccessfulLogin = 0;
oLogin.LoginAttempts = 0;
oLogin.Password = txt_Senha.Text;
oLogin.Rights = "USER";
oLogin.Status = 1;
}
MailEnable.Administration.Mailbox mailBoxCreate = new MailEnable.Administration.Mailbox();
mailBoxCreate.Postoffice = iCliente.URL;
mailBoxCreate.MailboxName = txt_Email.Text;
mailBoxCreate.RedirectAddress = txt_Redirect.Text;
mailBoxCreate.RedirectStatus = 0;//recuperar valor da checkbox
mailBoxCreate.Limit = 51200; //-1 for unlimited
mailBoxCreate.Status = 1;
mailBoxCreate.AddMailbox();
MailEnable.Administration.AddressMap mailAMap = new MailEnable.Administration.AddressMap();
mailAMap.Account = iCliente.URL;
mailAMap.DestinationAddress = "[SF:" + iCliente.URL + "/" + txt_Email.Text + "]";
mailAMap.SourceAddress = "[SMTP:" + txt_Email.Text + "#" + iCliente.URL + "]";
mailAMap.AddAddressMap();
But does not work, it creates the email but no password!
:(
Follow my class running perfect.
using System;
using System.Data.SqlClient;
using System.IO;
using System.Xml.XPath;
using MailEnable;
namespace BLL
{
public class MailEnable_Geral
{
public string _Email { get; set; }
public bool CriarEmail(string _senha, string _redirect, long _ativarRedirect)
{
string[] vPostoffice = _Email.Split('#');
string _username = vPostoffice[0];
string _postoffice = vPostoffice[1];
string _domain=_postoffice;
bool _retorno = true;
try
{
MailEnable.Administration.Mailbox mb = new MailEnable.Administration.Mailbox();
mb.Postoffice = _postoffice;
mb.MailboxName = _username;
mb.Host = _domain;
mb.Limit = 51200;//50MB
mb.RedirectAddress = _redirect;
mb.RedirectStatus = _ativarRedirect;//Ativa ou desativa Redirect
mb.Status = 1;
mb.AddMailbox();
MailEnable.Administration.Login login = new MailEnable.Administration.Login();
login.Account = _postoffice;
login.Description = _username + " at " + _domain;
login.Host = _domain;
login.Rights = "USER";
login.Status = 1;
login.Password = _senha;
login.UserName = _username + "#" + _postoffice;
login.AddLogin();
MailEnable.Administration.AddressMap map = new MailEnable.Administration.AddressMap();
map.Account = _postoffice;
map.DestinationAddress = "[SF:" + _postoffice + "/" + _username + "]";
map.SourceAddress = "[SMTP:" + _username + "#" + _domain + "]";
map.Scope = "";
if (map.AddAddressMap() == 0)
{
throw new Exception("Failed address map");
}
}
catch (Exception e)
{
_retorno = false;
}
return _retorno;
}
}
}

What's wrong with this linqTOsql self referencing object mapping?

I'm trying to create a self referencing object using linqTOsql mapping. So far, I am definitely in over my head. Here's the code I have:
[Table]
public class Category
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
public Int64 catID { get; set; }
public Int64 parentCatID { get; set; }
public string catName { get; set; }
public string catDescription { get; set; }
internal EntityRef<IEnumerable<Category>> _category;
[Association(ThisKey = "parentCatID", Storage = "_category")]
public IEnumerable<Category> category {
get { return _category.Entity; }
set { _category.Entity = value; }
}
}
My fakeRepository is defined like this:
// Fake hardcoded list of categories
private static IQueryable<Category> fakeCategories = new List<Category> {
new Category { catID = 1, parentCatID = 0, catName = "Root", catDescription = "" },
new Category { catID = 2, parentCatID = 1, catName = "Category w/subs", catDescription = "" },
new Category { catID = 3, parentCatID = 1, catName = "Category no subs but now has subs", catDescription = "" },
new Category { catID = 4, parentCatID = 2, catName = "Zub Cat", catDescription = "" },
new Category { catID = 5, parentCatID = 2, catName = "Sub Cat", catDescription = "" },
new Category { catID = 6, parentCatID = 0, catName = "Another Root", catDescription = "" },
new Category { catID = 7, parentCatID = 0, catName = "Ze German Root", catDescription = "" },
new Category { catID = 8, parentCatID = 3, catName = "Brand new cats", catDescription = "" },
new Category { catID = 9, parentCatID = 8, catName = "Brand new cats sub", catDescription = "" },
}.AsQueryable();
I pass Category to the view like this:
public ActionResult CategoryTree()
{
IQueryable<Category> cats = genesisRepository.Category
.Where(x => x.parentCatID == 0)
.OrderBy(x => x.catName);
return View(cats);
}
The problem that I'm running into is that all of this compiles, but I don't get anything beyond the root categories. Model[0].category is returning null.
What is wrong with my self-referencing object?
Edit
I wonder if it's not working because I don't have a real linq-to-sql data context in my fakeRepository. If that's the case, is there a way around that? Can I can get this to work without a connection to a database?
Yeah, you hit the nail on the head. It's not working because you're using a fake repository.
Linq-to-Sql does all the wiring up for you and sets the related collections based on the properties (& their attributes) that you setup in your model.
I don't know how to accomplish this without a connection to the database because internal EntityRef<IEnumerable<Category>> _category; is completely foreign to me - I'm more of a POCO model type of guy.
After a quick google, I found this - How to: Map Database Relationships (LINQ to SQL)
Could you change your model to read:
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
public Int64 CatId { get; set; }
[Column]
public Int64 ParentCatId { get; set; }
[Column]
public string CatName { get; set; }
[Column]
public string CatDescription { get; set; }
private EntitySet<Category> _ChildCategories;
[Association(Storage = "_ChildCategories", OtherKey = "ParentCatId")]
public EntitySet<Category> ChildCategories
{
get { return this._ChildCategories; }
set { this._ChildCategories.Assign(value); }
}
private EntityRef<Category> _ParentCategory;
[Association(Storage = "_ParentCategory", ThisKey = "ParentCatId")]
public Category ParentCategory
{
get { return this._ParentCategory.Entity; }
set { this._ParentCategory.Entity = value; }
}
Now because your ChildCategories is of type EntitySet<Category> (which inherits from IList<T>) you should be able to wire fake relationships up yourself.
So you could do something like this:
private static IQueryable<Category> GetFakeCategories()
{
var categories = new List<Category> {
new Category { CatId = 1, ParentCatId = 0, CatName = "Root", CatDescription = "" },
new Category { CatId = 2, ParentCatId = 1, CatName = "Category w/subs", CatDescription = "" },
//Blah
new Category { CatId = 8, ParentCatId = 3, CatName = "Brand new cats", CatDescription = "" },
new Category { CatId = 9, ParentCatId = 8, CatName = "Brand new cats sub", CatDescription = "" }
};
//Loop over the categories to fake the relationships
foreach (var category in categories)
{
category.ChildCategories = new EntitySet<Category>(); //new up the collection
foreach (var subLoopCategory in categories)
{
if (category.ParentCatId == subLoopCategory.CatId)
category.ParentCategory = subLoopCategory;
if (category.Id == subLoopCategory.ParentCatId)
category.ChildCategories.Add(subLoopCategory);
}
}
return categoies.AsQueryable();
}
It works in my head at least... :-)
HTHs,
Charles
EDIT: Re: Comment below about a null reference on _childCategories.
You could change the model to look like:
private EntitySet<Category> _ChildCategories = new EntitySet<Category>();
It is supposed to be null. You are getting all categories where the ParentId = 0 ... and you don't have a child with an Id of 0. So that seems right to me.
It is not showing any subcategories because it has no subcategories to show. Try this:
IQueryable<Category> cats = genesisRepository.Category
.Where(x => x.parentCatID != 0)
.OrderBy(x => x.catName);
The parentCatId needs to point to a valid CatId for it to be a subcategory. This query should get you all the categories that are subcategories.

Resources