vendredi 31 juillet 2015

mvc rout and get string

im begginer in asp.net mvc

i write this rout code

    routes.MapRoute(
        name: "test",
        url: "test/{name}",
        defaults: new { controller = "Home", action = "test"}
    );

and this controller

public ActionResult test(string data)
{                   

    switch (data)
    {
        case "test1":
            return View("test1");
        case "test2":
            return View("test2");
        case "test3":
            return View("test3");
        default:
            return View("test1");
    }

}

and in my url http://localhost:3598/test/test1

but i get null data in parameter in controller

how i can get 'test1' in switch (data) ?

thank you for your help

RESTier OData Function returning EntitySet. "The related entity set could not be found from the OData path"

Added a function on RESTier OData

var ambilLocationsByMarketId = new EdmAction(ns, "AmbilLocationsByMarketId", location.GetEdmTypeReference(true), false, null);
model.AddElement(ambilLocationsByMarketId);
var entityContainer = (EdmEntityContainer)model.EntityContainer;
entityContainer.AddActionImport("AmbilLocationsByMarketId", ambilLocationsByMarketId);

Implemented the custom function in my DomainController

[HttpGet]
[EnableQuery]
[ODataRoute("AmbilLocationsByMarketId")]
public IHttpActionResult AmbilLocationsByMarketId()
{
    var locations = DbContext.Locations.Where(l => l.Name.Contains("Hotel")).Select(l => l);
    return Ok(locations);
}   

But I keep getting this result in return

{
  "error": {
    "code": "",
    "message": "An error has occurred.",
    "innererror": {
      "message": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'.",
      "type": "System.InvalidOperationException",
      "stacktrace": "",
      "internalexception": {
        "message": "The related entity set could not be found from the OData path. The related entity set is required to serialize the payload.",
        "type": "System.Runtime.Serialization.SerializationException",
        "stacktrace": "   at System.Web.OData.Formatter.Serialization.ODataFeedSerializer.WriteObject(Object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)\\\r\\\n   at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)\\\r\\\n   at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\\\r\\\n--- End of stack trace from previous location where exception was thrown ---\\\r\\\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\\\r\\\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\\r\\\n   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\\\r\\\n   at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()"
      }
    }
  }
}

How do I assign the right return EntitySet Collection on RESTier?

Cannot resolve symbol 'Model'

I keep getting this error, with or without resharper, VS seems to build through it since it's on view. I've reviewed a lot of articles on the matter, most connect it to Resharper but this is still here even though i uninstalled resharper just instead of that error message, it wants me to reference Model to something.

On another PC this works well, I have no changes made (I've reverted them all)... Tried several times, restarting VS, cleaning up SVN, cleaning up solution, reinstalled Resharper over and over, analyzed with resharper (results gave nothing concrete). Any ideas?

Session Time Out Pop Up

I have to show session timeout pop up (MVC 4.0).

It is working with single page, but when I put it on _Layout page and open two different/same pages of website in two different tabs then timer is working independently on both pages although my code in on common layout.

CODE:

var timeOutMinutes = 1;
var timeOutSeconds = timeOutMinutes * 60;
var popUpShown = false;
var logOutCalled = false;
$(document).ready(function () {
    setInterval(TimerDecrement, 1000); // Call Every Second

    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        if (!popUpShown) {
            timeOutSeconds = timeOutMinutes * 60;
        }

    });
    $(this).keydown(function (e) {
        if (!popUpShown) {
            timeOutSeconds = timeOutMinutes * 60;
        }
    });

    $("#pnlPopup").css("display", "none");
    $('#pnlPopup').dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        width: 'auto',
        maxWidth: 700,
        height: 'auto',
        fluid: true,
        hide: 'fold',
        show: 'clip',
        position: 'center',
        title: 'Session Expiring',
        dialogClass: "noclose"
    });

    $("#btnYes").click(function () {
        StayLoggedIn();
    });

    $("#btnNo").click(function () {
        LogOut();
    });
});

function StayLoggedIn() {
    // DO STUFF
}

function LogOut() {
    // LOG OUT ACTION
}

function TimerDecrement() {
    if (timeOutSeconds > 0) {
        timeOutSeconds--;
    }
    else {

        if (!logOutCalled) {
            logOutCalled = true;
            LogOut();
        }
        else {
            logOutCalled = true;
        }
    }
    document.getElementById("seconds").innerHTML = timeOutSeconds;
  document.getElementById("secondsIdle").innerHTML = timeOutSeconds;
    if (timeOutSeconds < 50) {
        popUpShown = true;
        $("#pnlPopup").dialog("open");
    }
}

FIDDLE

How can I make the session time out counter sync for all pages of website by using it on layout.

MVC 5, want to add email address to userprofile, which table should I add to? userprofile or webpages_membership? (database design)

I have a new MVC5 web app, and currently, as of default, table: userprofile stores username and userId.

CREATE TABLE [dbo].[UserProfile] (
[UserId]            INT            IDENTITY (1, 1) NOT NULL,
[UserName]          NVARCHAR (MAX) NULL,
[FirstName]         VARCHAR (MAX)  NULL,
[LastName]          VARCHAR (MAX)  NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC)
);

table: webpages_membership stores userpassword.

CREATE TABLE [dbo].[webpages_Membership] (
[UserId]                                  INT            NOT NULL,
[CreateDate]                              DATETIME       NULL,
[ConfirmationToken]                       NVARCHAR (128) NULL,
[IsConfirmed]                             BIT            DEFAULT ((0)) NULL,
[LastPasswordFailureDate]                 DATETIME       NULL,
[PasswordFailuresSinceLastSuccess]        INT            DEFAULT ((0)) NOT NULL,
[Password]                                NVARCHAR (128) NOT NULL,
[PasswordChangedDate]                     DATETIME       NULL,
[PasswordSalt]                            NVARCHAR (128) NOT NULL,
[PasswordVerificationToken]               NVARCHAR (128) NULL,
[PasswordVerificationTokenExpirationDate] DATETIME       NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC)
);

I want to add emailaddress and emailaddressConfirmed to the table. which one should I add to? Or build one bit table that encompasses everything?

Also, I know nothing about membership and roles, should I invest sometime to learn about it? (Or is it only useful for esoteric things? )

How can I have access to Glimpse MessageBroker outside of the ASP.NET MVC project?

I am using Glimpse.Mvc5 (1.5.3) in a MVC5 project and I am making a custom tab. This tab needs information that will be logged from inside another project.
This project is not MVC, and is referenced by my MVC project.

I've managed to get the MessageBroker in two ways, but I don't think either of them are perfect:

By GetConfiguredMessageBroker

IMessageBroker broker = GlimpseConfiguration.GetConfiguredMessageBroker();

I first tried this, with success, but the method is marked as deprecated, so no deal

By GlimpseRuntime

GlimpseRuntime glimpseRuntime = HttpContext.Current.Application.Get("__GlimpseRuntime") as GlimpseRuntime;
IMessageBroker broker = glimpseRuntime.Configuration.MessageBroker;

Then I tried this, also with success, but two things bothered me: I had to add a reference to System.Web (for the HttpContext) which is really out of place in my project.
Using "__GlimpseRuntime" looks like something that could break in future releases.

I also realize this is breaking abstraction (a WEB tool showing up in my other project), so if a better answer doesn't use the MessageBroker altogether it is fine by me.

user account specific connectionstrings

I am a novice in C# MVC and I have a MVC5 project, where each specific user will be connected to a specific mssql db. So is it possible to set a user-specific connectionstrings in the web.config. My second question is, as the number of users will grow, will this kind of set up (one project with many user-specific connection strings) will affect the speed?

OAuth - Authorization server if hosted on web farm how to generate bearer token

we have formsauthentication using Machine keys if it is to be hosted on web farm

how can I host authorization server (say WebAPI) in web farm which will produce same bearer token ?

do i need to setup same Machine Key configuration on all servers ?

MVC pass POSTed data to a View

My Index View displays a table of members loaded from it's Index() action method. Each table row has a checkbox. Outside the table is a Remove button.

The Remove button (when clicked) sends a POST request containing the ViewModel data (i.e. rows IDs) to it's POST action method Index().

All pretty standard so far. Until the next part (which I'm not happy about)...

In the Index() post action method, I store the rows IDs to TempData and then RedirectToAction to the Remove() GET action method. I would like to commit the data to the database here, but I have to display a "Are you sure you want to delete these records" page. Hence the redirect.

In the Remove() GET action method, I fetch the row data from TempData, then display the rows (using their IDs I fetch data from the database). Clicking the Submit button sends a POST request and the Remove() POST action method deletes these rows.

Using the TempData between both these GET/POST request 'pairs' looks like a path, i.e. poor design to get it to work. Given the data is a collection, List<int>(), i.e. a complex type, I can't use RedirectToAction here.

Question: Is there a better way to pass the POSTed data (selected rows) to be displayed to a View?

There are a number of SO posts asking whether a RedirectToAction via POST is possible, and the answer seems to 'No'. Which is understandable.

An Option: If there's no other approach, then I might have to consider using a Bootstrap Modal with the selected row data displayed, and a Remove button which POSTs via Ajax. But the problem with this is trying to read a list of selected (checkbox checked) rows from a View via jQuery appears difficult (for me with some working jQuery knowledge). Then POSTing via Ajax.

Code snippets below, I've removed unrelated code so ignore any syntax/spelling mistakes.

Index View

@model MyProject.Models.Members.MembersViewModel

... more view code

<div class="row">
    <div class="col-md-12">
        @using (Html.BeginForm("Index", "Members", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
        {
            @Html.AntiForgeryToken()

            ... table with @EditorFor()

            <div class="col-md-2">
                <input type="submit" value="Remove" id="buttonRemove" class="btn btn-primary" />
            </div>
        }
    </div>
</div>


Controller Index() action methods

public ActionResult Index()
{
    MembersViewModel membersViewModel = new MembersViewModel();

    // Fetch members from the database
    List<Member> members = _BLL.GetAllMembers();

    // Map domain model to viewmodel
... automapper code here
    membersViewModel.Members = members;
    return View(membersViewModel);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MembersViewModel membersViewModel)
{
    // Get the ids of the items selected (GetSelectedIDs() method on VM iterates through private list and returns selected IDs)
    IEnumerable<int> selectedMembersIDs = membersViewModel.GetSelectedIDs();

    // Store IDs
    TempData["SelectedMembers"] = selectedMembersIDs.ToList();
    return RedirectToAction("Remove");
}


Controller Remove() action methods

public ActionResult Remove()
{
    List<int> selectedMembersIDs = TempData["SelectedMembers"] as List<int>;
    if (selectedMembersIDs.Count == 0)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    // Fetch members details
    List<Member> members = _BLL.GetSelectedMembers(selectedMembersIDs);
    if (members.Count == 0)
    {
        return HttpNotFound();
    }

    // Map domain model to viewmodel
    DeleteMembersViewModel deleteMembersViewModel = new DeleteMembersViewModel();
    foreach (Member member in members)
    {
        deleteMembersViewModel.Members.Add(member);
    }            
    return View(deleteMembersViewModel);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Remove(DeleteMembersViewModel deleteMembersViewModel)
{
    List<int> selectedMembersIDs = new List<int>();
    foreach(Member member in deleteMembersViewModel.Members)
    {
        selectedMembersIDs.Add(member.ID);
    }

    _BLL.RemoveGroupMembers(selectedMembersIDs);
    return RedirectToAction("Index");
}

Durandal not passing parameters to MVC controller action

I'm having a problem using parameters in Durandal for an ASP.NET MVC application...

I use MVC Route Attributes, for example: [Route("admin/pages")], [Route("admin/blog")], etc..

And I integrate Durandal as follows:

main.js:

app.start().then(function() {
    viewEngine.viewExtension = '/';

    viewLocator.convertModuleIdToViewId = function (moduleId) {
        return moduleId.replace('viewmodels', '');
    };

    app.setRoot('viewmodels/admin/shell', 'entrance');
});

This works nicely, as the viewId ends up matching the MVC route.

However, I now face a serious problem with trying to use parameters in the routes. For example, I have one route as follows:

[Route("admin/localization/localizable-strings/{languageId}")]

and my Durandal route for this is:

localization/localizable-strings/:languageId

Example anchor tag:

<a href="/admin/#localization/localizable-strings/1" class="btn btn-primary btn-xs">Localize</a>

This doesn't work, as it seems Durandal doesn't pass the parameter to the server. It simply retrieves the HTML from /admin/localization/localizable-strings which returns a 404 page because no parameter was passed to the MVC action.

What are my options here?

Detailed documentation about mapping a web templete inside Orchard CMS

I found a web template on the net link and I want to allow end-users to edit the website using CMS. I found Orchad CMS, which is based on ASP.Net MVC. But the problem I'm facing is that I didn't find the full documentation on how I can map a web template similar to the one I provide to be managed inside a CMS such as Orchard so that end-users (non-technical users) can add new images, change the home page message, add new projects, etc.

How I can map image gallery inside Orchard

I am working on a web template that contain an images gallery. And when you click on an image it will open a larger image inside a slide show. this is how the image gallery looks like link

Now I want to map this image gallery using Orchard CMS. So end-users can chose to add a picture and its slide show picture (mainly two pictures ; small one and high resolution one)? So can anyone advice how I can accomplish this inside Orchard cms ?

Dynamically building a viewmodel and applying UI validation,Asp.Net MVC 5

in my applictaion,based on the selection of a field on the UI,I am loading a list of fields to be displayed from the database on the UI.Based on the selection,it is configured in the database each field is required or optional.After the UI is built,I do a post to the same view model(In the controller action).

What is the best way to do this?

I thought about doing this using reflection and add attributes on the properties based on the IsRequired flag against each field in the database,but i guess i have to eliminate the fields not needed from the UI.

So should i create a class as below as the best option or do i have something else?

Public Class ViewModelTicket
{
   Public string EmailAddress{get;set}
   Public bool IsRequired{get;set}
   Public bool ShouldDisplay{get;set}

}

and throw a bunch of if else statements on the View ?

Thanks

MVC : PHP Laravel Vs Asp.NET

I am starting to build an E learning platform, Application will be expected to cater whole amount of user , there would be some automated jobs, and the vast range of learning material to be stored on server. moreover i will also be dealing with APIs & third party Library.

I am a bit confuse in selection of framework, to build, with having two different Options i.e. PHP Laravel & ASP.NET MVC. I also had research on internet regarding the pros and cons of Both but the major Criteria are :

  • Performance
  • License. (Open Source or PAID)
  • flexibility (easily maintainable)
  • -

Would Laravel make a better choice given the nature of our workflow in the circumstances?

Thanks in Advance

How to i add a custom style_formats with using data from the database on tinymce? (For ASP.NET MVC)

I use TinyMCE editor. And i want to create a custom inline styles for a span tag. But style datas should come from the database. In this way the data can be obtained.

    $(document).ready(function () {

        $.ajax({
            type: "POST",
            url: '@Url.Action("GetFormats", "Editor")',
            dataType: "json",
            success: function (formats) {
                $.each(formats, function (index, format) {
                    // Datas from database
                });
            }
        });
    });

and define tinymce

    tinymce.init({           
    selector: "textarea",
        theme: "modern",
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern imagetools"
        ],
        toolbar1: "insertfile undo redo | styleselect formatselect fontselect fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
        toolbar2: "cut copy paste | searchreplace | print preview removeformat | forecolor backcolor emoticons",

        image_advtab: true,

        style_formats: [
        {
            title: 'My_Style_Combo', inline: 'span', styles: { color: 'rgb(0, 0, 255)', fontFamily: 'comic sans ms,cursive', fontSize:'12px',textDecoration:'underline' } 
        }
       //------> How can I integrate my each data here like this format type?
        ]

    });

I'm sorry for my bad English if you have difficulty in understanding.

I hope it has been a true expression. Thank you in advance for your answers.

Upgrade resulted in an error for every Ref parameter

I have been running a an MVC 5 site and wanted to upgrade to 5.2.3. When I install the 5.2.3 nuget package and try to run the site that was working I now get an error in the RouteCOnfig file, "routes.MapMvcAttributeRoutes();"

There is an error for every method call that has a ref parameter the error is always something like:

Cannot call action method '{what ever method has ref param}' on controller 'AllThings.WebUI.Controllers.PostController' because the parameter 'AllThings.Entities.Post& post' is passed by reference. Parameter name: methodInfo

What am I missing?

Code sample

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

        routes.MapMvcAttributeRoutes();

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

        routes.MapRoute(null, "{controller}/{action}");


    }
}

I have cut out most of the code so the ref method call can be easily seen on the setpostcoredetails call.

[Route("~/{site}/edit")]
    [HttpPost]
    [Authorize]
    public ActionResult Edit(string site, PostViewModel postViewModel)
    {
            IPostRepository postRepository = contextFactory.GetPostRepository();
            Post post = postRepository.Posts.FirstOrDefault(i => i.PostId == postViewModel.PostId);

            SetPostCoreDetails(ref post, User.Identity.GetUserId(), postViewModel);

            LoadEditUIOptions(postViewModel);
            return View(postViewModel);
        }
    }



private void SetPostCoreDetails(ref Post post, string userId, PostViewModel postViewModel)
    {

    }

PCI Complaint ASP.NET MVC Hosting

Apparently, GoDaddy cannot disable ftps on their shared hosting, meaning I am unable to pass a PCI Scan.

Can anyone recommend(from personal experince), a hosting provider with the following:

  • Option to allow FTPS only
  • MVC5 support
  • atleast 5 emails
  • 5GB bandwidth

How to run ASP.NET MVC app in IIS 10 on Windows 10

I installed IIS 10 through windows features and published MVC app into the IIS folder, then executed "dism /online /enable-feature /featurename:IIS-ASPNET45" command but still getting error:

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory

I've done this in windows 7 with "aspnet_regiis -I" command instead of "dism /online /enable-feature /featurename:IIS-ASPNET45" and web app loaded just fine from localhost, but I can't seem to get this to work on Windows 10.

Entity Framework GroupBy Multiple Tables Using Foreign Key

I have two tables, and I calculate Post Views from Views table using ViewDate column and then I want to get PostTItle using .GroupBy for Entity Framework using foreign key PostID.

Posts table:

PostID   PostTitle
--------------------
1         post one
2         post two 
3         post three
4         post four
5         post five
6         post six

Views table:

ViewID     ViewDate             PostID   
---------------------------------------
  1        2015 07 17 19:00:00        1
  2        2015 07 17 20:00:00        1
  3        2015 07 17 21:00:00        2
  4        2015 07 18 19:00:00        2
  5        2015 07 19 19:00:00        2
  6        2015 07 21 19:00:00        1
  7        2015 07 23 19:00:00        2

so far this is what I have done

    return _db.ObjectSet.Where(p => DateTime.Now >= EntityFunctions.AddDays(p.ViewDate, -14))
        .GroupBy(y => y.PostID, y => y.ViewDate, (ID, Date) => new ExampleViewModel
        {
            Post_ID = ID,
            View_Date = Date.Count()
        }).OrderByDescending(z => z.View_Date).Take(5);

but using this solution I can only assign Post_ID and View_Date to ExampleViewModel, How can I get the PostTitle using the foreign key?

Note: I am trying to get most viewed (Hot) Posts in last 14 days

Please help

How to call an image from the database using a webservice and using jquery to call this method

I am calling an image for when a particular condition is met, i want to call this image through a webservice then use a function in jquery to call the method. But i am unable to gain access to a variable defined within the method to successfully draw this image.

This is the code in my webservice

   [WebMethod]
  public void DisplayStar()
    {
        List<The_Factory_Chante.Models.Star> stars;

                using (The_Factory_Chante.Models.The_FactoryDBContext db2 = new The_Factory_Chante.Models.The_FactoryDBContext())
                {

                    string imageSource = "";

                    stars = db2.Stars.ToList();

                    foreach (var item in stars)
                    {
                        if (item.starImage != null)
                        {
                            string imageBase = Convert.ToBase64String(item.starImage);
                            imageSource = string.Format("data:image/gif;base64,{0}", imageBase);
                        }

                    }
                }
     }

This is the code found in my .cshtml class to call the method in jquery

function DisplayStar() {

                $.ajax({
                    url: "../../http://ift.tt/1JBoTtL",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                    }
                });
           };

The problem is i want to use this piece of code to be able to successfully draw this image but i am unable to gain access to the "imageSource" variable in my method.

<img src="@imageSource" class="star"/>

Can anyone help me with this or possibly shed light in any other way to achieve this. Thank you.

WP8 only way to display mvc web service is to include <.fiddler> in url

I am trying to narrow down what is causing my Windows Phone 8 app to fail when trying to connect to my web service from a device. It works perfectly fine in the emulator just not the device, and nothing online seems to have a solution for this scenario. So I am using fiddler to help with tracing what is causing the 'web service not found' exception. On the WP8 device web browser, if I search the following url it is successful, and the host appears in the fiddler debugger:

http://ift.tt/1fQmtLM

If however, I change the url to my original url it fails to find the page and fiddler shows that nothing has happened in the debugger:

http://localhost:54931/test

I'm thinking that understanding what is happening here will help me narrow down the cause of my scenario. Does anyone understand what is happening?

C# URL query string parameters not parsing correctly in FireFox or Chrome

I have a function in my code to open various reports in SSRS, which may or may not need to accept a parameter(s). I'm passing the URL and parameters as follows:

var reportUrl = ConfigurationManager.AppSettings["ReportServerUrl"];
        var reportPathComponents = ConfigurationManager.AppSettings["ReportPath"].Split(';');
        var reportPath = string.Join("&", reportPathComponents);

        return reportUrl + string.Format(reportPath, start.ToShortDateString(), end.ToShortDateString());

Possible inputs are:

reportUrl = "http://ssrs14devreports..." ReportPath = "Report;rs:Command=Render;start={0};end={1}"

This works just fine in IE 11 but in the latest Chrome and FireFox browsers it encodes the "&" as "&".

ASP.net MVC framework and caching and executing javascript

First of all, excuse my terminology as I'm not an ASP.net MVC framework developer. My company is using an ASP.net MVC 5 framework. I'm developing the analytics code using Adobe DTM for this new framework. The issue I'm having is I recently worked on an Angular/Node.js implementation where my JavaScript files were only loaded initially and then ran on every view without being reloaded allowing me to keep track of states etc. I'm now working at a new company and they are using a ASP.net MVC 5 framework, but the JavaScripts are being reloaded every view. From what the developers are telling me, it is a hybrid where some pages use a controller and other pages don't. Is there a way to load JavaScript one time (initial load) and keep the JavaScript running (not destroying objects/variables)?

Thanks!

How to update Visual Studio project files from Azure server

I have an ASP.NET MVC5 website being hosted for free in Azure.

In my Visual Studio project solution there are some CSV files I use for data storage(instead of a SQL Server database to keep the website free) and these files are modified by users.

How do I update my local files with the files in the Azure server. Or better yet, how do I get any changes made in the Azure server to my local Visual Studio solution.

Linq Query Nested select + distinct

I'm having a really hard time converting this query to LINQ.

select fk, count(*)
from (
    select distinct fk, attribute1, attribute2
    from table
) a
group by fk
having count(*) > X

I need each distinct combination of fk, attr1, attr2 grouped by fk only where count is bigger than x (parameter).

Any ideas?

Windows 10 IIS redirecting external IP to index html

I created default ASP.NET MVC 4 project in VS 2015 Community and tried to setup IIS to work with it. I just added this project to Sites List and bound it to port 80 (forwarding enabled). It's ok if I try to load localhost. But when I try to load my external IP, it suddenly redirects me to /index.html (that is 404 not found). Nevertheless if I go to my external IP with /Home, it redirects me to /Home/Index view as needed. It is also ok if I create an index.html page in the root of my project. But I just want to setup default project to work with IIS on my external IP. Could somebody help, please?

It is completely default project. Route config:

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

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

Building ASP application on TeamCity

I have web solution (MVC 5). Also in this this solution there are few console applications. I can buil entire solution locally without any errors. But on TC I can't build Web solution (but can all console apps and class libraries). I'm getting such error:

error CS0246: The type or namespace name 'HttpRequestMessage' could not be found (are you missing a using directive or an assembly reference?)
error CS0246: The type or namespace name 'HttpRequestMessage' could not be found (are you missing a using directive or an assembly reference?)
error CS0246: The type or namespace name 'AuthenticationHeaderValue' could not be found (are you missing a using directive or an assembly reference?)

Only these 3 entities can not be found in a different files. I can see referenced System.Net, System.Net.Http, System.ServiceModel.Channels assemblies. I'm sure (from build logs) they are referenced from 4.5 (all projects built with 4.5)

What can the problem in?

Saving Multiple Entries of an Entity in MVC with Entity Framework

I am trying to have a view where I can update multiple entries of the same entity type simultaneously. The data all come from a I have the following setup, but it won't save the entries properly.

View

@model List<WebApplication1.Models.A>


@using (Html.BeginForm("updateInlinePost", "Default", "POST"))
{
    <table class="table">
        <tr>Headings</tr>
        @for (int i = 0; i < Model.Count(); i++)
        {
        <tr>
            @Html.EditorFor(m => Model[i], "EditorTemplate")
        </tr>
        }
        </table>

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

Editor Template

@model WebApplication1.Models.A

            <td>@Html.DropDownListFor(model => model.Status, new SelectList(new List<String> { "Open", "Resolved", "Cancelled" }, "Value"), Model.Status)
            </td>             
            <td>
                @Html.EditorFor(model => model.Revised_Estimate, new { style = "width:5px" })
            </td>
            <td>
                @Html.EditorFor(model => model.Actual_Completion_Date, new { htmlAttributes = new { @Value = Model.Actual_Completion_Date, @class = "form-control" } })
            </td>

Controller

[HttpPost]
public ActionResult update(List<A> aList)
{
    for (int i = 0; i < aList.Count(); i++ )
    {
        A entry = aList.ElementAt(i);
        db.Save(entry);  // Built-in function to save each entry
        db.SaveChanges();
    }
    return RedirectToAction();
}

Any pointers why this is not saving properly?

Entity-framework SQL query on DateTime

I want to get 5 popular stories using Entity-framework query in a time span for example in 7 days and 14 days. I am storing views in a separate table with DateTime parameters with StoryID.

Stories Table

StoryID--------Story
1-----------story one
2-----------story two 
3-----------story three
4-----------story four
5-----------story five
6-----------story six

Views Table

ViewID---------ViewDate---------StoryID
1------2015-07-17 19:00:00--------1
2------2015-07-17 20:00:00--------1
3------2015-07-17 21:00:00--------2
4------2015-07-18 19:00:00--------2
5------2015-07-19 19:00:00--------2
6------2015-07-21 19:00:00--------1
7------2015-07-23 19:00:00--------2

Can you guys please help me figuring this out. Thanks

split string in single lines and save the data

I try to split array in single lines and save it to xml file. It is about IpAddress. You can put some strings under each other. But now it is one long string

I have this:

internal void Deserialize(Product product) {
        XElement settings = XElement.Parse(product.AuthenticationSettings ?? "<settings/>");

        if (settings == null || settings.Attribute("authenticationrequired") == null || settings.Attribute("authenticationrequired").Value != "true")
            return;

        XElement conditions = settings.Element("preconditions");
        if (conditions == null)
            return;

        //XElement[] conditions2 = settings.Element[("preconditions")];
        //if (conditions == null)
        //    return;


        XElement condition = conditions.Element("residentsonly");
        if (condition!= null)
            this.ResidentsOnly = (condition.Value == "1");

        condition = conditions.Element("minimumage");
        if (condition != null) {
            int age = 0;
            if (Int32.TryParse(condition.Value, out age))
                this.MinimumAge = age;
        }

        condition = conditions.Element("redirecturl");
        if (condition != null) {
            this.RedirectUrl = condition.Value;
        }

   condition = conditions.Element("ipaddress");
        if (condition != null) {

            string[] lines =  IpAddress.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            //condition = IpAddress.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            for (int i = 0; i < lines.Length; i++) {
                if ( lines[i] != null){
                lines[i] = condition.Value.ToString();
            }
                //lines = string.Join("\n", condition.Value.ToArray());
            }


        }
    }

it is about IPaddress.

But the problem is lines is always null. Thank you.

This is the IpAddress:

 [Display(Name = "PreConditionIpAddress", ResourceType = typeof(Resources.Entity.Product))]
        public string IpAddress { get; set; }

This is my serialize method:

internal string Serialize(EditProductModel model) {
            if (this.ResidentsOnly == false && this.MinimumAge == 0)
                return model.Product.AuthenticationSettings;

            XElement settings = XElement.Parse(model.Product.AuthenticationSettings ?? "<settings/>");
            if (settings == null || settings.Attribute("authenticationrequired") == null || settings.Attribute("authenticationrequired").Value != "true")
                return model.Product.AuthenticationSettings;

            settings.Add(
                new XElement("preconditions",
                    new XElement("residentsonly", this.ResidentsOnly ? "1" : "0"),
                    new XElement("minimumage", this.MinimumAge),
                    new XElement("redirecturl", this.RedirectUrl),
                    new XElement("ipaddress", this.IpAddress)
                )
            );

            return settings.ToString();
        }

I have it now like this:

public class PreConditionSettings
    {
        [Display(Name = "PreConditionResidentsOnly", ResourceType = typeof(Resources.Entity.Product))]
        public bool ResidentsOnly { get; set; }

        [Display(Name = "PreConditionMinimumAge", ResourceType = typeof(Resources.Entity.Product))]
        public int MinimumAge { get; set; }

        [SfsHelpers.PreConditionRedirectValidation(ErrorMessageResourceType = typeof(Resources.Entity.Product), ErrorMessageResourceName="PreConditionRedirectUrlValidation")]
        [Display(Name = "PreConditionRedirectUrl", ResourceType = typeof(Resources.Entity.Product))]
        public string RedirectUrl { get; set; }

        [Display(Name = "PreConditionIpAddress", ResourceType = typeof(Resources.Entity.Product))]
        public string IpAddress { get; set; }

        public PreConditionSettings() {
            this.ResidentsOnly = false;
            this.MinimumAge = 0;
            this.RedirectUrl = null;
            this.IpAddress = null;
        }


        public static string[] replacer(Dictionary<string, string> dic, string IpAddress)
        {
            foreach (KeyValuePair<string, string> entry in dic) {
                IpAddress = IpAddress.Replace(entry.Key, entry.Value);
            }
            string[] lines = IpAddress.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

            return lines;
        }

        internal string Serialize(EditProductModel model) {
            if (this.ResidentsOnly == false && this.MinimumAge == 0)
                return model.Product.AuthenticationSettings;

            XElement settings = XElement.Parse(model.Product.AuthenticationSettings ?? "<settings/>");
            if (settings == null || settings.Attribute("authenticationrequired") == null || settings.Attribute("authenticationrequired").Value != "true")
                return model.Product.AuthenticationSettings;

            settings.Add(
                new XElement("preconditions",
                    new XElement("residentsonly", this.ResidentsOnly ? "1" : "0"),
                    new XElement("minimumage", this.MinimumAge),
                    new XElement("redirecturl", this.RedirectUrl),
                    new XElement("ipaddress", this.IpAddress)
                )
            );

            return settings.ToString();
        }

        internal void Deserialize(EditProductModel model) {
            Deserialize(model.Product);
        }

        internal void Deserialize(Product product) {
            XElement settings = XElement.Parse(product.AuthenticationSettings ?? "<settings/>");

            if (settings == null || settings.Attribute("authenticationrequired") == null || settings.Attribute("authenticationrequired").Value != "true")
                return;

            XElement conditions = settings.Element("preconditions");
            if (conditions == null)
                return;            

            XElement condition = conditions.Element("residentsonly");
            if (condition!= null)
                this.ResidentsOnly = (condition.Value == "1");

            condition = conditions.Element("minimumage");
            if (condition != null) {
                int age = 0;
                if (Int32.TryParse(condition.Value, out age))
                    this.MinimumAge = age;
            }

            condition = conditions.Element("redirecturl");
            if (condition != null) {
                this.RedirectUrl = condition.Value;
            }           



            condition = conditions.Element("ipaddress");             
            if (condition != null) {

                IpAddress = "";
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("<ipaddress>", string.Empty);
                dic.Add("</ipaddress>", string.Empty);
                dic.Add(" ", Environment.NewLine);
                replacer(dic, IpAddress);
                this.IpAddress = condition.Value;


            }
        }
    }

Now the output is: 777777 99999999 8888888 .

But it has to be:

<ipaddress>77777777</ipaddress>
<ipaddress>99999999999</ipaddress>
<ipaddress>888888888888</ipaddress>

Thank you

Html table not populating from ViewModel

I am trying to populate an HTML table with data from a table in my database. The issue is simply that the HTML table is not getting populated with any data.

Here is the ViewModel:

    public class TestViewModel
{
    public string MatchedId { get; set; }
    public string UnmatchedId { get; set; }
    public string Auth { get; set; }
    public DateTime CreditDate { get; set; }
    public string CreditNumber { get; set; }
    public decimal CreditAmount { get; set; }
    public DateTime DeniedDate { get; set; }
    public int DeniedReasonId { get; set; }
    public string DeniedNotes { get; set; }
}

Controller Action:

   [HttpPost]
public ActionResult UploadValidationTable(HttpPostedFileBase csvFile)
{
    var inputFileDescription = new CsvFileDescription
    {
        SeparatorChar = ',',
        FirstLineHasColumnNames = true
    };
    var cc = new CsvContext();
    var filePath = uploadFile(csvFile.InputStream);
    var model = cc.Read<Credit>(filePath, inputFileDescription);

    try
    {
        var entity = new Entities();

//model here is the .csv, doesn't have anything to do with this issue
        foreach (var item in model)
        {
            var tc = new TemporaryCsvUpload
            {
                Id = item.Id,
                CreditAmount = item.CreditAmount,
                CreditDate = item.CreditDate,
                CreditNumber = item.CreditNumber,
                DeniedDate = item.DeniedDate,
                DeniedReasonId = item.DeniedReasonId,
                DeniedNotes = item.DeniedNotes
            };
            entity.TemporaryCsvUploads.Add(tc);
        }
        entity.SaveChanges();

        System.IO.File.Delete(filePath);

//This is where the database table is getting filled
 entity.Database.ExecuteSqlCommand("Insert into CsvReport Select  p.Id as MatchedId, case when p.Id is null then t.Id end as UnmatchedId, p.Auth,p.CreditDate, p.CreditNumber,p.CreditAmount, p.DeniedDate,p.DeniedReasonId, p.DeniedNotes from TemporaryCsvUpload t left join PermanentTable p on p.Id = t.Id;");


        TempData["Success"] = "Updated Successfully";

    }
    catch (LINQtoCSVException)
    {
        TempData["Error"] = "Upload Error: Ensure you have the correct header fields and that the file is of .csv format.";
    }

    return View("Upload");
}

View:

@model IEnumerable<TestProject.TestViewModel>

                        @if (Model != null)
                    {
                        foreach (var item in Model.Where(x => x.IdMatched != null))
                        {
                            <tr>
                                <td>
                                    @item.MatchedId
                                </td>
                                <td>
                                    @item.Auth
                                </td>
                                <td>
                                    @item.CreditDate
                                </td>
                                <td>
                                    @item.CreditNumber
                                </td>
                                <td>
                                    @item.CreditAmount
                                </td>
                                <td>
                                    @item.DeniedDate
                                </td>
                                <td>
                                    @item.DeniedReasonId
                                </td>
                                <td>
                                    @item.DeniedNotes
                                </td>
                            </tr>
                        }
                    }

It's a little weird because I am populating the database with an SQL command. What am I missing here? Do I need to try and pass it through the controller action? Let me know if you need more information. Thanks!

MVC: Send parameters to method by a button

I have the following button in a View

    <button id="Export" class="btn btn-default custom" type="button">
          <i class="glyphicon glyphicon-file"></i>Export to Excel
    </button>

And I want it to export a list of materials that I have in a ViewData

I already have the logic. The code could be in a ActionResult or a normal method and it would be something like this:

    [HttpPost]
    public void Export(List<int> listPassed)
    {
           //stuff here
    }

I tried adding href="@Url.Action("Export", "Materials", new { export_documentation = true })" but it didn't work out.

I could do it with an override of the ActionLink method but I would lose the glyphicon. Thing that I want to avoid. Overrides of the ActionLink that tricks the helper to have a glyphicon also didn't work out.

I tried Ajax but I suck at jscript and ajax and all that stuff at the moment.

So, how can send the parameters to the method?

How to update related data using entity framework 6

I have an entity "Person", which has a related entity "Hobby". A person can have several hobbies. I want to create a view model that allows new hobbies to be added and/or existing hobbies to be removed from a Person entity.

The code below works, but I imagine it is rather inefficient.

var newHobbies = new List<Hobby>();

foreach (Hobby hobby in vm.Hobbies)
{
    var originalHobby = db.Hobbies.Find(hobby.HobbyID);
    newHobbies.Add(originalHobby);
}

originalPerson.Hobbies = newHobbies;

I prefer to do something like this:

var newHobbies = db.Hobbies.Where(x => vm.Hobbies.All(y => x.HobbyID == y.HobbyID)).ToList();   
originalPerson.Hobbies = newHobbies;

But I get an error: Only primitive types or enumeration types are supported in this context.

How can I update related data without going to the database multiple times?

MVC Razor - add session variable to view markup

This was an easy item in WebForms, but is eluding me in MVC.

Trying to add a session variable to html markup, but can't find a way to get it to work..

Tried

<div class="panel-body">
<p>It might suprise you to know that you can upgrade from @Session("CurrentProvider") to blah blah....</p>
</div>

Wrapping it in code tags and all sorts.

Any ideas?

Thanks