Create a dropdown list for members on the front page of my site - sql

I are using umbraco 7.
I want to create a drop down list of members (From MSSql) on the front page of my site.
I have a nuPicker Sql Dropdown setup in datatypes and can load this in the back office fine.
Now I want to get it on the front screen.
Once there it needs to load a whole heap of custom information.
Before changing needs to test custom information and warn if needs to be saved because of changes.
Who do I do this

Worked it out.
Don't use nuPicker
public IEnumerable<Some Model> GetData()
{
var db = applicationContext.Current.Database.Database;
var tbl = db.Fetch<Some Model>(#" Some Sql Script ");
return tbl;
}
public List<SelectListItem> BuildDropDown()
{
List<SelectListItem> lst = new List<SelectListItem>
IEnumerable< Some Model> Members = GetData();
for each item in Members)
{
lst.Add(new SelectListItem { Value = item.Label, Text = item.Label });
}
}

Related

how to set the selected value in the drop down list populated with ViewData in mvc

I am new to MVC, please help me to set the selected value in drop down list populated using View Data. I have gone through so many solutions but every solutions deals with selecting value for single drop down. I have same drop down listed using the foreach loop. Setting selected value for each dropdown in that foreach loop.
My code is shown below.
[In view]
int i = 0;
foreach (var item in Model.Select((x, j) => new { Data = x, Index = j + 1 })) {
#Html.DropDownListFor(model => item.Data.CategoryID,(IEnumerable<SelectListItem>)ViewData["categories"], new { #id = "category" + i })
i++;
}
[in controller]
SelectList selectList = new SelectList((IEnumerable<Category>)ConvertCategoryToList(dt1), "CategoryID", "CategoryName");
ViewData["categories"] = selectList;
There is a lot missing from your sample (e.g.what a category looks like, what the Edit actions look like, what is dt1, what the model is you pass to the view etc), but I will try based on what is shown.
Problem 1: Can't use foreach in binding
You can't use a foreach with a collection of form items. The items have no way of knowing which individual element to bind with (when they are sent back to the server they need more information to make each entry unique).
Solution:
It only knows how to bind if you use indexing (e.g. using for (int i=0; < count; i++){ #Html.DropDownListFor(model=>item[i]...)
Problem 2: Selected values only can come from SelectList!
This is the most irritating feature of DropDownListFor and appears to be a bug. It will not take the current selected value from the bound data. It will only take a current value from a SelectList, which means you need a unique SelectList for every dropdown.
Solution:
Create a unique SelectList in the view, per drop down required, with the item value as the current selection.
With some faking of your data, I got the following working:
Example
Controller:
Only store the list of items for the SelectList in the ViewBag:
ViewData["categories"] = ConvertCategoryToList(dt1);
View:
1. You need to pass a List and not an IEnumerable as IEnumerable cannot be indexed.
#model List<MyApplication.Item>
2. Create a SelectList for each dropdown
SelectList newSelectList = new SelectList((IEnumerable<MyApplication.Category>)ViewData["categories"], "CategoryID", "CategoryName", Model[i].Id);
3. Use the indexing method for addressing your items in the collection.
#Html.DropDownListFor(m => Model[i].Id, newSelectList, "Select an item")
Problem 3: What data to pass?
The other issue with your code, as-it-stands, is what to pass back and forth to/from the edit view? At the moment I would guess (from the variable name dt1) you are passing a DataTable(?). You will need to be very explicit about the data you are using in order to get a clean solution to this one. I would suggest posting a second question with all your code and Razor view HTML.
If you need to see more of my sample code (below), please post your own code so I can make them consistent.
Full dummy controller code below
public class TestController : Controller
{
public List<Category> dt1 { get; set; }
public TestController()
{
this.dt1 = new List<Category>();
for (int i = 1; i <= 10; i++)
{
this.dt1.Add(new Category() { CategoryId = i, CategoryName = string.Format("Category {0}", i) });
}
}
[HttpGet]
public ActionResult Edit()
{
//SelectList selectList = new SelectList((IEnumerable<Category>)ConvertCategoryToList(dt1), "CategoryID", "CategoryName");
ViewData["categories"] = ConvertCategoryToList(dt1);
List<Item> items = new List<Item>();
items.Add(new Item(){Id = 1});
items.Add(new Item(){Id = 2});
items.Add(new Item(){Id = 3});
items.Add(new Item(){Id = 4});
items.Add(new Item(){Id = 5});
return View(items);
}
[HttpPost]
public ActionResult Edit(FormCollection form)
{
// Turn form submission back into a compatible view model
List<Item> items = new List<Item>();
foreach (string key in form.Keys)
{
string val = form[key];
items.Add(new Item() { Id = int.Parse(val) });
}
// Recreate the select list
ViewData["categories"] = ConvertCategoryToList(dt1);
return View(items);
}
List<Category> ConvertCategoryToList(IEnumerable<Category> dt)
{
return dt.ToList();
}
}
Note: The post version of Edit simply recreates the list of data (using the selected values posted back) and returns to the Edit view. This is just for testing.
Screen shot
Dummy category class
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
Full test View
#model List<MyApplication.Item>
#using (Html.BeginForm())
{
for (int i = 0; i < Model.Count; i++)
{
SelectList newSelectList = new SelectList((IEnumerable<MyApplication.Category>)ViewData["categories"], "CategoryID", "CategoryName", Model[i].Id);
#Html.DropDownListFor(m => Model[i].Id, newSelectList, "Select an item")
}
<input type="submit" value="Submit"/>
}

Developing a user search page in asp.net MVC 4 using Activedirectory

I am developing a ASp.net MVC 4 Intranet application.
So when I login I can see my account getting displayed.
Now to authorise the account I have developed a custom authorization provider by following the below link :http://www.codeproject.com/Articles/607392/Custom-Role-Providers
now my problem is after the initial authorization I add myself to superadmin role who has acess to Index.cstml where there is a text box and a search button.
basically here on this page I want to search user from active directory and display it so that I can assign some roles to the user.
How do I do that?
please provide the code how to connect to Active directory, where to provide the connection string for LDAP and the excat method which will help me in searching the user from active directory and dispaly it on the index view.
Below is what I have tried:
Entities: ADuser->property UserLoginName ,UserDispalyName
Model: has a method that returns the serch user from AD and add it to entity
public class ADUserModel
{
public List<ADUser> GetUserFromAD(string name) //Get Network Users (AD)
{
//ArrayList searchUser = new ArrayList();
var domainContext = new PrincipalContext(ContextType.Domain);
var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, "Domain Users");
UserPrincipal user = new UserPrincipal(domainContext);
user.Enabled = true;
user.Name = name + "*";
PrincipalSearcher pS = new PrincipalSearcher();
pS.QueryFilter = user;
PrincipalSearchResult<Principal> results = pS.FindAll();
var list = new List<ADUser>();
//searchUser.Add(results);
foreach (var item in results)
{
var users = new ADUser();
users.UserLoginName = item.SamAccountName;
users.UserDisplayName = item.DisplayName;
list.Add(users);
//searchUser.Add(users);
}
return list;
}
}
Controller: has an action method that will return the view
public class ManageUsersController : Controller
{
//
// GET: /ManageUsers/
public ActionResult Search(string searchString)
{
ADUserModel model = new ADUserModel();
var list = new List<ADUser>();
if (searchString != null)
{
list = model.GetUserFromAD(searchString);
return View("Search");
}
else
{
return View("Search");
}
}
}
View: Search.cshtml
#model IEnumerable<FMSKendoUI.Entities.ADUser>
#{
ViewBag.Title = "Search";
}
#Html.BeginForm("Search","ManageUsers",FormMethod.Get)
{
#Html.TextBox("Search") <input type="submit" value="Search" />
}
#if (Model.Count() != 0)
{
#foreach (FMSKendoUI.Entities.ADUser model in Model)
{
#Html.DisplayFor(m => model.UserLoginName)
#Html.DisplayFor(m => model.UserDisplayName)
}
}
But my problem is:
During my first page load I would need only the textbox and search button.
and on the search button click I need to call the controller search method.
Since during the first time my entity is null it is giving me null exception.
my entity get loaded only after I provide the search string and call the model method.
I am unable to achieve this. Please help me on this.

PublicAccess permissions not working in Umbraco 6

I am trying to display a table listing some documents (nodes) to the users. Those documents are protected using role permissions (right click > Public Access > Role Permissions) and I want to show only those to which this user has access.
After checking here and there, I've seen that there isn't any "Node.Permissions" way, so you have to go through Access.HasAccess().
I have used that, and I have set the permissions, but when I use the method it returns always true. What am I doing wrong?
This is the code to build the list of nodes, which works perfectly:
public static List<Node> GetAllNodeChildrenRecursively(int nodeId, string typeName)
{
var node = new Node(nodeId);
var lstNodes = new List<Node>();
foreach (Node childNode in node.Children)
{
var child = childNode;
if (child.NodeTypeAlias == typeName)
{
lstNodes.Add(childNode);
}
if (child.Children.Count > 0)
{
lstNodes.AddRange(GetAllNodeChildrenRecursively(childNode.Id, typeName));
}
}
return lstNodes;
}
This is the code to remove those I haven't access to:
var availableNodes = new List<Node>();
foreach(Node n in nodes)
{
if(Access.HasAccces(n.Id, memberId))
{
availableNodes.Add(n);
}
}
return availableNodes;
Well, Access.HasAccess returns always true, and the member I am using to test is not part of the MemberGroup that has access to that node. Am I setting permissions wrong or not checking it properly or what?
I'm lost.
As far as I know you should use the following method:
*There are a few different calls to HasAccess so it might depend on your version of Umbraco as well.
var availableNodes = new List<Node>();
try
{
//this will throw an argument exception if there is not a current user logged in
var currentMember = System.Web.Security.Membership.GetUser();
foreach (Node n in retVal)
{
if (Access.HasAccess(n.Id, n.Path, currentMember))
{
availableNodes.Add(n);
}
}
}
catch(ArgumentException e)
{
//do something when there is not a logged in member
}
return availableNodes;

Copying sitecore rendering to new template programmatically using renderingDefinition.ItemId?

I have a custom sitecore button which changes the template of the current item, simple enough.
However as part of this I'm trying to also migrate the renderings of the old layout to a new layout if it's of a certain sublayout type by ItemId. However the ItemId that is returned is always null, the only value I get back from the RenderingDefinition is the UniqueId.
What am I doing wrong?
I have used this blog post as a guide.
The Code
public class ConvertToNewTemplateCommand : Command
{
protected void Run(ClientPipelineArgs args)
{
if (!SheerResponse.CheckModified())
return;
Item item = Context.ContentDatabase.Items[args.Parameters["id"]];
if (args.IsPostBack)
{
if (args.Result == "yes")
{
//Get current layout details
var originalLayoutXml = item[FieldIDs.LayoutField];
//Get new template
TemplateItem hubTemplate = Context.ContentDatabase.GetTemplate("some guid...");
//Change template
item.ChangeTemplate(hubTemplate);
//Reset laytout
ResetLayout(item);
//Get reset layout
var newLayoutXml = item[FieldIDs.LayoutField];
//Add all the module containers to the new layout in the central column
MoveModuleContainers(item, originalLayoutXml, newLayoutXml);
}
}
}
private void MoveModuleContainers(Item item, string oldXml, string newXml)
{
var oldLayout = LayoutDefinition.Parse(oldXml);
var newLayout = LayoutDefinition.Parse(newXml);
bool updated = false;
var oldRenderings = (oldLayout.Devices[0] as DeviceDefinition).Renderings;
var newRenderings = (newLayout.Devices[0] as DeviceDefinition).Renderings;
foreach (RenderingDefinition rendering in oldRenderings)
{
// Here is where the rendering.ItemID is always null
if (rendering != null && !String.IsNullOrEmpty(rendering.ItemID) && new Guid(rendering.ItemID) == new Guid("matching guid..."))
{
rendering.Placeholder = "middlecolumn";
newRenderings.Add(rendering);
updated = true;
}
}
if (updated)
{
// Save item...
}
}
}
I got onto Sitecore support in the end which informed me that I should use:
Sitecore.Data.Fields.LayoutField.GetFieldValue(item.Fields[Sitecore.FieldIDs.LayoutField])
instead of:
item[FieldIDs.LayoutField]
to get the items layoutField correctly. This results in the rendering values being parsed correctly and as they say the rest is history.

Cannot get data updates on NotifyPropertyChanged collection

I'm building a Mango app that writes data to a SqlCe database; I have a ListBox bound to a DataSource that must show items when they are added to the database, but when I add/update data I cannot get updates and they are only shown when I reload the page.
Here are some snippets:
public class TimeTrackerViewModel: INotifyPropertyChanged, INotifyPropertyChanging
{
private List<TimeItems> _timeItems;
public List<TimeItems> TimeItems
{
get { return _timeItems; }
set
{
NotifyPropertyChanging("TimeItems");
_timeItems = value;
NotifyPropertyChanged("TimeItems");
}
}
public void LoadCollectionsFromDatabase()
{
// Specify the query for all to-do items in the database.
var times = from t in db.Times
select new TimeItems
{
DtIn = t.DtIn,
DtOut = t.DtOut,
Id = t.Id
};
// Query the database and load all to-do items.
TimeItems = new List<TimeItems>(times);
}
.....
.....
}
When I add data to the Times table I don't see db updates to the listBox bound to the TimeItems collection.
What am I doing wrong?
Make TimeItems an ObservableCollection