I'am creating an appliaction in ASP.NET MVC 5 with SQL Server where one of the module is a News. News can be added by Administrator to main page. Users can comment the news. I would like to know how to implement real-time adding comments to news, which means that when user is reading for example news with ID=5 and somebody post a comment in this news i would like to get this comment without refreshing the page. I heard about SignalR ,but i don't know how to call update ONLY FOR USERS who are reading a specific news with for example ID=5.How to send update only for this users? Not for all logged in users, but only for a specific users which are currently on the specific news?

my database schema is like this :

  • (annonce:product)= One to Many
  • (annonce:region)= One to Many
  • (product:category) = many to many

i want to add new annonce using entity framework (disconnected mode) so I :

  • select regions and i add it to newAnnonce
  • select categories add it to first product then the second.(lets say (cat1 ->prod1 ,cat2->prod1) and (cat1->prod2)
  • add these tow products to newannonce. But i receive this error : An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key", this is because prod1 contains cat1 and prod2 contains cat1. I ask how can i and add these tow products whitout having a duplication of cat1

I'm using the default ASP.Net MVC template in Visual Studio. I'm using the ASP.Net Identity code that was created for me in the template. I'd like for the DBContext I use to be aware of the relationship between the ApplicationUser entity (AspNetUser table) and the rest of my entities. For example, I want to be able to have an ApplicationUser.Messages property that exhibits the relationship between the ApplicationUser and Message entities. I have my DbContext for all non-Identity entities in a Data Access Layer project. And the template ApplicationDbContext is in the UI Layer. In order to keep the relationships between the Identity entities and my custom entities, I need to merge into one DbContext, right? How do I do this?

Here is some sample code of what I have:

The IdentityUser and DbContext created for me in the UI Layer project from the MVC template with my custom Messages property:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    public ICollection<Message> Messages { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

The Message class I have in my Domain/Business Logic Layer:

public class Message
{

    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    [Required]
    public string Body { get; set; }

    [Required]
    public DateTime Created { get; set; }
}

The DBContext I have in my Data Access Layer project:

public class PSNContext : DbContext, IPSNContext
{
    public PSNContext()
        :base ("DefaultConnection")
    {
    }

    public DbSet<Message> Messages { get; set; }
}

It doesn't feel right to bring UI-specific code like this from the ApplicationUser in the UI Layer into my Business Logic Layer:

var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

Is there a better way to do this?

I have a listview with item template and theres two asp labels which is dynamically bind. And i want to get the values of the two labels. How to do that?

<asp:ListView ID="lstItems" runat="server" OnItemDataBound="lstItems_ItemDataBound">
                              <LayoutTemplate>
                                   <asp:PlaceHolder ID="itemPlaceholder" runat="server" />      
                                </LayoutTemplate>
                              <ItemTemplate>
                                   <div class="col-md-4">
                                          <section class="panel">
                                              <div class="pro-img-box">
                                                  <img src='<%#Eval("FileImage")%>'alt="" height="222" width="279"/>
                                                  <asp:Button runat="server" CommandArgument='<%#Eval("ItemId")%>' ID="btnAddCart" OnCommand="btnAddCart_Command"` CssClass="btn-success col-lg-5t" Text="Add to Cart" ></asp:Button>



                                              </div>

                                              <div class="panel-body text-center">
                                                  <h4>
                                                     <asp:Label runat="server" ID="lblid" Visible="true"><%#Eval("ItemID") %></asp:Label>
                                                      <asp:Label runat="server" ID="lblname"><%#Eval("Name_")%></asp:Label>

                                                  </h4>
                                                  <asp:Label runat="server" ID="lblquantity"><%#Eval("Quantity")%></asp:Label>
                                              </div>
                                          </section>
                                      </div>
                              </ItemTemplate>
                              </asp:ListView>**strong text**

I have a URL which when I open in browser, it will redirect to another URL pointing to pdf file. How to get that final url to that file programmatically ins asp.net?

e.g. http://www.redirection.com/?p=110 will get me to test.library.net/test.pdf.

I need that second url without opening first one in browser. thanks

i want to add comments from my database to the update panel on click of a button. this is my aspx page-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default12.aspx.cs" Inherits="Default12" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:Button ID="Button" runat="server" Text="Button" onclick="Button_Click" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Button" EventName = "Click"/>
        </Triggers>
        <ContentTemplate>
            <asp:PlaceHolder ID="CommentPlaceHolder" runat="server"></asp:PlaceHolder>
        </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

this is my cs page-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.SqlClient;
using System.Data;

public partial class Default12 : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader dr;
    string str;
    protected void Page_Load(object sender, EventArgs e)
    {
        str = @"Data source=INSPIRATION\SQLEXPRESS; Initial Catalog=ComputerPedia; Integrated security= true";
        con = new SqlConnection(str);
        if (con.State == ConnectionState.Closed)
            con.Open();
        cmd = new SqlCommand("Select Comment from CommentTable", con);
        dr = cmd.ExecuteReader();
    }
    protected void Button_Click(object sender, EventArgs e)
    {
            dr.Read();
            Response.Write(dr[0].ToString());
            Label l = new Label();
            l.ID = "l1";
            l.Text = dr[0].ToString();
            CommentPlaceHolder.Controls.Add(l);
            UpdatePanel1.Update();
    }
}

but this is not working. There is no problem with the connection because ic opied the connection code from a working webpage and the query is also working in sql. please help me with this. Thanks!

I have a question about how i need to manage my Dispose method, when i am implementing a repository class inside my asp.net mvc web application.

Currently i have the following:-

  1. i am using VS 2013, and i created a new asp.net mvc-5 web application.
  2. i uses entity framework 6.0 to map my database tables inside my web application and generates a .edmx file.
  3. I created a new Controller class for one of my model objects, using "MVC 5 controller , using entity framework" scaffold .

now inside the generated controller class i got this dispose method:-

 public class DeptsController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
//code goes here
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }

now i want to move my data access code to be inside a separate Repository class, and to be initiating my DbContext object inside the Repository class rather than inside the controller class.

so i created the following repository class:-

public class repository

    {
        private ApplicationDbContext db = new ApplicationDbContext();
        //code goes here...
        public void Dispose()
        {
            db.Dispose();
        }

and i modified my controller class to be using the repository class as follow:-

 public class DeptsController : Controller
    {
        //private ApplicationDbContext db = new ApplicationDbContext();
        private repository repo = new repository();
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                repo.Dispose();
            }
            base.Dispose(disposing);
        }
    }

so can anyone adivce on the following :-

  1. since i will be moving my data access logic to be inside my repository , so what else i need to dispose other than the DbContext ? i mean before using the Repository , calling base.Dispose(disposing); inside the controller will make sure all the unmanaged resources are disposed correctly.. but when i moved my data access to be inside the repository , how i can make sure that all the unmanaged resources consumed by the repository are disposed ?? and is calling base.Disposed(disposing) inside the controller class , will also dispose any unmanaged resources consumed inside the repository class ?

Can anyone adivce on this ?

I have a list collection of umbraco pages and i want to loop through checking if a bool property is true and if so i want to apply a specific class to the div

How can i write an else if ternary operator in razor to apply a class to to a div. If i wasnt using ternary then it would look like this

if package.GetPropertyValue<bool>("test")
{
  <div class="test1"></div>
}
else if (package.GetPropertyValue<bool>("test1"))
{
  <div class="test1"></div>
}
else if (package.GetPropertyValue<bool>("test2"))
{
  <div class="test2"></div>
}

in my razor view it would be something like as follows (but not right)

@(package.GetPropertyValue<bool>("test") ? "test" : package.GetPropertyValue<bool>("test1") ? "test1" : "test2" )

many thanks paul

I have a list of (string) column headings for which I want to create dynamic textboxes in order to add a new record, like this.


Model

    public class AddModel
    {
        public Dictionary<string, string> DynamicHeadings{ get; set; }
    }

Controller

    public ActionResult InsertRecord()
    {
        AddModel model = new AddModel();
        model.ColumnHeadings= getColumnHeaderList();

        return PartialView("~/Views/Partials/_addPartial.cshtml", model);
    }

    [HttpPost]
    public ActionResult InsertRecord(AddModel model)
    {
         //add the record using the updated model
    }

View

    @using (Html.BeginForm("InsertRecord", "DataController", FormMethod.Post))
    {  
       @foreach (var heading in Model.ColumnHeadings)
       {
         <div class="control-group">
            <span><label class="control-label">@heading.Field</label></span>  
              <div class="controls">
              @{
                  var fieldName = @heading.Field;
                  Html.TextBox("?", ?somevalue?);
               }
              </div>
         </div><br />
       }
       <button type="submit">submit</submit>
    }

Question

Is this possible? How could I pass a dictionary containing the heading and its corresponding values via the model using razor?

I have a gridview but currently it only sets one header. What I want it to do is add new header columns at the end of the table based on the number of users.

 protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView1.UseAccessibleHeader = true;
            GridView1.AutoGenerateColumns = false;
            int i = 6;
            string constr = ConfigurationManager.ConnectionStrings["CMT"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "SELECT * FROM [user]";
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {                                  
                            GridView1.Columns[6].HeaderText = sdr["user_first_name"].ToString();
                            break;
                       }
                    }
                    conn.Close();
                }
            }
        }
}

I am new with VB and combining JavaScript. This is easy question, but for a reason or other I am not able to figure it out.

I am not able to build IF-statement correctly. Please could you help me? I have looked and googled, but have not found such answer that would help me to get this correct. Otherwise my code works ok. Here is the code I have:

<script type="text/javascript">
var markers = [
<asp:Repeater ID="rptMarkers" runat="server">
<ItemTemplate>
{
"title": '<%# Eval("pvm")%>',
"lat": '<%# Eval("lat")%>',
"lng": '<%# Eval("lng")%>',
"icon": '<%# Eval("Ikoni")%>',
"description": "<span style=’font-size:18px;font-weight:bold;><%#Eval("pvm")%> <%# Eval("Otsikko")%></span><hr>" +
"Text: <%# Eval("Nimi")%> <br> Merkki: <%# Eval("Tunniste")%> <br>"+
"<%# Eval("Info")%>"

--> This should be in IF-statetement; If there is "Photo" information this is taken along, but otherwise left out;

+"</div><div><img src=<%# Eval("Photo")%> height='150'></img></div></div>"

<--

} </ItemTemplate> ...

Please, given me some guidance.

How do I delete the files in a folder in a directory via a button click?

This is the currant method I have tried.

    protected void BtnDel_Click(object sender, EventArgs e)
{
    Array.ForEach(Directory.GetFiles(Server.MapPath("/Notes/"), File.Delete)
}

This doesn't seem to be working so any alternative would be appreciated

what is the header bytes for JPG image, downloaded from facebook or tell me the way to resolve my issue. Issue is that, when i upload FB downloaded image in my project, it cross over my JPG validation i.e JPG image header bytes. (Described below). Normal JPG header bytes does not working on FB downloded images.

imageHeader.Add("JPG", new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 });
imageHeader.Add("JPEG", new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 });
imageHeader.Add("PNG", new byte[] { 0x89, 0x50, 0x4E, 0x47 });

I am working on an ASP .NET project, and currently I am using this code to store and retrieve DateTime on cookies:

HttpCookie cookie = new HttpCookie("myCookie");
if (Request.Cookies["myCookie"] != null)
{
    cookie = Request.Cookies["myCookie"];
}
else
{
    cookie["From"] = DateTime.Now.AddDays(-7).ToShortDateString();
    cookie["To"] = DateTime.Now.ToShortDateString();
    Response.Cookies.Add(cookie);
}
model.FromDate = DateTime.Parse(cookie["From"]);
model.ToDate = DateTime.Parse(cookie["To"]);

And in my View I am using Razor to recovery the model values like this:

<input type="text" id="from" value="@Model.FromDate.ToShortDateString()" readonly="readonly" />
<input type="text" id="to" value="@Model.ToDate.ToShortDateString()" readonly="readonly" />

It is working fine when I run it locally, but when I uploaded to production, when recovering the DateTime from cookie, the date is changed in one day. For example, I selected a date range from 3/25/2016 to 4/1/2016, then I have gone to another page, and when I came back to this page, the page showed a date range from 3/24/2016 to 3/31/2016, decreased in one day.

Do you know what I am doing wrong here, why this just happens in production (I suppose is something related to server date) and, finally, what is the best way to store and retrieve a DateTime on cookie?

How do you properly create a Web API POST of complex object or multiple parameters using Angular2?

I have a service component in Angular2 as seen below:

public signin(inputEmail: string, inputPassword: string): Observable<Response> {
    return this.http.post('/api/account/signin', JSON.stringify({ Email: inputEmail, Password: inputPassword}), this.options);
}

The targeted web api is seen below:

[HttpPost]
[Route("signin")]
public async Task<IActionResult> Signin(string email, string password)
{
       ....
}

This does not work because I need to convert the parameters of the web api into a single POCO class entity with Email and Password properties and put the [FromBody] attribute: Signin([FromBody] Credential credential)

Without using [FromURI] (POST requests with query strings?), how can I make POSTs of multiple parameters or complex objects without converting these parameters into a single POCO class?

Because what if I have numerous Web API POST actions with parameters like (string sensitiveInfo1, string name, int sensitiveInfo2) or (ClassifiedInfo info, string sensitiveInfo1, string sensitiveInfo2), do I need to convert them all to POCO classes and always use [FromBody]?

PS. I was using RestangularJS before and it can posts anything (mulitple primitive objects and complex objects) without my Web API actions having [FromBody] attributes. Will about to investigate how RestangularJS do it.

I'm facing issues while running my application built on ASP.NET Core using Docker in Visual Studio. My application only uses dnxcore50 framework. My project.json file is:

{
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
  },
  "frameworks": {
    "dnxcore50": { }
  },
  "exclude": [
    "wwwroot",
    "node_modules"
  ],
  "publishExclude": [
    "**.user",
    "**.vspscc"
  ],
  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel"
  }
}

I have tried following approaches:

  1. When my dnvm points to runtime dnx-coreclr-win-x64.1.0.0-rc1-update1 as shown in figure below.

enter image description here

My application builds successfully. But, I get following error on running/debugging the application on docker and my application gets stuck at "Opening site http://192.168.99.100:5000" enter image description here

  1. As the above error message suggests there is mismatch in framework, I changed the default and active runtime to dnx-coreclr-linux-x64.1.0.0-rc1-update1 by modifying default alias and executing command dnvm use default -p. Then, I restart my VS (to make sure the changes are visible in VS).

enter image description here

However, my application still builds on DNX version v4.5.1 as suggested in the build logs below:

1>  Information: [LoaderContainer]: Load name=Microsoft.Dnx.Tooling
1>  Information: [PathBasedAssemblyLoader]: Loaded name=Microsoft.Dnx.Tooling in 2ms
1>  Information: [Bootstrapper] Runtime Framework: DNX,Version=v4.5.1
1>  Microsoft .NET Development Utility Mono-x64-1.0.0-rc1-16231

Hence, the application again fails to run with the same error as in point 1.

Additionally, on changing the default runtime dnu restore stops working from command line and gives with following error:

'dnu' is not recognized as an internal or external command, operable program or batch file.

Interestingly, the 'dnu' restore command continues to work from VS (as suggested in VS build logs).

  1. I then tried to change dnvm runtime to dnx-mono.1.0.0-rc1-update1. But it fails with following error:

Cannot find dnx-mono.1.0.0-rc1-update1.1.0.0-rc1-update1, do you need to run 'dnvm install default'? At C:\Program Files\Microsoft DNX\Dnvm\dnvm.ps1:1659 char:9 + throw "Cannot find $runtimeFullName, do you need to run '$Com ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (Cannot find dnx...stall default'?:String) [], Run timeException + FullyQualifiedErrorId : Cannot find dnx-mono.1.0.0-rc1-update1.1.0.0-rc1-update1, do you nee d to run 'dnvm install default'?

What runtime I need to use to run docker from VS and how I can change it? Request your help to resolve the issue.

I am converting a web form to MVC C# razor project. I like to know how I will get the same functionality in Razor where it will create a link and sumbit the form into the same page. The web form code is -

<asp:LinkButton ID="lnkBtn_1" runat="server" Text='<%#Eval("Sales") %>' OnCommand="LinkButton1_Command" CommandArgument='<%#Eval("Sales") %>' ></asp:LinkButton>

Thanks in advance

After user fills some values in the form and clicks the submit button I want to disable some controls on the form for example some text boxes and some drop down controls.

Currently my drop down starts like this:

<select name="myquestion_@i" id="questionselect" >

How can I modify it to get disabled after Submit button is clicked? I don't want JS. Just directly with MVC.

I am new to MVC but I think I should do something like this maybe?

<select name="myquestion_@i" id="questionselect" disabled = @Model.DissableIt>

Currently in my form starting with @using (Html.BeginForm I have a submit button like this:

<input id="submitButton" type="submit" value="Update stuff" />

Now after they submit, I want to show ANOTHER button instead of that button for example:

<input id="continueButton" type="button" value="Continie to next page" />

So I understand I should have a property on my model for example @Model.ShowSubmitButton that goes true or false. From my learning I should do something close to

@if(Model.ShowSubmitButton)
    <input id="submitButton" type="submit" value="Update stuff" />
else
    <input id="continueButton" type="button" value="Continie to next page" />

But I can't get the Razor syntax wrong if actually my way of doing it is correct to begin it. So I need help with this part. And I want do it with MVC, not with JS because I don't know JS yet.

I am thinking of having something like this:

 @if(Model.ShowSubmitButton)
 {
    <input id="submitButton" type="submit" value="Update stuff" />
 }
 else
 {
    <input id="continueButton" type="submit" value="Continue to next page" />
 }

Then in controller is it possible to know which button it is getting called from? I originally had my controller method working with the first button, now adding a second button with different functionality, wanted to see if using the same method I can determine which button was clicked ? and if it is not possible this way, then what do you suggest?

I'm trying to cycle through a 3x3 grid with the top row being 1, 2, 3, and so on so you can add a picture to one space on the grid and it's stored in a local database. When I'm outputting my data i'm using Razor to grab everything in my list. like so:

@foreach (var pref in Model.userPref)
{
    var title = @pref.title.ToLower().Replace(" ", "-");

    <div class="favourite-app" data-position="@pref.position_id" data-appid="@pref.app_id"><a href="@pref.url" class="@title" target="_blank">@pref.title</a></div> 
}

Now the issue I'm having is that's only outputting the content in the database, I can't get it to add in the empty divs around the pictures. I've tried to put a for loop around it and count up to 9 and make an if statement however I'm not having any luck with that, it's just outputting 9 of each app.