mercredi 31 août 2016

MVC Authentication In Controller

We are trying to do some website which has login screen. But we have a problem. Our domain is localhost/Login/User. But if user enters localhost/Home/Index, he/she can reach our main site without login. So we wrote [Authorize] to our Index Controller. But I couldn't find out what I must use. Am I have to use AuthorizeAttribute in our project?

#Login Page
public class LoginController : Controller
{
     //GET: Login
    [IntranetAction]
    public ActionResult Users()
    {
        return View();
    }

    public ActionResult Authentication(UserLoginInfo loginInfo)
    {
        bool isAuthenticated = new LdapServiceManager().isAuthenticated(loginInfo);


        if (isAuthenticated)
        {
            //AUTHORIZED
            Session["userName"] = loginInfo.username;
            return Redirect("/Home/Index");
        }
        //WORNG PASSWORD, BACK TO LOGIN PAGE
        TempData["message"] = "Yanlış kullanıcı adı ya da şifre";
        return Redirect("/");
    }
}

Index Page

[Authorize]
public ActionResult Index()
{
    Session["ip"] = Request.UserHostAddress;
    if (IsDbExists())
    {
        _contactList = new List<Contact>();
        UpdateOperations();
        return View(_contactList);
    }

    Response.Redirect("/Loading/LoadingScreen");
    return null;
}

How can I access index in my LoginController/Authentication function

how to check paypal email Id using GetVerifiedStatus method in mvc3

Please any one guide me how to check email id is exists or not in paypal using adaptive api in asp.net mvc3

thanks in advance

lundi 29 août 2016

MVC C# .Net SQL String New line characters

I'm trying to pass a bunch of form values as parameters to a stored procedure but if i add them to a new line the string is getting '\n\r' new line characters & the SQL code execution is failing. Could you please suggest a better approach for this,

Code Snippet:

sqlstring = @"GetPerfCountersData_N '" + c.servername + "','" + c.countertype.Trim() + "','" + c.counterlist.Trim() + "','" + c.dbname + "','" + c.startdate + "'";

Thanks

SignalR connections with backplate

We are trying to scale out our environment. I was using a ConnectionMapper class like the one here: http://ift.tt/1xmEnNh to keep a list of connections.

How would I make this work in a cluster (2 nodes)? would I implement a backplane? http://ift.tt/1uW6SyR

And then move the connection mappings to SQL DB?

This is for an MVC application.

The remote server returned an error: (500) Internal Server Error in mvc

why I am getting "The remote server returned an error: (500) Internal Server Error. Please review my below code

private object ViewProgramDetails(Func<string, JsonResult> GetPrograms,string epicid)
        {
            try
            {
                var path = WebConfigurationManager.AppSettings["ProgramDetailsUrl"] + "?epicid=" + epicid;

                XElement elem = XElement.Load(path);


                var inputheaderdictionary = new Dictionary<string, string>();
                Dictionary<string, string> xmlDatadictionary = elem.Attributes().ToDictionary(attribute => attribute.Name.ToString().ToUpper(), attribute => attribute.Value);

                List<string> elementList = (from InputHeaderElements val in Enum.GetValues(typeof(InputHeaderElements)) select val.ToString().ToUpper()).ToList();

                foreach (string ele in elementList)
                {
                    if (xmlDatadictionary.ContainsKey(ele))
                    {
                        try
                        {
                            if (!ele.ToUpper().Equals("EPIC") && !ele.ToUpper().Equals("EEQU"))
                            {
                                inputheaderdictionary.Add(ele, xmlDatadictionary[ele]);

                            }


                        }
                        catch (Exception)
                        {
                            //do nothing
                        }
                    }
                }

                var result = inputheaderdictionary.ToList();

                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(string.Empty);
            }

        }

Iam struck on this line. and dont knw what to do.I check many solution from stackOverflow but didnt get an idea.This below line through an error.

XElement elem = XElement.Load(path);

Can anyone solve me problem.Thanks

dimanche 28 août 2016

Add data from one model to another?

I am displaying data from database using a model. While displaying data I have added one more column with textboxes so that a user can input the quantity in that text box. After submitting the data I want that data to be stored in different table how can I achieve the.

for Example

I have a table Inventory id name mrp

View I have four columns id name mrp (Textbox)

The View data should get submitted to Orders table.

How can I do this.

samedi 27 août 2016

Need help in restful apis in AKA-HTML

I need help to write restful apis in AKKA-HTTP with scala in which read data from database. ALL CRUD(Create, Retrieve, Update and Delete). Plz Help me in this ..

vendredi 26 août 2016

How to use c# MVC MapRoute correctly

I have url like this

http:www.site.com/Item(this is View)/Title(Rich url for SEO)/231698507985 (Id of item)

How can I correctly maproute this to the View "Item" ? and in same time read Id of an item?

AreaPartial in MVC3

I have to reproduce one behavior from a MVC4 projet in a MVC3 one: rendering a partial area. In the MVC4 project I use this extention function :

/// <summary>Renders a partial view that is found in the specified area</summary>
public static MvcHtmlString AreaPartial(HtmlHelper helper, string viewPath, 
                                        System.Web.Mvc.ViewDataDictionary viewData = null, 
                                        object model = null)
{
    return helper.AreaPartial(
        partial: viewPath,
        area: null,
        model: model,
        viewData: viewData);
}

In the MVC3 it does not seem that AreaPartial exists... What could be done to achieve the same result in MVC3?

C# ExecuteSqlCommand Is Not Returning Output From Stored Proceedure

Salaamun Alekum My C# ExecuteSqlCommand is not returning output from stored proceedure.

I actually need last inserted row's Id

Here is my Stored Proceedure

ALTER PROCEDURE [dbo].[PatientInsert]
@FirstName nvarchar(Max),
@MiddleName nvarchar(Max),
@LastName nvarchar(Max),
@Gender nvarchar(Max),
@CNICNumber nvarchar(Max),
@DateOfBirth datetime,
@Country nvarchar(max),
@StateOrProvince nvarchar(max),
@City nvarchar(max),
@Address nvarchar(max),
@CellNumber nvarchar(max),
@TelephoneNumber nvarchar(max),
@Email nvarchar(max),
@NOKFirstName nvarchar(max),
@NOKLastName nvarchar(max),
@NOKRelation nvarchar(max),
@NOKCNICNumber nvarchar(max),
@NOKCellNumber nvarchar(max),
@Title int,
@PicturePath nvarchar(max),
@LastCreatedId INT  OUTPUT
AS 
BEGIN 
     SET NOCOUNT ON 

INSERT INTO [dbo].[Patients]
           ([FirstName]
           ,[MiddleName]
           ,[LastName]
           ,[Gender]
           ,[CNICNumber]
           ,[DateOfBirth]
           ,[Country]
           ,[StateOrProvince]
           ,[City]
           ,[Address]
           ,[CellNumber]
           ,[TelephoneNumber]
           ,[Email]
           ,[NOKFirstName]
           ,[NOKLastName]
           ,[NOKRelation]
           ,[NOKCNICNumber]
           ,[NOKCellNumber]
           ,[Title]
           ,[PicturePath])

     VALUES
          (
            @FirstName ,
            @MiddleName ,
            @LastName ,
            @Gender ,
            @CNICNumber ,
            @DateOfBirth,
            @Country ,
            @StateOrProvince ,
            @City ,
            @Address ,
            @CellNumber ,
            @TelephoneNumber ,
            @Email ,
            @NOKFirstName ,
            @NOKLastName ,
            @NOKRelation ,
            @NOKCNICNumber ,
            @NOKCellNumber ,
            @Title,
            @PicturePath
        )

        SELECT @LastCreatedId = SCOPE_IDENTITY()

END

I have tested this stored proceedure and it is working perfectly in SQL Server Management Studio

Here Is Stored Procedure Execution Image as I am using SCOPE_IDENTITY() and returning it as OUTPUT throught @LastCreatedId

You can see in image data is inserting perfectly in database but in C# I can send data correctly to database but can not retentive OUTPUT data of @LastCreatedId

And here is my C# code to use this stored procedure

public int PatientInsert(Patient PatientInstance)
        {
            using (var context = new HMContext())
            {
                try
                {

                    //Int32 LastCreatedId = new Int32();

                    var returnCode = new SqlParameter("@LastCreatedId", SqlDbType.Int);
                    returnCode.Direction = ParameterDirection.Output;

                    insertRow =
                    context.Database.ExecuteSqlCommand("PatientInsert @FirstName ,@MiddleName,"
                    +"@LastName,@Gender,@CNICNumber,@DateOfBirth,@Country,@StateOrProvince,@City,"
                    + "@Address,@CellNumber,@TelephoneNumber,@Email,@NOKFirstName,@NOKLastName,@NOKRelation,"
                    + "@NOKCNICNumber,@NOKCellNumber,@Title,@PicturePath,@LastCreatedId",
                    new SqlParameter("@FirstName", PatientInstance.FirstName),
                    new SqlParameter("@MiddleName", PatientInstance.MiddleName),
                    new SqlParameter("@LastName", PatientInstance.LastName),
                    new SqlParameter("@Gender", PatientInstance.Gender),
                    new SqlParameter("@CNICNumber", PatientInstance.CNICNumber),
                    new SqlParameter("@DateOfBirth", PatientInstance.DateOfBirth.Value.ToShortDateString()),
                    new SqlParameter("@Country", PatientInstance.Country),
                    new SqlParameter("@StateOrProvince", PatientInstance.StateOrProvince),
                    new SqlParameter("@City", PatientInstance.City),
                    new SqlParameter("@Address", PatientInstance.Address),
                    new SqlParameter("@CellNumber", PatientInstance.CellNumber),
                    new SqlParameter("@TelephoneNumber", PatientInstance.TelephoneNumber),
                    new SqlParameter("@Email", PatientInstance.Email),
                    new SqlParameter("@NOKFirstName", PatientInstance.NOKFirstName),
                    new SqlParameter("@NOKLastName", PatientInstance.NOKLastName),
                    new SqlParameter("@NOKRelation", PatientInstance.NOKRelation),
                    new SqlParameter("@NOKCNICNumber", PatientInstance.NOKCNICNumber),
                    new SqlParameter("@NOKCellNumber", PatientInstance.NOKCellNumber),
                    new SqlParameter("@Title", PatientInstance.Title.ToString()),
                    new SqlParameter("@PicturePath", (PatientInstance.PicturePath==null?"":PatientInstance.PicturePath)),
                    returnCode
                    );
                    return (int)returnCode.Value;
                }
                catch (Exception exp)
                {
                    var me = exp.Message;
                    return -1;
                }
            }
        }

I get {} value from returnCode.Value And if I try to cast it to integer it gives me exception Specified cast is not valid.

What should I do to possibly retrieve value of @LastCreatedId as OUTPUT value from the Stored Procedure

jeudi 25 août 2016

Receiving "error An item with the same key has already been added" whenever adding a specific partial view to the view. Asp.net mvc3, vs 2010.

Can any one please help here! In my application I have a view which is rendering a number of partial views. Whenever I am adding a particular view say a.ascx and trying to submit the FORM I start getting this error. The control is not being passed to the action method as I have added a breakpoint there getting the error from the view itself. Checked the respective models but no repetition of property or method found. Any help in this regard will be very much helpful, I have spent 2 days on this already.

MVC Passing Parameters

I'm a MVC newcomer. I would like to pass the parameter adminNo, but it's always null. I have been stuck with this problem for the past few days.

Controller

public ActionResult PledgeForm(string adminNo)
        {
            var result = new StudentJournalQuery().GetStudentInfo(adminNo);
            return View(result);
        }

RouteConfig

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
              name: "Default1",
              url: "{controller}/{action}/{adminno}",
              defaults: new { controller = "Home", action = "Index", adminno = UrlParameter.Optional }
          );

ActionMethod

<a href="@Url.Action("PledgeForm", "ManageSipStudentJournal", new {adminNo = @Model.adminNo, area= string.Empty})">View Pledge Form</a>

SQL Query Here is the SQL query

public StudentJournalSummary GetJournalSummary(string adminNo)
        {
            var StudentJournalSummary = new StudentJournalSummary();
            const string _CountSql =
                @"select count(sjd.WeekNo) TotalWeek, sum(sj.TotalDaysRecord) TotalDaysRecord, count(case sjd.JournalStatusCode when  'D' then 1 else null end) PendingComplete from StudentJournalDate sjd left outer join 
                (select sj.WeekNo, 
                 case when RTRIM(sj.Day1Journal) = '' or sj.Day1Journal is null then 0 else 1 end +
                 case when RTRIM(sj.Day2Journal) = '' or sj.Day2Journal is null then 0 else 1 end +
                 case when RTRIM(sj.Day3Journal) = '' or sj.Day3Journal is null then 0 else 1 end +
                 case when RTRIM(sj.Day4Journal) = '' or sj.Day4Journal is null then 0 else 1 end +
                 case when RTRIM(sj.Day5Journal) = '' or sj.Day5Journal is null then 0 else 1 end +
                 case when RTRIM(sj.Day6Journal) = '' or sj.Day6Journal is null then 0 else 1 end +
                 case when RTRIM(sj.Day7Journal) = '' or sj.Day7Journal is null then 0 else 1 end as TotalDaysRecord 
                 from StudentJournal sj ) as sj  on sjd.WeekNo = sj.WeekNo";

            using (var connection = Db.SqlServer())
            {
                StudentJournalSummary = connection
                 .Query<StudentJournalSummary>(_CountSql, new { adminNo }).FirstOrDefault();
            }

            return StudentJournalSummary;
        }

mercredi 24 août 2016

How do I remove a element from web.config using transformation?

I would like to remove the entire element sessionState from my web.config using transformation.

I have tried , but the element wasn't removed.

lundi 22 août 2016

ASP.Net MVC Controller FromUri to Model - Can we define the order?

In my applicantion, I browse to the URL by supplying the parameters through query string. Based on the URI, the respective controller's action is triggered, and the parameters supplied are auto-mapped to my model.

URL: http://{host}:{port}/{Website}/{controller}/{Action}?{QueryString}

URI: /{controller}/{Action}?{QueryString}

My URI: Employee/Add?EmployeeCode=Code3&EmployeeId=103

EmployeeModel

public class EmployeeModel
{
        public Employee()
        {
        }

        public string EmployeeId 
        { 
            get; 
            set; 
        }

        public string EmployeeCode 
        { 
            get; 
            set; 
        }

        //Some more properties here
}

EmployeeController

[HttpGet]
[Route("Add")]
public IActionResult Add([FromUri] EmployeeModel model)
{
        //Some code here
}

While this all works fabulous, when I browse through, below is the order in which break-points hit,

  1. Add method of EmployeeController
  2. Default constructor of EmployeeModel
  3. set method of EmployeeId property of EmployeeModel
  4. set method of EmployeeCode property of EmployeeModel

I suspect the order in which the properties get initialized is based on the order they are declared in the class.

But, to create an instance and initialize the properties the framework must be using reflection. And as per the MSDN documentation for Type.GetProperties the order is not guarateed.

The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.

I basically want the initialization to take place in a specific order, is this possible?

How to call action method on selection of dropdown using razor view

<select id="TypeOfUser" name="typeOfUser" class="active text-normal">
     <option value="2" onclick="location.href='@(Url.Action("Index", "User", new { typeOfUser = 2}))'">CMS Users</option>
     <option value="3" onclick="location.href='@(Url.Action("Index", "User", new { typeOfUser = 3}))'">Site Users</option>
</select>

on selection of dropdown item I want to call my action method with selected value-

public async Task<IActionResult> Index([FromQuery] int typeOfUser = 2)
{
   SearchUsersResponse searchUserResponse = await new SearchUsersHandler(_db).Handle(new SearchUsersCommandAsync
   {
       Type = typeOfUser
   });

   return View("Index", searchUserResponse);
}

Currently on dropdown selection change I am not able to call action method. PS- I dont want to use JQuery/Javascript.

How to determine if the date pick/choose from datepicker is a holiday?

I am developing an asp.net mvc3 project. I have this picture below dated 8/29/2016 it must be a holiday. And also I have a table in my SQL Server 2k8 for holidays so that date fall on holiday from my sql table. I want is if it fall on holiday the No. of Days must -(minus) the # of holiday depending on how many holiday/s in the duration of filing.

PICTURE

I have this code below for my Start Leave

$("#LSDate").change(function (event) {
    var start = $("#LSDate").val();
    var end = $("#LEDate").val();
    var EmployeeId = $("#hidEmployeeId").val();
    var LeaveTypeId = $("#LeaveType").val();
    saveHalfDay = false;
    saveHalfDayPM = false;
    $("#LeaveIsHalfDay").attr("checked", false);
    if (LeaveTypeId == 3) {
        $.ajax({
            type: "POST",
            url: '../Attendance/_NoDaysApplied',
            data: '&EmployeeId=' + EmployeeId + '&StartDate=' + start + '&LeaveTypeId=' + LeaveTypeId,
            dataType: 'json',
            success: function (response) {
                if (response != null) {
                    $("#LEDate").val(response.msg);
                    $("#txtNoDays").val(response.noofdays);
                    $("#txtNoHrs").val(response.noofdays * 8);
                }
                else {
                    alert("Saving failed. Date Applied exists!");
                    $("#LSDate").val("MM/dd/yyyy");
                    $("#LEDate").val("MM/dd/yyyy");
                    $("#txtNoDays").val(0);
                    $("#txtNoHrs").val(0);
                }
            },
            error: function (reponse) { }
        });
    }
    else if (end != "MM/dd/yyyy" && end != "") {
        $.ajax({
            type: "POST",
            url: '../Attendance/_NoDaysLeaveApplied',
            data: '&EmployeeId=' + EmployeeId + '&StartDate=' + start + '&EndDate=' + end + '&LeaveTypeId=' + LeaveTypeId,
            dataType: 'json',
            success: function (response) {
                if (response != null) {
                    //alert("sucess" + response);
                    var dayoff = response.dayoff;
                    var a = $("#LSDate").datepicker('getDate').getTime(),
                    b = $("#LEDate").datepicker('getDate').getTime(),
                    c = 24 * 60 * 60 * 1000,
                    diffDays = Math.round(Math.abs((a - b) / (c)));
                    var days = (diffDays) + 1;
                    var numdays = (days - dayoff);
                    if (a > b) {
                        numdays = 0;
                        alert("End of Leave must be greater than start of leave.");
                    }
                    var hrs = numdays * 8;
                    $("#txtNoDays").val(numdays);
                    $("#txtNoHrs").val(hrs);
                    if ($("#LeaveType").val() == 16) {
                        var url1 = '../BenefitManagement/_SELValidation';
                        var _data1 = '&StartDate=' + $("#LSDate").val() + '&EndDate=' + $("#LEDate").val();
                        SELValidation(url1, _data1)
                    }
                }
                else {
                    alert("Please contact the administrator."); //alert("Saving failed. Date Applied exists!");
                    $("#LSDate").val("MM/dd/yyyy");
                    $("#LEDate").val("MM/dd/yyyy");
                    $("#txtNoDays").val(0);
                    $("#txtNoHrs").val(0);
                }
            },
            error: function (reponse) { }
        });
    }
});

Start Leave Controller

[HttpPost]
    public ActionResult _NoDaysApplied(string EmployeeId, string StartDate, int LeaveTypeId)
    {
        int empId = Convert.ToInt32(EmployeeId);
        DateTime Sdate = Convert.ToDateTime(StartDate);
        DateTime Edate = Sdate;
        var response = new JsonResult();
        var LeavePolicy = (from a in db.LeavePolicies where a.LeaveTypeId == LeaveTypeId select a).SingleOrDefault();
        var Employee = (from a in db.Employees where a.EmployeeId == empId select a).SingleOrDefault();
        if (LeavePolicy.IsIncludeRestDay == true)
        {
            if (Employee.OriginalAppointment != null)
            {
                if (LeaveTypeId == 3 && Employee.OriginalAppointment.Value.AddDays(720) <= DateTime.Now)
                {
                    Edate = Sdate.AddDays(59);
                    var strEdate = Edate.ToString("MM/dd/yyyy");
                    int IsExist = (from ld in db.LeaveDetails where ld.TranDate >= Sdate && ld.TranDate <= Edate && ld.TranType == "L" && ld.EmployeeId == empId && ld.IsDisApproved == false && ld.TotalHours > 0 select ld.TranDate).Count();
                    if (IsExist == 0)
                    {
                        response.Data = new
                        {
                            msg = strEdate,
                            noofdays = 60
                        };
                    }
                    else
                    {
                        response.Data = new
                        {
                            msg = "Leave exists."
                        };
                    }
                }
                else if (LeaveTypeId == 3 && Employee.OriginalAppointment.Value.AddDays(270) >= DateTime.Now)
                {
                    TimeSpan diff = DateTime.Now - Employee.OriginalAppointment.Value;
                    int noofdays = diff.Days / 12;
                    Edate = Sdate.AddDays(noofdays - 1);
                    var strEdate = Edate.ToString("MM/dd/yyyy");
                    int IsExist = (from ld in db.LeaveDetails where ld.TranDate >= Sdate && ld.TranDate <= Edate && ld.TranType == "L" && ld.EmployeeId == empId && ld.IsDisApproved == false && ld.TotalHours > 0 select ld.TranDate).Count();
                    if (IsExist == 0)
                    {
                        response.Data = new
                        {
                            msg = strEdate,
                            noofdays = noofdays
                        };
                    }
                    else
                    {
                        response.Data = new
                        {
                            msg = "Leave exists."
                        };

                    }
                }
            }
            else
            {
                response.Data = new
                {
                    msg = "Original Appointment is required."
                };
            }
        }
        return response;
    }

End Leave Date Picker

$("#LEDate").change(function (event) {
    var end = $("#LEDate").val();
    var start = $("#LSDate").val();
    var EmployeeId = $("#hidEmployeeId").val();
    var LeaveTypeId = $("#LeaveType").val();
    $("#LeaveIsHalfDay").attr("checked", false);
    saveHalfDay = false;
    saveHalfDayPM = false;
    if (start == "MM/dd/yyyy") {
        alert("Please fill in Start Date!");
    }
    else {
        $.ajax({
            type: "POST",
            url: '../Attendance/_NoDaysLeaveApplied',
            data: '&EmployeeId=' + EmployeeId + '&StartDate=' + start + '&EndDate=' + end + '&LeaveTypeId=' + LeaveTypeId,
            dataType: 'json',
            success: function (response) {
                if (response != null) {
                    //alert("sucess" + response);
                    var dayoff = response.dayoff;
                    var a = $("#LSDate").datepicker('getDate').getTime(),
                    b = $("#LEDate").datepicker('getDate').getTime(),
                    c = 24 * 60 * 60 * 1000,
                    diffDays = Math.round(Math.abs((a - b) / (c)));
                    var days = (diffDays) + 1;
                    var numdays = (days - dayoff);
                    if (a > b) {
                        numdays = 0;
                        alert("End of Leave must be greater than start of leave.");
                    }
                    var hrs = numdays * 8;
                    $("#txtNoDays").val(numdays);
                    $("#txtNoHrs").val(hrs);

                    if ($("#LeaveType").val() == 16) {
                        var url1 = '../BenefitManagement/_SELValidation';
                        var _data1 = '&StartDate=' + $("#LSDate").val() + '&EndDate=' + $("#LEDate").val();
                        SELValidation(url1, _data1)
                    }
                }
                else {
                    alert("Please contact the administrator.");
                    $("#LSDate").val("MM/dd/yyyy");
                    $("#LEDate").val("MM/dd/yyyy");
                    $("#txtNoDays").val(0);
                    $("#txtNoHrs").val(0);
                }
            },
            error: function (reponse) { }
        });
    }
});

End Leave Controller

 [HttpPost]
    public ActionResult _NoDaysLeaveApplied(string EmployeeId, string StartDate, string EndDate, int LeaveTypeId)
    {
        int empId = Convert.ToInt32(EmployeeId);
        DateTime Sdate = Convert.ToDateTime(StartDate);
        DateTime Edate = Convert.ToDateTime(EndDate);
        var res = new JsonResult();
        int IsExist = (from ld in db.LeaveDetails where ld.TranDate >= Sdate && ld.TranDate <= Edate && ld.TranType == "L" && ld.EmployeeId == empId && ld.IsDisApproved == false && ld.TotalHours > 0 select ld.TranDate).Count();
        var LeavePolicy = (from a in db.LeavePolicies orderby a.LeavePolicyId where a.LeaveTypeId == LeaveTypeId select a).FirstOrDefault();
        if (LeavePolicy.IsIncludeRestDay == false)
        {
            int checkshift = (from sd in db.ShiftDetails where sd.EmployeeId == empId && sd.DateApplied >= (Sdate) && sd.DateApplied <= (Edate) select sd.EmployeeId).Count();
            int dayoff = 0;
            if (IsExist == 0)
            {
                if (checkshift > 0)
                {
                    int isDayoff = (from sd in db.ShiftDetails where sd.EmployeeId == empId && sd.DateApplied >= (Sdate) && sd.DateApplied <= (Edate) && (sd.IsDayOff == true) select sd.EmployeeId).Count();
                    int isHoliday = (from sd in db.ShiftDetails where sd.EmployeeId == empId && sd.DateApplied >= (Sdate) && sd.DateApplied <= (Edate) && (sd.IsHoliday == true) select sd.EmployeeId).Count();
                    dayoff = (isDayoff + isHoliday);
                }
                else
                {
                    TimeSpan diff = Edate - Sdate;
                    int days = diff.Days;
                    for (var i = 0; i <= days; i++)
                    {
                        var testDate = Sdate.AddDays(i);
                        switch (testDate.DayOfWeek)
                        {
                            case DayOfWeek.Saturday: dayoff++;
                                break;
                            case DayOfWeek.Sunday: dayoff++;
                                break;
                        }
                    }
                }
            }
            else
            {
                return null;
            }

            res.Data = new
            {
                dayoff
            };
        }
        else
        {
            res.Data = new
            {
                dayoff = 0
            };
        }
        return res;
    }

MVC3 Textbox mask format

I'm creating a form using MVC3 (existing application, unable to upgrade to newer version) and I would like to make a textbox that takes a fixed-length value. The "catch" is that I'd like to prepend the text with a specific value that never changes.

The textbox needs to enforce a format of XYZ123456 where XYZ is auto-prepended to the textbox at load time.

Currently I have the following model:

public class ConfirmationModel {
    [DisplayFormat(DataFormatString = @"{XYZ:000000}", ApplyFormatInEditMode = true)]
    public string XYZNumber { get; set; }
}

And in my view:

@Html.EditorFor(m => m.XYZNumber)

For the DisplayFormat attribute, I have also tried @"{0:XYZ000000}".

The current result is an empty textbox. The XYZ portion is an identifier that never changes, so I'd like it to be in the text box (and uneditable) when the form loads.

Likely, this is an issue with my format string - I'm not sure the proper syntax for this format.

Can someone please help me create a masked textbox with the requested format? I must stick with MVC3 and would prefer not to use any external tools.

The (crudely drawn) result should look like: (label) [XYZ______]

Thanks!

How to pass value from MVC view to controller

Here is my View

                @using (Html.BeginForm("SearchUser", "User", FormMethod.Get))
                {
                    <input type="text" id="keyText">
                    <input type="submit" value="Search" class="btn btn-success btn-lg" />
                }

In my controller I am having a method for SearchUser -

[HttpGet]
public async Task<IActionResult> SearchUser ([FromQuery] string keyText)
{
    SearchUsersCommandAsync command = new SearchUsersCommandAsync
    {
        Key = keyText
    };

    var response = await new SearchUsersHandler(_db).Handle(command);
    return View("Detail", response);
}

However when i receive the request KeyText always null. Whats wrong I am doing here?

dimanche 21 août 2016

How to use CheckBoxFor in MVC forms with other form controls

basically i have a form with a textbox, radio button and a check box control. now i face problem with the checkbox control when i submit my page I have a model like this

public class PersonDetails
{
    public int personID { get; set; }
    public string PersonName { get; set; }
    public string Gender { get; set; }
    public List<Education> Education { get; set; }
    public string EmailID { get; set; }
    public string Address { get; set; }

}

public class Education
{
    public string Qualification { get; set; }
    public bool Checked { get; set; }

    public List<Education> GetQualification()
    {
        return new List<Education>{
    new Education {Qualification="SSC",Checked=false},
    new Education {Qualification="HSC",Checked=false},
    new Education {Qualification="Graduation",Checked=false},
    new Education {Qualification="PostGraduation",Checked=false} 
    };
    }
}

and i have a view like this

@using (Html.BeginForm("GetDetails", "User", FormMethod.Post, new { id = "person-form" }))
{
    <div class="col-xs-12">
    <label>Person Name</label>
    @Html.TextBoxFor(x => x.PersonName)
    </div>
    <div class="col-xs-12">
    <label>Gender</label>
    @Html.RadioButtonFor(x => x.Gender, "Male")
    @Html.RadioButtonFor(x => x.Gender, "Female")
    </div>
    <div class="col-xs-12">
    <label>Education</label>
    @{
    Html.RenderPartial("Qualification", new LearnAuthentication.Controllers.Education().GetQualification());
    }

    </div>

    <div class="col-xs-12">
    <input type="submit" value="Submit" />
    </div>
}

and the partial view like this

@model List<LearnAuthentication.Controllers.Education>
<br />
@for (int i = 0; i < Model.Count(); i++)
{
    @Html.HiddenFor(x => Model[i].Qualification)
    @Html.CheckBoxFor(x => Model[i].Checked)
    @Html.DisplayFor(x => Model[i].Qualification)
<br />
}

and my action method is this

[HttpPost]
public ActionResult GetDetails(PersonDetails personDetails)
{
    return View();
}

now when i run my app i tend to get all the information but when i submit the page i get this property with null values

public List Education { get; set; }

can any of you guys help me on what i am doing wrong or could you direct me to the right path on how to achieve this.

Add value to Parent when value is added to Child MVC

I saw some questions and answers about adding a value to a child when add/update the parent, but my question is the opposite. I have a model Component with a parent-child relationship:

public class Component
    {
        public virtual int ComponentId { get; set; }

        public virtual string Type { get; set; }
        public virtual string Name { get; set; }

        public virtual Course Course { get; set; }

        public virtual int ParentId { get; set; }
        public virtual Component Parent { get; set; }
        public virtual List<Component> Childs { get; set; }

        public virtual List<Evaluation> Evaluations { get; set; }

}

And i need to give a grade to each child to each user. I have this model:

public class Evaluation
    {
        public virtual int EvaluationId { get; set; }

        public virtual int ComponentId { get; set; }
        public virtual Component Component { get; set; }

        public virtual int UserCourseId { get; set; }
        public virtual UserCourse User { get; set; }

        public virtual int Grade { get; set; }
    }

And a view that gets a component selected and allows to choose the user and give a grade. It's only allowed to give a grade to the last child, and the grade of their parent would be the same grade of the child (the ideia is in the future to have more childs and the grade of the parent would be the sum of their grade). So i need to create a new row on the database with the same grade but with the parent id of the component selected. I tried this code but it doesn't work:

[HttpPost]
        [ValidateAntiForgeryToken]
public ActionResult Create(Evaluation evaluation)
{                 

    if (ModelState.IsValid)
    {
        if (evaluation.Component.ParentId != 0)
        {
            var nota = new Evaluation
            {
                ComponentId = evaluation.Component.ParentId,
                UserCourseId = evaluation.UserCourseId,
                Grade = evaluation.Grade
            };
            db.Evaluations.Add(nota);
            db.SaveChanges();
        }

        db.Evaluations.Add(evaluation);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(evaluation);
}

(Note that this code can and probably is totally wrong) How can i do this? Thanks

samedi 20 août 2016

How to store parameters on Project Load, and keep live it for the session

I am storing all menu items in DB, and when a user visits my project, I want to get all the menu items. Then, store it somewhere, so I wont go to db on every PageLoad.

So, my question is where I should store those menu items, what is the best practice?

This might seem so stupid but I want to learn the best practice.

vendredi 19 août 2016

jquery history.go() to a specific page after navigating to different pages

I have a scenario where I want to return to a specific page after I navigate to different pages. The scenario is that a user makes a search, gets the results in the same page. He can then make updates on the a specific result on a different page. I would like to create a link that can bring the user back to the search result page. I am trying to user history.go(specificnumber), but how can I get the variable specificnumber from when the user make its first search to the number of page visited or loaded after the search. Or am I in the wrong direction for the implementation?

How to remove weird string after URL in ASP.Net MVC3

I'm working with ASP.NET MVC3, I created my routes and compose my urls but I have something weird in my url after navigated in browser.

  1. Url actually rendered: /controller/action/page.html
  2. Url navigated: /controller/action/page.html#.V7cdQJh97cw

I think that maybe is SessionID but I can't know how to remove it.

Appreciate any helps!

jeudi 18 août 2016

MVC Code First Or Model First or Hybrid approach?

I want to develop MVC 3 application which will be frequently used by around 3000 users daily. Daily insert and update operations will be required to perform on the database related to application. Sometimes deletion will also be required. Database contains approx. 30-35 tables of which 10 tables will be frequently used. But the table structures in the database will not be changed frequently.

While using code first approach I have read that we need to drop and create the entire database in case of any changes.

This application will be frequently accessing database and some complex operations needs to performed in backend every time the application is used. The UI of application is also going to be more complex.

I will be using Visual Studio 2012 Express Edition with backend as Sql Server 2008 R2.

Can anyone please help me and guide me which approach would be better for me where in this application performance has high priority rather than UI?

It is possible to avoid making condition in 12:00 time?

Hello I have this code below to format 12 hrs from my mvc3 controller to my jqgrid. I have a value of null from my database but it return 12:00 I want is if it is null I want to return a blank space or blank.

            string FitaIn1 = Convert.ToDateTime(req.FAIn1).ToString("hh:mm");
            string FitaOut1 = Convert.ToDateTime(req.FAOut1).ToString("hh:mm");
            string FitaIn2 = Convert.ToDateTime(req.FAIn2).ToString("hh:mm");
            string FitaOut2 = Convert.ToDateTime(req.FAOut2).ToString("hh:mm");
            string FitaCorIn1 = Convert.ToDateTime(req.FACorrectionIn1).ToString("hh:mm");
            string FitaCorOut1 = Convert.ToDateTime(req.FACorrectionOut1).ToString("hh:mm");
            string FitaCorIn2 = Convert.ToDateTime(req.FACorrectionIn2).ToString("hh:mm");
            string FitaCorOut2 = Convert.ToDateTime(req.FACorrectionOut2).ToString("hh:mm");

At the same time I encounter this problem i try this code below because the null value returns 12:00

if (FitaIn1 == "12:00") { FitaIn1 = "00:00"; }

It is possible to log-in / log-out in 12:00 noon right?. I'm out of idea.

How to get the current time in server side?

I'm using asp.net mvc3.

Scenario:

(PC1) as server side or where I publish my project and (PC2) as client or where I am using my current PC. In PC1 the current time is 10:00 AM and in PC2 is 01:00 PM with the same or different date/s. I have a button in my veiw (cshtml) for getting the time of the PC1 after i click the button.

So far I tried the code DateTime.Now() in controller but it is getting what the current time in my current PC?. Not sure about this one.

How to solve this kind of problem?

SqlQuery(): A member of the type, 'id', does not have a corresponding column in the data reader with the same name

Error:

The data reader is incompatible with the specified '[table name]'. A member of the type, 'id', does not have a corresponding column in the data reader with the same name.

Hello,

I'm executing a SQL query using .SqlQuery(). When I do a regular SELECT *, the statement executes fine. But when I add a Group By clause, I receive the above error. I don't understand what this means. I have an ID column in the table. Here's the two SQL statements:

Works:

SELECT TOP 100 * FROM <table name>

Throws Error:

SELECT YEAR(VisitDate) FROM <table name> GROUP BY YEAR(VisitDate)

Here is the Entity Mode for that table:

enter image description here

Redirect to different page on button click

I have a website where I need to redirect the users according to their role. On button click, if the user is admin, redirect to another page; else reload the same page. But my following code doesn't check for the role. On button click, the index page is loaded no matter who logs in.

View:

@model namespace.ViewModels.LoginVM
@{
    ViewBag.Title = "Login";
}

<h1>User Login</h1>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <br />
    <div style="background-color: skyblue; width: 50%">
    <div style="padding-left: 1em">
        <div class="display-label" style="font-size: large">
            Enter User Info<br />
            <br />
        </div>
        <div>
            <div class="editor-label">@Html.LabelFor(model => model.empID)</div>
            <div class="editor-field">@Html.TextBoxFor(model => model.empID)
                @Html.ValidationMessageFor(model => model.empID)
            </div>
            <br />
        </div>
        <br />
        <div>
            <input id="submit" type="submit" value="Submit" />
        </div>
    </div>
    </div>
    <br />
}

Controller:

public class LoginController : Controller
{
    [HttpPost]
    public ActionResult Login(LoginVM model) 
    {
        MySQL msql = new MySQL();            
        var empID= model.empID
        var role = msql.Select("Select `role` from empDB where `eID` = '" + empID + "'");
        if(role == "admin") 
        { 
            return RedirectToAction("Index","Home"); 
        }
        else 
        {
            return View(); 
        }            
    }
}

HS.264 (.MOV) is not working in chrome and working in firefox but its muted (Video.js issue)

enter image description here

Above picture is Firefox enter image description here

and this is chrome need to intigrate web video player in asp.net mvc which will play MOV format.

mercredi 17 août 2016

Change values after get file excel with EPPLUS - MVC

I have a input text date time with format : dd/mm/yyyy ,

and Action ExportExcel :

public ActionResult ExportExcel(Datetime date)
{
 var stream = CreateExcelFile();

        var buffer = stream as MemoryStream;

        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        Response.AddHeader("Content-Disposition", "attachment; filename=ExcelDemo.xlsx");

        Response.BinaryWrite(buffer.ToArray());

        Response.Flush();
        Response.End();

        return RedirectToAction("Index");      
}

Before i submit form to this action, i format input text : mm/dd/yyyy .

When i get file excel, i want to reformat input text : dd/mm/yyyy.

Textbox with 5 length of value in asp.net mvc3

Hello I am using this function code below to automatic add a colon(:) after I entered two numbers in a textbox

    function limit(){    
    if (document.getElementById('FitaCorrectionIn1').value.length == 2) {
                document.getElementById('FitaCorrectionIn1').value += ":";
                return false;
            }
return false
    }

And here for the max length of 5

 <input id="ID" type="text" style="width: 100px" onkeydown="limit()"
                            maxlength="5" />

And for my problem # 1 is after the textbox filled with time for example 10:00 I can manage to erase the 00 using the backspace and my problem is I want to erase also the added colon using the backspace is there any way to solve this?.

For the problem # 2 is for example I want enter a time of 1:00 but the output is 1::00 I need to have a condition for this or any way to solve?.

How to store join query data and retrieve using foreach loop from layout page in asp.net mvc

I am new in asp.net mvc. I am trying to build role wise dynamic menu show in the view page. Each user can have multiple role. I have a join query like:

My Controller looks like with join query:

 var query= (from rMPageMap in db.RoleModulePageMaps
                                 join userRole in db.UserRoleMaps
                                 on rMPageMap.RoleId equals 
                                 join roleMaster in db.RoleMasters
                                 on rMPageMap.RoleId equals roleMaster.Id
                                 join modMaster in db.ModuleMaster
                                on rMPageMap.ModuleId equals modMaster.Id
                                 join sModMaster in db.SubModuleMasters
                           on rMPageMap.SubModuleId equals sModMaster.Id
                                 join pMaster in db.PageMasters
                                 on rMPageMap.PageId equals pMaster.Id
                               where (userRole.UserId == appuser.Id &)
                                 select new
                                 {

                                     rMPageMap.RoleId,
                                     rMPageMap.PageMaster.Name,
                                     roleMaster.Id,
                                     roleName = roleMaster.Name,
                                     modId = modMaster.Id,
                                     moduleName = modMaster.Name,
                                     subModuleId = sModMaster.Id,
                                     subModuleName = sModMaster.Name,
                                     pageId = pMaster.Id,
                                     pageName = pMaster.Name,
                                     parentPageId = pMaster.ParentPageId,
                                     rMPageMap.AddData,
                                     rMPageMap.EditData,
                                     rMPageMap.ViewData,
                                     rMPageMap.DeleteData,
                                     rMPageMap.ShowInDashBoard,
                                     rMPageMap.ShowInMenu
                                 });
Session["rolemodulepage"] = query;

I find the values in the session while debugging. but i can not retrieve data from this using foreach loop in layout page. Here is my view page that i try ro retrieve but does not work.

View Page:

  @if (Request.IsAuthenticated)
  {
  var sessionVar = System.Web.HttpContext.Current.Session["rolemodulepage"];

  foreach(var i in sessionVar) // error
  {
      @i.... // error 
  }
// So here how to retrieve data from session using foreach loop. I tried but does not work. Pls help. If you have some resource for dynamically mane show in view page pls share with me.

Pls help..Thanks in advance.

mardi 16 août 2016

How to get the value of label in cshtml

I am working with mvc3 asp.net project. And as title above how to get the value of a label from .cshtml

This is how I make my label and it has a value of date today <label>@DateTime.Now.ToString("MM/dd/yyyy")</label>.

I tried this one <label id= "ID">@DateTime.Now.ToString("MM/dd/yyyy")</label> but it return a "(no value or empty)" value. Any suggestion will accept thanks.

I want to get the value from .cshtml label to javascript/js

Here is the output if I use alert using with ID.

UPDATE

Here is the button where I want to get the value of the said label

$("#btnCaptureIn1").click(function (event) {  
var date = new Date();
var hours = date.getHours();
var minushrs = 12;
var hrs = hours - minushrs;
var minutes = date.getMinutes();
var today = hrs + ":" + minutes;
document.getElementById('FAIn1').value = today;
var FADATED = $("#ID").val();
alert(FADATED);
var faid = $("#hidFieldAssignmentId").val();
var ans = confirm("Are you sure you want to save?");
if (ans) {
    $.ajax({
        type: "POST",
        url: '../Request/CaptureTimeIn1?FAID=' + faid + '&faDate=' + FADATED,          
        dataType: 'json',
        success: function (response) {
            alert("Successfully saved!");
            $("#FAIn1").val('');
            $("#FiTATimeList").trigger("reloadGrid");
        },
        error: function (reponse) { }
    });
} else {
    $("#FAIn1").val('');
}
$("#FAIn1").val('');

});

can create related post ? MVC 4

i want how create related posts in the post ?

like :

related posts

and how creat next and last post ? like

next post

in MVC 4

lundi 15 août 2016

Two button submit form to 2 url - MVC [duplicate]

This question already has an answer here:

I have two button :

<button id="btn-1" type="submit" >Show Data</button>
<button id="btn-2" type="submit" >Export Excel</button>

and a form :

<form role="form" action="Product/PostProduct" method="get">
....
</form>

I want to submit form to 2 URL :

  • button 1 submit form to URL : "Product/PostProduct"
  • button 2 submit form to URL : "Product/...."

dimanche 14 août 2016

sub folder in not creating on azure in asp.net mvc5 application

I am ruing my website on azure, every folder is present on site directory in azure but uploadimages is my sub folder of content is absent from wwwroot, and images is not uploading also I am using var path =Path.Combine(Server.MapPath("~/Content/UploadImages/")+filename); same with document upload

samedi 13 août 2016

The remote certificate is invalid according to the validation procedure. Identity Server

On one computer I have 2 projects - a client application and another that holds the identity server and identity manager. When I run the client site on this computer everything works. I am able to sign in, register etc. This project was already set up and working.

I made a copy of the projects and put them on another computer. I have set the sites up in IIS and created a self signed certificate.

When I run the client site and attempt to sign in I get the yellow asp.net error page with the message "The remote certificate is invalid according to the validation procedure". When stepping through with the debugger I also see: "The underlying connection was closed: could not establish trust relationship for the ssl/tls secure channel"

I figure the errors have to do with the certificate so in MMC I made sure that the certificates are installed in the trusted root certification authorties folder.

The other thing I did was check the web.config files in the projects. In the client site I have something like:

<oidcClient clientId="codeclienthere" 
            clientSecret="secrethere"
            signingCertificate="keythatmatches_certificate_hash_here"             
            issuerName="https://identityurlhere/issuer"
            ...

Then in the identity server and identity manager web.config files I have something like:

<appSettings>
    <add key="owin:AppStartup" value="startup" />
    <add key="Issuer" value="identity_url_here/issuer" />
    <add key="Thumbprint" value="‎‎keythatmatches_certificate_hash" />
    <add key="WebClientId" value="codeclienthere"/>
    <add key="WebClientSecret" value="secrethere"/>
    ...

I changed the signing certificate and thumbprint values to match the certificate hash. For the attribute "issuerName" and key "Issuer" I tried leaving it the same, setting it the name of the certificate and prepending "CN=" to the name of the certificate. I am unsure what value should go here. I am also unsure what other things I should check.

using overided CSS style for popovers from a custom.css file in a ASP.NET MVC Helper TextBoxFor input box

Hi I'm following this excellent tutorial about over riding the default popover styles using a custom CSS file. http://ift.tt/2aSRek4

I want to use popovers on fields from my data model using ASP.NET MVC 4 bootstrap3 and Razor views in my view model to display messages on focus to tell the user if a field is mandatory to fill out on a long web registration form. This way they don't need to re-fill out the form if they miss a field that needs to be populated at the end of the registration form. I want to accomplish this by using Html helper methods Html.TextBoxFor on each field using code like this.

Html.TextBoxFor(model => model.Address2, htmlAttributes: new {

               data_container = "body",
               data_toggle = "popover",
               data_trigger = "focus",
               data_role = "tooltip",
               data_class = "arrrow",
               data_placement = "right",
               data_content = "Address2 is not mandatory field to complete"

           }) 

On the link above I want to incorporate the class popover3 and have those stlyes displayed on thee popover in the view when user mouses or tabs over field. The Html to do this from the tutorial above is this.

' data-toggle="popover" data-placement="right" data-content="Address2 is not a mandatory field">

Now I want to take the attributes of the overridden CSS from above class in the Html Popover3 and put it in the above helper method so it shows the enhanced popover in the view. How do I get the class=popover3 attributes into the Html TextBoxFor helper method?

vendredi 12 août 2016

Login failed. The login is from an untrusted domain

Introduction I deployed my application Here on GearHost, everything went well. I clearly understand that its database access issue within application because some of the pages are accessible where no db connection is required like about-us.

Error : Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.

Connection String

<add name="IMConn" connectionString="Data Source=mssql3.gear.host;Initial Catalog=IMDb;Integrated Security=True;user id=****;password=******"  providerName="System.Data.SqlClient" />

If someone have idea about that problem, please help.Thanks for your time.

MS Sql - ENABLE_BROKER is not working on Hosting Server

Once I try to execute below query on sql server, i am facing error which i mentioned below. but the same query is working on my local sql server why?

ALTER DATABASE databasename SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;

Error Details: User does not have permission to alter database 'databasename', the database does not exist, or the database is not in a state that allows access checks. Msg 5069, Level 16, State 1, Line 1 ALTER DATABASE statement failed.

how to get the date and time in from PC2 to PC1?

Hello I'm having trouble how can I overcome this problem I search some articles but some examples provided is in PHP. As my title above how can I get the Date and Time from the PC2(Server side where I publish my project) (example of date and time is 8/12/2016 4:40 PM) -- and the current time of my PC1(client side who use the project) (example of date and time is 8/10/2016 5:00). What I want is, I want to display the server side time into one of my label in a view. And even I manipulate / change the PC1 date and time setting the label don't affect / change because it came from the PC2 time. I tried to use Datetime.now() and try to change the setting time from the PC1 and my label date also change after I refresh the page.

How to Override Default credentials in MVC Mailer

How to Override Default credentials in MVC Mailer. My code is pasted below. it always take the default configuration from the Config File.

MailMessage Msg = iUserMailer.EmailPurchaseOrder(purchaseOrderId, ContactName, EmailTo, Subject, BCC, EmailBody, strPdfFile);

                if (Employee.CompanyEmail != null && Employee.CompanyEmail != "" && EmailConfig != null)
                {
                    using (var smtp = new SmtpClient())
                    {
                        smtp.Host = EmailConfig.SMTPServerName;
                        smtp.Credentials = new System.Net.NetworkCredential(Employee.CompanyEmail, Employee.EmailPassword);
                        smtp.EnableSsl = EmailConfig.EnableSSL;
                        smtp.Port = EmailConfig.Port;
                        smtp.Send(Msg);
                    }
                }
                else
                {
                    Msg.Send();
                }

jeudi 11 août 2016

How to do ( Date and Time ) don't change even I change the date setting in my pc?

I'm developing an mvc3 project asp.net. I am having what code to use for this problem. I try to use DateTime.Now the displayed date in my label(where i put the date from my controller) and i change the date time setting in my PCthe displayed date is also changing. What i want is even i change the date and time in my pc the displayed date won't affect and stick to the date where it is publish(PC1).

Can we add Models in Layout.cshtml?

i have layout of 4 pages and at header i need to access name of logged in admin. how to access that database model in admin in starting of layout i have added

    @model ProjectName.Models.Admin

and while accessing name from admin i am writing

    @Model.Name

it gives error how to do it in proper way to access that attribute in Layout and it cant be partial view it should be layout so kindly help

Is it proper form to extend a model object (e.g. Product) and add a Create() method that inserts into the database? (MVC 5 Entity Framework 6)

So I am currently extending the classes that Entity Framework automatically generated for each of the tables in my database. I placed some helpful methods for processing data inside these partial classes that do the extending.

My question, however, is concerning the insertion of rows in the database. Would it be good form to include a method in my extended classes to handle this?

For example, in the Product controller's Create method have something like this:

[HttpPost]
public ActionResult Create(Product p)
{
    p.InsertThisProductIntoTheDatabase();  //my custom method for inserting into db
    return View();
}

Something about this feels wrong to me, but I can't put my finger on it. It feels like this functionality should instead be placed inside a generic MyHelpers.cs class, or something, and then just do this:

var h = new MyHelpers();
h.InsertThisProductIntoTheDatabase(p);

What do you guys think? I would prefer to do this the "correct" way.


MVC 5, EF 6

mercredi 10 août 2016

Issue in Webgrid in MVC

I am using this

  WebGrid grid = new WebGrid(source: Model, rowsPerPage: 09, canPage: true, defaultSort: "Station", ajaxUpdateContainerId: "PassengerArea",ajaxUpdateCallback: "SetImage");

and with that using this on client side

 function SetImage() {
            $("#grid tfoot tr:first td a").each(function () {
                var text = $(this).text().trim();
                if (text == "<< First") {
                    $(this).html('<img src="/Content/Images/firstpage.gif" />');
                }
                if (text == "Last >>") {
                    $(this).html('<img src="/Content/Images/lastpage.gif" />');
                }
                if (text == "< Prev") {
                    $(this).html('<img src="/Content/Images/previouspage.gif" />');
                }
                if (text == "Next >") {
                    $(this).html('<img src="/Content/Images/nextpage.gif" />');
                }
            });
            $("#grid tfoot tr:first td[colspan=8]").attr('colspan', 6);
            var newrow = "<td colspan='2'>Showing Pages  @currentpage.ToString()  of  @TotalPage.ToString() </td>";
            $('#grid tfoot tr').append(newrow);
            $('thead > tr > th > a[href*="sort=@grid.SortColumn"]').parent()
               .append('@(grid.SortDirection == SortDirection.Ascending ? "▲" : "▼")');
            $('#grid thead tr th:first').html(
              $('<input/>', {
                  type: 'checkbox',
                  click: function () {
                      var checkboxes = $(this).closest('table').find('tbody tr td input[type="checkbox"]');
                      checkboxes.prop('checked', $(this).is(':checked'));
                  }
              })
        );
        }

Now when I define this function in Jquery it is giving me error as function is undefined...

Now which is the right place to define this function

Server.TransferRequest doesn't send passed header

My target is to send my own items of header of HTTP Response using Server.TransferRequest.

I'm trying to do something like that:

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();    

var headers = new NameValueCollection
{
    {"ErrorUrl", Context.Request.RawUrl},
    {"ErrorCode", code.ToString()}
};

Server.TransferRequest("~400.html", true, "GET", headers);

But Chrome shows me in Response Headers:

Accept-Ranges:bytes
Content-Length:573
Content-Type:text/html
Date:Wed, 10 Aug 2016 14:32:36 GMT
ETag:"a9d0dad4fbd1d11:0"
Last-Modified:Wed, 29 Jun 2016 11:46:10 GMT
X-Content-Type-Options:nosniff
X-Frame-Options:deny
X-SourceFiles:=?UTF-8?B?RDpcS0ZTXE1haW5cUHJvZHVjdFxLREMuVXNlcldlYlxLREMuVXNlcldlYi5XZWJSb2xlXHNyY1xWaWV3c1xlcnJvclxlbi1VU1w0MDMuaHRtbA==?=
X-XSS-Protection:1

Please, help me to get expected header. Thanks

mardi 9 août 2016

Facing issue in MVC Pageing using jquery

My webgrid Code as Follows: PassengerArea

<div id="PassengerArea">
        @if (Model.Count() > 0)
        {
            <div id="grid1" class="row container" style="width:84%;margin-left:8%;">
                <div class="col-md-12" style="width:100%;color:black;margin-top:10px;padding-left:0px;padding-right:0px;">
                    @grid.GetHtml(
         htmlAttributes: new { id = "grid" },
          tableStyle: "webgrid",
         headerStyle: "webgrid-header",
      footerStyle: "webgrid-footer",
      alternatingRowStyle: "webgrid-alternating-row",
         selectedRowStyle: "webgrid-selected-row",
         rowStyle: "webgrid-row-style",
          mode: WebGridPagerModes.All,

         firstText: "<< First",
         previousText: "< Prev",
         nextText: "Next >",
         lastText: "Last >>",
        //pageable: {

        //               refresh: true,
        //   }

        columns: grid.Columns
        (


            grid.Column(format: @<text> <input type="checkbox" value="@item.ID" name="ids" /> </text>, header: ""),
            grid.Column("Station", format: @<text>@Html.ActionLink((string)item.Station, "EditEmployee", "Home", new { id = item.ID }, new { @class = "modal1" })</text>),
            grid.Column("FlightNo", "Flight No.", format: @<text>@Html.ActionLink((string)item.FlightNo, "EditEmployee", "Home", new { id = item.ID }, new { @class = "modal1" })</text>),
            grid.Column("FlightDate", "Flight Date", format: @<text>@Html.ActionLink((string)item.FlightDate.ToString("dd MMM yyyy"), "EditEmployee", "Home", new { id = item.ID }, new { @class = "modal1" })</text>),
            grid.Column("No_Of_Passengers", "No. of Pax", format: @<text>@Html.ActionLink(((int)item.No_Of_Passengers).ToString() != null ? ((int)item.No_Of_Passengers).ToString() : "NULL", "EditEmployee", "Home", new { id = item.ID }, new { @class = "modal1" })</text>),
            grid.Column("StatusDescription", "Status", format: @<text>@Html.ActionLink((string)item.StatusDescription != null ? (string)item.StatusDescription : "NULL", "EditEmployee", "Home", new { id = item.ID }, new { @class = "modal1" })</text>),
            grid.Column("TextMsg", "LDM", format: @<text>@Html.ActionLink((string)item.TextMsg, "EditEmployee", "Home", new { id = item.ID }, new { @class = "modal1" })</text>),
            grid.Column(format: @<button style="background-color:rgb(255,95,1);border-color:rgb(255,95,1);" type="submit" name="Command" value="@item.ID" > Preview </button>)
            @*grid.Column(format: @<input id="btnPreievew" type="submit" value="Preview"  name="Command"  data-val1="@item.ID" style="background-color:rgb(255,95,1);border-color:rgb(255,95,1);" />)*@
            )

            )
                </div>
            </div>
        }

        @*</div>*@


        else
        {
            <div style="width:80%;margin-left:10%;">
                <div class="row container">
                    <div class="col-md-12" style="width:100%;color:black;margin-top:10px;text-align:center;">

                        @Html.Label("", "No Records are Found!!!!", new { id = "lblMessage" })

                    </div>
                </div>
            </div>


        }      
    </div>

I add a checkbox in the grid header in 1 column- for multiple Selection and with that I add some image in paging Link using JQuery and code is as follows:

   @model IEnumerable<UCR.Models.usp_FlightsStatusGrid_Result>

@{


    WebGrid grid = new WebGrid(source: Model, rowsPerPage: 09, canPage: true, defaultSort: "Station", ajaxUpdateContainerId: "PassengerArea");
    int? TotalPage = grid.PageCount;
    int? currentpage = grid.PageIndex + 1;

    ViewBag.Title = "Upload Passengers";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var message2 = TempData["AlertMessage"] ?? string.Empty;
    var message = TempData["AddAlertMessage"] ?? string.Empty;
    var message1 = TempData["EditAlertMessage"] ?? string.Empty;
    var message10 = TempData["ColumnMessage"] ?? string.Empty;
    var xyz = TempData["AlertMessage21"] ?? string.Empty;
    //string Message = "";
    //if (@ViewBag.NoData != null)
    //{
    //    Message = ViewBag.NoData.ToString();
    //}

}

jquery code:

 $("#grid tfoot tr:first td a").each(function () {


           var text = $(this).text().trim();
           if (text == "<< First") {
               $(this).html('<img src="/Content/Images/firstpage.gif" />');
           }
           if (text == "Last >>") {
               $(this).html('<img src="/Content/Images/lastpage.gif" />');
            }
            if (text == "< Prev") {
                $(this).html('<img src="/Content/Images/previouspage.gif" />');
           }
            if (text == "Next >") {
               $(this).html('<img src="/Content/Images/nextpage.gif" />');
           }
        });

For multiple Selection Code as Follows in JQuery:

 $('#grid thead tr th:first').html(
       $('<input/>', {
       type: 'checkbox',
       click: function () {
           var checkboxes = $(this).closest('table').find('tbody tr td input[type="checkbox"]');
           checkboxes.prop('checked', $(this).is(':checked'));
       }
       })
    );

Now Problem is for controlling the refreshing problem in webgrid when I add the ajaxUpdateContainerId:"PassengerArea" in above code with div id refreshing problem is solved but my header checkbox in 1 st column get removed and paging Images get removed which is given through this code dynamically at runtime in jQuery.

What is the best way to get the date and time in server side?

I'm developing an asp.net mvc3 project. I have a trouble in this problem that I encounter. I will give a scenario so that it will understand well.

Scenario:

I have 2 PC (PC1(server) and PC2(client)). For example both two PC has different date and time let say for PC1 is +8GMT Date 8/10/2016 and for PC2 +8GMT Date 8/9/2016. I am using the PC2 the client and i'm using a code for getting the time is DateTime.Now(); in my controller and the time is display in label in one of my views. I tried to adjust the Date and Time of the PC2 the label for displaying t he time also change. What I want is even I change the Date and Time in PC2 it won't affect/change the displayed Date and Time in my label it will stick on what the Date and Time in the PC1.

Any suggestions are welcome.

Compiler error CS1061 in MVC3

enter image description here

In MVC3 am getting the error in above screen shot error. How can I solve it?

lundi 8 août 2016

How to post list file from MVC to Web API

In MVC , i use HttpPostedFileBase to get file from form(multipart/form-data) :

View :

<form role="form" enctype="multipart/form-data">
<input type="text" name="ProductCode"/>
<input type="text" name="ProductCat"/>
<input type="text" name="Price"/>
<input type="text" name="file" multiple/>
</form>

Model :

public class Product
{
public int ProductId{set;get;}
public string ProductCode {set;get;}
public int ProductCat {set;get;}
public decimal Price{set;get;}
} 
public class ProductData
{
public Product pro { set; get; }
public List<HttpPostedFileBase> file { set; get; } 
}

Action :

public ActionResult PostProduct(Product prop,List<HttpPostedFileBase> file)
{

ProductData data = new ProductData();
data.pro=prop;
data.file=file;
client.BaseAddress = new Uri("http://localhost/99");

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage res = client.PostAsJsonAsync("/api/product/postproduct",data).Result;
// in here , i get error :"error getting value from 'readtimeout' on 'system.web.httpinputstream'",and i cannot post data to web API
if(res.IsSuccessStatusCode)
{
return PartialView("_Success");
}
else
return PartialView("_Error");
}

In web API :

[Route("postproduct")]
[ResponseType(typeof(Product))]
public IHttpActionResult PostProduct(ProductData prod)
{
....
}

i don't know how to post data(model,file)from MVC to Web API ?

ASP redirect script not added www when needed

My script redirects users who type in domain.com, http://domain.com, http://www.domain.com, etc... to http://www.domain.com... but does not always work.

When domain.com is used as the url my script does not always redirect correctly to https://www.domain.com ... This happens a lot with IE. I tried added www to my response.redirect() but it would add wwwwww.domain.com if they user was being redirected from http://www.domain.com to https:// ... any idea on how I can fix this so that all domain variation will be redirect to https://www.domain.com

dim srvname, scrname
if Request.ServerVariables("HTTPS") = "off" then 
    srvname = Request.ServerVariables("SERVER_NAME") 
    scrname = Request.ServerVariables("SCRIPT_NAME") 

    Select Case srvname
    Case "localhost"
        'do nothing
    Case "domain.com"
        'do nothing
    Case "www.domain.com"
        'do nothing
    Case Else
        response.redirect("https://" & srvname & scrname) 
    End Select
end if 

dimanche 7 août 2016

How to post model and file to web API 2 from Web MVC

I have a Controller in MVC as :

public ActionResult PostProduct(Product prod,HttpPostedFileBase file)
{
....

}

Product model :

public string ProductCode {set;get;}
public string ProductCat {set;get;}

I want to post model and file to web API. How can i do that ?

MCV Token Box how to implement

I am wanting to implement a token box like the one on this site for Tags in an MCV web application. See http://ift.tt/2aMuTly for another example. The DevExpress products are not BootStrap compatible so I am looking for an alternative.

Questions: 1. Is there an alternative to the DevExpress tokenbox (open source, code example, etc.)? 2. How should the underlying database schema be designed? For example, if I am looking up a list of people for the source data do I store the selected persons in one field in the underlying table using the ID's separated by a delimiter? or would it work better to have a related table that has the parent record ID, then the ID, etc. of the item used in the tag?

Any pointers or examples is appreciated.

Thanks

samedi 6 août 2016

Dropdownlist in ASP.NET MVC 5 page - not associated with model value (for many to many)

I would like to have a dropdown list in a view. It should contain a list of tags (from a simple tag table - tagID & tagName).

There should be a button 'add'. This would then add the selected tag to this place record (via a many to many relationship junction table).

This select list does not need to be associated with an TagID because it's a many to many relationship. @Html.DropDownListFor() seems to specifically be used for a one to many relationship.

Do I just need to manually output the select list - based on say a list of tags I pass in via the view model? Or is there a quicker / easier way to do this / can an existing helper be used?

(I like the select list + Add button technique - a radio button list will be too large, and multi select boxes are unintuitive).

Once a tag is added I will put it in a simple table I output to the page also - which will have a 'remove' button.

vendredi 5 août 2016

revoke and delete file after specific time asp.net mvc

I upload a file in my website and make download link for user with a guid + file extension and copy that new file in another folder.

I want to revoke download link and delete that new file after 10 minutes , or is that true to revoke link after one time request?

How i can do this ?

How to get time , date and year in server side

Hello guys I am developing an asp.net MVC3 project, I would like to ask how to get the time date and year from the server side. For example scenario I have 2 PC, PC 1 is my server and PC 2 is for my client side. The PC 1 Time is 8/10/2016and for my PC 2 is 8/5/2016. And I have a Button for capturing a time for the log.in. What I want now is the time that I want to capture is the time in the PC 1(server side) not the time in my current PC (PC2 / client side). And also I have a text box / label that determine the current date of the Server side(but failed to do it). For these two problems how to solve?. Because I am only using the code DateTime.Now for capturing the time and getting the date.

For the second scenario my current date and time in my PC 2(client side) is 8/5/2016 if I change my date in PC 2 the labe which contain the date from the server side(but failed to do) is also changing. What code should I use?.

Parse data to nested JSON

I want to create nested JSON. I getting data from sql table. Data Format in table:

+---------------------+---------+
|    Domain           |  Action |
+---------------------+---------+
| Keyword             |  New    |
| Keyword             |  Edit   |
| Keyword             |  Delete |
| Keyword.Case        |  New    |
| Keyword.Case        |  Edit   |
| Keyword.Case        |  Delete |
| Keyword.Case.Action |  New    |
| Keyword.Case.Action |  Edit   |
| Keyword.Case.Action |  Delete |
| User                |  New    |
| User                |  Edit   |
| User                |  Delete |
+---------------------+---------+

I have retrieved the data from sql table using linq query. And Now i want to parse it to get hierarchical structure mentioned below. I think data should be in following format:

[
 {
   "Domain": "Keyword",
   "Actions": ["New", "Edit", "Delete"],
   "Nodes": [
             {
               "Domain": "Keyword.Case",
               "Actions": ["New", "Edit", "Delete"],
               "Nodes": [
                         {
                          "Domain": "Keyword.Case.Action",
                          "Actions": ["New", "Edit", "Delete"],
                          "Nodes": []
                          }
                         ]
              }
             ],
 {
   "Domain": "User",
   "Actions": ["New", "Edit", "Delete"],
   "Nodes": []
 }
]


Dot (.) means that it is child node. For example keyword.case.action; In this example Keyword is parent of Case and Case is parent of Action means action is child of case and case is child of keyword. I want something like that:

  • Keyword
    • Edit
    • Delete
    • New
    • Keyword.Case
      • Edit
      • Delete
      • New
      • Keyword.Case.Action
      • Edit
      • Delete
      • New
  • User
    • Edit
    • Delete
    • New

Can anyone help please? Thanks in advance

jeudi 4 août 2016

bootstrap datetimepicker position is wrong

I have the following html generated

<form action="/Home/UpdateMeetingWithId" method="post">
   <input name="__RequestVerificationToken" type="hidden" value="P-Ijqa8mk1lgxnRGypuf84s6p76pktsoZvTVHrvyc7MXCUMw8vvLUOfjJ-qfV-JrtaY_GpFDfjUKCbR2Qkjt_Q0i21WHK13cc7gSu-64qYfbMIlZnqZBI7nvbD3UNcIDZwaxkTHRFA9KMzJDJpfaWw2" />                
   <table class="table">
      <thead>
         <tr>
            <td>Start time</td>
            <td>End time</td>
            <td>Notify host by</td>
            <td>Reason</td>
            <td>Actions</td>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>Fri 05 Aug 2016 14:00</td>
            <td>Fri 05 Aug 2016 15:00</td>
            <td>
               SMS
            </td>
            <td>sdfsd</td>
            <td nowrap>
               <a class="btn btn-default" href="/Home/ReinviteVisitor?meetingIdToEdit=7&amp;visitorId=00000000-0000-0000-0000-000000000000&amp;email=sdfs%40asdf.com">Edit</a>
               <a class="btn btn-default" href="/Home/DeleteMeetingWithId?meetingId=7" onclick="return confirm(&#39;Are you sure you wish to delete this meeting?&#39;);">Delete</a>
            </td>
         </tr>
         <tr>
            <td nowrap>
               <input class="form-control datetimepicker" data-val="true" data-val-date="The field Start Time must be a date." data-val-required="The Start Time field is required." id="MeetingToEdit_StartTime" name="MeetingToEdit.StartTime" type="text" value="05/08/2016 14:20" />
               <span class="field-validation-valid text-danger" data-valmsg-for="MeetingToEdit.StartTime" data-valmsg-replace="true"></span>
            </td>
            <td nowrap>
               <input class="form-control datetimepicker" data-val="true" data-val-date="The field End Time must be a date." data-val-required="The End Time field is required." id="MeetingToEdit_EndTime" name="MeetingToEdit.EndTime" type="text" value="05/08/2016 15:30" />
               <span class="field-validation-valid text-danger" data-valmsg-for="MeetingToEdit.EndTime" data-valmsg-replace="true"></span>
            </td>
            <td>
               <select class="form-control" data-val="true" data-val-required="The On visitor arrival field is required." id="MeetingToEdit_HostNotificationMethod" name="MeetingToEdit.HostNotificationMethod">
                  <option selected="selected" value="SMS">SMS</option>
                  <option value="CALL">CALL</option>
               </select>
            </td>
            <td>
               <input class="form-control" data-val="true" data-val-required="The Reason for invitation field is required." id="MeetingToEdit_Title" name="MeetingToEdit.Title" type="text" value="sdfds" />
               <span class="field-validation-valid text-danger" data-valmsg-for="MeetingToEdit.Title" data-valmsg-replace="true"></span>
            </td>
            <td nowrap>
               <input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="MeetingToEdit_Id" name="MeetingToEdit.Id" type="hidden" value="4" />
               <input id="MeetingToEdit_SubjectId" name="MeetingToEdit.SubjectId" type="hidden" value="00000000-0000-0000-0000-000000000000" />
               <input data-val="true" data-val-required="The FirstName field is required." id="MeetingToEdit_FirstName" name="MeetingToEdit.FirstName" type="hidden" value="sdf" />
               <input data-val="true" data-val-required="The LastName field is required." id="MeetingToEdit_LastName" name="MeetingToEdit.LastName" type="hidden" value="sdf" />
               <input data-val="true" data-val-required="The Email field is required." id="MeetingToEdit_Email" name="MeetingToEdit.Email" type="hidden" value="sdfs@asdf.com" />
               <input id="MeetingToEdit_Company" name="MeetingToEdit.Company" type="hidden" value="dsf" />
               <input id="MeetingToEdit_HostFirstName" name="MeetingToEdit.HostFirstName" type="hidden" value="neee" />
               <input id="MeetingToEdit_HostLastName" name="MeetingToEdit.HostLastName" type="hidden" value="Admin" />
               <input id="MeetingToEdit_HostEmail" name="MeetingToEdit.HostEmail" type="hidden" value="admin@admin.com" />
               <input id="MeetingToEdit_HostMobile" name="MeetingToEdit.HostMobile" type="hidden" value="+61400000014" />
               <a class="btn btn-default" href="/Home/ReinviteVisitor?visitorId=00000000-0000-0000-0000-000000000000&amp;email=sdfs%40asdf.com">Cancel</a>
               <input type="submit" class="btn btn-default" value="Update" />
            </td>
         </tr>
      </tbody>
   </table>
</form>

But the datetimepicker is in the wrong positions. See screenshot below: enter image description here

It gets worse as the there is more rows in the table. The further down the textbox for the datetimepicker is, the higher the datetimepicker gets. Weird issue, anyone see what is going on here?

How to iterate through values of text boxes ,and send them to controller using ajax?

I am working on shopping cart using asp.net mvc .I have made complete functionality of shopping cart where user can remove product or update its quantity via text box. But i don't like the part where i have 2 extra links on the right side of each product in cart (update quantity and remove product).I am fine with remove product links cos it makes sense to have remove link for each product. Now i want to have only one button or link called save changes. On click on that button/link i want to gather values from each quantity text box ,pass it to controller and do what its need to be done and return as json object from controller. Problem is that i use ajax for few days only so far and don't know how to iterate/gather values from text boxes in my view and send them to controller.

This is how my shopping cart looks like. enter image description here

This is my view

@model OnlineShop.ViewModels.ShopingCartViewModel

@{
    ViewBag.Title = "Shopping Cart";
 }

@section scripts{
<script type="text/javascript">
    $(function () {
        // Document.ready -> link up remove event handler
    $(".RemoveLink").click(function () {
    // Get the id from the link

    var recordToDelete = $(this).attr("data-id");

    if (recordToDelete != '') {
    // Perform the ajax post
    $.post("/ShopingCart/RemoveFromCart", { "id": recordToDelete },
    function (data) {
        // Successful requests get here
        // Update the page elements
    if (data.ItemCount == 0) {
    $('#row-' + data.DeleteID).fadeOut('slow');
}   else {
    $('#item-count-' + data.DeleteID).text(data.ItemCount);
    }
    $('#cart-total').text(data.CartTotal);
    $('#update-message').text(data.Message);
    $('#cart-status').text('Cart (' + data.CartCount + ')');
    });
    }
    });
    });
    $(function () {
        // Document.ready -> link up remove event handler
        $(".UpdateLink").click(function () {
            // Get the id from the link

            var recordToUpdate = $(this).attr("data-id");
            var countToUpdate=$("#" + $(this).attr("txt-id")).val();


            if (recordToUpdate != '') {
                // Perform the ajax post
                $.post("/ShopingCart/UpdateCartQuantity", { "id": recordToUpdate, "cartCount": countToUpdate},
                function (data) {
                    // Successful requests get here
                    // Update the page elements
                    if (data.ItemCount == 0) {
                        $('#row-' + data.DeleteID).fadeOut('slow');
                    } else {
                        $('#item-count-' + data.DeleteID).text(data.ItemCount);
                    }
                    $('#cart-total').text(data.CartTotal);
                    $('#update-message').text(data.Message);
                    $('#cart-status').text('Cart (' + data.CartCount + ')');
                });
            }
        });
    });
    function handleUpdate() {
    // Load and deserialize the returned JSON data
    var json = context.get_data();
    var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
    // Update the page elements
    if (data.ItemCount == 0) {
    $('#row-' + data.DeleteID).fadeOut('slow');
}   else {
    $('#item-count-' + data.DeleteID).text(data.ItemCount);
    }
    $('#cart-total').text(data.CartTotal);
    $('#update-message').text(data.Message);
    $('#cart-status').text('Cart (' + data.CartCount + ')');
}
</script>
    }
<div class="container">
<h3>
    <em>Review</em> your cart:
</h3>
<p class="button">
    @Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>

<div id="update-message">
</div>

<table class="table-bordered">
    <tr>
        <th>
            Image
        </th>
        <th>
            Product Name    
        </th>
        <th>
            Price (each)    
        </th>
        <th>
            Quantity
        </th>
        <th></th>
        <th></th>
    </tr>
    @{int i = 0;}
    @foreach (var item in Model.CartItems)
    {
        <tr id="row-@item.RecordID">
            <td>
                <img src="@Url.Content(item.Product.ProductImg)" class="img-responsive" style="width:60px;height:60px;padding:5px;"/>
            </td>
            @*need to be done later*@ 
            <td>

                @Html.ActionLink(item.Product.ProductName, "Details", "Store", new{id =item.ProductID}, null) 
            </td>
            <td>
                @item.Product.ProductPrice
            </td>
            <td>
                @Html.TextBoxFor(model=>model.CartItems[i].CartCount,new { style="width:60px;text-align:center;"})
            </td>
            <td>
                <a href="#" class="UpdateLink" data-id="@item.RecordID" txt-id="CartItems_@(i)__CartCount">
                    Update Quantity

                </a>&nbsp;|&nbsp;
            </td>
            <td>
                <a href="#" class="RemoveLink" data-id="@item.RecordID">
                    Remove from
                    cart
                </a>
            </td>
        </tr>

        i++;
    }
    <tr>
        <td>
        </td>
        <td></td>
        <td></td>
        <td></td>
        <td align="center"> <b>Total</b></td>

        <td id="cart-total" align="center">
           <b> @Model.CartTotal</b>
        </td>
    </tr>
</table>
</div>

If u need more info , ill be glad to provide.

How to kill session manually in asp.net? [duplicate]

This question already has an answer here:

This is interview question , it is possible to kill session manually ? what does it mean ?

Profile Picture change Navigation menu MVC

I have user Login In My Site. when user Login Profile change picture login user Picture. i have Navigation menu Right of Site Top corner Profile picture change options there until not its Working Default

Naviagation:
 <span>

 <img alt="image" class="img-circle" src="~/Images/2_final.png" />
@*<img alt="image" class="img-circle" src />*@
</span>

I have Profile picture Change function Working profile page

   <div class="ibox-content no-padding border-left-right">
    <a href="@Url.Action("ProfileEdit","Account")" class="pull-right"><ngbutton class="btn btn-info " type="button"><i class="fa fa-paste"></i>Editt</ngbutton></a>
    <img alt="image" class="img-responsive" src="~/Images/@string.Format("{0}.png",Model.Id)">
   </div>

I have code added Img tag Code to Navigation layout Shared Menu under View Folder I am getting error LIke

System.Collections.Generic.List<Inspinia_MVC5.Entityframework.TP_InternalClients>' does not contain a definition for 'Id'

setting up LDAP server on windows 8.1

I am working on a project where I need to give demo to client that a asp.net mvc application is performing authentication against LDAP directory. I have windows 8.1 installed on my machine. How can I install and configure LDAP server ( or some third party free ldap server) on windows 8.1?

Please suggest.

mercredi 3 août 2016

Sage Pay Error processing transaction ,Server error 5006

I'm using SagePay server integration for my project.i'm able to send my request. but my problem is response url.

I'm using azure portal(Azure App Services).After i publish my project i can go to sagepay also.

This is my web config

<sagePay>
    <add key="NotificationHostName" value="tdm.azurewebsites.net" />
    <add key="NotificationController" value="PaymentResponse" />
    <add key="NotificationAction" value="Notify" />
    <add key="SuccessAction" value="Success" />
    <add key="FailedAction" value="Failed" />
    <add key="VatMultiplier" value="1" />
    <add key="VendorName" value="VVVVVVV" />
    <add key="Mode" value="Test" />
  </sagePay>

I think these parts are ok.i just added payment response controller and relevant views. so after i provide test card,then it looks like this. all necessary things here.

Transaction Details Image

So in final step i'm getting following error.

Server error 5006: Unable to redirect to Vendor's web site. The Vendor failed to provide a RedirectionURL. HTTP error 500: The request was unsuccessful due to an unexpected condition encountered by the server.

Transaction Registration Image

I would be very grateful if Someone can help to solve this matter.

Regards, Thilan

Inside of controller actions, why can't one path to an object's related tables? (more inside)

So I post to the controller action below and I would like to "path" to this Car object's Client. When I attempt to do this, however, I get a

Null Reference Exception (Object reference not set to an instance of an object) error.


For some reason, Client is null.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ClientID,Name")] Car myCar)
{
    if (ModelState.IsValid)
    {
        db.myCars.Add(myCar);
        db.SaveChanges();

        //why is Client null here (Null Exception)?
        myCar.Client.UpdateLastModified();

        return RedirectToAction("Details", "Cars", new { id = myCar.ClientID });
    }
}

Is there any way to make this work? Also, if anyone could explain why this is happening, it would help me a great deal.

Thank you in advance.


edit: I'm using Linq-to-SQL, MVC 5, EF 6

mardi 2 août 2016

error CS0103: The name 'Content' does not exist in the current context

I have an error

d:..\Views\Shared_LayoutLatest.cshtml(10): error CS0103: The name 'Content' does not exist in the current context

in LayoutLatest.cshtml line 10 has below code

 @Content.Stylesheet("styleblue.css", Url)

Why this error. it works fine till yesterday /

Why do I get a null exception when attempting to path from inside a class method to a related table? (code sample)

So the Car and Client tables have a relationship in the db, but for some reason I am not able to path from within the Car class to the Client table (see code below). Why is this? Also, how do I make this (or something like it) work?

public partial class Car()
{    
      public void SetAsPrimary()
      {
         //why does this return a null exception? (Client is null- it can't path to it)
         string carClientsName= this.Client.Name;
      }
}

Post an image as Facebook page not as page owner - programmatically c#

I am using below code to post an image to facebook page programmatically. Its posting as Page Owner. How can I post as the Facebook page?

 [FacebookAuthorize("user_friends", "publish_pages","publish_actions", "manage_pages")]
    public async Task<ActionResult> Index(FacebookContext context)
    {
        ViewBag.AppUrl = GlobalFacebookConfiguration.Configuration.AppUrl;
        if (ModelState.IsValid)
        {
            var user = await context.Client.GetCurrentUserAsync<MyAppUser>();
            var imagePath = "path-of-the-image";
            System.IO.File.Exists(imagePath);
            dynamic parameters = new ExpandoObject();

            parameters.message = "caption here";
            parameters.subject = "Test subject";
            parameters.source = new FacebookMediaObject
            {
                ContentType = "image/gif",
                FileName = Path.GetFileName(imagePath),

            }.SetValue(System.IO.File.ReadAllBytes(imagePath));

            //Post to facebookPage
            dynamic result2 = context.Client.Post("page-id-as-string/photos", parameters);
            return View(user);
        }

Cache issue of data annotation attribute

I am overriding System.ComponentModel.DisplayNameAttribute attribute to change display name, When language is change from drop down.

The override is caching the data, i am getting the updated value of DisplayName attribute after few minute.

public class DisplayNameAttribute : System.ComponentModel.DisplayNameAttribute
    {
        public DisplayNameAttribute(string messageKey)
        {
            base.DisplayNameValue = GetLocalizeData(messageKey);
        }
    }

lundi 1 août 2016

Pass data from Model to View

I have a model with a list of data and my View accesses the model properties and renders the database status. There are several boxes in my view which displays color according to their respective values in the database. And each div corresponds to one item in the database.

I know I haven't coded my View in a correct way but it is what I want my view to look like (each div ID corresponding to the respective boxID in the database and displaying its respective color). And I want 500 database values represented in the View.

@model List<My.Namespace.BoxStatusModel>

<table>
    <tr class="first">
        <td class="dclass1">    
            <div id="@boxStatus.boxID" class="top @boxStatus.Color">
            <div id="@boxStatus.boxID" class="top @boxStatus.Color">
            <div id="@boxStatus.boxID" class="bottom @boxStatus.Color">
            <div id="@boxStatus.boxID" class="bottom @boxStatus.Color">
        </td>
        <td class="dclass2">    
            <div id="@boxStatus.boxID" class="top @boxStatus.Color">
            <div id="@boxStatus.boxID" class="top @boxStatus.Color">
            <div id="@boxStatus.boxID" class="bottom @boxStatus.Color">
            <div id="@boxStatus.boxID" class="bottom @boxStatus.Color">
        </td>
        ...          
    </tr>
    <tr class="second">
    ...
    </tr>
</table>

My Controller

public class HomeController : Controller
{       
    public ActionResult Index()
    {
        MySQL msql = new MySQL();                          
        List<List<string>> results = msql.SelectTable("Select boxID, boxStatus from BoxStatusModel");
        List<BoxStatusModel> model = new List<BoxStatusModel>();    

        for (int i = 0; i < results.Count; i++)
        {
                model.Add(new BoxStatusModel()
                {
                    slotID = results[i][0],
                    currentStatus = results[i][1]
                });
        } 
        return View(model);
    }        
}

My ViewModel

namespace My.ViewModels
{
    public class BoxStatusModel
    {
        public int ID { get; set; }

        public string boxID { get; set; }

        public string boxStatus { get; set; }

        public string Color
        {
            get
            {
                switch (boxStatus)
                {
                    case "busy":
                    return "red";

                    case "available":
                    return "green";

                    default:
                    return "";
                }
            }
        }
    }
}