Generate a list/reference of dynamically added inputs - c#

I am working in an CMS called RiSE, and have many constraints. I am also thinking in PHP while trying to output C#.
I have a contact form that is being dynamically generated by being put together by "iParts". Each iPart includes an ASCX file into the wizardry of templates and junk.
As an example, I could have 2 iParts that each add a text box. How do I generate a list of these 2 text boxes that I can recall after post as to get the values?
What I am doing now, and almost works....
I have what I think is called a controller, and it (I think) defins a property like so;
namespace EmailForm
{
[DataContract(Name = "EmailForm")]
public class EmailForm : iPartCommonBase
{
public static Dictionary<String, String> inputs = new Dictionary<String, String>();
}
}
Now in my (I think) Controller, I add to the Dictionary inputs like so;
EmailForm.inputs[randId + "_" + inputEmailLabel.ToString()] = input.UniqueID;
What I end up with is a key value pair list that contains a label prefixed with some random string (to prevent crashes/overwrites) and the id.
When the form is submitted I loop through the dictionary and use the ID string to access the posted value. Pretty straight forward, BUT, if I reload the page say 3 times before filling the form and hitting submit, I end up with 6 entries into my Dictionary, all but the last 2 reference non-existant ID's.
What should I do differently? (and unfortunately, use LAMP is not an option)

In the end I have found a simple solution, I think it's a hack, but so is ASP
if (Request.Form.AllKeys.Contains(post.Value))
{
emailBody.Add(post.Key.Substring(8) + ": " + Request.Form[post.Value]);
}
The Dictionary still contains "rogue" entries, but I filter them out by existing post data.

Related

C# How to add string variables with values to the any System.Collections class and retrieve them

So I have a slightly interesting problem right here. What I'm trying to achieve is to add between 1000 to 2000 string variables to the list and later compare them with another strings. So far I can achieve this by using below code:
var list = new List<string>();
var item_1 = "USA";
var item_2 = "Canada";
var item_3 = "Cuba";
...................
var item_N = "Country_N";
list.Add(item_1);
list.Add(item_2);
list.Add(item_3);
.................
list.Add(item_N);
And comparing them with another strings looks like below (using FluentAssertions class):
list[0].Should().Match(stringToCompare_1);
list[1].Should().Match(stringToCompare_2);
list[2].Should().Match(stringToCompare_3);
The biggest problem that I see here is it's sort of hard to memorize what string was added to a particular index of the list (unstoppable scrolling between the code is boring). My question: is there any more elegant way to handle this situation? Something that might look like below (List class method ValueOf is fictional):
var list = new List<string>();
var item_1_USA = "USA";
var item_2_Canada = "Canada";
var item_3_Cuba = "Cuba";
list.ValueOf(item_1_USA).Should().Match(stringToCompare_1);
list.ValueOf(item_1_Canada).Should().Match(stringToCompare_2);
list.ValueOf(item_1_Cuba).Should().Match(stringToCompare_3);
As many suggested (including #Postlagerkarte) to edit the question to clarify what I'm trying to achieve. I'm testing the web app, and while going through every step of this application (imagine booking engine), I need to capture and store different info (like user's First Name, Last Name, Email Address, Phone Number, etc). The amount of the captured info can sometimes exceed 2000 items. Currently I'm using data structure List. Later, at the final step of my application, I need to compare my stored values with what ever present on this final page. For instance: user's first name, that was captured on Step 2 of the booking engine must match with value on final step. List Contains method won't be suitable here as it can validate incorrect information. Accessing the values using list[0]....list[N] is very inconvenient, as I can forget what exactly was stored at that index. I'm solving it now by scrolling through the code to return back. Any wise navigation is appreciated.
You can use a Dictionary<string, string> for this. The key of each value would be a field or info identifier: userFirstName, userAge, etc. As you process data you add it to your dictionary with whatever value you are reading.
When validating, you look up the stored value with the field identifier and compare it to whatever data shows upon your last page.
You can also consider using an enumeration as your key instead of string although if you avoid magic strings literals and use constants you should be ok.
Why can't you use the Contains() method saying
list.Contains(stringToCompare_1);

Add Reference/Issue number to webform

Hi I am using Visual Studio 2013, c# asp.net. I have created a online docket for staff to fill out, I was wondering can you add a reference number/ issue number to the web form. Each staff member will fill out this form and they could be similar, so I want each form to have there own unique number however I am not to sure which way to go about it. The form is going to be the same for everyone so I want each one that is filled out to have a different number. Should I place a label and have an array list to generate random numbers or is there a more straight forward way?
An alternative to keeping a number in the database and having to detect collisions etc you could use the Guid: Guid.NewGuid()
Sample usage:
Guid uniqueId = System.Guid.NewGuid();
string x = uniqueId.ToString();
Keep a number in a database. On each form generated, take this number, increment it, and save the new number to the DB.

Creating a new form - Sharepoint

So I have the code as such:
private void newAddFormForMembers(SPList list, SPWeb web)
{
list = web.Lists["MemberRecords"];
string url = string.Format("_layouts/createform.apsx", web.ServerRelativeUrl, list.RootFolder.Url);
var form = web.GetFile(url);
if (form != null)
{
list.DefaultNewFormUrl = url;
list.Update();
}
}
I have used SharePoint 2010 designer to go and grab the existing html for the creatform form when adding items to a particular list. I added in two new fields, first and last name. The list contains a member name, I removed this field from the create form because:
When I hit submit to add the item to the list, first and last name need to format them selves into "lastname, first name". Now I could submit the form back to my self - How do I do that? - and then do my string manipulation How do i get the values form a field? - and then push the information to the list How do I do that? but then I have anew issue
Edit will look the exact same as add, first and last name fields, how would I take the information from the list and populate the new edit form, particularly first and last name fields, keeping in mind that in the list they are in the format of "lastname, firstname"?
This is all being done programatically
Instead of change html newForm for the list try to write an Event Receiver
Instead of delete field from the newForm try to hide columns (You can do that programmatically or using external tool such as Sharepoint Manager
Adding fields to the new/edit form and grab value on postback event I think is not simple/possible (via javascript you can access onPreSave where you can manipulate item values before postback, here you can write some jscript for save values into field but on edit is hard to split values).
You can: create two column on your list FirstName and LastName, plus a third field FullName (hidden for new/edit form) and with an EH on Added/Updated you can write FullName = LastName + ", " + FirstName or without EH you can create a calculated Field.

Remove part of the Request.Form

In a C# MVC3 solution I'm passing the request.form as a string to a webservice (I understand it would be much better to break it down and populate a model but it's compromised with old code and mainly with time) and at a step the string is huge due to many options and failed in the service.
Actually I won't need all of this options, which are basically several dropdownlists from which I just need one of them, so I'm trying to figure out how to change the request.form in order to remove the redundant ones and just keep the one selected.
To put this into context, this should be part of the string (just a middle chunk of it)
NG2BEF01-16344-181-E-16344-0-SHW_SHR*16344*MAT*1*2500*1600=0&NG2BEF01-16344-181-E-16344-0-SHW_SHR*16344*MAT*2*5500*6200=0&NG2BEF01-16344-181-E-16344-0-SHW_39S*16344*EVE*1*1500*0=2
And I would like to remove all of the options appart from (in this portion) the last one wich =2. This 0's and the 2 come from a dropdown list which name is all the rest of the parameter (ie NG2BEF01-16344-181-E-16344-0-SHW_39S*16344*EVE*1*1500*0) although it may be completely different, not always follow this pattern.
Is there any way I can get rid of the dropdown lists I leave to 0 in the request.form before submitting (or even in the controller would be acceptable)?
You could filter out values that you don't want to keep:
var values = HttpUtility.ParseQueryString("NG2BEF01-16344-181-E-16344-0-SHW_SHR*16344*MAT*1*2500*1600=0&NG2BEF01-16344-181-E-16344-0-SHW_SHR*16344*MAT*2*5500*6200=0&NG2BEF01-16344-181-E-16344-0-SHW_39S*16344*EVE*1*1500*0=2");
string result = string.Join("&", values.Cast<string>().Where(key => values[key] == "2").Select(key => string.Format("{0}={1}", key, HttpUtility.UrlEncode(values[key]))));
// The result variable will contain only kvps where the value equals 2

Getting more than one item from a database in ASP .NET MVC 3

I'm creating a database where users can enter some Error Reports and we can view them. I'm making these database with C# in the ASP MVC 3 .NET framework (as the tags imply). Each Error Report has a unique ID, dubbed ReportId, thus none of them are stored under the same Id. However, whenever a User creates a new Error, I pass their User Name and store it in with the rest of the report (I use User.Identity.Name.ToString() to get their name and store it as a string). I know how to get a single item from the data using a lambda expression, like so:
db.DBSetName.Single(g => g.Name == genre)
The above code is based on an MVC 3 tutorial (The Movie Store one) provided by ASP. This was how they taught me how to do it.
My major question is: is there a member function like the .Single one that will parse through the whole database and only output database entries whose stored User Name matches that of the currently logged in user's? Then, I can use this to restrict User's to being only able to edit their own entries, since only their entries would be passed to the User's View.
What would be the best way to implement this? Since the ReportId will not be changed, a new data structure can be created to store the user's Errors and passed through to the Index (or Home) View of that particular controller. From there they should be able to click any edit link, which will pass the stored ReportId back to the Edit Action of this particular controller, which can then search the entire database for it. Am I right in assuming this would work? And would this be ideal, given that the other items in the database are NOT passed through to the Index in this method, meaning the User does not have access to the other items' ReportId's, which the user needs to pass into the Edit Action for it to work? If this is ideal, this is the method that requires me to know how to parse through a database and grab every element that fits a particular description (stored User Name matches User's current User Name).
Or would a better approach be to pass the whole database to the Index View and only output the database entries that have User Name values that match the current logged in user's? I guess this could be done in a foreach loop with a nested if loop, like so:
#foreach(var item in db.Reports)
{
if(item.UserName == User.Identity.Name.ToString())
{
...code to output table...
}
}
But this passes the whole database which gives the user a lot more info than they need. It also gives them potential access to info I don't want them to have. However, I don't have to make a new data structure or database, which should lower server memory usage and fetch time, right? Or are databases passed by copy? If so, this method seems kinda dumb. However, I don't know if the first method would fracture the database potentially, this one certainly would not. Also don't remember if I NEED an else statement in C#, I'm more familiar with C++, where you don't need one and you also don't need {}'s for single line if's, if I need one: please don't judge me too harshly on it!
Small note: I am using CRUD Controllers made with the Entity First Framework in order to edit my database. As such, all creation, reading, updating, and deletion code has been provided for me. I have chosen not to add such basic, common code. If it is needed, I can add it. I will add what the Edit Action looks like:
public ActionResult Edit(string id)
{
Report report = db.Reports.Find(id);
return View(report);
}
It accepts a string as an id, ReportId is the id used and it IS a string. It is a randomly generated GUID string made with the GUID.NewGuid().ToString() function. I will also be doing the comparison of names with:
Model.UserName == User.Identity.Name.ToString()
Which was shown earlier. Sorry if this is too much text, I wanted to provide as much info as possible and not make anyone mad. If more info is needed, it can certainly be provided. So at the end of the post, the major question actually comes down to: which of the above two methods is best? And, if it's the first one, how do I implement something like that?
Thanks for your help!
Unless I'm completely misunderstanding you, you just want .Where()
Like this:
var reports = db.Reports.Where(r => r.genre == inputGenre);
This would get you an IEnumerable of Report, which you could then use however you wish.

Categories