Loading a menu structure on every razor page in asp .NET Core - asp.net

After user authentication I'm supposed to change the user menu based on the roles of the user.
To do this, I created a service which fetched the menu the user is expected to see:
public List<MenuStructure> LoadCompleteMenuRole(string role)
{
List<MenuStructure> resultList = null;
var menuHeaders = LoadMenuHeadersForTheGivenRole(role);
if (menuHeaders != null && menuHeaders.Count > 0)
{
resultList = new List<MenuStructure>();
foreach (var menuHeader in menuHeaders)
{
var menuStructure = new MenuStructure
{
MenuName = menuHeader.HeaderName,
Caption = menuHeader.Caption
};
var menuDetails = LoadMenuDetailsForTheGivenHeader(menuHeader.Id);
if (menuDetails != null && menuDetails.Count > 0)
{
menuStructure.MenuElements = new List<MenuElement>();
foreach (var menuDetail in menuDetails)
{
var menuElement = new MenuElement
{
ElementName = menuDetail.DetailName,
ElementCaption = menuDetail.Caption,
Destination = menuDetail.Destination
};
menuStructure.MenuElements.Add(menuElement);
}
}
resultList.Add(menuStructure);
}
}
return resultList;
}
My problem? Where do I implement the service so the menus get loaded in every razor page I create?

Related

Getting Null data from google adwords api

I want to fetch location details for all the ads from google adwords but I am getting null entries.I am not able to get any data from adwords api .Help me in That as according to my knowledge there is not problem with my code and I am not able to find any solution for that.My code that I have tried is written below.
public void GetLocationAds()
{
AdWordsUser user = new AdWordsUser();
{
try
{
int offset = 0;
// Create selector.
using (CampaignCriterionService campaignCriterionService =
(CampaignCriterionService)user.GetService(AdWordsService.v201809.CampaignCriterionService))
{
Selector selector = new Selector()
{
fields = new string[]
{
CampaignCriterion.Fields.CampaignId,
CampaignCriterion.Fields.CampaignCriterionStatus,
//Location.Fields.LocationName,
//Location.Fields.CriteriaType,
//Location.Fields.ParentLocations,
//LocationCriterion.Fields.CanonicalName,
//LocationCriterion.Fields.CountryCode,
CampaignCriterion.Fields.IsNegative,
},
// predicates = new Predicate[]
//{
// Predicate.Equals( "CriteriaType","LOCATION"),
//},
paging = Paging.Default,
ordering = new OrderBy[]
{
OrderBy.Asc( CampaignCriterion.Fields.CampaignId)
}
};
CampaignCriterionPage page = new CampaignCriterionPage();
do
{
// Get the ad groups.
page = campaignCriterionService.get(selector);
// Display the results.
if (page != null && page.entries != null)
{
int j = selector.paging.startIndex;
foreach (CampaignCriterion campaignCriterion in page.entries)
{
var campaignId = campaignCriterion.campaignId;
bool IsLocation = campaignCriterion.isNegative;
var CampaignCriterionType = campaignCriterion.CampaignCriterionType;
}
}
else
{
Console.Write("No campaignCriterion were found.");
}
selector.paging.IncreaseOffset();
}
while (selector.paging.startIndex < page.totalNumEntries);
}
}
catch (Exception ex)
{
}
}
}
Kindly help me in that.

View not update after POST although View Model updated

I am writing ASP.NET Custom Component, I want to update my view with following code below:
#if (Model.TableDatasource != null){
//Write some thing to html page example: tables or span
}
At the first, Model.TableDatasource is null, user choose information and Controller Review View(Model) like this:
var model = new PrintDeliveryTicketModel()
{
PlantList = CommonHelper.GetPlantList(),
};
if (request == null)
{
return View(model);
}
else
{
var currentPlant = JsonConvert.DeserializeObject<PlantList>(request);
var FullModel = new PrintDeliveryTicketModel()
{
PlantList = CommonHelper.GetPlantList(),
CurrentPlant = JsonConvert.DeserializeObject<PlantList>(request),
DriverList = JsonConvert.DeserializeObject<List<Drivers>>(CommonHelper.GetDriver(currentPlant.CodePlant, currentPlant.PlantNo.Value).Content.ReadAsStringAsync().Result),
CustomerList = JsonConvert.DeserializeObject<List<Customer>>(CommonHelper.GetCustomer().Content.ReadAsStringAsync().Result),
RecipeList = JsonConvert.DeserializeObject<List<Recipe>>(CommonHelper.GetRecipe(currentPlant.CodePlant, currentPlant.PlantNo.Value).Content.ReadAsStringAsync().Result),
SitesList = JsonConvert.DeserializeObject<List<Site>>(CommonHelper.GetSite().Content.ReadAsStringAsync().Result),
// TruckList = JsonConvert.DeserializeObject<List<Truck>>(CommonHelper.GetTruck().Content.ReadAsStringAsync().Result)
};
return View(FullModel);
}
At the Debug time, I notice that break-point stop at return View(FullMode) and Break-point at ViewFile(cshtml) has value. but nothing printed at view.
Hope some help.

The procedure does not work properly Entity Framework ASP.NET MVC 5 C#5

I have been facing this problem with assigning users to a proper role. The code looks just fine, but in reality half of the users gets a proper role, the other half stays without a role at all. Here is the method which does it:
public IdentityResult RefreshUserGroupRoles(long? userId)
{
if (userId == null) throw new ArgumentNullException(nameof(userId));
var user = _userManager.FindById(userId.Value);
if(user == null)
{
throw new ArgumentNullException(nameof(userId));
}
// Remove user from previous roles:
var oldUserRoles = _userManager.GetRoles(userId.Value);
if (oldUserRoles.Count > 0)
{
_userManager.RemoveFromRoles(userId.Value, oldUserRoles.ToArray());
}
// Find the roles this user is entitled to from group membership:
var newGroupRoles = this.GetUserGroupRoles(userId.Value);
// Get the damn role names:
var allRoles = _roleManager.Roles.ToList();
var addTheseRoles = allRoles.Where(r => newGroupRoles.Any(gr => gr.AppRoleId == r.Id));
var roleNames = addTheseRoles.Select(n => n.Name).ToArray();
//_db.Database.CurrentTransaction.Commit();
// Add the user to the proper roles
var transaction = _db.Database.BeginTransaction();
IdentityResult result;
try
{
result = _userManager.AddToRoles(userId.Value, roleNames);
transaction.Commit();
_db.DbContextTransactionAu.Commit(); //This is for Audit
}
catch (Exception)
{
transaction.Rollback();
throw;
}
_db.DbContextTransactionAuDispose?.Dispose();
return result;
}
public IEnumerable<AppGroupRole> GetUserGroupRoles(long userId)
{
var userGroups = this.GetUserGroups(userId).ToList();
if (userGroups.Count == 0) return new Collection<AppGroupRole>().AsEnumerable();
var userGroupRoles = new List<AppGroupRole>();
foreach(var group in userGroups)
{
userGroupRoles.AddRange(group.AppRoles.ToArray());
}
return userGroupRoles;
}
Any idea what could be wrong?

In Skype bot framework Attachments Content null

I'm trying to access the list of attachments sent by the user to the skype bot that I'm developing.
Here is how I access the attachment details ,
public async Task<HttpResponseMessage> Post([FromBody]Activity message)
{
if (message.Attachments != null)
{
if (message.Attachments.Count > 0)
{
List<Attachment> attachmentList = message.Attachments.ToList();
foreach (var item in attachmentList)
{
var name = item.Name;
var content = item.Content;
}
}
}
}
But I get null for the following even though the attachment count is greater than zero,
var name = item.Name;
var content = item.Content;
Am I doing this right?
Maybe do something like this...
List<Attachment> attachmentList = message?.Attachments?.Where(x => x != null)?.ToList() ?? new List<Attachment>();
This would hopefully always set attachmentList to an empty list or a list containing non null items?

How to get files from onedrive in c#

We have a requirement that is we need to access onedirve through asp.net/C# and need to get the latest uploaded file..?
Please help me how to solve this type of requirement..?
i tried the following code..
i used following namespaces. but didn't work
using Microsoft.Live.Web.Samples.ConnectAppUserWithMSAccount.Filters;
using Microsoft.Live.Web.Samples.ConnectAppUserWithMSAccount.Models;
private LiveAuthClient MSAuthClient
{
get
{
if (this.liveAuthClient == null)
{
IDictionary<int, string> secretMap = new Dictionary<int, string>();
secretMap.Add(ClientSecretKey, ClientSecret);
this.liveAuthClient = new LiveAuthClient(ClientId, secretMap, null, this);
}
return this.liveAuthClient;
}
}
private MSAccountStatus MSAccountStatus
{
get
{
if (this.msAccountStatus == Controllers.MSAccountStatus.None)
{
using (UsersContext db = new UsersContext())
{
MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name);
this.msAccountStatus = msAccount != null ? MSAccountStatus.Connected : MSAccountStatus.NotConnected;
}
}
if (this.msAccountStatus == MSAccountStatus.Connected)
{
LiveConnectSession session = this.MSAuthClient.Session;
if (session == null || session.Expires < DateTimeOffset.UtcNow)
{
this.msAccountStatus = MSAccountStatus.ConnectedWithError;
}
}
return this.msAccountStatus;
}
}

Resources