how to change people picker value in infopath form after every form updating - infopath

I have a state machine workflow and related task. Task can be edited until it satisfy some conditions. Task formed by infopath. These task contains one people picker field. I assign 3 fields with these values:
private void createTask_Operator_MethodInvoking(object sender, EventArgs e)
{
this.createTask_Id = Guid.NewGuid();
this.createTask_Properties.ExtendedProperties["ows_TaskDisplayName"] = "user1";
this.createTask_Properties.ExtendedProperties["ows_TaskAccountId"] = #"SP\user1";
this.createTask_Properties.ExtendedProperties["ows_TaskAccountType"] = "User";
}
It is works, I can see in my form value these user. But when I change the user(for example: "user2") and submit the form, I cannot retrieve my manually changed field value, it always returns values of "user1".
private void onTaskChanged_Operator_Invoked(object sender, ExternalDataEventArgs e)
{
this.onTaskChanged_AfterProperties = this.onTaskChanged.AfterProperties;
this.onTaskChanged_BeforeProperties = this.onTaskChanged.BeforeProperties;
// here I cannot retrieve changed field value, always returns: SP\user1
this.workflowProperties.Item["UserName"] =
this.onTaskChanged_AfterProperties.ExtendedProperties["TaskAccountId"].ToString();
this.workflowProperties.Item.Update();
}
Please, if you faced such problem, help me with that...

I'm having a little trouble understanding your problem, but here are two answers. To successfully set the value of a people picker field, you have to correctly populate all three fields: DisplayName, AccountId, and AccountType. AccountType is always "User", but the other two have to align with your AD or wherever you're getting your user data from. To get data from a people picker, the best solution often includes the double eval trick: eval(eval(person, "concat(my:AccountId, ';')"), "..") This handles multiple entries correctly, if you mean that you're only getting the first in the list.

Related

asp.net dynamic data web site : passing default value while inserting/updating records

I am working in ASP.NET Dynamic Data web application and have an issue of passing default value while inserting/updating records. In my application all table has following common column:
CreatedBy (Default Value : Logged in user)
CreatedDate (Default Value : DateTime.Now)
modifiedBy (Default Value : Logged in user)
ModifiedDate (Default Value : DateTime.Now)
I want to keep these column hide in Insert and Edit page and want that default value will be inserted automatically in the respective column.
Please suggest me.
Thanks
paul
I see you are doing simple Auditing have a look at my blog post here Basic Auditing for Dynamic Data with Entity Framework 4.x hope that helps.
It's never good to do this sort of thing in the page, it's always best to do it in your data model/layer. You can use my A New Way To Do Column Generation in Dynamic Data ... to hide the columns in all pages.
Ref:
Maintaining a Log of Database Changes - Part 1
In order to maintain a history of changes to the database's data we
need to record every insert, update, and delete to some sort of
"history" table. In addition to capturing the data that was inserted,
updated, or deleted, we also need to note what user made the
modification, as well as the date and time it was made.
More Reference:
Best design for a changelog / auditing database table?
Log changes to database table with trigger
To customize ORM Entity Framework check following links:
How to use Default column value from DataBase in Entity Framework?
How to: Execute Business Logic When Saving Changes
solution i have implemented finally:
protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
e.Values.Add("CreatedBy", HttpContext.Current.User.Identity.Name);
e.Values.Add("CreatedDate", DateTime.Now);
}
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
e.OldValues.Add("ModifiedBy", null);
e.OldValues.Add("ModifiedDate", null);
e.NewValues.Add("ModifiedBy", HttpContext.Current.User.Identity.Name);
e.NewValues.Add("ModifiedDate", DateTime.Now);
}
My solution is a bit different from Paul's requirements.
In the file DynamicData\PageTemplates\Insert.aspx.cs I made edits to show my defaults for new records in any table having the shared fields. The user can still put in something else on insert.
public partial class Insert : System.Web.UI.Page
{
protected MetaTable table;
protected void Page_Init(object sender, EventArgs e)
{
table = DynamicDataRouteHandler.GetRequestMetaTable(Context);
var values = table.GetColumnValuesFromRoute(Context);
// set default values for meta data of new records across all tables
// unknown values will be skipped
values.Add("creationDate", DateTime.Now);
values.Add("modificationDate", DateTime.Now);
values.Add("modificationUser", HttpContext.Current.User.Identity.Name.Substring(
HttpContext.Current.User.Identity.Name.IndexOf("\\") + 1));
FormView1.SetMetaTable(table, values);
DetailsDataSource.EntityTypeFilter = table.EntityType.Name;
}
[...]
}
For editing records with existing values, I made changes to some DynamicData\FieldTemplates files.
public partial class Text_EditField : System.Web.DynamicData.FieldTemplateUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
// ...
// show current user as value for the modification user upon editing records
if (Column.Name == "modificationUser")
{
FieldValue = Page.User.Identity.Name.Substring(Page.User.Identity.Name.IndexOf("\\") + 1);
}
}
[...]
}
It will show the updated value on the page for editing, but after updating the changes won't persist! An additional change to the Edit page template is required:
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
// make sure a meta data update is always triggered by setting a different old value
// required for the edit components
if (e.OldValues.Contains("modificationUser"))
{
e.OldValues["modificationUser"] = string.Empty;
e.OldValues["modificationDate"] = DateTime.MinValue;
}
}

ASP Multiselect listbox separator

I have encountered a problem and I didn't manage to find any soultions yet. Let me simplify things a bit.
I have 2 forms, the first contains an ASP ListBox with multi select mode enabled. I submit the form and in the other form I use just for testing purposes this snippet of code:
protected void Page_Load(object sender, EventArgs e)
{
foreach (string formKey in Request.Form.AllKeys)
{
if (formKey != null)
{
if (formKey.Equals("ctl00$MainContent$ListBox1"))
Label1.Text = Request.Form[formKey];
}
}
}
The problems is that the values that come from the listbox (the values that i selected in the previous form) are separated by "," for ex. "test1,test2,test3". How can i change this separator to "$" for example? I need to change it because the actual values may contain "," and i don't manualy feed them to the listbox.
I can't use any other mode of transfering this values between the form because the entire application uses this model. The values that i get are then sent to a workflow where there will be manipulated and in the workflow i need to know where each listbox item starts and ends so it must be an unique separator.
Any help is apreciated! Thank you very much
Thank you MatteKarla but unfortunately this does not solve my problem. Yes, this is a good way of transfering the values from one form to another.
However i must use the method I described above with Request form keys because the listbox is one of many others "parameters" that are generated at runtime and have their values sent to a workflow method that takes this values. And i can't afford to change that in my application.
My problem is that coma (",") separator is used by default with a multiselect listbox.
I thought that there maybe is a method to change that separator from coma to another char because the coma can also be included in the value itself and this will create confusion.
As i said if i select three values test1, test2 and test3, the result with my method will be a string looking like "test1,test2,test3". However a "test1$test2$test3" would be much better.
But I'm affraid that changing this default separator is not possbile. I must think at a method to overcome this problem like replacing before feeding the listbox all the intended coma from the values with some other char not to create confusion. But this is not a great way of doing it.
On your first page/form (First.aspx.cs) create a public property with the listbox:
public ListBox PostedListBox { get { return ListBox1; } }
Set the postback-url for the button to Second.aspx
Second page in the aspx-file after the #Page-directive add:
<%# PreviousPageType VirtualPath="~/First.aspx" %>
Then in Form_Load on Second.aspx.cs you can extract the values:
if (PreviousPage != null)
{
ListBox postedListbox = PreviousPage.PostedListBox;
foreach (var index in postedListbox.GetSelectedIndices())
{
var itemText = postedListbox.Items[index].Text;
}
}
Or you could just try to locate the control by using:
if (PreviousPage != null)
{
var control = PreviousPage.FindControl("ListBox1") as ListBox;
}
Third Edit:
You could use GetValues:
Request.Form.GetValues("ctl00$MainContent$ListBox1");
returns a string array containing each of the selected items.

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)

Adding TextBocex, CheckBoxes on Request C#

I will be starting a project soon at my company and the client would like to have the option in the portal to add textboxes or checkboxes as an administrator,,, so for instance initially I may have something like
Name [textBox]
Phone [textBox]
So the client would like to log in as an admin and be able to add
Name [textBox]
Phone [textBox]
Receive Brochure [checkBox] //added by client.
Forget about the portal and the admin part.. what I would like to know is what would be the best way to design this (the user to be able to add elements)
Any ideas would be much appreciated
Regards
You could create an additional aspx-form in which the User (or the Admin) is able to define and create his/her own forms, you supply the Variable names and they choose to add the controls, save it in a specific scheme in the Database, e.g.
UserForm:
UserID FormID
Form:
FormID FormName
FormElement:
FormID VariableName ControlType Index
Of course this could also be done by an administrator and be visible by everyone.
To view the specific forms you could add yet another aspx-page containing the following code:
protected void Page_Load(object sender, EventArgs e)
{
//you saved the FormName or ID to Session when you accessed it
string formName = Session["FormName"].ToString();
//this handles getting the elements for this Form from DB
List<FormElement> elementList = FormElement.GetForForm(formName);
this.renderForm(elementList);
}
private void renderForm(List<FormElement> eList)
{
foreach(FormElement fe in eList)
{
//Labels left, Controls right, of course this is just a design decision
if(fe.Index%2==1)
{
Label lbl = new Label();
lbl.Text = fe.Variable;
lbl.ID = fe.ControlType + fe.Variable;
divLeft.Controls.Add(lbl);
}
else
{
dynamic ctrl = null;
switch (fe.ControlType)
{
case "TextBox":
ctrl = new TextBox();
break;
case "CheckBox":
ctrl = new CheckBox();
break;
default:
break;
}
ctrl.ID = fe.ControlType + fe.Variable;
divRight.Controls.Add(ctrl);
}
}
}
Later on after the User hitting submit you'd be able to receive the values entered into those Controls by accessing divRight.FindControl(fe.ControlType + fe.Variable) since that should be unique per Form.
This approach assumes you're using .NET 4.0 (because of dynamic), but of course you can do this just fine without it, it'll just be more code.
Please let me know if this is what you searched for or if it was helpful.
Thanks,
Dennis
From what I have done in the past where I had to create a dynamic survey based on a client needs. I had a database that contained the following tables:
Survey - stores list of client surveys.
Controls - listed the type of controls that would be needed. For example, textbox, checkbox etc.
Survey Controls - links all the controls required for a survey.
User values - stores the values entered in a controll based on the survey used.
I then added some logic to dynamically create the controls based on a survey selected by reading the values from my database.

How to find number of elements when adding and deleting elemnts dynamically using jQuery?

I'm working on a web application (with ASP.NET 2.0 (C#) and jQuery)
In my application we have an interface using which our employees are able to enter records of a comany. We provided the interface with basic fields, Company Name, Contact Person, phone, etc. Now as you know some companies have thier branches, some have few (1 to 10) and some have many (100-200) branches. We have also provided a dynamic interface using jQuery, which allows our employees to add branches depending on number of branches a particular company have.
For addition, we have used jQuery's append function as ..
$("#branches").append("branch html fields text liek a html input field with id 'Namebranch1' ");
Now, with adding we have also provided a button with evey branch field seprately for deleting that particular branch. For deleting I have used
$("#branch1").remove()
Let's say, I have added 5 branches, then before submitting, I feel that branch number 3 is not necessary to enter, So I have deleted that branch data.
So the process of adding and removing is as follows, we have added
1,2,3,4,5
Then, We deleted 3rd branch and now we have
1,2,4,5
Now as we have 4 elements, so whenever my user is adding or deleting a branch I am adding 1 and substracting 1 from a javascript variable respectively. And then entering that variable in a hidden field, so that when user submit data then I'll have the correct number of count that how any branches are added by the user and on the basis of this count, I know that how many times I have to run the loop to catch up all branches data seprately.
But the problem is when user submit the form then I am running a loop 4 times, what it means, I'll get data of 1,2 and 4 branches but as loop will stop when it completed 4 cycles then, data of 5th branch which is actully 4 will be missing. Because elements which will be posted when user will sibmit form are as (branchName5, branchTitle5 etc.)
I hope you guys understand what I need? Please tell me some logical solution of this problem.
Thanks
Get rid of the hidden counter variable, and just iterate through Request.Form.Keys looking for branch*. Then, you'll just process any form variables that start with branch.
class Branch { public string Name; public string Title; }
void OnLoad(EventArgs e) {
base.OnLoad(e);
var branches = new Dictionary<int, Branch>();
foreach (string key in Request.Form.Keys) {
if (!key.StartsWith("branch")) continue;
int id;
if (key.StartsWith("branchTitle")) {
id = int.Parse(key.Substring("branchTitle".Length));
branches.Ensure(i).Title = Request.Form[key];
} else if (key.StartsWith("branchName")) {
id = int.Parse(key.Substring("branchName".Length));
branches.Ensure(i).Name = Request.Form[key];
}
}
}
// Ensure extension method
T Ensure<K, T>(this Dictionary<K, T> d, K key) where T:new {
if (!d.ContainsKey(key)) {
d.Add(key, new T());
}
return d[key];
}
maybe this is a clue? in submit do ....
$('#branches').each( function (i) { this.id = 'branch' + i } );

Resources