thank you for your reply,
i added BeginExecuteCore in base controller like this
`public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
//string email = string.Empty;
dbEntities dbcontext = new dbEntities();
var userRoleName = (from n in dbcontext.VAgentClientEmails where n.Email == User.Identity.Name select n.Role).FirstOrDefault();
if (userRoleName == "SuperAdmin")
RouteData.Values["role"] = userRoleName;
else
RouteData.Values["role"] = "";
return base.BeginExecuteCore(callback, state);
}`
and i have given in home controller like this
[Route("~/{role}/SavedSearch/Index")]
public ActionResult Index()
{
...
}
its working for admin/savedsearch/index
and also if i give fjsdfk/savedsearch/index its working
in the above case it should not work..
and in else case i dont want role
do i need to do any changes?
Related
I am able to get the User.Identity.Name value from Login Controller after redirect to Dashboard(another Controller) i am not able to receive the User.Identity.Name value (i am getting Null value)
below is my code:-
[HttpPost]
public async Task<ActionResult> SignInCallback()
{
var token = Request.Form["id_token"];
var state = Request.Form["state"];
var claims = await ValidateIdentityTokenAsync(token, state);
var id = new ClaimsIdentity(claims, "Cookies");
Request.GetOwinContext().Authentication.SignIn(id);
string Id = System.Web.HttpContext.Current.User.Identity.Name;
return Redirect("/Dashboard");
}
After return Redirect("/Dashboard"); Getting null value in Dashbord Controller.
Below is my Dashborad controller code :-
public ActionResult Index()
{
string Id = System.Web.HttpContext.Current.User.Identity.Name;
return View();
}
I'm trying to build a Workflow that add a Contact to a marketing list.
Everything seems to be fine, but when the code finishes firing, and I go to the marketing list -> members the contact is not in the list.
public class ContactToMList : CodeActivity
{
[Input("Contatto")]
[ReferenceTarget("contact")]
public InArgument<EntityReference> contact { get; set; }
[Input("Marketing List")]
[ReferenceTarget("list")]
public InArgument<EntityReference> MList { get; set; }
[Input("Inserimento")]
public InArgument<bool> inserimento { get; set; }
bool action = false;
private static IOrganizationService myService = null;
private static Log_Entity log = new Log_Entity(string.Empty, myService);
protected override void Execute(CodeActivityContext executionContext)
{
try
{
ITracingService tracingService = executionContext.GetExtension<ITracingService>();
// Create the context
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
// Create the Organiztion service
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
myService = service;
log.WriteLog("");
// Get the target entity from the context
Entity target = (Entity)context.InputParameters["Target"];
Guid contactiId = contact.Get<EntityReference>(executionContext).Id;
Guid ListId = MList.Get<EntityReference>(executionContext).Id;
bool insert = inserimento.Get<bool>(executionContext);
// Prepare DataContext by using AutoGenerated cs file
XrmDataContext datacontext = new XrmDataContext(service);
var MyContact = (from c in datacontext.ContactSet where c.ContactId == contactiId select c.Id).ToArray();
var MyList = (from l in datacontext.ListSet where l.Id == ListId select l).ToList().FirstOrDefault();
// tutti i membri della lista di marketing
var members = (from m in datacontext.ListMemberSet where m.ListId.Id == MyList.ListId select m.EntityId.Id).ToArray();
foreach (Guid id in members)
if (MyContact.FirstOrDefault() == id)
action = true;
if (insert && !action)
{
AddListMembersListRequest AddMemberRequest = new AddListMembersListRequest();
AddMemberRequest.ListId = ListId;
AddMemberRequest.MemberIds = MyContact;
// Use AddListMembersListReponse to get information about the request execution
AddListMembersListResponse AddMemberResponse = service.Execute(AddMemberRequest) as AddListMembersListResponse;
//service.Update(MyList);
}
else if (!insert && action)
{
RemoveMemberListRequest RemoveMemberRequest = new RemoveMemberListRequest();
RemoveMemberRequest.ListId = ListId;
RemoveMemberRequest.EntityId = MyContact.FirstOrDefault();
// Use AddListMembersListReponse to get information about the request execution
RemoveMemberListResponse RemoveMemberResponse = service.Execute(RemoveMemberRequest) as RemoveMemberListResponse;
// service.Update(MyList);
}
}
catch (Exception ex)
{
log.WriteLog(ex.Message);
}
}
}
aren't you erasing your values for AddMemberRequest.MemberIds after you set it?
EDIT:
Ok, I think I found it this time. Your public InArgument<bool> inserimento { get; set; } is likely the culprit.
In this case, your Workflow activity expects this to be defined upstream of the call to this Workflow. It's very likely statically set and never changed for both the Insert and Remove instances. If this is true, then it's being essentially hard coded for the Insert case, which makes the else if (!insert && action) evaluate to True for Remove and the if (insert && !action) evaluate to False for the Insert.
Since the code does work for Remove, it's reasonable to assume the bool action is working; therefore, I would start by looking into the other bool variable.
Let me know if I've missed it. (or if I'm right, I wouldn't mind the green check mark.)
I need to recurse through the contents of a document library and display them on a webpage using MVC. However I get the following error when trying to run my code: " The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."
Any help would be appreciated!
Here is my code:
public class HomeController : Controller
{
public ActionResult Index()
{
DefaultModel model = new DefaultModel();
using (ClientContext context = new ClientContext("MySPSite"))
{
List list = context.Web.Lists.GetByTitle("DocumentLibrary");
Folder rootFolder = list.RootFolder;
IEnumerable<SharePointItemBaseModel> items = ProcessFolder(rootFolder);
model.items.AddRange(items);
}
return View(model);
}
public IEnumerable<SharePointItemBaseModel> ProcessFolder(Folder folder)
{
List<SharePointItemBaseModel> listItems = new List<SharePointItemBaseModel>();
foreach (Folder childFolder in folder.Folders)
{
FolderModel folderModel = new FolderModel();
IEnumerable<SharePointItemBaseModel> childFolders = ProcessFolder(childFolder,context);
folderModel.Items.AddRange(childFolders);
listItems.Add(folderModel);
}
foreach (Microsoft.SharePoint.Client.File file in folder.Files)
{
DocumentModel documentModel = new DocumentModel();
documentModel.Name = file.Title;
documentModel.modifiedBy = file.ModifiedBy.ToString();
listItems.Add(documentModel);
}
return listItems;
}
public ActionResult About()
{
return View();
}
}
}
I managed to fix this myself.
In my recursive method I just used
context.Load(folder.Folders);
and
context.Load(folder.Files);
this initialized the collection allowing me to use it in my foreach loops
My question is related to this one, but instead of changing a question I thought it Would be better to ask a new one.
I've now got a list of IContent items using the _taxonomyService.GetContentItems(term)
as suggested by #Bertrand Le Roy in the question mentioned above
But how do I turn this into a useful Html string, that I can update on the client via an ajax post?
public class HomeController : Controller
{
private readonly IOrchardServices _services;
private readonly IBlogService _blogService;
private readonly IBlogPostService _blogPostService;
private readonly IFeedManager _feedManager;
private readonly IArchiveConstraint _archiveConstraint;
private readonly ITaxonomyService _taxonomyService;
public HomeController(
IOrchardServices services,
IBlogService blogService,
IBlogPostService blogPostService,
IFeedManager feedManager,
IShapeFactory shapeFactory,
IArchiveConstraint archiveConstraint,
ITaxonomyService taxonomyService) {
_services = services;
_blogService = blogService;
_blogPostService = blogPostService;
_feedManager = feedManager;
_archiveConstraint = archiveConstraint;
T = NullLocalizer.Instance;
Shape = shapeFactory;
_taxonomyService = taxonomyService;
}
dynamic Shape { get; set; }
public Localizer T { get; set; }
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult ListByArchive(string path, IEnumerable<string> category)
{
try
{
// get year and month from path
path = path.ToLower().Substring(path.LastIndexOf(#"/archive/", StringComparison.Ordinal) + 9);
var date = path.Split('/');
var month = int.Parse(date[1]);
var year = int.Parse(date[0]);
// get list of terms ids from strings
var taxonomyPart = _taxonomyService.GetTaxonomyByName("Category");
var terms = category.Select(cat => _taxonomyService.GetTermByName(taxonomyPart.Id, cat)).ToList();
// get list of content items by term avoiding duplicates
var posts = new List<IContent>();
foreach (var term in terms)
{
var items = _taxonomyService.GetContentItems(term);
foreach (var item in items)
{
if (!posts.Select(p => p.Id).Contains(item.Id))
{
posts.Add(item);
}
}
}
// filter by date
var byDate = posts.Where(x =>
{
var publishedUtc = x.ContentItem.As<CommonPart>().CreatedUtc;
return
publishedUtc != null
&& publishedUtc.Value.Month == month
&& publishedUtc.Value.Year == year;
});
....
This gets me my list of IContent, but how do I get a the html for the rendered list ?
I've tried
var range = byDate.Select(x => _services.ContentManager.BuildDisplay(x, "Summary"));
var list = Shape.List();
list.AddRange(range);
dynamic viewModel = Shape.ViewModel().ContentItems(list);
var html = View((object)viewModel);
return Json(new { html = html });
but it returns an empty view,
{"html":{"MasterName":"","Model":[],"TempData":[],"View":null,"ViewBag":{},"ViewData":[],"ViewEngineCollection":[{"HostContainer":{}}],"ViewName":""}}
I have a view called ListByArchive.cshtml, that matches the one it the orchard.blog module.
As an aside, I should be returning a partial view result, instead of a jason result, but when I change the Action result type I get a 404. result from the server.
This is never going to work the way you think it does:
var html = View((object)viewModel);
The easiest way to return HTML representing the content item is to:
Mark your action with ThemedAttribute, ie. [Themed(false)]
Return new ShapeResult(this, viewModel) (full view) or new ShapePartialResult(this, viewModel) (partial view) instead of Json(new { html = html })
Rendering a shape/view to string inside the action is also possible, but way more tricky.
EDIT: I assumed you already have /Views/ViewModel.cshtml file in place. Like Bertrand Le Roy noted below - if it's not there, you need to add one to be able to create a shape using Shape.ViewModel().
I have a WCF REST service that takes some parameters and sends an email. The template for the email is an MVC3 action. Essentially I want to render that action to a string.
If it were an ASP.NET WebForm, I could simply use Server.Execute(path, stringWriter, false). However when I plug in the path to my action, I get Error executing child request.
I have full access to HttpContext from my service (AspNetCompatibilityRequirementsMode.Allowed).
I know there are other answers out there for rendering actions to strings from within the context of a controller. How do I do this when I'm outside that world, but still on the same server (and, for that matter, in the same app)?
I cobbled together an answer based on several different google searches. It works, but I'm not 100% sure it's as lean as it could be. I'll paste the code for others to try.
string GetEmailText(TemplateParameters parameters) {
// Get the HttpContext
HttpContextBase httpContextBase =
new HttpContextWrapper(HttpContext.Current);
// Build the route data
var routeData = new RouteData();
routeData.Values.Add("controller", "EmailTemplate");
routeData.Values.Add("action", "Create");
// Create the controller context
var controllerContext = new ControllerContext(
new RequestContext(httpContextBase, routeData),
new EmailTemplateController());
var body = ((EmailTemplateController)controllerContext.Controller)
.Create(parameters).Capture(controllerContext);
return body;
}
// Using code from here:
// http://blog.approache.com/2010/11/render-any-aspnet-mvc-actionresult-to.html
public class ResponseCapture : IDisposable
{
private readonly HttpResponseBase response;
private readonly TextWriter originalWriter;
private StringWriter localWriter;
public ResponseCapture(HttpResponseBase response)
{
this.response = response;
originalWriter = response.Output;
localWriter = new StringWriter();
response.Output = localWriter;
}
public override string ToString()
{
localWriter.Flush();
return localWriter.ToString();
}
public void Dispose()
{
if (localWriter != null)
{
localWriter.Dispose();
localWriter = null;
response.Output = originalWriter;
}
}
}
public static class ActionResultExtensions
{
public static string Capture(this ActionResult result, ControllerContext controllerContext)
{
using (var it = new ResponseCapture(controllerContext.RequestContext.HttpContext.Response))
{
result.ExecuteResult(controllerContext);
return it.ToString();
}
}
}