Thursday 11 June 2015

repository method implementation

public class QuestionRepository : IQuestionRepository



{

private readonly IAmbientDbContextLocator _ambientDbContextLocator;

private AuthDbContext DbContext



{

get



{

var dbContext = _ambientDbContextLocator.Get<AuthDbContext>();

if (dbContext == null)

throw new InvalidOperationException("No ambient DbContext of type AuthDbContext found. This means that this repository method has been called outside of the scope of a DbContextScope. A repository must only be accessed within the scope of a DbContextScope, which takes care of creating the DbContext instances that the repositories need and making them available as ambient contexts. This is what ensures that, for any given DbContext-derived type, the same instance is used throughout the duration of a business transaction. To fix this issue, use IDbContextScopeFactory in your top-level business logic service method to create a DbContextScope that wraps the entire business transaction that your service method implements. Then access this repository within that scope. Refer to the comments in the IDbContextScope.cs file for more details.");

return dbContext;



}

}

public QuestionRepository(IAmbientDbContextLocator ambientDbContextLocator)



{

if (ambientDbContextLocator == null) throw new ArgumentNullException("ambientDbContextLocator");



_ambientDbContextLocator = ambientDbContextLocator;

}

public List<Question> GetAll()



{

return DbContext.Questions.ToList<Question>();



}

public Question Get(int questionId)



{

return DbContext.Questions.Find(questionId);



}

public Task<Question> GetAsync(int questionId)



{

return DbContext.Questions.FindAsync(questionId);



}

public void Add(Question question)



{

DbContext.Questions.Add(question);

}

public void RemoveUserQuestion(Guid userId, int userQuestionId)



{

var uq = DbContext.UserQuestions.FirstOrDefault(x => x.QuestionId == userQuestionId &&



x.UserGuid == userId);

DbContext.UserQuestions.Remove(uq);

DbContext.SaveChanges();

}

public int AddUserQuestion(UserQuestion userQuestion)



{

DbContext.UserQuestions.Add(userQuestion);

return userQuestion.Id;



}

public IList<UserQuestion> GetUserQuestions(Guid userGuid)



{

var ql = (from u in DbContext.UserQuestions

join q in DbContext.Questions on u.QuestionId equals q.Id

where u.UserGuid == userGuid

select new



{

QuestionId = u.QuestionId,

Answer = u.Answer,

UserGuid = userGuid

}).ToList().Select(q => new UserQuestion(q.UserGuid, q.QuestionId, q.Answer)).ToList<UserQuestion>();

return ql;



}

public void RemoveUserQuestions(Guid userGuid)



{

var uq = DbContext.UserQuestions.Where(x => x.UserGuid == userGuid).ToList();



DbContext.UserQuestions.RemoveRange(uq);

DbContext.SaveChanges();

}

public UserQuestion GetUserAnswer(Guid userGuid, int questionid)



{

var useranswer = DbContext.UserQuestions.Include("Question").FirstOrDefault(x => x.UserGuid == userGuid && x.Question.Id == questionid);

if (useranswer != null)



{

return new UserQuestion



{

Answer = useranswer.Answer,

};

}

return null;



}

 

 

public void Update(Question question)



{

DbContext.Entry(question).State = EntityState.Modified;



DbContext.SaveChanges();

}

}


Repository Interface in MVC


 you can use all these  interface in...

public interface IUserRepository : IRepository<User>



{
 
User FindByUserName(string userName);

User FindByEmail(string email);

User FindByResetToken(Guid resetToken);

void Update(User item);

User Get(Guid userId);

Task<User> GetAsync(int userId);

void Add(User user);

User FindByUserNameUserGuid(string userName, string userGuid);

User FindByUserEmailUserGuid(string userEmail, string userGuid);



}

Wednesday 10 June 2015

how to call web api in mvc controller for post method


//[HttpPost]
   public async Task<ActionResult> AddEmp(MyObj myObj)
{
  try
{
  var apiResult= await SendToApi(HttpVerbs.Post, "Employee/AddEmp", myObt);
if (apiResult.IsSuccessStatusCode)
{
  try
{
  return new HttpStatusCodeResult(HttpStatusCode.OK);
}
  catch (Exception ex)
{
  Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.BrokenRules);
}
  return new HttpStatusCodeResult(HttpStatusCode.OK);
}
  // If Failed return status code and the Broken rules
Response.StatusCode = (int)apiResult.StatusCode;
return Json(apiResult.Content.ReadAsAsync<List<CustomRule>>().Result);
}
  catch (Exception ex)
{
  Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.CustomRule);
}

how to call web api in mvc controller get method


[HttpGet]
public async Task<ActionResult> GetAllEmp(atring type)
{
  if (!string.IsNullOrEmpty(type?.ToString()))
{
  var apiResult =await SendToApi(HttpVerbs.Get,string.Format("Employee/GetAllEmp/{0}", type), ));
if (apiResult .IsSuccessStatusCode)
{
  return Json(apiResult.Content.ReadAsAsync<List<MyEmpObjModel>>().Result,JsonRequestBehavior.AllowGet);
}
  // If Failed return status code and the Broken rules
Response.StatusCode = (int)(apiResult .StatusCode;
return Json((apiResult .Content.ReadAsAsync<List<CustomRule>>().Result);
}
  Response.StatusCode = (int) HttpStatusCode.BadRequest;
return Json(new CustomRule("", "Etype required"));
}

Friday 5 June 2015

update method in repository


in interface
 void Update(User user);

implementation

 public void Update(User user)
        {
            DbContext.Entry(user).State = EntityState.Modified;
            DbContext.SaveChanges();
        }

how to add method in repository in MVC C#


add in interface

 public interface IUserRepository : IRepository<User>
    {
        void Add(User user);
}

implementation

 public void Add(User user)
        {
            DbContext.Users.Add(user);
            user.Events.Add(new NewUserEvent { User = user });
        }