dropdown values according to rights - asp.net

There is multiple values in that dropdown ..
e.g.
Car
Truck
Bike
Drink
Factory
There is another login page Login.aspx .
Login code
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//Label1.BackColor = "F8D8D7";
loginmethod(txt_us.Text, txt_pwd.Text);
Response.Redirect("WebForm1.aspx");
}
catch( Exception )
{
Label1.Text = ("Incorrect UserName/Password");
Label1.Visible = true;
}
txt_us.Text = "";
txt_pwd.Text = "";
}
public bool loginmethod(string UserName,string Password)
{
TrackDataEntities1 td = new TrackDataEntities1();
splogin1_Result sp = td.splogin1(UserName, Password).FirstOrDefault();
if(sp.Password==txt_pwd.Text)
{
return true;
}
else
{
return false;
}
}
Now there is two users .. admin and user . Now i want when admin login then with their id and password then he see some values from this list and when user login then he will see some values from this list for example when admin login then he may able to see only Factory value and when user login then he able to see all values except factory
UPDATE
in login.aspx i save username is session
Session["UserName"] = txt_us.Text;
in form.aspx
Here first i create sp
ALTER procedure [dbo].[spadminlist]
as
select Region from tblReg
where Region in ('Factory')
then i add this sp in form.aspx
//this linq query for selecting all values
var list = tea.tblReg.AsEnumerable()
.Where(x => !x.Region.Any(char.IsDigit) && (x.Region != ""))
.GroupBy(x => x.Region)
.Select(x => new { Region = x.Key, Value = x.Key })
.ToList();
//this is for admin
if (Session["UserName"] = "admin")
{
List<spadminlist_Result> admin = tea.spadminlist().ToList();
}
and filling dropdown
if (!Page.IsPostBack)
{
regiondrop.DataSource = list;
regiondrop.DataTextField = "Region";
regiondrop.DataValueField = "Region";
regiondrop.DataBind();
Label4.Visible = false;
}
but this show error and also how i fill dropdown with admin sp because there is queries
Error 3 Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?)
how i do this ?

For Dynamic list:
Get from the backend whether user is admin or normal user.
List<string> menuItems = new List<string>();
if(logged_user == "ADMIN")
{
menuItems.add("item1");
menuItems.add("item2");
}
else
{
menuItems.add("item1");
menuItems.add("item2");
}
DropDownList1.DataTextField = "user_name";
DropDownList1.DataValueField = "user_id";
DropDownList1.DataSource = menuItems;
DropDownList1.DataBind();
For Static list:
if(logged_user == "ADMIN")
{
DropDownList1.Items.FindByText("Item1").Enabled = false;
OR
DropDownList1.Items[i].Enabled = false;
}
else
{
Same process as above.
}
DropDownList1.DataTextField = "user_name";
DropDownList1.DataValueField = "user_id";
DropDownList1.DataBind();

Related

How to refresh ListView in previous activity by updating DB in current activity?

I am using Xamarin Android. In the current activity i am having an editing form and on button click event i have an update query in the current activity.
private void OnclickSaveDATAButton(object sender, EventArgs e)
{
var CNICCARDNUMBER = Intent.Extras.GetString("NIC");
var conn = Connection();
conn.BeginTransaction();
var hf = conn.Table<mof>();
var search = hf.Where(x => x.CNICNO == CNICCARDNUMBER).ToList().FirstOrDefault(); //Linq Query
var Hofid = Convert.ToString(search.HOFID);
var data = conn.Query<hof>("UPDATE hof SET HOFNAME = ? WHERE HOFID = ?", Name.Text, Hofid);
conn.Commit();
if (data!= null)
{
Toast.MakeText(this,"Updated Successfully", ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "Update failed", ToastLength.Short).Show();
}
}
When I go back to previous activity on back button event
public override void OnBackPressed()
{
Intent intent = new Intent(this, typeof(SearchingActivity));
intent.SetFlags(ActivityFlags.ClearTop);
StartActivity(intent);
}
In the previous activity i am having select query on tab selection event. when i select the tab, I want to refresh the ListView and display the updated data instead of old one.
else if (CurrentTab.Position == 1)
{
Gridd = (ListView)FindViewById(Resource.Id.gridview);
Gridd.Visibility = ViewStates.Visible;
var CNICCARDNUMBER = Intent.Extras.GetString("cnic");
var conn = Connection();
var Hofid = 2;
data1 = new List<string>();
var data = conn.Query<combine>("SELECT hof WHERE hof.HOFID=?", Hofid);
foreach (var values in data)
{
data1.Add("CNIC:" + Convert.ToString(values.CNICNO));
data1.Add("Health card Number:" + Convert.ToString(values.CARDNO));
}
Gridd = (Listview)FindViewById(Resource.Id.gridview);
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, data1);
if (data1.Count() > 0)
{
Gridd.SetAdapter(adapter);
// Gridd.Adapter = adapter;
Gridd.ItemClick += Gridd_ItemClick;
}
else
{
Toast.MakeText(this, "No Data returned.", ToastLength.Short).Show();
}
}
Q: How to achieve this?
You can get the new data from DB and then call the listviewAdapter.OnNotifyPropertyChanged() in your onResume() method of your previous activity.
That would refresh your list.

AspNetUsers cannot update custom column

So I have the problem with .net identity model. I created boolean variable IsEnabled in my ApplicationUserManager, trying to make a "block account" method. So it's working fine, anybody with IsEnabled=false cannot login in to my site. The problem is while Im trying to implement administartion method for this variable (Block_Account() for example) I cannot persist my changes in a user. Here is a code;
protected void Block_Click(object sender, EventArgs e)
{
string itemID;
using (GridViewRow row = (GridViewRow)((Button)sender).Parent.Parent)
{
HiddenField lUId = (HiddenField)row.FindControl("ClientId");
itemID = lUId.Value;
}
var user = Context.GetOwinContext().Get<ApplicationDbContext>().Users.Where(a => a.Email == itemID).FirstOrDefault();
//Label1.Text = user.UserName;
if (user.IsEnabled == true || user.IsEnabled == null)
{ user.IsEnabled = false; }
else { user.IsEnabled = true; }
Context.GetOwinContext().Get<ApplicationDbContext>().SaveChanges();
}
And another try
protected void Block_Click(object sender, EventArgs e)
{
string itemID;
using (GridViewRow row = (GridViewRow)((Button)sender).Parent.Parent)
{
HiddenField lUId = (HiddenField)row.FindControl("ClientId");
itemID = lUId.Value;
}
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = manager.FindByEmail(itemID);
Label1.Text = user.UserName;
if (user.IsEnabled == true || user.IsEnabled == null)
{ user.IsEnabled = false; }
else { user.IsEnabled = true; }
manager.Update(user);
Context.GetOwinContext().Get<ApplicationDbContext>().SaveChanges();
}
Both not working actually.
So I got the right value from GridView and find a User with a right email, but after making changes, they wont appear in my database.

Update the database record in SqlLite Database

Here my insert code of SQLLite Database in Windows 8 and I want to update the records which are added in database
private async void insert(object sender, RoutedEventArgs e) {
if (txt1.Text != "" && txt2.Text != "" && txt3.Text != "") {
var dbpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "data.db3");
using (var db = new SQLite.SQLiteConnection(dbpath)) {
// Create the tables if they don't exist
db.Insert(new person() {
id= Guid.NewGuid(),
name = txt1.Text.ToString(),
address = txt2.Text.ToString(),
phone = Convert.ToDouble(txt3.Text.ToString()),
});
db.Commit();
db.Dispose();
db.Close();
}
} else {
throw new NullReferenceException("Enter The Data In Textboxes");
}
}
In SQLite there's Get<T> method which accept primary key as argument and it will return the row as object. Update method accept the object as parameter and it will update the existing record. Here I am giving you method to update person record.
private void UpdateRecord(int primaryKey)
{
var dbpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "data.db3");
using (var db = new SQLite.SQLiteConnection(dbpath))
{
var objPerson = db.Get<person>(primaryKey);
objPerson.name = "New name";
objPerson.address = "New address ";
objPerson.phone = Convert.ToDouble("New phone number");
db.Update(objPerson);
//You don't need to use db.Commit(), db.Dispose() & db.Close() because you are using "using" keyword.
}
}

How to programmatically grant 'Read' permission to a Group/user for a particular list in sharepoint

How to programmatically grant 'Read' permission to a Group/user for a particular list?.
I have created a group in Share Point manually.
Created a list too.
Now i want to add 'Read' permission to the particular list for a particular group/user.
The webpart works fine.
But does not update the permission.
Kindly help.
I am pasting the code below...
protected void Button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(TextBox1.Text) || string.IsNullOrEmpty(TextBox2.Text))
{
Label4.Text = "Please Enter Some Values";
//Label4.ForeColor = System.Drawing.Color.Red;
}
else
{
SPWeb web = SPContext.Current.Web;
SPGroup group = web.SiteGroups[TextBox2.Text];
SPWebApplication webApp = web.Site.WebApplication;
webApp.FormDigestSettings.Enabled = false;
web.AllowUnsafeUpdates = true;
SPRoleDefinition rDefination = web.RoleDefinitions.GetByType(SPRoleType.Reader);
SPRoleAssignment rAssignment = new SPRoleAssignment(group);
rAssignment.RoleDefinitionBindings.Add(rDefination);
SPList list = web.Lists[TextBox1.Text];
list.BreakRoleInheritance(true);
//SPItem item = list.
//item.RoleAssignments.Add(rAssignment);
list.Update();
Label4.Text = "Permission is successfully on item";
//Label4.ForeColor = System.Drawing.Color.Green;
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
web.RoleAssignments.Add(rAssignment);
web.Update();
web.AllowUnsafeUpdates = false;
webApp.FormDigestSettings.Enabled = true;
}
}
try to use this the code below. runwithelevatedprivileges will allow the simple user to update the list.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
if (string.IsNullOrEmpty(TextBox1.Text) || string.IsNullOrEmpty(TextBox2.Text))
{
Label4.Text = "Please Enter Some Values";
//Label4.ForeColor = System.Drawing.Color.Red;
}
else
{
SPWeb web = SPContext.Current.Web;
SPGroup group = web.SiteGroups[TextBox2.Text];
SPWebApplication webApp = web.Site.WebApplication;
webApp.FormDigestSettings.Enabled = false;
web.AllowUnsafeUpdates = true;
SPRoleDefinition rDefination = web.RoleDefinitions.GetByType(SPRoleType.Reader);
SPRoleAssignment rAssignment = new SPRoleAssignment(group);
rAssignment.RoleDefinitionBindings.Add(rDefination);
SPList list = web.Lists[TextBox1.Text];
list.BreakRoleInheritance(true);
//SPItem item = list.
//item.RoleAssignments.Add(rAssignment);
list.Update();
Label4.Text = "Permission is successfully on item";
//Label4.ForeColor = System.Drawing.Color.Green;
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
web.RoleAssignments.Add(rAssignment);
web.Update();
web.AllowUnsafeUpdates = false;
webApp.FormDigestSettings.Enabled = true;
}
});
SPListItem listitem = listPositional.Items.Add();
listitem["Title"] = "data1";
//listitem["Enc"] = "Encrypted data";
listitem.Update();
listitem.BreakRoleInheritance(false);
SPGroup group = myWeb.SiteGroups["Restricted Readers"];
GrantPermission(listitem, myWeb, SPRoleType.Reader, group);
private static void GrantPermission(SPListItem CurrentListItem, SPWeb oSPWeb, SPRoleType SPRoleType, SPPrincipal SPPrincipal)
{
try
{
//Create one Role Definition i.e Full Controls, Contribute rights or Read rights etc.
SPRoleDefinition oSPRoleDefinition = oSPWeb.RoleDefinitions.GetByType(SPRoleType);
//Create one Role Assignment for the specified SP user or group.
SPRoleAssignment oSPRoleAssignment = new SPRoleAssignment(SPPrincipal);
//Bind the role definition to the role assignment object created for the user or group.
oSPRoleAssignment.RoleDefinitionBindings.Add(oSPRoleDefinition);
//Add it to the specified list item.
CurrentListItem.RoleAssignments.Add(oSPRoleAssignment);
//update the list item so that specified user assignment will have the access.
CurrentListItem.Update();
}
catch (Exception ex)
{
throw ex;
}
}

Selected Index changed doesnt fire

I have a drop down list that is populated on page load and by default the selected index is 0 and its set to an emty string. On page load if we change the selected value the selected index method doesnt fire.
if(!page.isPostback)
{
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.selectedIndex = 1;
this.ddl.SelectedValue = Id.ToString();
}
}
That's as it should be. If you want to execute some piece of logic from both the event and/or from page load, put that logic in a separate method so you can call it easily from your page load.
private void BindList()
{
this.ddl.Items.Clear();
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
this.ddl.Items.SelectedIndex = 0;
}
if(!page.isPostback)
{
BindList();
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.ddl.Items.ClearSelection();
this.ddl.Items.FindByValue(Id.ToString()).Selected = true;
}
}

Resources