Validate Data in a CSV file using MVC - asp.net-mvc

I am trying to validate the UK phone number contain in a CSV file before inserting the data in the table. At the moment the if statement is not working when the mobile number is valid the code doesn't jump to the else block. See the code below.
Controller code
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> BulkMEssage(TextMessage messagedetail,
HttpPostedFileBase attachmentcsv,
MobileRecipient messagelink, int ddlshedule, string date)
{
if (ModelState.IsValid)
{
CsvFileDescription csvFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
CsvContext csvContext = new CsvContext();
StreamReader streamReader = new
StreamReader(attachmentcsv.InputStream);
IEnumerable<MobileRecipient> list =
csvContext.Read<MobileRecipient>(streamReader,
csvFileDescription);
foreach (var mobilenumber in list)
{
var phoneno = #"/^ (\+44\s ? 7\d{ 3}|\(? 07\d{ 3}\)?)\s ?\d{ 3}\s ?\d{ 3}$/";
if ((!mobilenumber.MobileNumber.Equals(phoneno)))
{
error message Here with the wrong format number
}
else
{
Insert Data in the database
}
}
}
I think I am using the regular expression the wrong way. The column name in my CSV file is called "MobileNumber". Please suggest if you have any better way to do this.

Related

Edit operation not saving to the DB

I posted the question earlier, but didn't receive any correct responses, hence posting again with some edits. I have a function that accepts two parameters, IDs and Dates. When I had put breakpoints, I was able to see the Ids and the Dates selected on the page as parameter values. However, after hitting the process button, nothing happens, meaning this data isn't getting saved to the DB.
Model Classes:
public class Hello{
public string ID{ get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date{ get; set; }
}
Controller Class:
[HttpGet]
public ActionResult Selection(string ids, string dates)
{
model = new Hello();
ExtensionDB db = new ExtensionDB();
string[] IDS = ids.Split(',');
string[] DATES = dates.Split(',');
List<Hello> list = new List<Hello>();
for (int i = 0; i < IDS.Length; i++)
{
if (IDS[i] != null && IDS[i] != "")
{
Hello item = new Hello { ID = IDS[i], Date = DateTime.Parse(DATES[i]) };
list.Add(item);
}
}
if (ModelState.IsValid)
{
foreach (var row in db.Table1)
{
foreach (var row2 in db.Table2)
{
if (row.UID== row2.CID) // UID and CID are Foreign keys that join these two tables
{
foreach (var item in list)
{
if (row.UID == Convert.ToInt32(item.ID))
{
row2.ReportedDate = item.Date;
}
db.SaveChanges();
}
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
I will add the view class if needed, however the problem is here.. You can also refer to it here: Saving changes to the DB MVC
Your code does not attempt to update anything. Start with confirming what the data you are passing to this POST call contains, and what you want to do with it. It looks like what you are trying to do is update the dates for a number of records. Looking at your previous post (no need to re-post another question with the same code) there are a few things..
First: Structure the data you want to pass to the POST call into a collection of simple objects containing an id and a date. For example:
{
id = rid,
date = date
}
and add those to the collection named something like "updateData" rather than two separate arrays of IDs and dates. Then in the server-side code, declare a simple view model class:
public class UpdateDateViewModel
{
public int Id { get; set; }
public DateTime Date { get; set; }
}
In the ajax call instead of:
data: { ids: ids, dates: dates },
you'll want something like:
data: { updates: updateData },
where updateData is your collection of id + date pairs.
and use that view model in your method:
public ActionResult Process(IList updates)
Provided that request data is sent as Json, ASP.Net should translate that data automatically for you, though you may need to configure ASP.Net to translate the camelCase vs PascalCase. Worst case, to test, you can use camelCase property names ("id" and "date")
Now when it comes to updating the data: Server side, please get in the habit of using meaningful variable names, not "c", "i", etc. It makes code a lot easier to understand.
public ActionResult Process(IList<UpdateDateViewModel> updates)
{
using (db = new DB())
{
//rp = new RequestProcess(); - Assuming RequestProcess is an Entity?
//var c = rp.getStuff(); - No idea what this getStuff() method does...
foreach(var update in updates)
{
var request = db.RequestProcesses.Find(update.Id);
if (request != null)
request.RequestDate = update.Date; // If we find a matching request, update it's date.
else
{ // Doesn't exist, create it and add it to the DbSet.(table)
var request = new RequestProcess { Id = update.Id, RequestDate = update.Date };
db.RequestProcesses.Add(request);
}
db.SaveChanges();
}
}
}
Now this is a very bare bones guess at what you may be trying to do. Ideally though, updates should be completely separate from adds in the sense that an update should only deal with existing records. If it comes across an ID that it cannot find it should throw an error, ignore, and/or return a status to the user that something wasn't right. Creating new entries should be a separate call and ensure that records are properly initialized with their required fields.
Your original code looked to be taking a list of IDs, but then creating a new entity and calling that "getStuff" method that didn't have the DbContext, or any of the values from the POST call, but then attempting to copy values from that entity into the string parameters that you passed (which would overwrite the Json string) None of that would have updated an entity which would never have updated your data.
Take it slow and follow the examples before attempting to adapt them to your ideas. It will be a lot more constructive and less frustrating then writing a bunch of code that doesn't really make much sense, then wondering why it doesn't work. Your original code has probably a dozen or more problems and inefficiencies. Simply pasting it up on Stack will get a lot of confusing comments based on these problems which don't really help with the first issue you want to solve. Strip it back to the minimum, start with getting the data you need to the server in a meaningful way, then from that, attempt to use that data to update your entities.

Throw into the database as it looks in HTML form

It is such that I have to "update" the database with new content and I print it in pure HTML, but when I throw it into the database with the HTML as it has allocated so that it will in no way throw it into the database
[HttpPost]
[ValidateInput(false)]
public ActionResult index(IndholdViewModel model)
{
if (ModelState.IsValid)
{
var forsideindhold = db.forsides.FirstOrDefault(i => i.Id == 1);
if (forsideindhold != null)
{
//error here
forsideindhold.tekst = new HtmlString(model.Indhold);
.SubmitChanges();
return RedirectToAction("index/Opdater");
}
}
return View();
}
Error happens here:
forsideindhold.tekst = new HtmlString(model.Indhold);
What I well only imagine this is that it remove the HTML it has got hold of by my model.indhold and throw it into the database.
Error are:
cannot convert from 'System.Web.HtmlString' to 'string'
Well your problem is that you can't pass to HtmlString constructor HtmlString.
But actually i can't understand why you need it as long as forsideindhold.tekst is string. You should write it like this:
forsideindhold.tekst = model.Indhold.ToString();
Or:
forsideindhold.tekst = new HtmlString(model.Indhold.ToString()).ToString();
check your value is null or not before insert to model.
if(!string.IsNullOrWhiteSpace(model.Indhold)) forsideindhold.tekst = new HtmlString(model.Indhold.ToString()).ToString();

Linq query returns sql and not data from database

I'm not sure what the problem is but I cant seem to get my program to display the correct information. The requirements for my application are to take a pdf and populate the form fields with information from a database. The problem is that it does not return the information from the database and instead returns the sql generated from entity framework.
(text) SELECT
[Extent1].[Applicant_ID] AS [Applicant_ID]
FROM [dbo].[W4] AS [Extent1]
This is what is displayed in the pdf textbox.
This is my query
public class Query
{
ApplicatoinContext context = new ApplicatoinContext();
public List<W4> GetId()
{
return (from p in context.w4
select new W4 { Applicant_ID = p.Applicant_ID }).ToList();
}
}
My controller
public class ApplicationController : Controller
{
// GET: Application
public ActionResult Index()
{
string template = #"c:\users\carisch\documents\visual studio 2013\Projects\Idea\Idea\fw4.pdf";
string newFile = #"c:\users\carisch\documents\visual studio 2013\Projects\Idea\Idea\Newfw4.pdf";
PdfReader reader = new PdfReader(template);
PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
AcroFields fields = stamper.AcroFields;
Query num = new Query();
var query = num.GetId();
fields.SetField("f1_15_0_", query.ToString());
stamper.FormFlattening = false;
stamper.Close();
return File(#"c:\users\carisch\documents\visual studio 2013\Projects\Idea\Idea\Newfw4.pdf", "application/pdf");
}
}
I'm pretty new to programming so any help would be greatly appreciated.

DataTables editable cant figure out how to delete/update rows

I am trying to implement dataTables plugin in server-side mode to render a table on my webpage. I am coding ASP.NET with c# and MVC.
I want to edit (delete/update/add) data to the table and write any change to my database.
But in difference to the example of this tutorial: http://www.codeproject.com/Articles/165410/ASP-NET-MVC-Editable-DataTable-jQuery-DataTables-a data provided by my controller does not contain a single primary key, but a compound key:
projectId and
questionId
Here's my controller, which provides data from my database:
public ActionResult AjaxHandler(jQueryDataTableParamModel param)
{
var any = (from pq in _db.ProjectQuestions
join q in _db.Question
on pq.QuestionID equals q.QuestionID
join c in _db.Category
on q.CategoryID equals c.CategoryID
select new
{
projectID = pq.ProjectID,
questionID = q.QuestionID,
categoryName = c.CategoryName,
questionName = q.QuestionName,
questionDescription = q.QuestionDescription
});
int count = any.Count();
var result = new List<object[]>();
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = count,
iTotalDisplayRecords = count,
aaData = any
},
JsonRequestBehavior.AllowGet);
}
So far the standard DeleteData/UpdateData and AddData methods dont even receive any value for id.
public string DeleteData(int id)
{
return "ok";
}
How can I use the CRUD-functionality of Editable if my data has to be identified by two parameters?
So far I couldn't find any solution to edit data. Many thanks in advance.
_tek
I would suggest you to use Grid view function.
Please follow this video:
http://www.youtube.com/watch?v=vZIOI136IKY

How do I pass my data to a JsonResult so that it formats correctly

I am using a MooTools TextboxList in my MVC app to create an autocomplete Tag suggester, similar to the StackOverflow one.
The script uses Json to do the suggestions. The Json string it seems to expect is different than I am able to generate. From the script's demo, it should look something like this:
[[32,"Science",null,null]]
But I can't figure out how to get the string to come out of MVC quite like that. Best I get looks more like:
[{"id":11,"text":"Science"}]
With the actual field names showing up.
Here is my controller method:
public JsonResult Suggest(string search)
{
JsonResult jsonresult = new JsonResult();
var tags = from t in db.Tags
where t.Text.Contains(search)
select new {id=t.TagID, text=t.Text};
var result = DoSomethingTo(tags); // <---????????
jsonresult.Data = result;
jsonresult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsonresult;
}
I've tried several variations of passing variables into the JsonResult.Data without much luck. I've tried arrays, custom objects, etc. I'm just not getting it. I'm certain it's very
Edit: That should have said "I'm certain it's very easy."
It's an array of arrays of objects. You could generate it like this:
return Json(new[] { new object[] { 32, "Science", null, null } });
and within your select action you could try something along the lines of:
public ActionResult Suggest(string search)
{
var tags = from t in db.Tags
where t.Text.Contains(search)
select new object[] { t.TagID, t.Text };
return Json(tags.ToList(), JsonRequestBehavior.AllowGet);
}
Based on another question, I ended up going old-school on it... building the string manually.
public ContentResult Suggest(string search)
{
var tags = from t in db.Tags
where t.Text.Contains(search)
orderby (t.Text)
select t;
var builder = new StringBuilder();
builder.Append("[");
foreach (Tag tag in tags)
builder.AppendFormat("[{0}, \"{1}\", null, null]", tag.TagID, tag.Text);
var result = builder.ToString().TrimEnd(new char[] { ',', ' ' }) + "]";
ContentResult res = new ContentResult();
res.Content = result;
return res;
}

Resources