Populate Drop Down List based on multiple user roles - c#

I am trying to populate a DropDownList based on roles. I have a view in SQL with the value and text of each item based on the user role (Windows Auth) and can populate the DropDownList if a user was in all roles with:
using (var db=new GPSE_2.DAL.GPSE2Entities())
{
var locations = (from loc in db.LocationLOBViews
orderby loc.LocationNumber
select new { loc.DataValue, loc.DataText});
ddlShops.DataValueField = "DataValue" ;
ddlShops.DataTextField = "DataText";
ddlShops.DataSource = locations.ToList();
DataBind();
}
I would like to add items only the logged in user is a member of. Users can be in multiple groups(roles).
For instance, the logged in user is in a group called Location 01 LOB 100 and they are also in a group called Location 01 LOB 200 and also in Location o2 LOB 100. Only those options should appear in the DropDownList.
I was able to loop through the roles the user is in by the code below.
string UPN = UserPrincipal.Current.UserPrincipalName.ToString();
WindowsIdentity wi = new WindowsIdentity(UPN);
string GroupName;
foreach (IdentityReference group in wi.Groups)
{
GroupName = group.Translate(typeof(NTAccount)).ToString();
if (GroupName.Contains("Location 01 LOB 100"))
{
var item = new ListItem
{
Text = "Location 01 LOB 100",
Value = "01,100"
};
ddlShops.Items.Add(item);
}
}
Now I am trying to combine the 2 I ran into problems adding loc.DataValue and the loc.DataText to the DDL if the query returns results. This is where I an stuck, it adds the string in the quotes instead of the values.
using (var db = new GPSE_2.DAL.GPSE2Entities())
{
string UPN = UserPrincipal.Current.UserPrincipalName.ToString();
WindowsIdentity wi = new WindowsIdentity(UPN);
string GroupName;
foreach (IdentityReference group in wi.Groups)
{
GroupName = group.Translate(typeof(NTAccount)).ToString();
var locations = (from loc in db.LocationLOBViews
where loc.DataValue.Contains(GroupName)
orderby loc.LocationNumber
select new { loc.DataValue, loc.DataText });
if (locations !=null)
{
var item = new ListItem
{
Text = "DataText",
Value = "DataValue"
};
ddlShops.Items.Add(item);
}
}
}
Thanks,
-Doug

I got it working by creating a list of groups the user is in and then populating the Drop Down List with the appropriate information.
private List<string> GetGroups()
{
string UPN = UserPrincipal.Current.UserPrincipalName.ToString();
List<string> result = new List<string>();
WindowsIdentity wi = new WindowsIdentity(UPN);
foreach (IdentityReference group in wi.Groups)
{
string GroupName = group.Translate(typeof(NTAccount)).ToString();
//if text location and lob is in the name add to results
if (GroupName.Contains("Location") && GroupName.Contains("LOB"))
{
string DataValue1 = GroupName.Substring(GroupName.Length - 3);
string DataValue2 = GroupName.Substring(GroupName.Length - 10, 2);
string DataValue = DataValue2 + "," + DataValue1;
result.Add(DataValue);
}
}
result.Sort();
return result;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (var db = new GPSE2Entities())
{
for (int i = 0; i < GetGroups().ToArray().Length; i++)
{
string DataValue = GetGroups().ToArray()[i].ToString();
var locations = (from loc in db.LocationLOBViews
where loc.DataValue == DataValue
orderby loc.LocationNumber
select loc).FirstOrDefault();
if (locations != null)
{
var item = new ListItem
{
Text = locations.DataText,
Value = locations.DataValue
};
ddlShops.Items.Add(item);
}
}
}
ddlShops.Items.Insert(0, "--Select Location and LOB--");
}
}

Related

I can't sort a column descending ASP MVC

I need to sort the PROMEDIOCAL field in descending order but when implementing the sort it doesn't work. It lists me correctly by ID and I can also search by DISTRICT but I cannot sort the PROMEDIOCAL field in descending order when clicking on the header in the table
Controller:
public ActionResult ListarProfxServicio(int id, string CadenaBusqueda, string Orden)
{
List<TB_Profesionales> lista = new List<TB_Profesionales>();
ViewBag.cal = String.IsNullOrEmpty(Orden) ? "cod_asc" : "";
var data = from c in db.TB_Profesionales where c.IDSERVICIO == id select new {c.IDUSUARIO, c.NOMBRE, c.APELLIDO, c.SEXO, c.DISTRITO, c.DESCRIPCIÓN, c.PROMEDIOCAL};
var data2 = from c in db.TB_Profesionales select c;
foreach (var pro in data)
{
TB_Profesionales p = new TB_Profesionales();
p.IDUSUARIO = pro.IDUSUARIO;
p.NOMBRE = pro.NOMBRE;
p.APELLIDO = pro.APELLIDO;
p.SEXO = pro.SEXO;
p.DISTRITO = pro.DISTRITO;
p.DESCRIPCIÓN = pro.DESCRIPCIÓN;
p.PROMEDIOCAL = pro.PROMEDIOCAL;
lista.Add(p);
}
switch (Orden)
{
case "cod_asc":
data = data.OrderByDescending(s => s.PROMEDIOCAL);
break;
}
if (!String.IsNullOrEmpty(CadenaBusqueda))
{
data2 = data2.Where(s => s.DISTRITO.ToUpper().Contains(CadenaBusqueda.ToUpper()));
return View(data2.ToList());
}
return View(lista.ToList());
}
View:
<th>
#Html.ActionLink("Cod", "ListarProfxServicio", new {Orden = ViewBag.cal })
</th>
Problem
You are performing sorting in data but you are returning lista to the View. So your lista is never been sorted.
public ActionResult ListarProfxServicio(int id, string CadenaBusqueda, string Orden)
{
List<TB_Profesionales> lista = new List<TB_Profesionales>();
var data = from c in db.TB_Profesionales where c.IDSERVICIO == id select new {c.IDUSUARIO, c.NOMBRE, c.APELLIDO, c.SEXO, c.DISTRITO, c.DESCRIPCIÓN, c.PROMEDIOCAL};
...
foreach (var pro in data)
{
...
lista.Add(p);
}
switch (Orden)
{
case "cod_asc":
data = data.OrderByDescending(s => s.PROMEDIOCAL);
break;
}
...
return View(lista.ToList());
}
Solution
Change the below part to sort for lista.
switch (Orden)
{
case "cod_asc":
lista = lista.OrderByDescending(s => s.PROMEDIOCAL);
break;
}
Recommendation
The data and foreach part can be refactored together as:
List<TB_Profesionales> lista = from c in db.TB_Profesionales
where c.IDSERVICIO == id
select new TB_Profesionales
{
IDUSUARIO = c.IDUSUARIO,
NOMBRE = c.NOMBRE,
APELLIDO = c.APELLIDO,
SEXO = c.SEXO,
DISTRITO = c.DISTRITO,
DESCRIPCIÓN = c.DESCRIPCIÓN,
PROMEDIOCAL = c.PROMEDIOCAL
};

Compare Two Complex List of data

When I am Trying to save current list of data into database, I need to get already existing data from database, and need to compare with current list of data.
I have two lists one is PreviousList(existing data from DB) and other is CurrentList(Modified data)
public class SoftClose
{
public int ID = -1;
public int AID = -1;
public int WFID = -1;
public string PREFIX;
public DateTime SCDATE;
public string STATUS;
}
In CurrentList I modified Prefix to D2 where ID=1 and added new row(Id=4)...
My req is
When I am trying to save CurrentList to Db,
If there is any new Prefix in CurrentList that is not there in PreviousList I need to insert that new row and need to change Status to ADD for that row.
I changed Prefix to D2 where Id = 1 in CurrentList. D1 is there is DB and but not in CurrentList so i need to delete it. So i need to change the status to DELETE for that record. I should not insert D2 record where id=1 becuase D2 is already there. If I changed to D5 where Id = 1 then I need to insert it because D5 is not there in DB So i need to change the status to UPDATE.
How to do this? What is the best approach to compare lists
here is a solution you could try:
List<SoftClose> previousList = new List<SoftClose>(){
new SoftClose(){ID=1, Status = "NO_CHANGE",AID="19", Prefix = "D1"},
new SoftClose(){ID=2, Status = "NO_CHANGE",AID="20", Prefix = "D2"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID="21", Prefix = "D3"}
};
List<SoftClose> currentList = new List<SoftClose>(){
new SoftClose(){ID=1, Status = "NO_CHANGE",AID="19", Prefix = "D2"},
new SoftClose(){ID=2, Status = "NO_CHANGE",AID="20", Prefix = "D2"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID="21", Prefix = "D6"},
new SoftClose(){ID=4, Status = "NO_CHANGE",AID="22", Prefix = "D4"},
new SoftClose(){ID=5, Status = "NO_CHANGE",AID="22", Prefix = "D5"}
};
var addlist = currentList.Where(c => previousList.All(p => !p.ID.Equals(c.ID) && !p.Prefix.Equals(c.Prefix)));
foreach(var n in addlist)
{
var index = currentList.FindIndex(p => p.Prefix.Equals(n.Prefix));
currentList[index].Status = "ADD";
}
var updateORdeletelist = currentList.Where(c => c.Status.Equals("NO_CHANGE") && previousList.Exists(p => p.ID.Equals(c.ID) && !p.Prefix.Equals(c.Prefix)));
foreach (var n in updateORdeletelist)
{
var index = currentList.FindIndex(p => p.Prefix.Equals(n.Prefix));
if (previousList.FindIndex(p => p.Prefix.Equals(n.Prefix)) < 0)
currentList[index].Status = "UPDATE";
else
currentList[index].Status = "DELETE";
}
foreach (var item in currentList)
{
Console.WriteLine($"Id:{item.ID}, Desc1:{item.Prefix}, Status:{item.Status}");
}
output
Id:1, Desc1:D2, Status:DELETE
Id:2, Desc1:D2, Status:NO_CHANGE
Id:3, Desc1:D6, Status:UPDATE
Id:4, Desc1:D4, Status:ADD
Id:5, Desc1:D5, Status:ADD
There is a tool called Side by Side SQL Comparer in C# at https://www.codeproject.com/Articles/27122/Side-by-Side-SQL-Comparer-in-C.
basic use of the component:
using (TextReader tr = new StreamReader(#"c:\1.sql"))
{
sideBySideRichTextBox1.LeftText = tr.ReadToEnd();
}
using (TextReader tr = new StreamReader(#"c:\2.sql"))
{
sideBySideRichTextBox1.RightText = tr.ReadToEnd();
}
sideBySideRichTextBox1.CompareText();
You load the left and right sides to their respective variables sideBySideRichTextBox1.LeftText and sideBySideRichTextBox1.RightText and compare them with sideBySideRichTextBox1.CompareText();
In your case the 1.sql and 2.sql would be your PreviousList and CurrentList -database files.
There is more detailed documentation at the project-site.

How to apply multiple optional filters in a LINQ query

I have a page where user can select any number of search filters to apply search
When user clicks on search, these parameters are passed to my GetIndicatorData method to perform the query. However, it doesn't seem to work for me.
Here is my code
public static List<tblindicators_data_custom> GetIndicatorsData(string status, int service_id, int operator_id, string year, string frequency)
{
var date = Convert.ToDateTime(year + "-01-01");
int[] numbers = status.Split(',').Select(n => int.Parse(n)).ToArray();
var ict = new ICT_indicatorsEntities();
var result = from ind in ict.tblindicators_data
join ser in ict.tblservices on ind.service_id equals ser.Id
join oper in ict.tbloperators on ind.operator_id equals oper.Id
where numbers.Contains(ind.status) && (ind.date_added.Year == date.Year)
select new
{
ind.Id,
ind.service_id,
ind.survey_id,
ind.operator_id,
ind.type,
ind.date_added,
ind.quater_start,
ind.quater_end,
ind.status,
ind.month,
service = ser.name,
operator_name = oper.name
};
List<tblindicators_data_custom> data = new List<tblindicators_data_custom>();
foreach (var item in result)
{
tblindicators_data_custom row = new tblindicators_data_custom();
row.Id = item.Id;
row.survey_id = item.survey_id;
row.service_id = item.service_id;
row.service_name = item.service;
row.operator_id = item.operator_id;
row.operator_name = item.operator_name;
row.date_added = item.date_added;
row.quater_start = item.quater_start;
row.type = item.type;
row.quater_end = item.quater_end;
row.month = item.month == null? DateTime.Now:item.month;
row.status = item.status;
data.Add(row);
}
return data;
}

Listing in WCF Entity

I have a problem with LINQ query (see comment) there is a First method and it only shows me the first element.
When I write in the console "Sales Representative" it shows me only the first element of it as in
I would like to get all of data about Sales Representative. How can I do it?
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
//Employee matchingProduct = database.Employees.First(p => p.Title == imie);
var query = from pros in database.Employees
where pros.Title == imie
select pros;
// Here
Employee pp = query.First();
pracownikDane = new PracownikDane();
pracownikDane.Tytul = pp.Title;
pracownikDane.Imie = pp.FirstName;
pracownikDane.Nazwisko = pp.LastName;
pracownikDane.Kraj = pp.Country;
pracownikDane.Miasto = pp.City;
pracownikDane.Adres = pp.Address;
pracownikDane.Telefon = pp.HomePhone;
pracownikDane.WWW = pp.PhotoPath;
}
return pracownikDane;
}
Right now you are just getting the .First() result from the Query collection:
Employee pp = query.First();
If you want to list all employees you need to iterate through the entire collection.
Now, if you want to return all the employee's you should then store each new "pracownikDane" you create in some sort of IEnumerable
public IEnumerable<PracownikDane> GetPracownik(string imie) {
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
var EmployeeList = new IEnumerable<PracownikDane>();
foreach(var pp in query)
{
EmployeeList.Add(new PracownikDane()
{
Tytul = pp.Title,
Imie = pp.FirstName,
Nazwisko = pp.LastName,
Kraj = pp.Country,
Miasto = pp.City,
Adres = pp.Address,
Telefon = pp.HomePhone,
WWW = pp.PhotoPath
});
}
return EmployeeList;
}
Then, with this returned List you can then do what ever you wanted with them.

foreach loop is not working in mvc

foreach (int workFlowServiceDetail in workFlowServiceDetails)
{
using (var db = new AdminDb())
{
string workFlowServiceDtl = (from perm in db.WorkFlowPermission.AsNoTracking()
where perm.WorkFlowPermissionId == workFlowServiceDetail
select perm.Service).FirstOrDefault();
//to select eligibility rules against this service
string eligibility = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId) && permission.WorkFlowPermissionId == workFlowServiceDetail
select permission.EligibilityRule).FirstOrDefault();
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
string[] strTxt = workFlowServiceDtl.Split(';'); //split the service name by ';' and strore it in an array
string serviceUrl = string.Empty;
string workFlowServiceName = string.Empty;
string classpath = string.Empty;
workFlowServiceName = strTxt[0].ToString();
workFlowServiceName = workFlowServiceName.Replace(" ", "");//get the service name by removing empty blank space for the word
classpath = strTxt[1].ToString();
//Invoke REST based service (like Node.Js service)
if (strTxt.Length == 4)
{
serviceUrl = strTxt[3].ToString();
}
//Invoke c# based service
else
{
serviceUrl = string.Empty;
}
var userLists = PermissionCallMethod(classpath, workFlowServiceName, new[] { workFlowImplemented, eligibility }, serviceUrl);
/*****************************************Problem in this loop**********/
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Aspir.Pan.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
}
}
serviceName = string.Empty;
permissionId = 0;
return null;
Inside this loop a condition is checked to find a particular user form alist of user.Once the condition is true it jump out of the loop without checking the next one.
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Asire.Pan.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
this is mainly because of the " return userList". so how can i make the loop run again. or please suggest some way to make it work.Is it possible to copy that returning userList to some List and return it after the loop.If so how can i write i list there. Please help me..?
Remove return in Foreach loop
var userListsTemp=null;
foreach (int workFlowServiceDetail in workFlowServiceDetails)
{
using (var db = new AdminDb())
{
string workFlowServiceDtl = (from perm in db.WorkFlowPermission.AsNoTracking()
where perm.WorkFlowPermissionId == workFlowServiceDetail
select perm.Service).FirstOrDefault();
//to select eligibility rules against this service
string eligibility = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId) && permission.WorkFlowPermissionId == workFlowServiceDetail
select permission.EligibilityRule).FirstOrDefault();
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
string[] strTxt = workFlowServiceDtl.Split(';'); //split the service name by ';' and strore it in an array
string serviceUrl = string.Empty;
string workFlowServiceName = string.Empty;
string classpath = string.Empty;
workFlowServiceName = strTxt[0].ToString();
workFlowServiceName = workFlowServiceName.Replace(" ", "");//get the service name by removing empty blank space for the word
classpath = strTxt[1].ToString();
//Invoke REST based service (like Node.Js service)
if (strTxt.Length == 4)
{
serviceUrl = strTxt[3].ToString();
}
//Invoke c# based service
else
{
serviceUrl = string.Empty;
}
var userLists = PermissionCallMethod(classpath, workFlowServiceName, new[] { workFlowImplemented, eligibility }, serviceUrl);
/*****************************************Problem in this loop**********/
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Aspir.Pan.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
//return userLists;
if(userListsTemp==null)
{
userListsTemp=userLists;
}
else
{
userListsTemp.Concat(userLists).ToList();
}
}
}
}
serviceName = string.Empty;
permissionId = 0;
return null;

Categories