Saving CheckBox control values - asp.net

I am using asp.net and I am trying to save checkbox values into a database. Multiple checkboxes may be entered into the same field in the database. So for instance I have two checkboxes with names "Comma" and "Hyphen" and if the user checks both of these then the database will store the values ',','-'. How do you do this?
thanks

To save multiple values into the same column I'd recommend using a flag enumeration. Here is a code sample using checkboxes.
If you really have to store the values in a comma-delimited format, might try something like this:
List<string> values = new List<string>();
if (cbComma.Checked) {
values.Add("','");
}
...
string result = values.ToArray().Join(",");

I'd agree with David Thomas Garcia's recommendation if you can save the value to the database using the enumeration (as an int or whatever was appropriate for the amount of options you'll have).
If that's not an option though, and you are bound to storing them in the database as a string of characters I'd do something like the following:
private void LoadData()
{
string dbVal = DataAccess.GetDbVal(); //Get your value from the database.
chkComma.Checked = dbVal.Contains(",");
chkDash.Checked = dbVal.Contains("-");
}
private void SaveData()
{
string dbVal = "";
if(chkComma.Checked)
dbVal += ",";
if(chkDash.Checked)
dbVal += "-";
DataAccess.SaveDbVal(dbVal); //Send the value of dbVal to your data layer to be saved.
}
Note that this does not include any separation of the values to be saved in the value stored in the database, but if you needed that you could use a List and do what David Thomas Garcia mentioned with the .ToArray().Join(","); in the SaveData() and in the LoadData() just make dbVal a List and the syntax doesn't need change.

Related

How do I add an array of names in a single event?

In my application I can add more than one person at a time. I want to log multiple names in a single event.
I have a bunch of data is "Persons". Persons contains Name
In my application I can add more than one person at a time. I want to log multiple names in an event
What is the best way to log the data in AI?
The only way I can think of this, but its not the ideal way
foreach (Persons person in persons) {
if (person.IsNew)
{
personName += Person.Name + ",";
}
metricRecorder.AddProperty("personNameAdded", personName);
}
The above is not ideal way as when the data gets into AI, it would require regex to separate the name or even get the count of the names etc...
I can't find anything in the documents, how would I approach this?
You can add each name as a property of EventTelemetry.
A sample code like below, you can modify your code as per the sample:
TelemetryClient client = new TelemetryClient { InstrumentationKey = "xxxxxxxxxxxx" };
EventTelemetry eventTelemetry = new EventTelemetry();
eventTelemetry.Name = "event_1";
List<string> names = new List<string>();
names.Add("ivan");
names.Add("jack");
names.Add("nancy");
names.Add("tina");
names.Add("sarah");
int i = 0;
foreach (string n in names)
{
eventTelemetry.Properties.Add("name_"+i, n);
i++;
}
client.TrackEvent(eventTelemetry);
Then in the logs of application insights:

Add new tags on dcm4chee

I'm working with dcm4chee now,and I have the demand to add some custom fields,for example patient's ID card number,mobile fhone number and address.
After googling some related information,I am still confused and don't know what to do.Has any one ever done this?
i've done it on some other cases. In my case i've to modify existing tag with new value. Here the code, hope it give you some pointer.
public static void changementTag(File file, int tagChooser, String aModify, VR vr, String newString )
{
try
{
DicomInputStream dis = new DicomInputStream(file);
DicomObject dio = dis.readDicomObject();
dis.close();
String fileName = file.getAbsolutePath() + ".ori";
File originFile = new File(fileName);
file.renameTo(originFile);
boolean change = false;
dio.putString(tagChooser, vr, newString);
change = true;
if(change)
{
FileOutputStream fos = new FileOutputStream( new File(file.getParent()+ "/" + file.getName()));
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dos = new DicomOutputStream(bos);
dos.writeDicomFile(dio);
dos.close();
originFile.delete();
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
As already pointed out by #jap1968, you can add
Other Patient IDs (0010,1000)
to include any additional patient ID numbers. This attribute is part of the Patient Identification Module, which attributes are generally expected in most DICOM objects.
From the Patient Demographic Module, which is normally an optional set of attributes, you can then for example reuse these attributes:
Patient’s Telephone Numbers (0010,2154)
Patient’s Address (0010,1040)
Depending on which DICOM toolkit you are using to process your DICOM objects, there will be different methods for attribute insertion. In dcm4che, you should be able to use one of the available DicomObject.put... methods to insert a new value in your DICOM object. Just remember that for correctness, you should update the SOP Instance UID (and potentially other UID:s) for the modified object.
Have a look at these Dicom fields:
Other Patient IDs (0010,1000)
Other Patient IDs Sequence (0010,1002)
Maybe you do not need to add custom fields (at least for the patient ID card), but just use some of the already existing ones.

Using Auto Increment ID with ASP.NET checkbox list

First and foremost, I'm pretty new to programming, so attention to detail is appreciated.
I've currently got an asp checkbox list that receives data from an SQL table. I'm encountering a problem where if there's 2 items that are exactly the same, my remove function will remove both items. The following is the code for that:
protected void btn_remove_Click(object sender, EventArgs e)
{
for (int i = 0; i < UPCList.Items.Count; i++)
{
if (UPCList.Items[i].Selected)
{
var item = UPCList.Items[i];
var frcID = item.Value;
_itemNumberRepository.Delete(frcID);
}
}
Response.Redirect("WebForm2.aspx");
Response.End();
}
public string Delete(string itemCode)
{
string connectionString = foobar
Int32 returnDeleted = 0;
string deleteUpcCode =
"DELETE FROM compare1 "
+ string.Format("WHERE itemcode = '{0}'",itemCode);
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(deleteUpcCode, connection);
command.Connection.Open();
returnDeleted = command.ExecuteNonQuery();
command.Connection.Close();
}
return returnDeleted.ToString();
}
I've been told to use Auto Incrementing ID from SQL so that each row will have a unique ID so I can delete only the selected lines. However, I don't even have a clue how to do that. I've already turned on the identity option in SQL for the itemcode column, but aside from that, I'm lost. How do I go about using that ID to delete only selected items from the checkbox list in asp?
When you say the items are "exactly the same", do you mean that they have the same item code? And item codes are allowed to be duplicated in your system (i.e. is that the correct business rule)?
If so, that's why you need a auto-generated ID for each line, so that each row is unique. Which means that you need to use that ID in your DELETE query instead of the item code.
Typically, in a (ASP.NET) web app, this sort of thing is done with a "grid". You can use a GridView with two columns: one is a checkbox and another column is just a label showing the item code. Each row is bound to the ID field.
So, I recommend that you start by checking out GridView (there's lots of examples out there on the web): MSDN documentation for GridView

ASP.NET 4 : Comparing the result set of an object and a string

I am retrieving the contents of a database using a object (its returning only one field) and then comparing it with a string which has been hashed with SHA1 .The code is as follows :
protected void Onbutton_click_login(object sender, System.EventArgs e)
{
var dbcontext = new PrepLicensingSolution2010.DAL.LicensingEntities1();
var user = dbcontext.getloginname(loginName.Text);
string HashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(Password.Text, "sha1");
if (user.ToString() == HashedPassword)
{
Response.Redirect("faqs.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
I put breakpoints and checked the data at each stage of the flow and the data in the object result set and in the string are the same but even then the conditional if fails
whats interesting is both the types being compared are of the type string and of the same value,so why is that that the redirect goes to the default.aspx page.
The image contains the data from the breakpoints
Any inputs would be great.
Thanks
Based on the screenshot, user.ToString() looks to be returning the string {System.Data.Objects.ObjectResult<string>}. This, of course, does not equal the hashed password.
Your problem is that the result of your getloginname call is a sequence of strings containing a single string, not a single string itself. The default implementation of ToString() simply returns the class name, and you can see it in the Value column for the "user" row in the screenshot. Changing your conditional statement to the following should fix it:
if (user.FirstOrDefault() == HashedPassword)

Change Single URL query string value

I have an ASP.NET page which takes a number of parameters in the query string:
search.aspx?q=123&source=WebSearch
This would display the first page of search results. Now within the rendering of that page, I want to display a set of links that allow the user to jump to different pages within the search results. I can do this simply by append &page=1 or &page=2 etc.
Where it gets complicated is that I want to preserve the input query string from the original page for every parameter except the one that I'm trying to change. There may be other parameters in the url used by other components and the value I'm trying to replace may or may not already be defined:
search.aspx?q=123&source=WebSearch&page=1&Theme=Blue
In this case to generate a link to the next page of results, I want to change page=1 to page=2 while leaving the rest of the query string unchanged.
Is there a builtin way to do this, or do I need to do all of the string parsing/recombining manually?
You can't modify the QueryString directly as it is readonly. You will need to get the values, modify them, then put them back together. Try this:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("page", "2");
string url = Request.Url.AbsolutePath;
string updatedQueryString = "?" + nameValues.ToString();
Response.Redirect(url + updatedQueryString);
The ParseQueryString method returns a NameValueCollection (actually it really returns a HttpValueCollection which encodes the results, as I mention in an answer to another question). You can then use the Set method to update a value. You can also use the Add method to add a new one, or Remove to remove a value. Finally, calling ToString() on the name NameValueCollection returns the name value pairs in a name1=value1&name2=value2 querystring ready format. Once you have that append it to the URL and redirect.
Alternately, you can add a new key, or modify an existing one, using the indexer:
nameValues["temp"] = "hello!"; // add "temp" if it didn't exist
nameValues["temp"] = "hello, world!"; // overwrite "temp"
nameValues.Remove("temp"); // can't remove via indexer
You may need to add a using System.Collections.Specialized; to make use of the NameValueCollection class.
You can do this without all the overhead of redirection (which is not inconsiderable). My personal preference is to work with a NameValueCollection which a querystring really is, but using reflection:
// reflect to readonly property
PropertyInfo isReadOnly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isReadOnly.SetValue(this.Request.QueryString, false, null);
// remove
this.Request.QueryString.Remove("foo");
// modify
this.Request.QueryString.Set("bar", "123");
// make collection readonly again
isReadOnly.SetValue(this.Request.QueryString, true, null);
Using this QueryStringBuilder helper class, you can grab the current QueryString and call the Add method to change an existing key/value pair...
//before: "?id=123&page=1&sessionId=ABC"
string newQueryString = QueryString.Current.Add("page", "2");
//after: "?id=123&page=2&sessionId=ABC"
Use the URIBuilder Specifically the link textQuery property
I believe that does what you need.
This is pretty arbitrary, in .NET Core at least. And it all boils down to asp-all-route-data
Consider the following trivial example (taken from the "paginator" view model I use in virtually every project):
public class SomeViewModel
{
public Dictionary<string, string> NextPageLink(IQueryCollection query)
{
/*
* NOTE: how you derive the "2" is fully up to you
*/
return ParseQueryCollection(query, "page", "2");
}
Dictionary<string, string> ParseQueryCollection(IQueryCollection query, string replacementKey, string replacementValue)
{
var dict = new Dictionary<string, string>()
{
{ replacementKey, replacementValue }
};
foreach (var q in query)
{
if (!string.Equals(q.Key, replacementKey, StringComparison.OrdinalIgnoreCase))
{
dict.Add(q.Key, q.Value);
}
}
return dict;
}
}
Then to use in your view, simply pass the method the current request query collection from Context.Request:
<a asp-all-route-data="#Model.NextPageLink(Context.Request.Query)">Next</a>

Resources