How to call action result return json on another action result on asp.net core 2.2? - asp.net-mvc-4

Problem
How to call Action Result on another Action Result ?
I have two Action Result PostUserLogins and Action Result GetBranches
Can I call ActionResult getbranches inside ActionResult postlogin ?
[HttpPost(Contracts.ApiRoutes.Login.UserLogin)]
public IActionResult PostUserLogins([FromBody] Users user)
{
if (LoginStatus == 1)
{
// for Invalid Username Or password
dynamic request_status = new JObject();
request_status.Status = "failed";
request_status.Code = LoginStatus;
request_status.Message = errorMessage;
request_status.Branches = ????? How to call GetBranches Action;
// call action result to get GetBranches(Users user) as json;
JsonResults = "request_status" + JsonConvert.SerializeObject(request_status);
}
}
[HttpGet(Contracts.ApiRoutes.Login.GetBranches)]
public IActionResult GetBranches([FromRoute] string UserId)
{
List<Branches> branchesList = new List<Branches>();
for (int i = 0; i < dtBranches.Rows.Count; i++)
{
Branches branch = new Branches();
branch.BranchCode = Utilities.ObjectConverter.ConvertToInteger(dtBranches.Rows[i]["BranchCode"]);
branch.BranchName = Utilities.ObjectConverter.ConvertToString(dtBranches.Rows[i]["BranchAraName"]);
branchesList.Add(branch);
}
JsonResults = "request_status" + JsonConvert.SerializeObject(branchesList);
return Ok(JsonResults);
}

Regardless whether you could or not, you shouldn't.
The simplest way is to extract that logic to another method:
[HttpPost(Contracts.ApiRoutes.Login.UserLogin)]
public IActionResult PostUserLogins([FromBody] Users user)
{
if (LoginStatus == 1)
{
// for Invalid Username Or password
dynamic request_status = new JObject();
request_status.Status = "failed";
request_status.Code = LoginStatus;
request_status.Message = errorMessage;
request_status.Branches = GetBrancesImpl();
JsonResults = "request_status" + JsonConvert.SerializeObject(request_status);
}
}
[HttpGet(Contracts.ApiRoutes.Login.GetBranches)]
public IActionResult GetBranches([FromRoute] string UserId)
{
JsonResults = "request_status" + JsonConvert.SerializeObject(GetBrancesImpl());
return Ok(JsonResults);
}
private IEnumerable<Branches> GetBrancesImpl()
{
from branch in dtBranches.Rows
select new new Branches
{
BranchCode = Utilities.ObjectConverter.ConvertToInteger(dtBranches.Rows[i]["BranchCode"]),
BranchName = Utilities.ObjectConverter.ConvertToString(dtBranches.Rows[i]["BranchAraName"]),
};
}
Best would be to move this logic to a service class that holds the logic and can easily be tested.

If they are in the same controller,you could call it directly in PostUserLogins like:
public IActionResult PostUserLogins([FromBody] Users user)
{
//other logic
var result = GetBranches("myUserID") as OkObjectResult;
var json = result.Value.ToString().Substring(14);//remove the first "request_status" in the string to make it a valid json be deserialized later
request_status.Branches = JsonConvert.DeserializeObject<List<Branch>>(json);//get the Branch list
JsonResults = "request_status" + JsonConvert.SerializeObject(request_status);
}

Related

Getting ActionContext of an action from another

Can I get an ActionContext or ActionDescriptor or something that can describe a specific action based on a route name ?
Having the following controller.
public class Ctrl : ControllerBase
{
[HttpGet]
public ActionResult Get() { ... }
[HttpGet("{id}", Name = "GetUser")]
public ActionResult Get(int id) { ... }
}
What I want to do is when "Get" is invoked, to be able to have access to "GetUser" metadata like verb, route parameters , etc
Something like
ActionContext/Description/Metadata info = somerService.Get(routeName : "GetUser")
or
ActionContext/Description/Metadata info = somerService["GetUser"];
something in this idea.
There is a nuget package, AspNetCore.RouteAnalyzer, that may provide what you want. It exposes strings for the HTTP verb, mvc area, path and invocation.
Internally it uses ActionDescriptorCollectionProvider to get at that information:
List<RouteInformation> ret = new List<RouteInformation>();
var routes = m_actionDescriptorCollectionProvider.ActionDescriptors.Items;
foreach (ActionDescriptor _e in routes)
{
RouteInformation info = new RouteInformation();
// Area
if (_e.RouteValues.ContainsKey("area"))
{
info.Area = _e.RouteValues["area"];
}
// Path and Invocation of Razor Pages
if (_e is PageActionDescriptor)
{
var e = _e as PageActionDescriptor;
info.Path = e.ViewEnginePath;
info.Invocation = e.RelativePath;
}
// Path of Route Attribute
if (_e.AttributeRouteInfo != null)
{
var e = _e;
info.Path = $"/{e.AttributeRouteInfo.Template}";
}
// Path and Invocation of Controller/Action
if (_e is ControllerActionDescriptor)
{
var e = _e as ControllerActionDescriptor;
if (info.Path == "")
{
info.Path = $"/{e.ControllerName}/{e.ActionName}";
}
info.Invocation = $"{e.ControllerName}Controller.{e.ActionName}";
}
// Extract HTTP Verb
if (_e.ActionConstraints != null && _e.ActionConstraints.Select(t => t.GetType()).Contains(typeof(HttpMethodActionConstraint)))
{
HttpMethodActionConstraint httpMethodAction =
_e.ActionConstraints.FirstOrDefault(a => a.GetType() == typeof(HttpMethodActionConstraint)) as HttpMethodActionConstraint;
if(httpMethodAction != null)
{
info.HttpMethod = string.Join(",", httpMethodAction.HttpMethods);
}
}
// Special controller path
if (info.Path == "/RouteAnalyzer_Main/ShowAllRoutes")
{
info.Path = RouteAnalyzerRouteBuilderExtensions.RouteAnalyzerUrlPath;
}
// Additional information of invocation
info.Invocation += $" ({_e.DisplayName})";
// Generating List
ret.Add(info);
}
// Result
return ret;
}
Try this:
// Initialize via constructor dependency injection
private readonly IActionDescriptorCollectionProvider _provider;
var info = _provider.ActionDescriptors.Items.Where(x => x.AttributeRouteInfo.Name == "GetUser");

How to convert DocumentClient to IDocumentClient in gremlin?

I am using cosmos db to store and fetch data. Previously I was using DocumentClient like:
public class ProductRepository : IProductRepository
{
private DocumentClient _documentClient;
private DocumentCollection _graphCollection;
public ProductRepository(DocumentClient documentClient, DocumentCollection graphCollection)
{
_documentClient = documentClient;
_graphCollection = graphCollection;
}
public async Task Create(Product product)
{
var createQuery = CreateQuery(product);
IDocumentQuery<dynamic> query = _documentClient.CreateGremlinQuery<dynamic>(_graphCollection, createQuery);
if(query.HasMoreResults)
{
await query.ExecuteNextAsync();
}
}
public async Task<Product> Get(string id)
{
Product product = null;
var getQuery = #"g.V('" + id + "')";
var query = _documentClient.CreateGremlinQuery<dynamic>(_graphCollection, getQuery);
if (query.HasMoreResults)
{
var result = await query.ExecuteNextAsync();
if (result.Count == 0)
return product;
var productData = (JObject)result.FirstOrDefault();
product = new Product
{
name = productData["name"].ToString()
};
}
return product;
}
}
}
But it is not unit testable so I want to convert it to IDocumentClient but IDocumentClient doesn't contain definition for CreateGremlinQuery. So what is the best possible way to convert my methods so that they will be using IDocumentClient? Do I need to use CreateDocumentQuery? if yes, how can I convert CreateGremlimQuery to CreateDocumentQuery?
There are several ways to get around that. The simplest one would be to simply hard cast your IDocumentClient to DocumentClient.
If you go with that approach your code becomes:
public class ProductRepository : IProductRepository
{
private IDocumentClient _documentClient;
private DocumentCollection _graphCollection;
public ProductRepository(IDocumentClient documentClient, DocumentCollection graphCollection)
{
_documentClient = documentClient;
_graphCollection = graphCollection;
}
public async Task Create(Product product)
{
var createQuery = CreateQuery(product);
IDocumentQuery<dynamic> query = ((DocumentClient)_documentClient).CreateGremlinQuery<dynamic>(_graphCollection, createQuery);
if(query.HasMoreResults)
{
await query.ExecuteNextAsync();
}
}
public async Task<Product> Get(string id)
{
Product product = null;
var getQuery = #"g.V('" + id + "')";
var query = ((DocumentClient)_documentClient).CreateGremlinQuery<dynamic>(_graphCollection, getQuery);
if (query.HasMoreResults)
{
var result = await query.ExecuteNextAsync();
if (result.Count == 0)
return product;
var productData = (JObject)result.FirstOrDefault();
product = new Product
{
name = productData["name"].ToString()
};
}
return product;
}
}
You could also create your own extensions for IDocumentClient.
public static class MoreGraphExtensions
{
public static IDocumentQuery<T> CreateGremlinQuery<T>(this IDocumentClient documentClient, DocumentCollection collection, string gremlinExpression, FeedOptions feedOptions = null, GraphSONMode graphSONMode = GraphSONMode.Compact)
{
return GraphExtensions.CreateGremlinQuery<T>((DocumentClient)documentClient, collection, gremlinExpression, feedOptions, graphSONMode);
}
public static IDocumentQuery<object> CreateGremlinQuery(this IDocumentClient documentClient, DocumentCollection collection, string gremlinExpression, FeedOptions feedOptions = null, GraphSONMode graphSONMode = GraphSONMode.Compact)
{
return GraphExtensions.CreateGremlinQuery<object>((DocumentClient)documentClient, collection, gremlinExpression, feedOptions, graphSONMode);
}
}
It is a pre-release however, so I do think that Microsoft will get around moving the extension methods at the interface level.

multiple using for editorforModel

editorforModel but Now I need several different ones and I dont want to use html helpers onebyone. So I need something like this ;
#model JobTrackingSystem.Areas.Panel.ViewModels.Member.NewMemberModel
{
#Html.EditorForModel()
}
#model JobTrackingSystem.Areas.Panel.ViewModels.Member.MemberDashboardModel
{
#Html.EditorForModel()
}
So I want to keep them in 2 different divs in 1 page but also my controller wont allow using something like this
here is my controller ;
public ActionResult Add(NewMemberModel input, HttpPostedFileBase Resim)
{
if (!ModelState.IsValid)
{
ShowErrorMessage("Hatalı İşlem Yaptınız.");
return RedirectToAction("Index");
}
if (Resim == null)
{
ShowErrorMessage("Lütfen Boş Alan Bırakmayın.");
return RedirectToAction("Index");
}
var epostaKontrol = Db.MyMembers.FirstOrDefault(p => p.Mail == input.Mail);
if (epostaKontrol != null)
{
ShowErrorMessage("E-Mail Adresi Adı Kullanımda.");
return RedirectToAction("Index");
}
string[] folders = new string[] { "Uploads/Member/Orjinal/", "Uploads/Member/Kucuk/" };
string fileExt = Path.GetExtension(Path.GetFileName(Resim.FileName)).ToLower();
string orjName = Guid.NewGuid() + fileExt;
string filePath = Path.Combine(Server.MapPath("~/" + folders[0]), orjName);
string fileThumbPath = Path.Combine(Server.MapPath("~/" + folders[1]), orjName);
if (!(fileExt.Equals(".jpg") || fileExt.Equals(".jpeg") || fileExt.Equals(".png")))
{
ShowErrorMessage("Yalnızca .Jpg .Jpeg ve .Png Uzantılı Dosyalar Yükleyebilirsiniz.");
return RedirectToAction("Index");
}
Resim.SaveAs(filePath);
var thumber = ImageHelper.Thumber(750, filePath, fileThumbPath);
if (!String.IsNullOrWhiteSpace(thumber))
{
ShowErrorMessage(thumber);
return RedirectToAction("Index");
}
var item = new Member
{
Name = input.Name,
Mail = input.Mail,
SurName = input.SurName,
Phone = input.Phone,
Sira = Db.MyMembers.Max(m => (short?)m.Sira) ?? 0 + 1,
DepartmentType = (DepartmentTypeForUser)input.DepartmentTypeFor,
MemberType = (MemberTypeForUser)input.MemberTypeFor,
Image = "/" + folders[1] + orjName
};
item.SetPassword(input.Password);
Db.MyMembers.Add(item);
Db.SaveChanges();
ImageResizeModel model = new ImageResizeModel()
{
ImagePath = "/" + folders[1] + orjName,
ImageThumbPath = "/" + folders[1] + orjName,
SelectionSize = "[ 750, 750 ]",
};
return View("CropImage", model);
}
So How can I use multiple editorforModel for multiple times with different model field ? can I do anything in NewMemberModel class something like 2 methods and then call editorforModelMethod1 - editorforModelMethod2 ?
It's not entirely clear to me what you're asking (especially "controller won't allow", an actual error message would help us and could help you research the issue), but it looks like you could use a composite viewmodel:
public class NewMemberWithDashboardModel
{
public NewMemberModel NewMember { get; set; }
public MemberDashboardModel MemberDashboard { get; set; }
}
Then use it like this:
#Html.EditorFor(m => m.NewMember)
#Html.EditorFor(m => m.MemberDashboard)
And in your controller:
public ActionResult Add(NewMemberWithDashboardModel model, ...)

Issue with Web Api Custom Model Binder in MVC4

I am using Mvc4 with WebApi.
I am using Dto objects for the webApi.
I am having enum as below.
public enum Status
{
[FlexinumDefault]
Unknown = -1,
Active = 0,
Inactive = 100,
}
Dto structure is as follows.
[DataContract]
public class abc()
{
[DataMemebr]
[Required]
int Id{get;set;}
[DataMember]
[Required]
Status status{get;set}
}
I have created Custom Model Binder which will validate the enum(status) property in the dto object and return false if the enum value is not passed.
if the status enum property is not passed in the dto object,we should throw exception
public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
{
var input = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (input != null && !string.IsNullOrEmpty(input.AttemptedValue))
{
if (bindingContext.ModelType == typeof(Enum))
{
//var actualValue = null;
var value = input.RawValue;
in the api controller,i have action method like
public void Create([FromUri(BinderType = typeof(EnumCustomModelBinder))]abcdto abc)
{
In global.asax.cs
i have set like
GlobalConfiguration.Configuration.BindParameter(typeof(Enum), new EnumCustomModelBinder());
the issue i am facing is the custombinder
var input = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
,the input value is coming as null.
Please sugggest
I found the solution
This works fine,but the default implementation of model binder is missing.
public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var json = actionContext.Request.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(json))
{
var jsonObject = (JObject) Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();
var requiredProperties = bindingContext.ModelType.GetProperties().Where(p =>p.GetCustomAttributes(typeof(RequiredAttribute),
false).Any()).ToList();
var missingProperties = requiredProperties.Where(bindingProperty => !jsonPropertyNames.Contains(bindingProperty.Name)).ToList();
if (missingProperties.Count > 0)
{
missingProperties.ForEach(
prop =>
{
if (prop.PropertyType.IsEnum)
actionContext.ModelState.AddModelError(prop.Name, prop.Name + " is Required");
});
}
var nullProperties = requiredProperties.Except(missingProperties).ToList();
if (nullProperties.Count > 0)
{
nullProperties.ForEach(p =>
{
var jsonvalue = JObject.Parse(json);
var value = (JValue)jsonvalue[p.Name];
if (value.Value == null)
{
actionContext.ModelState.AddModelError(p.Name, p.Name + " is Required");
}
});
}
}
// Now we can try to eval the object's properties using reflection.
return true;
}

MVC4 - during post controller action, the WebSecurity.CurrentUserId is losing it's value, and becomes -1

Somehow, in this controller, after the SaveChanges, the CurrentUserId becomes -1.
The data post works, and the CurrentUserId has it's logged in value (example 8888), but after the SQL insert, the WebSecurity.CurrentUserId becomes -1. Any clue? During debug I can't find where and why.
// POST: /Account/Edit
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(UserProfile model)
{
if (ModelState.IsValid)
{
using (var context = new dbContext())
{
var id = WebSecurity.CurrentUserId;
var account = context.UserProfiles.Find(id);
UpdateModel(account);
context.SaveChanges();
return RedirectToAction("Index", "Account");
}
}
else
{
return View(model);
}
}
that will always return -1, what you need is the below code
int currentuserid = WebSecurity.GetUserId(username);
You can then validate that the userid above, matches the userid in the model, in order to prevent users, changing other users code
as Additional. I use this in my Base Controller:
public int GetUserId()
{
var userid = "0";
if (Request.IsAuthenticated && User.Identity.Name != null)
{
var membershipUser = Membership.GetUser(User.Identity.Name);
if (membershipUser != null)
{
if (membershipUser.ProviderUserKey != null)
{
userid = membershipUser.ProviderUserKey.ToString();
}
}
}
return Convert.ToInt32(userid);
}