Hello I want to make a button visibile when UserId stored in database match with current UserId.
string clientId = Context.User.Identity.GetUserId();
JobDescriptions job = new JobDescriptions();
if (job.PostedBy == clientId)
{
Button2.Visible = true;
else
{
Button2.Visible = false;
}
PostedBy is the Id of the user who posted on website saved on jobs table. Problem is that button is not visibile when my statement should work.
The solution
if (!String.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
int id = Convert.ToInt32(Request.QueryString["id"]);
JobReqModel model = new JobReqModel();
JobDescriptions job = model.GetJob(id);
string clientId = Context.User.Identity.GetUserId();
if (job.PostedBy == clientId)
{
Button2.Visible = true;
}
else
{
Button2.Visible = false;
}
}
Related
Context is not saving to the database no matter what i do it will insert a new record fine but not save. This is using sql server and the user had permissions ot update data have already checked this
private void btnOk_Click(object sender, EventArgs e)
{
SourceContext SourceDal = new SourceContext();
Appointment _appointment = new Appointment();
int errorCount = 0;
Patient _patient = new Patient();
_patient = SourceDal.getPatientByPatientId(txtPatientId.Text);
_patient.SSN = txtSSN.Text;
_patient.FirstName = txtPatientFirstName.Text;
_patient.LastName = txtPatientLastName.Text;
_patient.Middle = txtPatientMiddle.Text;
_patient.AddressOne = txtPatientAddressOne.Text;
_patient.City = txtPatientCity.Text;
_patient.State = txtPatientState.Text;
_patient.ZipCode = txtPatientZip.Text;
_patient.HomePhone = txtPatientHomePhone.Text;
_patient.WorkPhone = txtPatientWorkPhone.Text;
_patient.CellPhone = txtPatientCellPhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnWorkPhone.Checked == true)
_patient.ApptPhone = txtPatientWorkPhone.Text;
_patient.BirthDate = dtBirthDate.DateTime;
_patient.emailAddress = txtPatientEmail.Text;
_patient.Race = (int)dpRace.SelectedValue;
_patient.Ethnicity = (int)dpEthnicity.SelectedValue;
_patient.Language = (int)dpLanguages.SelectedValue;
_patient.AlertNote = txtPatientNotes.Text;
if (dpGender.Text == "")
{
dpGender.Focus();
errorCount = 1;
lblGenderRequired.Text = "* Gender is required.";
}
else
{
errorCount = 0;
lblGenderRequired.Visible = false;
}
_patient.Gender = dpGender.Text.Substring(0, 1);
_patient.PatientID = txtPatientId.Text;
txtPatientFirstName.Text = _patient.FirstName;
txtPatientLastName.Text = _patient.LastName;
// IF ITS SAVE NEW GO AHEAD ADD IT TO THE CONTEXT.
SourceDal.AddToPatient(_patient);
}
Add to paitent has the following
public void AddToPatient(Patient newPatient)
{
using (var myContext = new SMBASchedulerEntities(this.Connectionstring))
{
myContext.Patients.Add(newPatient);
if (newPatient.ID == 0)
{
myContext.Entry(newPatient).State = EntityState.Added;
}
else
{
myContext.Entry(newPatient).State = EntityState.Modified;
}
try
{
myContext.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Console.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
}
It adds in the record fine but it just wont save the current record no matter what i do even though all the details are correct. But when i reload the form and the application the update is not there the email address is not saved no are any the other updates.
I suspect I'm not familiar with that entity framework, as I'm unfamiliar with the some of that syntax, but you should be able to use something like this:
public void AddToPatient(Patient newPatient)
{
SMBASchedulerEntities dbContext = new SMBASchedulerEntities();
if (newPatient.ID.ToString() != "0")
{//Update the record
Patient updatePatient = dbContext.Patients.Single(p => p.ID == newPatient.ID);
updatePatient.FirstName = newPatient.FirstName;
updatePatient.LastName = newPatient.LastName;
...
...
dbContext.SubmitChanges();
}
else
{//Insert a new record
Patient insertPatient = new Patient();
insertPatient.FirstName = newPatient.FirstName;
insertPatient.LastName = newPatient.LastName;
...
...
dbContext.Patients.InsertOnSubmit(insertPatient);
dbContext.SubmitChanges();
}
}
To put this another way, check to see if you need to insert or update a new patient first, before inserting it every time.
I have a 3Layer ASP.NET project. I use a Login control with custom Login1_Authenticate. So I force Login control to use my own database and users. but the problem is adding roles to my users. control works fine with database, but I dont know how to add roles to my own users.
(note 1: I don't want to use "Web Site Administration Tool" to manage my users.)
(note 2: I configured aspnet_regsql.exe to my own database. but don't know hot to continue. )
my code:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
e.Authenticated = false;
try
{
BL_login G = new BL_login();
G.username = Login1.UserName.Trim();
G.password = Login1.Password.Trim();
if (G.SelectAdmin().Rows.Count != 0)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "Default.aspx";
Roles.AddUserToRole(G.username, "admin");
//Roles.AddUserToRole(G.username, "user");
}
else if (G.SelectUser().Rows.Count != 0)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "Default.aspx";
Roles.AddUserToRole(G.username, "user");
}
else { e.Authenticated = false; }
}
catch
{
e.Authenticated = false;
}
}
public class BL_login : DataAccess
{
//---
public string username;
public string password;
public DataTable SelectAdmin()
{
base.Link();
string Query = "SELECT users.idUser AS [کد کاربری], zones.nam AS [منطقه], users.state AS [وضعیت], users.username AS [نام کاربری], users.password AS [رمز عبور], users.role AS [دسترسی] FROM users INNER JOIN zones ON users.idZone = zones.idZone WHERE users.username='{0}' AND users.password='{1}' AND users.state='{2}'AND users.role='{3}' ";
Query = string.Format(Query, username, password, "1", "admin");
DataTable Output_Q = base.SelectDataText(Query);
base.UnLink();
return Output_Q;
}
public DataTable SelectUser()
{
base.Link();
string Query = "SELECT users.idUser AS [کد کاربری], zones.nam AS [منطقه], users.state AS [وضعیت], users.username AS [نام کاربری], users.password AS [رمز عبور], users.role AS [دسترسی] FROM users INNER JOIN zones ON users.idZone = zones.idZone WHERE users.username='{0}' AND users.password='{1}' AND users.state='{2}'AND users.role='{3}' ";
Query = string.Format(Query, username, password, "1", "user");
DataTable Output_Q = base.SelectDataText(Query);
base.UnLink();
return Output_Q;
}
//---
}
Presuming that you are using ASP.NET Membership:
if (G.SelectAdmin().Rows.Count != 0)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "Default.aspx";
Roles.AddUserToRole(G.username, "SomeRole");
}
I am trying to do a 3 tier volunteers sign up for packaging session system. First, on the page load, I get the details of certain packaging session:
if (!IsPostBack)
{
string packingID = Request.QueryString["id"];
packingIndv = packing.getPacking(packingID);
if (packingIndv == null)
{
lbl_msg.Text = "Error in getting packing session details!";
}
else
{
lbl_ID.Text = packingIndv.packingID;
lbl_date.Text = packingIndv.date.ToString("dd/M/yyyy", CultureInfo.InvariantCulture); ;
lbl_location.Text = packingIndv.location;
lbl_volunteerAvailable.Text = packingIndv.volunteerAvailable.ToString();
lbl_status.Text = packingIndv.status;
}
}
After that, volunteers can click on the join button, and the program will execute:
In presentation layer after join button is on click:
string userLogged = Session["userLogged"].ToString();
UserBLL user = new UserBLL();
string userID = user.getUserIDByName(userLogged);
PackingBLL packing = new PackingBLL();
string msg = "";
msg = packing.joinPacking(userID, lbl_ID.Text);
lbl_msg.Text = msg;
In business logic layer:
public string joinPacking(string userID, string packingID)
{
string returnMessage = "";
if(returnMessage.Length == 0)
{
Packing packing = new Packing(userID, packingID);
Boolean success = packing.checkJoinedSession();
if (success)
{
returnMessage += "Same volunteer cannot join same packing session for more than once! <br/>";
}
else
{
int nofRows = 0;
nofRows = packing.joinPacking();
if (nofRows > 0)
{
returnMessage = "Request to volunteer for packing session saved successfully.";
int successUpdate = packing.updateRemaining();
if (successUpdate > 0)
{
getPacking(packingID);
}
}
else
{
returnMessage = "Error! Please try again.";
}
}
}
return returnMessage;
}
In data access layer:
public int updateRemaining()
{
int result = 0;
using (var connection = new SqlConnection(FFTHDb.connectionString)) // get your connection string from the other class here
{
SqlCommand command = new SqlCommand("UPDATE PackingSession SET volunteerAvailable = volunteerAvailable + 1 WHERE packingID = '" + packingID + "'", connection);
connection.Open();
result = command.ExecuteNonQuery();
connection.Close();
}
return result;
}
For every join from each volunteer, the volunteer available will be increased by one. What I am trying to do is from the page load, I display the details of packaging session. Then when volunteer joins it, the volunteerAvailable will straight away increased by one. All my database works perfectly, it just wont increase the volunteer available automatically after each successful update sql statement, as in I have to refresh the browser in order to see the changes.
i am trying to set a value from server side in this code. i have a textbox to enter ticket number and when the ticket is validated and activated, i want the used property of this particulare ticket to be changed to true.
i have this code :
TicketBLL Tickets = new TicketBLL();
ClientDeviceBLL Devices = new ClientDeviceBLL();
if (String.IsNullOrEmpty(txtTicket.Text))
{
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVMember.Enabled = false;
CVMember.Visible = false;
CVInValid.Enabled = false;
CVInValid.Visible = false;
lblMessages.Text = MessageFormatter.GetFormattedErrorMessage("You can login using a Ticket Number.");
txtTicket.Focus();
}
else
{
Ticket = Tickets.GetTicketByTicketNumber(txtTicket.Text);
////// we must enter the value of the correct SN and the Client ID
Device = Devices.GetClientDeviceBySN(txtSN.Text , Convert.ToInt32(txtClientID.Text));
if (Ticket != null)
{
//Correct Ticket number
CVInValid.Visible = false;
CVInValid.Enabled = false;
if (Ticket.Used == true)
{
//ticket was used, internet forbidden
CVUsed.Visible = true;
CVUsed.Enabled = true;
CVMember.Enabled = false;
CVMember.Visible = false;
CVUsed.IsValid = false;
}
else
{
//if exists but not used, Ticket accepted
//check if device is a member if client divices
if (Device != null)
{
//internet access garanteed
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVMember.Enabled = false;
CVMember.Visible = false;
CVUsed.IsValid = true;
CVMember.IsValid = true;
//here is my error.
//ticket.used is not changing in the database so the next
//time he enters the same ticket number it would go through
//again.
Ticket.Used = true;
Response.Redirect("http://www.google.com");
}
else
{
//device not member, internet access forbidden
CVMember.Enabled = true;
CVMember.Visible = true;
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVUsed.IsValid = true;
CVMember.IsValid = false;
}
}
}
else
{
//Ticket Number is not valid
CVUsed.Visible = false;
CVUsed.Enabled = false;
CVMember.Enabled = false;
CVMember.Visible = false;
CVInValid.Enabled = true;
CVInValid.Visible = true;
CVInValid.IsValid = false;
}
}
how can i automatically update the ticket.used value in the database?!
Without making a connection to database you cannot update the value of ticket.used. If you want to know how to connect to database and update, use stored procedures of direct queries to do your work. Take a look at this.
I have the following code which creates a Task in Salesforce and then tracks a user's browsing history and stores it in SalesForce. Currently, it displays each and every page the user has browsed as an individual entry. I want to group all those entries together in the Browsing_History__c object instead of task being created every time a user visits a page.
Any help would be appreciated..I am not familiar with SF very much. :)
private void CreateTaskInSF(string id, string type, string details, string description)
{
// if there's a similar Event in the past 2 hours, don't add it
QueryResult qr = null;
try // get events from past 2 hours
{
qr = Binding.query("Select Details__c from Task WHERE WhoId='" + id + "' and Type__c='" + type + "' and CreatedDate > " + DateTime.UtcNow.AddHours(-2).ToString("s") + "Z");
}
catch (Exception e)
{
return;
}
bool logged = false;
if (qr != null) // if there are Tasks in past 2 hours
{
sforce.sObject[] browsing = qr.records;
if (browsing != null)
{
// iterate through events to make sure the new Task isn't logged
for (int i = 0; i < browsing.Length; i++)
{
Task currTask = (Task)browsing[i];
if (currTask.Details__c == details)
{
if (description != "") // is there a description to check for?
{
string oldTaskDescription = "";
if (currTask.Description != null)
oldTaskDescription = currTask.Description;
if (oldTaskDescription == description) // if there is a description match
logged = true;
}
else
logged = true; // there's no description, so check only on details field
}
}
}
}
if (logged == true)
{
return; // if Activity is already logged, don't log it again
}
else if (type == "Browsing")
{
QueryResult browsingQuery = null;
try // get events from past 2 hours
{
browsingQuery = Binding.query("Select Web_Browsing__c from Task WHERE WhoId='" + id + "' and Subject='" + type + "' and Details__c='" + details + "' and CreatedDate > " + DateTime.UtcNow.AddHours(-2).ToString("s") + "Z");
}
catch
{
}
Boolean createNewBrowsing = false;
if (browsingQuery != null) // if there are Tasks in past 2 hours
{
sforce.sObject[] webBrowsing = browsingQuery.records;
if (webBrowsing != null)
{
//find correct object and update Browsing_History__c
//Binding.update
}
else
{
createNewBrowsing = true;
}
}
else
{
createNewBrowsing = true;
}
if (createNewBrowsing)
{
Web_Browsing__c newTask = new Web_Browsing__c();
newTask.Lead__c = id;
newTask.Browsing_History_255__c = details;
newTask.Type__c = type;
newTask.Browsing_History__c = details;
newTask.CreatedDate = DateTime.Now;
//if(type == "Browsing") newTask. = details;
//SaveResult[] createResult = Binding.create(new sObject[] { newTask });
try
{
SaveResult[] createResult = Binding.create(new sObject[] { newTask });
}
catch (Exception e)
{
return;
}
}
}
else
{
// if this new Activity isn't logged, then create a new Activity Task
sforce.Task newTask = new sforce.Task();
newTask.WhoId = id;
newTask.Subject = type;
newTask.Details__c = details;
if (description != "") newTask.Description = description;
newTask.Status = "Completed";
newTask.Priority = "Normal";
newTask.ActivityDate = DateTime.Now;
newTask.ActivityDateSpecified = true;
// insert it
try
{
SaveResult[] createResult = Binding.create(new sforce.sObject[] { newTask });
}
catch (Exception e)
{
return;
}
}
}
You'll need to update your query to ask for the browsing history object and update the code to create a browsing history object instead of a task.
If you haven't already, review the Web Services API docs, it has examples for querying and creating in java/c#.