It seems this has been asked many times, in many ways, none of which seem to fit my exact situation.

Here's a line from my _LoginPartial.cshtml file:

@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })

See the part that says User.Identity.GetUserName()?

I want to change it to User.Identity.FirstName or User.Identity.GetFirstName().

I don't want it to say "Hello email address", but rather "Hello Bob"

My thought is that I'm simply wanting to show a new property (or method) on the Identity class. Obviously it must be more than that.

I've added the FirstName property and it is available in the AccountController.

public class ApplicationUser : IdentityUser
        public string FirstName { get; set; }
        public string LastName { get; set; }

It does not get exposed in the _LoginPartial file. I want it exposed there!

Thank you for your help

Hi I am getting the following exception.Please help me to resolve this .org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:, no session or session was closed


@RequestMapping(value = "/Request", method = RequestMethod.GET)
    public @ResponseBody String listApparoverRequest(
                                        HttpSession httpSession, 
                                        HttpServletRequest req,
                                        HttpServletResponse res,ModelMap modelMap) throws IOException {

        String json = new Gson().toJson(matlabRequestManger.getAllRequest());

        System.out.println(" MatlabRequest json  :-"+json);

        return json;

Entity Class:

public class MatlabRequest {
    int id;
    String tid;

    String approverTid;

    int licenseType;    

    int matlabUsage;

    int licenseNo;

    String directorName="";

    String requestTime="";
    String lastAssignedTime="";

    String lastDownloadedTime="";
    String closedTime="";

    String releasedTime="";

    private Collection <RequestedComputer> requestedComputerList=new ArrayList<RequestedComputer>();

    private Collection <RequestedVersion> requestedVersionsList=new    ArrayList<RequestedVersion>();

    @OneToMany(fetch=FetchType.LAZY ,mappedBy="matlabRequest")
    private Collection<RequestedToolboxes> requestedToolboxesList=new ArrayList<RequestedToolboxes>();

 - Entity class

public class RequestedComputer {

    String  computerName="";

    String hostId="";

    String osName="";

    public String getOsName() {
        return osName;

    public void setOsName(String osName) {
        this.osName = osName;

    String assignedDate="";

    String terminationTime="";

    String releasedTime="";

    MatlabRequest matlabRequest;


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi=""
    id="WebApp_ID" version="2.5">

  <display-name>Archetype Created Web Application</display-name>



<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <context:annotation-config />
    <context:component-scan base-package="" />

    <bean id="jspViewResolver"
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />

    <bean id="messageSource"
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    <bean id="propertyConfigurer"
        p:location="/WEB-INF/" />

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />

    <bean id="sessionFactory"
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
        <property name="hibernateProperties">
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="">update</prop>

    <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper"></bean>
    <bean id="matlabRequestDAO" class=""></bean>
    <bean id="matlabRequestManger" class=""></bean>
    <bean id="toolboxesDAO" class=""></bean>
    <bean id="toolboxManager" class=""></bean>

    <bean id="computerInfoDAO" class=""></bean>
    <bean id="requestedComputerManger" class=""></bean>

    <bean id="matlabVersionDAO" class=""></bean>
    <bean id="requestedMatlabVersion" class=""></bean>

    <bean id="toolboxRequestedDAO" class=""></bean>
    <bean id="requestedToolboxManager" class=""></bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager"
        <property name="sessionFactory" ref="sessionFactory" />


I'm new to Laravel and having trouble with subdirectories. I want to make an admin folder inside the controllers folder and so far it's working. but when I try to use Laravel's Input class it says that it couldn't find it.

My routes:

Route::group(array('prefix'=> 'admin', 'before' => 'auth.admin'), function() {



The Products Controller:

 <?php namespace admin;

    class ProductsController extends \BaseController {

    protected $layout = 'master';
     * Instantiate a new ProductsController instance.
    public function __construct()

     * Display a listing of the resource.
     * GET /products
     * @return Response
    public function index()
        $input = Input::all(); //here is where it finds the error

And the composer.json autoload:

"autoload": {

        "classmap": [

Thank you!


I have also tried to use Input (and \Input) and it returned the "Class 'Facade' not found" error, and when I tried:

use \Illuminate\Support\Facades\Facade;
use Input;

It still did not work.

Edit 2:

Now using:

use Illuminate\Support\Facades\Input;

and returning the same error.

How can i rewrite this script using Model View Controller?
How should i include View files?

$query = "SELECT SQL_CALC_FOUND_ROWS questions.question_id, questions.user_id, "
       .   "posts.post_id, posts.question_id, posts.user_id, posts.message, posts.image, posts.is_question, posts.created_at, posts.is_answer, "
       . // ...
       . "LIMIT $start, 10";
$result = mysqli_query($dbc, $query);

echo '<h2>' . $subject . '</h2>';
echo '<br />';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

    echo '<div class="question-container">'
       . '<div class="question-left">'
       .       '<a class="vote-up" title="This answer is useful" href="/ask/posts-nopage.php?v_pid=' . urlencode($row['post_id']) . '&amp;vote=+1&amp;qid=' . urlencode($question_id) . '"> </a>'
       .       '<div>' . $row['vote'] . '</div>'
       .       '<a class="vote-down"  title="This answer is not useful" href="/ask/posts-nopage.php?v_pid=' . urlencode($row['post_id']) . '&amp;vote=-1&amp;qid=' . urlencode($question_id) . '"> </a>'
       .      (($row['is_question'] == 0)
                 ? ((isset($_SESSION['user_id']) && $_SESSION['user_id'] == $row['user_id'])
                     ? '<a class="is-answer-' . (($row['is_answer'] == 1) ? 'yes' : 'no') . '" href="/ask/posts-nopage.php?ia_pid=' . urlencode($row['post_id']) . '&amp;ia_current=' . urlencode($row['is_answer']) . '&amp;qid=' . urlencode($question_id) . '"> </a>'
                     : '<span class="is-answer-' . (($row['is_answer'] == 1) ? 'yes' : 'no') . '"> </span>')
                 : '')
       .   '</div>'
       .   '<div class="question-right">'
       .     '<p class="post-text">'
       .        nl2br(htmlentities($row['message'])) . ((isset($row['image'])) ? '<br /><img alt="" src="_images/post/' . $row['image'] . '" />' : '')
       . //...
       .   '</div>'
       .   '</div>';

    $query_comment = "SELECT message, created_at FROM comments WHERE post_id={$row['post_id']}";
    $result_comment = mysqli_query($dbc, $query_comment);
    if ($result_comment && mysqli_num_rows($result_comment)) {
        echo '<div class="comments">';
        while ($row_comment = mysqli_fetch_array($result_comment, MYSQLI_NUM)) {
            echo '<p class="comment-text">' . htmlentities($row_comment[0]) . '</p>';
        echo '</div>';

    echo '</div></div>';

Does not need more details
Does not need more details
Does not need more details
Does not need more details

I'm learning to build gui applications. My current private project is working, the program is doing everything I want. But the implementation looks pretty bad and is not maintainable or extensible anymore. It is not really following MVC or other design pattern in the main parts. So I've started to rework it and would appreciate some advise.

The goal of the program: It is a monitoring tool getting the data from an external source all the time as long as the application is running. The data is displayed (some labels, text areas, an OSM map) and updated permanently. Depending on the data a button to start the recording of the data (into a file) is enabled or not. When the recording is stopped by the user (same button) some post actions are executed.

Due to lack of knowledge I have implemented two separate SwingWorkers, one to display the current data and one for the recording, started when the button is pressed (is reading the date too!). This is my main pain point. Just one data-retrieving SwingWorker must be sufficent.

So I have started to rework it. I have a gui view class. Once the gui is initialized the SwingWorker (as a gui member variable) is executed and updates the view elements. Fine. Works. But is this a nice approach? The SwingWorker is the central object. From my feeling it should not belong to the view. Other objects should also observe and use its progress. Whenever new data came in gui elements or others should get notified. So I could add several observers to the SwingWorker and call notify(myData) within the doInBackground() method.

My second, bigger issue is concerning the start-stop button to record my data. What kind of implementation approach would you suggest? My idea was to implement a PropertyChangeListener to get the button clicked action. But how can this handle/record the data from the SwingWorker and interrupt on demand? It must get notified permanently too. Or is there some other, better pattern to pulling the data on demand? Is there a nice example with a single SwingWorker and multiple independent listeners/observers?

Thanks in advance, Niels

I'm currently enjoying diving into Ember and learning a complete Front End MVC solution.

Currently, I'm a little stumped on getting data from our API as it doesn't follow the standard required by Ember's Adapter. Currently, our team are unable to change the structure of the API / JSON response due to the dependencies of third party applications.

RESTAdapter is looking for JSON like this:

  'episodes' : [
            id : '1',
            title : 'my first title'

Unfortunately all we get back is an array with each episode as an object, i.e. it cannot be a key with a value of array of objects.

        id : 1,
        title : 'my first title'
        id : 2,
        title : 'my second title'

Can anyone provide assistance on how to extend DS.RESTAdapter to follow this format?

Again, our server devs cannot change the API so we have to take the JSON response as is.


How can I redirect user after successful login to specific page. I need to do this by Authorize Attribute. In my problem I have to redirect user to page: Index/About when he/she would use specific login name, rest of users would be redirected to Index/Home.

I try this method:

public class AuthAttribute : AuthorizeAttribute
    private string userName;

    protected override bool AuthorizeCore(HttpContextBase filterContext)
        var authorized = base.AuthorizeCore(filterContext);

        if (!authorized)
            return false;

        string userAuthenticated = filterContext.User.Identity.Name;
        bool specialUser = userName.Equals(userAuthenticated,    StringComparison.OrdinalIgnoreCase);

        if (specialUser)
            filterContext.Items["RedirectToHomeAbout"] = true;
            return false;

        return true;

    public override void OnAuthorization(AuthorizationContext filterContext)

        if (filterContext.HttpContext.Items.Contains("RedirectToHomeAbout"))
            var routeValues = new RouteValueDictionary(new
                controller = "Home",
                action = "About",

            filterContext.Result = new RedirectToRouteResult(routeValues);

Thanks! MarQ

My MVC view has the following code -

@if(d.Listing.Port.Country.Name !=null) {...}

which returns an 'Object reference not set to an instance of an object.' error.

Both Port and Country are lazy loading properties.

Something wrong with my approach, not sure what!

regards, Guy


The Web API works great but I don't understand why am I getting the "no action was found on the controller that matches the request error" exception error if I changed the parameter from "long parmAccountId" to "long? parmAccountId"? (See the "?" next to long datatype).

Is there a way to make it work? Thanks..

public static class WebApiConfig
    public static void Register(HttpConfiguration config)

            name: "MemberApi",
            routeTemplate: "WebApi/Member/{controller}/{action}/{AccountId}/{UserId}",
            defaults: new { AccountId = RouteParameter.Optional, UserId = RouteParameter.Optional }

public class DigitalLoanJacketController : ApiController
    public string Post(long? parmAccountId, long? parmUserId, Foo parmFoo)

var jsonRequest = { "Id": 3, "Name": "Scott Fletcher"};

    type: "POST",
    async: false, /*false, //This need to be synchronous to the client can wait for a webserver response...*/
    url: "https://localhost:44301/WebApi/Member/DigitalLoanJacket/Upload/e/83",
    data: JSON.stringify(jsonRequest),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (parmData, parmTextStatus, parmXmlHttpRequest) {
        alert("AjaxStatus: " + parmTextStatus + "\nReadyState - " + parmXmlHttpRequest.readyState + "\nStatus: " + parmXmlHttpRequest.status + "\nStatusText: " + parmXmlHttpRequest.statusText + "\nResponseText: " + parmXmlHttpRequest.responseText);
    error: function (parmXmlHttpRequest, parmTextStatus, parmErrorThrown) {
        alert("AjaxStatus: " + parmTextStatus + "\nReadyState - " + parmXmlHttpRequest.readyState + "\nStatus: " + parmXmlHttpRequest.status + "\nStatusText: " + parmXmlHttpRequest.statusText + "\nResponseText: " + parmXmlHttpRequest.responseText);

Currently looking into Identity Server's implementation from Thinktecture and was curious does somebody tried to write his own ViewService instead of default EmbeddedAssetsViewService?

I would prefer to have something MVC based that would allow to edit the pages with Razor syntax, as mostly all my applications are ASP.NET MVC, I think it would make sense to have this possibility... don't think it should be too hard, just curious if somebody already did it and could share any experience?

I tried to Google it, but didn't find anything about this...

I recently got a new laptop and did a fresh installation of Visual Studio 2013 Professional. After installation, the first thing I did was to make sure that Nuget was set to automatically download missing packages.

I'm now trying to work on the same large solution I was using before getting my new laptop, but I'm getting some strange errors that I haven't been able to resolve after many hours of research.

The most obvious symptom of the issue is that I see many errors on Razor views. They are these types of errors:

  • Feature 'lambda expression' cannot be used because it is not part of the ISO-2 C# language specification

  • Feature 'anonymous types' cannot be used because it is not part of the ISO-2 C# language specification

  • Feature 'implicitly typed local variable' cannot be used because it is not part of the ISO-2 C# language specification

  • Feature 'extension method' cannot be used because it is not part of the ISO-2 C# language specification

Another symptom is that if I try to add a new view, none of the MVC items are available: for example, no .cshtml items. However, if I create a new solution, these items are available as expected.

I updated to Visual Studio 2013 Update 3 along with the fresh installation. The solution uses MVC 4 and Razor 2. I've checked the web.config and see nothing wrong - the version of Razor and MVC I want are correct.

Despite these errors, my project builds successfully. After the build, all of the 'implicitly typed local variable' errors disappear for a few minutes, then return. Another person is working on the same solution on an old laptop and is not experiencing these issues.

I'm hoping somebody can help. I need to resolve this issue because the lack of useful Intellisense is hurting my productivity.

That is a tricky question because I want to add Html Attributes to the EditorFor() but do not want to replace the ones that was already created. Let me explain:

I have a default Editor Template for string.cshtml with the following code:

    var htmlAttributes = ViewData;
    htmlAttributes["class"] = "text-box single-line form-control";
    htmlAttributes["placeholder"] = ViewData.ModelMetadata.Watermark ?? ViewData.ModelMetadata.DisplayName;
    htmlAttributes["title"] = ViewData.ModelMetadata.Watermark ?? ViewData.ModelMetadata.DisplayName;
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, htmlAttributes)

It is used to always add the following class, placeholder and title, based on the DisplayName DataAnnotation, for the Form Inputs, it is quite handy!

But the problem is that I'm having trouble adding the disable attribute for one specific Form Input with the common code:

@Html.EditorFor(x => x.Field, new { htmlAttributes = new { disabled = "" } })

When the Form Input is with a field that is not a string, it will not follow the created EditorTemplate and it will work with this exactly code, but when it is a string, the EditorTemplate replaces the Html Attributes.

Does anyone has any clue on this?

This question already has an answer here:

I am building an ASP.NET MVC website where I keep all of my localized string in a .resx resource file. However, if I try to embed any formatting or Unicode characters, I have a problem.

Example resource file [EN_US.resx]:

Key                       Value
INTRO_COLLEGE             This is a <strong>really</strong> nice college&hellip;

Example view:


My problem is, any HTML formatting or special characters are literally printed as they are written in the resource file, like this:

This is a <strong>really</strong> nice college&hellip;

How can I include HTML formatting and Unicode characters in a .resx file such that they are not automatically escaped when it is printed out?

How can i bind a DropDownList to SQL sever table in C#.

Here is the code i have so far:

string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sql = @"select Epic, Company from Company ";
SqlConnection conn = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet dataSet1 = new DataSet();
da.Fill(dataSet1, "Company");
DataTable dt = dataSet1.Tables["Company"];
DropDownList1.DataSource = dt;
DropDownList1.SelectedValue = "";

I am using the ComboBox from the Ajax Control Toolkit. All the following codes were generated by VisualStudio 2013 (using 4.5). I only chose the data connection. Why am I getting this JavaScript error:"Unable to get property 'createRange' of undefined or null reference" and how to fix the problem? Thank you.

 <asp:ComboBox ID="ComboBox1" runat="server" AutoCompleteMode="Append" 
     DataSourceID="SqlDataSource_countries" DataTextField="country" 
     DataValueField="ID_country" DropDownStyle="DropDownList" MaxLength="0" 
      style="display: inline;">

 <asp:SqlDataSource ID="SqlDataSource_countries" runat="server"
    ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" 
    SelectCommand="SELECT [ID_country], [country] FROM [countries] 
    ORDER BY [country]"></asp:SqlDataSource>

I have an IIS application where I am calling a routine in an unmanaged dll (written in powerBasic.) At first it works fine. But after it has been running a while we notice that the values of at least one parameter "goes missing" during the routine. For example we can log the ProductName parameter and it's there. Then after performing a routine that decodes a base64 string, it ends up blank. The ProductName parameter is not related to that routine. It is not touched, only read. That makes me think it's possibly memory related. If I do an iisreset, it's fine again for who knows how long. Has anyone seen this type of issue using DLLImport before? I'd be grateful for any points in the right direction:

    [DllImport("webty14calc.dll", EntryPoint = "CALCULATE", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern long Calculate(
        [In, MarshalAs(UnmanagedType.AnsiBStr)]  ref string TierID,
        [In, MarshalAs(UnmanagedType.AnsiBStr)]  ref string TaxpayerID,
        [In, MarshalAs(UnmanagedType.AnsiBStr)]  ref string ProductName,
        [In, MarshalAs(UnmanagedType.AnsiBStr)]  ref string SSN,
        [In, MarshalAs(UnmanagedType.AnsiBStr)]  ref string MasterAcctNum,
        [In, MarshalAs(UnmanagedType.AnsiBStr)]  ref string CalcType,
        [In, MarshalAs(UnmanagedType.AnsiBStr)]  ref string B64DataRecords,
        [In, Out, MarshalAs(UnmanagedType.AnsiBStr)] ref string result);

My problem is that the i donot get the latest tracks records in map. But in terminals it shows that the vehicle is active.But in my tracks its not updated.

Please help me

I need to submit a list of users. I have a MVC controller

public JsonResult Handler(List<User> users) {

where User is

public class User {
    public string name { get; set; }
    public string email { get; set; }

in JavaScript I send the array by jquery

    var users = {};
    for (var i = 0; i < 3; i++) {
        users [i] = {
            name: "User " + i, 
            email: "user" + i + ""

        type: "POST",
        data: {
                users: users
        url: "",
        success: callback

I get the list with 3 items, but parameters name and email are NULL.

Where am I wrong?

I was trying to display a Map.

But here I took the values for Latitude and Longitude getting from AngularJs,

How to assign these values to variable. Can any one suggest me the solution Please.

Here is my Code.

    <div id="map">
            var lat = {{proplist.propagentslattitude}};
            var long = {{proplist.propagentslongitude}};
        <script type="text/javascript" src=""></script>
        <div style="overflow:hidden;height:300px;width:920px;">
            <div id="gmap_canvas" style="height:300px;width:920px;"></div>
            <a class="google-map-code" href="" id="get-map-data">google maps</a>
            <style>#gmap_canvas img{max-width:none!important;background:none!important}</style>
            <a class="google-map-data" href="" id="get-map-data">sparmichl</a>
        <script type="text/javascript"> function init_map() { var myOptions = { zoom: 16, center: new google.maps.LatLng(lat, long), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions); marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(lat, long) }); infowindow = new google.maps.InfoWindow; google.maps.event.addListener(marker, "click", function () {, marker); });, marker); } google.maps.event.addDomListener(window, 'load', init_map);</script>

Here I have assigned the both latitude and longitude values.

How to assign proper way.

    var lat = {{proplist.propagentslattitude}};
    var long = {{proplist.propagentslongitude}};

I have done some work on ASP.NET MVC 3 but I'm no expert.

So, based on the pattern definition, the view has no direct awareness of the model and does not communicate with the model directly; only controller is directly dealing with model.

However, in ASP.NET MVC 3, I can access the model data directly from the view using Razor engine. Isn't that breaking the pattern design or am I missing something?

enter image description here

I am using TinyMCE 4.0 and everything works fine except binding with reference to this question I asked earlier and the answer .

The Problem:

I am able to bind the value into newProductText.ProductText but only when I format the the which is entered in the HTML WYSIWYG text editor space.

For example if I enter 'sample' as text and select it and change the size or font only then the $scope.newProductText.ProductText gets updated.

Setting up TinyMCE:

$scope.tinymceOptions = {
        selector: "textarea",
        theme: "modern",
        plugins: ["textcolor code link"],
        statusbar: false,
        browser_spellcheck: true,
        resize: false,
        menubar: false,
        toolbar1: "fontselect | fontsizeselect | bold italic underline | bullist numlist | alignleft aligncenter alignright | forecolor backcolor | link unlink | code",

Setting up Scope variable:

var NewCustomerProductText = {
    SalesPartNo: $scope.initial,
    LanguageCode: $scope.initial,
    ProductText: $scope.initial,
$scope.newProductText = NewCustomerProductText;


 @Html.Label("Language", new { @for = "language" })
 <select id="language" ng-model="newProductText.LanguageCode" ng-options="language.LanguageName for language in languages"><option value="">-- Choose Language --</option></select>
 @Html.Label("Sales Part No:", new { @for = "salesPartNo" })
 @Html.TextBox("salesPartNo", null, new { placeholder = "Click to select sales part no", @readonly = "readonly", ng_click = "OpenProducts()", ng_model = "newProductText.SalesPartNo" })
 @Html.TextArea("tinymce2", new { data_ui_tinymce = "tinymceOptions", ng_model = "newProductText.ProductText" })
 <button ng-click="addProductText()" /> Add </button>