samedi 29 octobre 2016

Visual Studios 2015 Keeps Launching with my domain name not localhost

I have an old website(asp.net mvc 3) that I have to move since one of my msdn subscriptions ran out on Azure. I loaded up the solution and hit F5 and it launched my browser but it is pointing to my domain name not my local host.

Then I just see a 500 error. I want to get back to local host and see if it works locally first before I deploy on a Vm I know have.

vendredi 28 octobre 2016

Why we have only two data structure "stack" and "heap"?

Why we have only two data structure "stack" and "heap"? like int value will be stored in stack and similarly reference type value will be stored in heap.

Why we cannot use some other data structure? Is there any specific reason to use only two these stack and heap.

Thanks a lot.

jeudi 27 octobre 2016

MVC 3 Editorfor template for dynamic property

I am trying to use the EditorFor template with a dynamic view

my view looks like

@model dynamic
.....
.....
<div class="form-group">
    @Html.LabelFor(x => x.AddressLine1, new { @class = "control-label" })
    <div class="input-field">
         @Html.TextBoxFor(x => x.AddressLine1, new { @class = "form-control" })
    <div class="help-block with-errors">
         @Html.ValidationMessageFor(x => x.AddressLine1)
    </div>
    </div>
</div>

But I am running into the error

CS1963 An expression tree may not contain a dynamic operation

Is it possible to use editorfor templates with dynamic views ? If so how could I get this to work

thanks

Multiple view models in Razor view

What would be the best way to for a razor view to handle multiple models? for an MVC3 application.

I have two models, both similar, but the Postcode field is required for one model and not for another

public class IrelandPostcodeLookupViewModel , IWithProgress
{
    readonly Progress _Progress = new Progress(Step.Delivery);

    public Progress Progress
    {
        get { return _Progress; }
    }

    [Required(ErrorMessage = "Please enter your house number or name")]
    [DisplayName("House number or name")]
    public string HouseNumber { get; set; }

    [StringLengthWithGenericMessage(50)]
    [DisplayName("Eircode")]
    public string Postcode { get; set; }

}

public class PostcodeLookupViewModel , IWithProgress
{
    readonly Progress _Progress = new Progress(Step.Delivery);

    public Progress Progress
    {
        get { return _Progress; }
    }

    [Required(ErrorMessage = "Please enter your house number or name")]
    [DisplayName("House number or name")]
    public string HouseNumber { get; set; }

    [StringLengthWithGenericMessage(50)]
    [Required(ErrorMessage = "Please enter your postcode")]
    [DisplayName("PostCode")]
    public string Postcode { get; set; }

}

In the controller I want to use a particular view model depending on a country I am passed. Something like

public virtual ActionResult PostcodeLookup(string country)
{
    if (country == Country.UnitedKingdom)
         return View(new PostcodeLookupViewModel());
    else
         return View(new IrelandPostcodeLookupViewModel());
}

I was handling this in the view with

@model dynamic

The problem I have with this is my view contains partial views

@Html.Partial("~/Views/Shared/_Progress.cshtml", Model.Progress)

and I run into the error 'HtmlHelper' has no applicable method named 'Partial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched'

Can anyone advise how I can handle the Partial View?

Thanks

ibm watson speech to text api for pure jquery/javascript

am complete new to the IBM watson Speech to Text and also not good at sending live audio files from html to server.

The intention is to integrate IBM watson speech to text (free version) in a web application to allow for dictation and note taking . have previously implemented the HTML speech api but the organization doesnt seem happy with its accuracy level .

as said that have only yet seen their demo which seems to show that live transcription is a possibility but cannot seem to find a sample code to use.

primarily intend to use on javascript code for the purpose (the application is however built in ASP MVC 3) .

it would be a great help if any guidance can be given or any step by step guide to implement speech to text in a web app that is free for use

any help appreciated.

mardi 25 octobre 2016

How to Pass javascript:window.open as Asp.net MVC @URL.action

I have this url which i am trying to access but it is not working on MVC

Can anyone convert it to @url.action below

  <td> <a href="javascript:window.open('../AspNetForms/P4C/P4CGeneric.aspx?appId=@item.Hivrp_app_name_fk&P=@item.rpt_path','mywindow','width=1100,height=800')">View/Run</a></td>

What is the best approch to be good at it so quickly?

i'm kind of new to asp.net. what is the best approch to be good at it so quickly?

vendredi 21 octobre 2016

ASP.NET MVC/WEB API Exception handling

I understand that there are multiple ways by which this can be achieved (try...catch...finally, OnException or ExceptionFilter) but my question is, can we just implement one strategy for controller and rest is OK?

What I mean to say is, say for example, I have an assembly "A" which is being called from my MVC application. now if I implement OnException for exception logging, will it take care all exceptions that are generated in assembly "A" and also in Controller? (Here we can assume that, the only way to access assembly "A" is by any action method from controller).

I just want to make sure by this is that MY ASP.NET application must not crash when hosted on IIS just because too many unhandled exceptions are generated. (The one that I don't know which will be ignore by OnException or ExceptionFilter)

Cannot convert from 'System.Web.Mvc.ModelStateDictionary' to 'Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary'

I have getting below errors

CS1503 Argument 3: cannot convert from 'System.Web.Mvc.ModelStateDictionary' to 'Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary'

When i try to build my WEB API project on MS VS 2015.

javascript - Highcharts - Type Bar - How to set different starting for each bar

I have bar chart, in which I want each bar to start different value. Now they all starts from 0. I have only find how to change the starting point, that would be the same for each. Like all staring from 1.

But I need the First to be draw like 1-2, Second: 1-4 and Third: 7-10. How can I vary it for different cases?

var chart = new Highcharts.Chart({
chart: {
        type: 'bar',
        renderTo: 'container'
 },
 xAxis: {
        categories: ['First', 'Second', 'Third']
 },
 series: [{
        data: [{
            name: 'Point 1',
            y: 2
        }, {
            name: 'Point 2',
            y: 4
        }, {
            name: 'Point 3',
            y: 10
        }]
 }]
 });

jeudi 20 octobre 2016

Split is not working in IE9

Split function is not working in IE9

Here is my code

 <script type="text/javascript">
        var currURL = window.location.href;
        $(document).ready(function () {
            var hasFilters = currURL.split('?')[1];
            alert(hasFilters);    
            if (hasFilters) {
                abc(currURL);
            }
        });
</script>

When I am running this script in IE9 at that time, in alert showing "undefined" while at other browser in alert shows concate string for currurl for ex : "abc=def:ijk!!a!!".

So I want to do same in IE9.

Maybe somebody can point me to the right answer? Thx

Sending List from View to Controller results in null List in MVC

I'm trying to create a List of users in MVC, where there's a button to add users generated randomly and there's a delete button for each user to erase them from the list. I send it from the Controller to the View and it generates one user. When I try to add one more, it just changes it. I guess it deletes the items in the List. I'm trying to pass the list back to the Controller, but it doesn't work. Can someone help please?

My Model:

public class UsersClass
{
    public int Code { get; set; }
    public string Name { get; set; }

    public UsersClass(int Code, string Name)
    {
        this.Code = Code;
        this.Name = Name;
    }
}

My Controllers:

List<UsersClass> UsersList = new List<UsersClass>();
public ActionResult Index()
{
    return View(UsersList);
}

[HttpPost]
    public ActionResult AddUser(List<UsersClass> UsersList)
    {
        if (UsersList == null)
        {
            int a = 123;
            UsersList = new List<UsersClass>();
        }
        Random generator = new Random();

        string[] vez_nevek = new string[10] { "Kovács", "Szekeres", "Király", "Szabó", "Vicha", "Kozma", "Ferencz", "Pócsi", "Tinka", "Horváth" };
        string[] ker_nevek = new string[10] { "Lajos", "Barnabás", "Róbert", "Balázs", "János", "Béla", "Petra", "Anna", "Ferenc", "Attila" };

        string vezetek_nev = vez_nevek[generator.Next(vez_nevek.Length)];
        string kereszt_nev = ker_nevek[generator.Next(ker_nevek.Length)];

        UsersList.Add(new UsersClass(generator.Next(100000, 999999), vezetek_nev + " " + kereszt_nev)); 

        return View("~/Views/UserManagement/Index.cshtml", UsersList);
    }

And my View to add a user:

<h2>User Management</h2>

@using (Html.BeginForm("AddUser", "UserManagement", FormMethod.Post)) {

int index = 0;
foreach (var item in Model)
{
    Html.Hidden("item[" + index + "].Code", item.Code);
    Html.TextBox("item[" + index + "].Name", item.Name);
    index++;
}
<input type="submit" value="Add User" />

}

mercredi 19 octobre 2016

How to get LinkedIn person posts feed

I have a requirement where i need to render LinkedIn posts feed on MVC application.I have created the Acccesstoken but the information when calling the API is as per the below but not the posts which i have shared .

Any suggestion on the same will be highly appreciated

{ "firstName": "xxxxx", "headline": "aaaa", "id": "bbb", "lastName": "ccccc", "siteStandardProfileRequest": {"url": "http://ift.tt/2eRCi8X"} }

How to change url segments in mvc?

Default behavior is that whether to append id at the end or url as url segment or not. I have two other parameter i.e. "NewYork" and "address" instead of id. How to make routing url in RouteConfig.cs to work something it like http://ift.tt/2ehwsfp.

dimanche 16 octobre 2016

How to take year 2016 onwards?

I have this code below working fine w/o the condition in the line payrollEndDate = p.PayrollEndDate.Value.Year >= 2016 because it gives me an error Invalid cast from 'Boolean' to 'DateTime'. and the code that I added is return a boolean

var per = (from p in db.Periods select new { periodId = p.PeriodId, periodStart = p.StartDate, periodEnd = p.EndDate, payrollEndDate = p.PayrollEndDate.Value.Year >= 2016 });
var periods = (from p in per.AsEnumerable() select new { perId = p.periodId, PayrollEndDate = Convert.ToDateTime(p.payrollEndDate).ToShortDateString() }).AsQueryable();
ViewBag.PeriodEndDate = new SelectList(periods, "PayrollEndDate", "PayrollEndDate", null);

How to take the year 2016 onwards?

HTML.BeginForm pass in arugment

I am new to MVC. A bit late to the game but I am trying to learn. I am sure this has been asked, but I am having trouble.

I want the form to post to

~/search/index/{argument}

For example:

http://localhost:53967/Search/index/foobar

The {argument} is the value of the textbox.

I have the following in my shared _Layout.chtml. The view is not bound to any Model as it will be a text field for searching.

<ul class="nav navbar-nav navbar-right">
   <li>
      @*/Search/index/{argument}*@
      @using (@Html.BeginForm("Index", "Search",  FormMethod.Get, new { @class = "navbar-form navbar-right" }))
      {
      <div class="input-group col-md-12 col-sm-12">                                
         @Html.TextBox("phrase", (String)ViewBag.Message, new { placeholder = "Search", @class = "form-control" })
         <span class="input-group-btn">
           <button class="btn btn-danger" type="button">
             <span class="glyphicon glyphicon-search"></span>
           </button>
         </span>
      </div>
      }                      
   </li>
</ul>

Here is my controller:

public class SearchController : Controller
    {
        // GET: /search/index/{argument}
        // example = http://localhost:53967/Search/index/foobar
        public ActionResult Index(String phrase)
        {
            String _phrase = phrase.Encode();

            ViewBag.Message = _phrase;

            return View();
        }

        [HttpPost] // post back
        public ActionResult Index(SearchModel model) {


            return View();
        }
    }

vendredi 14 octobre 2016

Unity resolver error using config

I am using Unity.MVC3 IOC container for DI. Trying to set up it using Unity configuration. With this configuration in place it is throwing " The type name or alias ExcelWriter could not be resolved. Please check your configuration file and verify this type name." error when it tries to resolves.

Interfaces are declared in a library: Framework
Namespace: Framework.Interfaces

namespace Framework.Interfaces
{
    public interface IExcelWriter
    {
        byte[] Write(DataTable dataTable);

        byte[] Write<T>(T data);
    }
}

Implemented classes are in separate library: ExcelUtility
Namespace: ExcelWorker

namespace ExcelWorker
{
    public class ExcelWriter : IExcelWriter
    {
        public byte[] Write(DataTable dt)
        {
            throw new NotImplementedException();
        }


        public byte[] Write<T>(T data)
        {
            throw new NotImplementedException();
        }
    }
}

And my configuration looks like :

<unity xmlns="http://ift.tt/1g8Zbje">
    <alias alias="IExcelWriter" type="Framework.Interfaces.IExcelWriter, Framework" ></alias>
    <assembly name="Framework" />
    <assembly name="ExcelUtility" />        
    <namespace name="ExcelUtility.ExcelWorker" ></namespace>
    <container>
      <register type="IExcelWriter" mapTo="ExcelWriter" />
    </container>
  </unity>

Cannot authenticate a call to ASP.NET MVC3 service with a self-signed client certificate

I have an ASP.NET MVC3 service running in IIS 7.5 with .NET Framework 4.5 where I want to secure access to one of the subpaths with a client certificate. For that subpath I crafted a controller with is labeled with a specially crafted attribute which would access the request client certificate

public class CheckCertAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Headers.Add(
            "CheckCertAttribute", "entered");
        var cert = filterContext.HttpContext.Request.ClientCertificate;
        // check the cert here, optionally return HTTP 403
    }
}

Initially OnActionExecuting() is being invoked but Certificate is null. Turns out I need to enable SslNegotiateCert in web.config:

<location path="PathOfInterest">
<system.webServer>
  <security>
    <access sslFlags="SslNegotiateCert"/>
  </security>
</system.webServer>
</location>

Once I do this the client always receives HTTP 403 and the attribute is no longer invoked.

The client certificate is self-signed and exported as .pfx (with a private key) so I guess the problem is that once it arrives on the server side the server doesn't like it and refuses to accept it and pass through. The client side uses HttpWebRequest:

var cert = new X509Certificate2(pathToPfx, password);
var request = (HttpWebRequest)WebRequest.Create("http://ift.tt/2e22U4z");
request.ClientCertificates.Add(cert);
request.GetResponse();

I've already used this approach earlier and it worked. The first case was when the client certificate was not self-signed but was signed by an intermediate certificate which in turn was signed by some trusted root authority - in this case my service configured very similarly would receive it just fine. The second case was using a self-signed client certificate to make Azure Management Service calls but in this case I have no idea how the server side is configured.

I therefore came to conclusion that it's a self-signed nature of the certificate which makes it "not working". I have so do something extra - perhaps add something into web.config or add the certificate into some certificate store on the server side. I just have no idea what this should be.

How do I make this setup work?

jeudi 13 octobre 2016

ASP.net MVC dynamic bundling of CSS

We are working on one requirement where we need to bundle CSS according to clients.

e.g. client1 will have style1 and client2 will have style2 folders and based on clients we need to bundle CSS. We can have N numbers of clients.

/MyApp/client1 - should have style1 CSS with bundling and minification

/myApp/client2 - should have style2 CSS with bundling and minification

from URL we are getting client ID parameter to decide which style folder needs to be load but how to achieve dynamic bundling and minification at runtime for loaded CSS?

Access to the path XXX is denied while uploading video in MVC

I have MVC application throwing error 'Access to path XXX denied' while uploading video. Error is not thrown when image is being uploaded.

Any thing wring in my code?

  [HttpPost]
        public ActionResult Index(HttpPostedFileBase video)
        {
            //var httpPostedFile = Request.Files[0];
            var ffMpeg = new NReco.VideoConverter.FFMpegConverter();   
            //ffMpeg.GetVideoThumbnail(Server.MapPath("~/Images"), "video_thumbnail.jpg");           

            var fileName = Path.GetFileName(video.FileName);
            var path = Server.MapPath("~/Images");
            video.SaveAs(path);
            ffMpeg.GetVideoThumbnail(path, "video_thumbnail.jpg");       


            return View();
        }

Validation for multiple partial views not working

I have a view with Tuple model. I'm loading 4 partial views in this main view as below

  1. @Html.Partial("~/Views/Partial/_Tab1Input.cshtml", Model.Item1.Tab1Input)
  2. @Html.Partial("~/Views/Partial/_Tab2Input.cshtml", Model.Item1.Tab2Input)
  3. @Html.Partial("~/Views/Partial/_Tab3Input.cshtml", Model.Item1.Tab3Input)
  4. @Html.Partial("~/Views/Partial/_Tab4Input.cshtml", Model.Item1.Tab4Input)

I'm loading these partial views on tab click. On click of submit, only active Tab is getting validated. Means if I'm in tab 2 partial view and clicked on submit, then required field validation will happen, but tab 1 partial view's validation will be ignored, and the form is getting Posted.

Please assist me so that on click of submit, all 4 partial views required field validation should happen.

Populating a View Model with a foreach loop when one field could be null?

I have some old tables from an old database which I am trying to use to populate a View Model. The controller action looks for records in one old table where the email matches the current users email and then populates the View Model based on a list derived from those matches. This is my controller action:

public PartialViewResult OldCourses()
    {
        var email = User.Identity.GetEmail();

        var reglist = nb.old_register
            .Where(i => i.email == email).ToList();

        if (reglist != null)
        {
            var viewModel = new OldCourseViewModel();

            foreach (var reg in reglist)
            {
                viewModel.StudentID = reg.studentid;
                viewModel.CourseTitle = nb.old_courses.FirstOrDefault(j => j.courseid == nb.old_Cohorts.FirstOrDefault(h => h.cohortname == reg.cohort).modulename).coursetitle;
                viewModel.Cohort = reg.cohort;
                viewModel.Progpct = nb.student_progress.FirstOrDefault(k => k.studentid == reg.studentid).percentage;
            };


            return PartialView("OldCourses", viewModel);
        }

It is possible for viewModel.Progpct to return null as there may not be an entry in the student_progress table for each record in reglist. This means I get an error, Object reference not set to an instance of an object.

The View Model is as follows:

public class OldCourseViewModel
{
    public int StudentID { get; set; }
    public string CourseTitle { get; set; }
    public string Cohort { get; set; }
    public decimal? Progpct { get; set; }
    public string icon_class { get; set; }
    public string icon_colour_class { get; set; }
    public string titleabbrev { get; set; }

}

The field 'percentage' from the old table is as follows:

public Nullable<decimal> percentage { get; set; }

None of the old tables have foreign key relationships and I can't change any of those tables in any way.

I appreciate that the foreach loop can't handle the null, even though the field is nullable in the View Model.

My first question is what is the best way to handle this situation so that this field can be returned null when it is null?

My second question is, if there are multiple records in the reglist, how can I make the foreach loop cycle through each record in the reglist and generate a new record in the View Model for each of those in the reglist?

Edit - On Stephen's suggestion, I did the following:

var pctcheck = nb.student_progress.FirstOrDefault(k => k.studentid == reg.studentid);

                if (pctcheck != null)
                {
                    viewModel.Progpct = pctcheck.percentage;
                }          

This answers my first question correctly.

Unexpected "foreach" keyword after "@" character. Once inside code, you do not need to prefix constructs like "foreach" with "@"

I am a beginner in .net I have an error in the following lines. I am not able to find out why the error actually arises.

@if(Model.FilteredDevice.Count()>0)
{
@foreach(FModel d in Model.FilteredDevice)
{
// other statements
}
}
else
{
<td> no text matching </td>
}

The complete error message is : An exception of type 'System.Web.HttpParseException' occurred in System.Web.WebPages.Razor.dll but was not handled in user code

Additional information: Unexpected "foreach" keyword after "@" character. Once inside code, you do not need to prefix constructs like "foreach" with "@".

mercredi 12 octobre 2016

Why is my controller action filter no longer invoked once I override SSL settings with a "location" element?

I have an ASP.NET MVC3 application with an action filter attribute applied to a controller:

public class MyFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Headers.Add(
            "MyFilterAttribute", "entered" );
    }

    public override void OnResultExecuted(
        ResultExecutedContext filterContext)
    {
         filterContext.HttpContext.Response.Headers.Add(
             "MyFilterAttribute", "exited" );
    }
}

[MyFilter]
public class MyController : Controller
{
    public ActionResult MyAction()
    {
        return new EmptyResult();
    }
}

MVC routing maps /MyPath/MyAction to the controller-action pair above.

and the client code invokes http://ift.tt/2dVY8oV and dumps the response headers.

Initially it works - I see that the response received on the client contains two MyFilterAttribute headers as expected.

Then I add a location element to web.config:

<configuration>
  // lots of stuff, then
  <location path="MyPath">
    <system.webServer>
      <security>
         <access sslFlags="SslNegotiateCert"/>
      </security>
    </system.webServer>
  </location>
</configuration>

and once I redeploy with these changes the response headers no longer contain the two MyFilterAttribute items.

Adding location to web.config is the only change. Once I remove it the old expected behavior is back.

It looks like adding a location elements somehow breaks MVC attributes.

What might be causing this behavior?

Is signalR is for chat application website only?

I found this blog which is implementing signalr to asp.net mvc3.

Is there any function of signalr like real time updating/reloading a jqgrid?

Scenario for jqgrid

I have to PC. PC1 is for Client and PC2 is for Server. PC2 is already open the view(included the jqgrid) that he needed to confirm the request from the PC1. What my project is doing so far is when requesting from PC1 the view from PC2 is needed to be refresh in order see the requested data from PC1.

If signalr don't support this what else is the best way to achieve my problem?.

mardi 11 octobre 2016

In ASP.NET is _bin_deployableAssemblies obsolete for ASP.NET MVC version 4+

I have been tabbed with upgrading an older ASP.NET MVC 3.0 application to ASP.NET MVC 5.0. In the solution there is a _bin_deployableAssemblies that contains some subset of ASP.NET MVC assemblies.

At the very least I need to upgrade the versions, but when I complete my upgrade can I do away with this and rely on nuget to bring the right versions of these to the bin folder?

samedi 8 octobre 2016

trying for user authentication for a web app project in .Net

I am trying to build a bank web app as part of our course project, but I get this error regarding user : System.InvalidOperationException: The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://ift.tt/WvrniC). When I try to migrate it gives error : The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.WishLists_dbo.Accounts_AccountId". The conflict occurred in database "db_9b1d65373e9b4f0faa8eecf677186e7d", table "dbo.Accounts", column 'Id'. Plz help

vendredi 7 octobre 2016

Display same data again and again in asp.net mvc

this is my linq code--------->     
     var coursename = Session["course"].ToString();
                var location = Session["location"].ToString();
                var result = (from insti in db.Institute_Master
                              join course in db.Course_Detail on insti.InstituteId equals course.InstituteId
                              join coursemaster in db.Course_Master on course.CourseId equals coursemaster.CourseId
                              join  facility in db.Facility_Detail  on insti.InstituteId  equals facility.InstituteId
                              join  masterfacility in db.Facility_Master on facility.FacilityMasterID equals masterfacility.FacilityMasterId
                              where coursemaster.CourseName == coursename || insti.City == location
                              select new
                              {
                                  //Id = insti.InstituteId,
                                  name = insti.InstituteName,
                                  university = insti.University,
                                  Contact = insti.ContactNo,
                                  address = insti.Address,
                                  email = insti.EmailId,
                                  zipcode = insti.Zipcode,
                                  country = insti.Country,
                                  state = insti.State,
                                  city = insti.City,
                                  start = insti.EstablishOn,
                                  image = insti.ProfilePhoto,
                                  fees = course.TotalFees,
                                  mode = course.Mode,
                                  coursename = coursemaster.CourseName,
                                  duaration = coursemaster.duration,
                                  discription = coursemaster.Discription,
                                  eligibility = coursemaster.Eligibility,
                                  recognization = coursemaster.Recognization,
                                  facility  = masterfacility.FacilityName


                              }).Distinct();

--> I Am Using AngularJs To display a data --> And my Record Is repeating for particular facility

this is my tables This is a problem that display same record again for his facility

Can Any One Help Me in this

Dynamic Model in MVC 4.0

Our Application is developed using MVC 4.0. We have a MVC view that's is attached to Dynamic Model.(@model dynamic)

When we submit the view , the dynamic model is posted as an object to Submit Action. Inside Submit Action, we are trying to capture this dynamic model and cast to a typed model. But it's not working, we tried all suggestions provided online but still no luck.

MVC View --> Attached to dynamic model (@model dynamic) On Submit click ---> Call Submit Action Result Method Submit Action Result ---> Catch the posted dynamic model and cast it to typed model. Let's say we have a typed model call product.cs. All we need to do is cast the posted dynamic model to product.cs in the submit action result!!!

jeudi 6 octobre 2016

string concatenation in aspx view engine using local variable. Not Razor mvc views

How can I string concatenate in ASPX view engine? I want to use my variable in generating ids dynamically(in below example, allow ability to add multiple education details).I want to replace (<%=CurrentEducation%>) with id count. I can easily do this in Razor but not in aspx views. Can you also point me the syntax declarations for <% %> things in aspx view engine please? I can find examples only in razor examples.

 <% dim currentEducation = 1 %>
                                <% for each item As EducationDetailsViewModel in Model.EducationDetails %>
                                <div class="row">
                                    <div class="col-md-11">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <%= Html.LabelFor(Function(x) item.Educationlevel, New With {.class = "control-label" + "test", .id="EducationDetails_(<%=CurrentEducation%>)_EducationLevel"})%><span class="text-danger">*</span>

                                                <%= Html.TextBoxFor(Function(x) item.Educationlevel,New With{.class="form-control"})%>
                                            </div>
                                            <div class="col-md-4">
                                                <%= Html.LabelFor(Function(x) item.SchoolName, New With {.class = "control-label"})%><span class="text-danger">*</span>
                                                <%= Html.TextBoxFor(Function(x) item.SchoolName,New With{.class="form-control"})%>
                                            </div>
                                            <div class="col-md-3">
                                                <%= Html.LabelFor(Function(x) item.YearsAttended, New With {.class = "control-label"})%>
                                                <%= Html.TextBoxFor(Function(x) item.YearsAttended,New With{.class="form-control"})%>
                                            </div>
                                            <div class="col-md-2">
                                                <%= Html.LabelFor(Function(x) item.IsGraduated, New With {.class = "control-label"})%>
                                                <%= Html.RadioButtonFor(Function(x) item.isGraduated, False, new with {.style="width:auto"})%>No:
                                            <%= Html.RadioButtonFor(Function(x) item.isGraduated, True, new with {.style="width:auto"})%>Yes:
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <%= Html.LabelFor(Function(x) item.AreaOfStudy, New With {.class = "control-label"})%>
                                                <div class="">
                                                    <%= Html.TextBoxFor(Function(x) item.AreaOfStudy,New With{.class="form-control"})%>
                                                </div>
                                            </div>
                                        </div>
                                        <br />
                                    </div>
                                    <div class="col-md-1">
                                        <span class="text-danger">X</span>
                                    </div>
                                </div>
                                <% currentEducation = currentEducation + 1 %>
                                <% next %>

mardi 4 octobre 2016

How to get the value of Hiddenfield Gridview in OnUpdate function?

My database is connected with the Gridview. I am using hidden field to get the unique element of the table for update query. After editing a row, when I want to execute the update query, I cant access the unique element of the table which in result will update the whole database table with same records. Kindly resolve!

lundi 3 octobre 2016

why my app has stopped working in asus phone with intel processor?

My app running in arm processor but it can't run in intel processor, I have built my app in android studio.

how to display the comments under the post

I Have problem in my project i'm new in MVC so plz help me out. I have problem to display the comments under the relevant the Post like we have post in face book and we comment just under the post and it display, I Have displayed and listed all the posts and under this i have displayed the comments field, i just want to know how the relevant comment can be displayed, View

    @foreach (Post item in Model.posts)
{
    foreach(Comment c in Model.comments)
    {
<div>

    <p>
        @item.Body
    </p>
    <p>@item.timeDate</p>
    <p>@c.Body</p>

</div>   
    using (Html.BeginForm("CreateComment", "Posts", FormMethod.Post))
    {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Comment</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.comment.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.comment.Name)
            @Html.ValidationMessageFor(model => model.comment.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.comment.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.comment.Email)
            @Html.ValidationMessageFor(model => model.comment.Email)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.comment.Body)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.comment.Body)
            @Html.ValidationMessageFor(model => model.comment.Body)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.comment.dateTime)
        </div>
        <div class="editor-field">
           @Html.TextBoxFor(model => model.comment.dateTime, new { id = "datepicker", @Value = @DateTime.Now })
           @Html.ValidationMessageFor(model => model.post.timeDate)
        </div>       
        <div class="editor-field">
           <input type ="text" hidden="hidden" value="@item.Id" name="txtpostId"/>
            @Html.ValidationMessageFor(model => model.comment.PostId)
        </div>

        <p>
            <input type="submit" value="Create"/>
        </p>
    </fieldset>
    }
  }
}

Controller

 public ActionResult Index()
    {
        objVmPost.comment = new Comment();
        objVmPost.post = new Post();
        List<Post> mylist = db.Posts.ToList();
        objVmPost.posts = mylist;
        List<Comment> cmntlist = db.Comments.ToList();
        objVmPost.comments = cmntlist;
        return View("Index",objVmPost);
    }
 [HttpPost]
    public ActionResult CreateComment(VmPost objVmpost)
    {
        objVmpost.comment.PostId = Convert.ToInt32(Request.Form["txtpostId"]);
        db.Comments.Add(objVmpost.comment);
        db.SaveChanges();
        List<Post> mylist = objPostDb.GetAll().ToList();
        objVmpost.posts = mylist;
        return View("index", objVmpost);
    }

Model

public partial class Comment
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Body { get; set; }
    public System.DateTime dateTime { get; set; }
    public int PostId { get; set; }

    public virtual Post Post { get; set; }
}

public partial class Post
    {
        public Post()
        {
            this.Comments = new HashSet<Comment>();
            this.Tags = new HashSet<Tag>();
        }

        public int Id { get; set; }
        public System.DateTime timeDate { get; set; }
        public string Body { get; set; }

        public virtual ICollection<Comment> Comments { get; set; }
        public virtual ICollection<Tag> Tags { get; set; }
    }

How would one log 400: Bad Request errors? Application_Error doesn't fire when Bad Requests occur

So I need to be able to log Bad Request errors (Error 400), but Application_Error doesn't fire for 400 errors, like it does for other errors (e.g. 404).

How would one log 400: Bad Request errors?


ASP.NET MVC 5

how to use multiple partial view on a single View

I have A From and a grid in wich m showing the list of my custumers. so this isn't possible on a single view so i using partial view technique.So i created a form as parial view and a list with partial view. u can say these are two small boxes which now i want to place in a Big box means on the main view.Problem is when i run the Partial views separatly they work correctly but when i Bind them with Index View The list don't show the data otherwise on separate debug it works fine. but why not work when bind with index view.

Insert

This is the form Code

<label>Customer_Name</label>
<input type="text" id="Customer_Name" name="Customer_Name" />
<label>Customer_phone</label>
<input type="text" id="Customer_phone" name="Customer_phone" />
<label>Customer_Address</label>
<input type="text" id="Customer_Address" name="Customer_Address" />
<label>Customer_Email</label>
<input type="text" id="Customer_Email" name="Customer_Email" />
<label>Company_NTN</label>
<input type="text" id="Company_NTN" name="Company_NTN" />
<label>Country</label>
<input type="text" id="Country" name="Country" />
<label>Company_Name</label>
<input type="text" id="Company_Name" name="Company_Name" />

<div class="">
    <div class="">
        <input type="submit" value="Create" class="btn btn-default" />
    </div>     
</div>

This is Details Partial View

@model IEnumerable<WebApplication8.Models.Customer_Data>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Customer_ID)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Customer_Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Customer_phone)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Customer_Address)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Customer_Email)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Company_NTN)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Country)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Company_Name)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Customer_ID)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Customer_Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Customer_phone)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Customer_Address)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Customer_Email)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Company_NTN)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Country)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Company_Name)
    </td>

 </tr>
}

</table>

Now Controller

namespace WebApplication8.Controllers
{
public class DefaultController : Controller
{
 private Hisaab_ApplicationEntities hisaabetities = 
 new Hisaab_ApplicationEntities();

 **Here in Index i have created a View with no Model** 

 public ActionResult Index()
    {
        return View();
    }

    public ActionResult Insert(Customer_Data customerData)
    {
        hisaabetities.Customer_Data.Add(customerData);
        hisaabetities.SaveChanges();

        return RedirectToAction("Index");
    }

    public ActionResult Details()
    {   
        var model = new ViewModel();
        model.Customer_Data = hisaabetities.Customer_Data.ToList();
        return PartialView(model);
    }
}
}

Index View where I am Calling the Both Partial view the List and the Form

 @{
     ViewBag.Title = "Index";
     }

    <h2>Index</h2>

    @Html.Partial("~/Views/Default/Insert.cshtml")
    @Html.Partial("~/Views/Default/Details.cshtml",
    new List<WebApplication8.Models.Customer_Data>())

dimanche 2 octobre 2016

why isn't my path true in Customer host?

I write below code for uploading image in my app.I set path for uploading image. below code is full correctly in my system and company's server. but when i publish customer site . in host can't find this path and produce HTTP ERROR 404.0 -NOT Found.

 `string pic = System.IO.Path.GetFileNameWithoutExtension(model.ImageUpload.FileName) + Guid.NewGuid() + System.IO.Path.GetExtension(model.ImageUpload.FileName);
                    string path = System.IO.Path.Combine(
                                           Server.MapPath("~"), "Areas/Administrator/uploads/", pic);
                    string PicPath = System.IO.Path.Combine("/Areas/Administrator/uploads", pic);
                    PicPath = PicPath.Replace("\\", "/");
                    model.ImageUpload.SaveAs(path);

                    bImageUpload.Inser(new Shared.Entities.SMP.ImageUpload
                    {
                        Title = model.Titel,
                        Lang = CultureHelper.GetLangFromCulture(),
                        ImageUrl = PicPath
                    });`