Friday 31 July 2015

Get data with where clause in MVC C# Linq

constituent.ForEach(x => constituentList.Add(new UpdateConstituentModel
        //        {
        //            Id=x.Id,
        //            FirstName = x.FirstName,
        //            LastName = x.LastName,
        //            DisplayName = x.DisplayName,
        //            EmailAdd = x.Emails.Where(y => y.EmailPriority == EmailPriority.First).Select(y => y.EmailAddress).FirstOrDefault(),
        //            PrimaryAddress = primaryAddress
        //        }));

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 });
        }

Monday 13 April 2015

join between 3 datatable in C#

  #region Join 3 DataTable for Common Date with Values
        public DataTable JoinDatatableForCommonData(DataTable dtTSeries, DataTable dtPcpSeries, DataTable dtSnSeries)
        {
            DataTable dtOutput = new DataTable("dtOutput");
            try
            {
                //dt.Columns.Add("Station Detail Id", typeof(string));
                dtOutput.Columns.Add("Date", typeof(string));
                dtOutput.Columns.Add("month_year", typeof(string));
                dtOutput.Columns.Add("Series1", typeof(decimal));
                dtOutput.Columns.Add("Series2", typeof(decimal));
                dtOutput.Columns.Add("Series3", typeof(decimal));

                var result = from dtT in dtTSeries.AsEnumerable()
                             join dtPcp in dtPcpSeries.AsEnumerable()
                             on dtT.Field<string>("month_year") equals dtPcp.Field<string>("month_year")
                             join dtSn in dtSnSeries.AsEnumerable()
                             on dtT.Field<string>("month_year") equals dtSn.Field<string>("month_year")


                             select dtOutput.LoadDataRow(new object[]
                            {
                              dtT.Field<string>("Date"),
                              dtT.Field<string>("month_year"),
                              dtT.Field<decimal?>("Value"),
                              dtPcp.Field<decimal?>("Value"),
                              dtSn.Field<decimal?>("Value")
                         
                            }, false);
                //---------------copy output of result into datatable named 'dtOutput'---------------//

                if (result != null && result.Count() > 0)
                {
                    dtOutput = result.CopyToDataTable();
                }
            }
            catch (Exception ex)
            {
                LoggerClass.ErrorException(ex.Message, ex);
            }
            return dtOutput;
        }
        #endregion

group the data in grid in C#

  #region Group the GridValue
        public DataTable GroupGrid(DataTable dt)
        {
            DataTable dtA = new DataTable();
            dtA = dt.Clone();
            string strCurrentValue = string.Empty;
            string strPreviousValue = string.Empty;
            int m;
            int n = 1;
            for (m = 0; m < dt.Rows.Count; m++)
            {
                if (n == 1)   // for first value
                {
                    DataRow dr = dtA.NewRow();
                    dr["Select"] = false;
                    dr["season"] = dt.Rows[0]["season"].ToString();         //season-> month/monsoon
                    dr["cluster_no"] = dt.Rows[0]["cluster_no"].ToString();
                    dr["equation"] = dt.Rows[0]["equation"].ToString();

                    dtA.Rows.Add(dr);
                }
                if (n > 1)
                {
                    if (m == 1)
                    {
                        object cellValuePrevious = dt.Rows[m]["season"];
                        strPreviousValue = cellValuePrevious.ToString().Trim();
                    }

                    object cellValue = dt.Rows[m]["season"];
                    strCurrentValue = cellValue.ToString().Trim();

                    if (strCurrentValue != strPreviousValue) // Now compare the current value with previous value
                    {
                        DataRow dr = dtA.NewRow();
                        dr["Select"] = false;
                        dr["season"] = dt.Rows[m]["season"].ToString();
                        dr["cluster_no"] = dt.Rows[m]["cluster_no"].ToString();
                        dr["equation"] = dt.Rows[m]["equation"].ToString();
                        dtA.Rows.Add(dr);
                        strPreviousValue = strCurrentValue;
                    }
                    else
                    {
                        DataRow dr = dtA.NewRow();
                        dr["Select"] = false;
                        dr["season"] = string.Empty;
                        dr["cluster_no"] = dt.Rows[m]["cluster_no"].ToString();
                        dr["equation"] = dt.Rows[m]["equation"].ToString();
                        dtA.Rows.Add(dr);
                        strPreviousValue = strCurrentValue;
                    }
                }
                n++;
            }
            return dtA;
        }
        #endregion

select value with where condition in C# linq

var riverId = _dtRiverList.AsEnumerable()
                                  .Where(r => r.Field<string>("river_name").Equals(basin))
                                  .Select(r => r.Field<Int32>("river_id"));
                if (riverId.Count() > 0)
                {
                    _dtSubBasin = new DataTable("_dtSubBasin");
                    objRModelingDAL.BasinId = riverId.ElementAt(0);
                    _dtSubBasin = objRModelingDAL.GetSubBasin();
                }

how to import row in C# datatable

 #region  Get Basin
        public DataTable GetRiver()
        {
            try
            {
                _dtRiverList = new DataTable("_dtRiverList");
                DataTable dt = objRModelingDAL.GetRiverList();
                _dtRiverList = dt.Clone();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (
                        (Convert.ToInt32(dt.Rows[i]["river_id"]) == 8) || (Convert.ToInt32(dt.Rows[i]["river_id"]) == 9) ||
                        (Convert.ToInt32(dt.Rows[i]["river_id"]) == 20) || (Convert.ToInt32(dt.Rows[i]["river_id"]) == 25) ||
                        (Convert.ToInt32(dt.Rows[i]["river_id"]) == 26) || (Convert.ToInt32(dt.Rows[i]["river_id"]) == 27) ||
                        (Convert.ToInt32(dt.Rows[i]["river_id"]) == 28)
                        )
                    {
                        _dtRiverList.ImportRow(dt.Rows[i]);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerClass.ErrorException(ex.Message, ex);
            }
            return _dtRiverList;
        }
        #endregion

Wednesday 18 March 2015

groupby query in C# linq

 var query = students.GroupBy(x => x.LastName)
                                .Select(g => g.FirstOrDefault())
                //.OrderByDescending(x => x.LastName)
                                .Select(x => new { lastName = x.LastName, fName = x.FirstName });

            var qqq = students.Select(s => s.LastName)
            .Distinct()
            .OrderByDescending(p => p)
            .Select(p => new { RR = p });


            var q = students.Where(x => x.LastName.Equals("Feng"));
            var q1 = students.GroupBy((x => x.LastName));

            Console.WriteLine("Group by a single property in an object:");

            var query1 =
                from s in students
                group s by s.LastName into newGroup
                orderby newGroup.Key
                select newGroup;

            foreach (var nameGroup in query1)
            {
                Console.WriteLine("Key: {0}", nameGroup.Key);
                foreach (var student in nameGroup)
                {
                    Console.WriteLine("\t{0}, {1}", student.LastName, student.FirstName);
                }
            }

Tuesday 17 March 2015

Type of hosting in WCF

WCF service can be hosted by following mechanism
  • IIS
    Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
  • Windows Activation Service
    (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
  • Self-Hosting
    WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
  • Windows Service
    WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

Convert XML to JSON using C#/LINQ

using System;using System.Linq;using System.Web.Script.Serialization;using System.Xml.Linq;class Program{
    static void Main()
    {
        var xml = 
        @"<Columns>
          <Column Name=""key1"" DataType=""Boolean"">True</Column>
          <Column Name=""key2"" DataType=""String"">Hello World</Column>
          <Column Name=""key3"" DataType=""Integer"">999</Column>
        </Columns>";
        var dic = XDocument
            .Parse(xml)
            .Descendants("Column")
            .ToDictionary(
                c => c.Attribute("Name").Value, 
                c => c.Value
            );
        var json = new JavaScriptSerializer().Serialize(dic);
        Console.WriteLine(json);
    }}
produces:
{"key1":"True","key2":"Hello World","key3":"999"}