Thanks for any help,

My question is simple, I want to create a website which allows users to register ad's like:

I want to sell my car, I want to register my company, I want to sell my house and etc...

Anything which allow users to register ads...

My question is how do I start?

It's pretty simple, however I didn't find any example.

Is there some project as mine with node.js involved?

Thank you so much for any help again!

I'd like to populate a list of CharacterViewModel with a single query if possible, but I'm unsure how, nor if PetaPoco can even do something like this. This is what the object and query look like:

    public class CharacterViewModel
{
    public Character Character { get; set; }
    public Entity Entity { get; set; }
    public Faction Faction { get; set; }
}


var characters = db.Query<CharacterViewModel>(
    @"SELECT c.*,e.*,f.*
        FROM [Character] c
        INNER JOIN [Entity] e ON e.Id = c.EntityId
        INNER JOIN [Faction] f ON f.Id = e.FactionId
        WHERE c.UserId = @0", 1)

Somehow I'd need to tell PetaPoco to map each JOIN to the respective POCO within the view model. Is this possible or am I going about it the wrong way?

I don't understand why I cannot receive on Web Api Get or Put method any data.. here is my simple ajax:

 $('#chk').click(function () {    
                $.ajax({
                    url: 'api/Customer',
                    type: 'POST', // I've also tried GET
                    dataType: 'xml', // I need xml
                    data: { '': true }, // I've also tried as a string 'true' & value: 'true'
                    contentType: 'application/xml',
                    success: function (data) {
                      alert(data); 
        });

and empty Web Api methods:

 public XElement Get() {}
 public void Post([FromBody] bool value){} //also tried as a string value

Also I want to mention that it goes to this methods, and can receive information back to page... Another adding the problem is in this line:

 contentType: 'application/xml',

when I comment it everything working fine, bt I need to send data as xml, and header should show application/text xml

I query a remote service to receive a batch of 100 products at a time and continue to do this until no more batches remain. I remap these 100 products to my own product object which I wish to validate and save to a database one at a time. If one doesn't validate I log the error and continue with the rest. Once the first 100 have been processed I go and get the next batch of 100. There are about 5000 in all.

The issue I'm seeing, after profiling my website, is that the Validator.TryValidateObject seems to exponentially take longer and longer to run. The first batch of 1000 took 10 mins, the second 1000 took 20 mins, the third 1000 took 30 mins. So it seems to take 10 mins longer each time.

The Product class has a buddy class ProductValidation with the appropriate data annotations for validation. I call product.IsValid().

    public class Product{
        public bool IsValid()
        {
            return this.IsValid<Product, ProductValidation>();
        }
    }

Using the following code:

    public static bool IsValid<T, U>(this T obj)
    {
        if (typeof(T) != typeof(U))
        {
            TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(T), typeof(U)), typeof(T));
        }

        var validationContext = new ValidationContext(obj, null, null);
        var validationResults = new List<ValidationResult>();
        //The line below slows everything down. If commented out all is fine
        Validator.TryValidateObject(obj, validationContext, validationResults, true);

        if (validationResults.Count > 0)
            return false;
        else
            return true;
    }

Why would the above scenario slow down exponentially? It's like the validator is re-validating all objects each time.

I am binding my drop down list with database using EF code first approach.My model class is department

  public class Department
{
    [Key]
    public int DepartmentID { get; set; }
    [Required]

    [Display(Name = "Department")]

    public string DepartmentName { get; set; }

}

I am getting all department name in ViewData

 ViewData["Departments"] = new SelectList(db.Departments,"DepartmentName");

In my view my code is this

@Html.DropDownList("Departments", "Select Department")

Thid code binding my data but not with name but their are 10 objects like MyProjectName.Models.Department

MyProjectName.Models.Department

MyProjectName.Models.Department

MyProjectName.Models.Department

MyProjectName.Models.Department ....

Need help what is going wrong in my code.

I've been trying to implement this solution to have a razor view page that makes use of an asp master page. The problem I'm encountering is that the master page cannot inherit the MVC ViewMasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="System.Web.Mvc.ViewMasterPage" %>

Parser Error Message: The type 'System.Web.Mvc.ViewMasterPage' is ambiguous: it could come from assembly 'C:\Projects\OpenDataPortal\OpenDataPortal\bin\System.Web.Mvc.DLL' or from assembly 'C:\Projects\OpenDataPortal\OpenDataPortal\bin\OpenDataPortal.DLL'. Please specify the assembly explicitly in the type name.

I inspected this ViewMasterPage with .NET Reflector and determined that it contains all the Html helpers etc. that are used on Razor pages. Thus, this should allow me to do the following on the RazorView.aspx page that uses this master page as in the solution (the Html helper and ViewBag):

<% Html.RenderPartial((string) ViewBag._ViewName); %>

I also determined that there should be nothing wrong with my MVC assembly in the web.config:

<dependentAssembly>
  <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
  <bindingRedirect oldVersion="1.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
</dependentAssembly>

I'm also not sure whether having a code-behind and/or designer for the master page and/or RazorView.aspx page would cause any problems.

I have 3 roles in my webapp: Admin,Moderator,User.

I have a user @model WebApplication2.Models.ApplicationUser I want to check inside Razor view if user.Roles contains role Moderator. How to do so? I tried @if(@Model.Roles.Contains(DON'T_KNOW_WHAT_TO_WRITE_HERE){}.

NOTE: I am not asking how to check if currently authorized user is in certain role.

While reading this article , i think i have found a mistake(pls correct me if wrong). Here when ViewState property is disabled in textbox, then how ASP runtime loaded data in Load View State event as no data gets saved when ViewState disabled.

As a result in the image below i think the highlighted portion should be empty.

enter image description here

Pls correct me if wrong

I have a problem when trying to communicate an android application with a web service. I get the following error when I try to get the users in a SQL Server 2012 database

09-28 13:47:10.966: E/ServicioRest(1244): org.json.JSONException: End of input at character 0 of 
09-28 13:47:10.966: E/ServicioRest(1244):   at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
09-28 13:47:10.966: E/ServicioRest(1244):   at org.json.JSONTokener.nextValue(JSONTokener.java:97)
09-28 13:47:10.966: E/ServicioRest(1244):   at org.json.JSONObject.<init>(JSONObject.java:154)
09-28 13:47:10.966: E/ServicioRest(1244):   at org.json.JSONObject.<init>(JSONObject.java:171)
09-28 13:47:10.966: E/ServicioRest(1244):   at com.example.web.MainActivity$TareaWSObtener.doInBackground(MainActivity.java:204)
09-28 13:47:10.966: E/ServicioRest(1244):   at com.example.web.MainActivity$TareaWSObtener.doInBackground(MainActivity.java:1)
09-28 13:47:10.966: E/ServicioRest(1244):   at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-28 13:47:10.966: E/ServicioRest(1244):   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-28 13:47:10.966: E/ServicioRest(1244):   at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-28 13:47:10.966: E/ServicioRest(1244):   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-28 13:47:10.966: E/ServicioRest(1244):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-28 13:47:10.966: E/ServicioRest(1244):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-28 13:47:10.966: E/ServicioRest(1244):   at java.lang.Thread.run(Thread.java:856)

Android code:

private class TareaWSObtener extends AsyncTask<String,Integer,Boolean> {

    private int idCli;
    private String nombCli;
    private String telefCli;

    protected Boolean doInBackground(String... params) {

        boolean resul = true;

        HttpClient httpClient = new DefaultHttpClient();

        String id = params[0];

        HttpGet del = 
                new HttpGet("http://10.0.2.2/Api/Clientes/Cliente/"+id);

        del.setHeader("content-type", "application/json");

        try
        {           
            HttpResponse resp = httpClient.execute(del);
            String respStr = EntityUtils.toString(resp.getEntity());

            JSONObject respJSON = new JSONObject(respStr);

            idCli = respJSON.getInt("Id");
            nombCli = respJSON.getString("Nombre");
            telefCli = respJSON.getString("Telefono");

        }
        catch(Exception ex)
        {
            Log.e("ServicioRest","Error al obtener los usuarios!", ex);
            resul = false;
        }

        return resul;
    }

    protected void onPostExecute(Boolean result) {

        if (result)
        {
            lblResultado.setText("" + idCli + "-" + nombCli + "-" + telefCli);
        }
    }
}

ASP .NET code

  public Cliente ObtenerCliente(int id)
    {
        Cliente cli = null;

        SqlConnection con = new SqlConnection(cadenaConexion);

        con.Open();

        string sql = "SELECT nombreUsuario,apellidosUsuario FROM Usuario WHERE idUsuario = @idcliente";

        SqlCommand cmd = new SqlCommand(sql, con);

        cmd.Parameters.Add("@idcliente", System.Data.SqlDbType.Int).Value = id;

        SqlDataReader reader =
            cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

        if (reader.Read())
        {
            cli = new Cliente();
            cli.Id = id;
            cli.Nombre = reader.GetString(0);
            cli.Apellidos = reader.GetString(1);
        }

        reader.Close();

        return cli;
    }




    // POST    /Api/Clientes/Cliente    { Nombre:"nombre", Telefono:123456789 }
    // PUT     /Api/Clientes/Cliente/3  { Id:3, Nombre:"nombre", Telefono:123456789 }
    // GET     /Api/Clientes/Cliente/3
    // DELETE  /Api/Clientes/Cliente/3
    public JsonResult Cliente(int? id, Cliente item)
    {
        switch (Request.HttpMethod)
        {
            case "POST":
                return Json(clientesManager.InsertarCliente(item));
            case "PUT":
                return Json(clientesManager.ActualizarCliente(item));
            case "GET":
                return Json(clientesManager.ObtenerCliente(id.GetValueOrDefault()), 
                            JsonRequestBehavior.AllowGet);
            case "DELETE":
                return Json(clientesManager.EliminarCliente(id.GetValueOrDefault()));
        }

        return Json(new { Error = true, Message = "Operación HTTP desconocida" });
    }

I think error is because de android app doesn't connect with web service but How I can know it? Thanks

I have a MVC project on hand where it is ready to be published and everything seems to be fine! But when i publish it the theme (look and feel) changes. I have implied a CSS bootstrap theme where i have the JS, CSS, IMG files on a separate folder lets call it (Folder A). It works fine when i just hit f5 (debug) the application but when i publish it, It doesn't have that theme. It seems the problem is with configuring the bundles but i couldn't figure that out. Any clues?
I tried to add bundles and still not working.

I tried to get a string attribute from my model to pass to javascript function that gets a String object but i keep getting an HTMLInputElement instead of string

<input type="radio" id="Paroxysmal" name="afeval" value="paroxysmal"> <label>Paroxysmal  </label> </br>
<input type="radio" id="Persistent" name="afeval" value="persistent"> <label>Persistent </label> <br>
<input type="radio" id="Permanent" name="afeval" value="permanent"> <label>Permanent  </label>

<script>                                   
    document.getElementById(@Model.Single(m => m.Diagnosis == "AF" && m.fieldType == "E").nameOf).checked=true;
</script>

From the model class:

public String nameOf { get; set; }

can i convert it do String? what else should i try?

Use in the application pattern "Repository". To create a separate class library, describe methods through interfaces. Decided to override the membership provider. In the library through References to add references to System.Web, create a class in it connect System.Web.Security, and I try to inherit from the abstract class MembershipProvider ... just says that this class does not exist as such, and many other MembershipUser ...

Step 1 : Unload Project - Right click on project in solution explorer, select Unload Project. Step 2 : Edit Project - Right click and select ‘Edit Project and project XML will load in the editor window. Step 3 : Find false in Project XML file and change this to true Step 4 : Save the Project XML file. Step 5 : Reload Project - Right click on the project and select ‘Reload Project’

Now when Project compile, views will also be compile.

Hi this should be a really simple problem with actual LINQ knowledge unlike me! I want to return only the last 20 records and normally .Take(20) when ordered by descending works but because I'm returning an instance of the model.CPU I don't know where to put the statement.

Help would be greatly appreciated, have been Googling for the past hour or so.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace hello_services.Controllers
{
    public class cpuController : ApiController
    {
        private Data.ResourceDataModelDataContext _context = new Data.ResourceDataModelDataContext();

        //WebAPI will respond to an HTTP GET with this method
        public List<Models.CPU> Get()
        {
            //get all of the records from the Counter_CPU table
            var cpuRecords = from e in _context.Counter_CPUs
                             select new Models.CPU
                             {
                                 Counter_CPU_ID = e.Counter_CPU_ID,
                                 //Counter_CPU_Time = e.Counter_CPU_Time,
                                 Counter_CPU_Percentage = e.Counter_CPU_Percentage
                             };


            return cpuRecords.ToList();
        }
    }
}

I have the following form within an ASP.NET MVC 5 application

@model ProjectOasis.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Admin", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label"})
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label"})
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
        </div>
    </div>
    //more form stuff
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Create" />
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

How do I make it so that whenever a value is entered into the m.Email textbox that the value is immediately copied into the m.UserName textbox? (I will be making the UserName textbox un-editable after I have this working).

Thanks.

I have written some code to setup server-to-server authentication between my service and Azure Active Directory.

As part of this code, I construct a token, digitally sign it and send it to Microsoft's STS server using System.Net.WebClient.UploadValues() method.

When running through a "test" console application, everything works fine. However, when I call the same code through an ASP.NET web application, the "UploadValues()" throws a (400): Bad Request exception.

Here is the code:

    public static string GetOAuthAccessTokenFromACS(string stsUrl, string assertion, string resource)
    {
        string accessToken = string.Empty;

        WebClient client = new WebClient();

        NameValueCollection values = new NameValueCollection();
        values.Add(JWTTokenHelper.ClaimTypeGrantType, "http://oauth.net/grant_type/jwt/1.0/bearer");
        values.Add(JWTTokenHelper.ClaimTypeAssertion, assertion);
        values.Add(JWTTokenHelper.ClaimTypeResource, resource);

        // ERROR: This line throws an exception
        byte[] responseBytes = client.UploadValues(stsUrl, "POST", values);

       // Additional code goes here
       ...
    }

STS Url and Resource are the same in both cases (when running through test Console and when called through ASP.NET web app).

Interestingly when I hit the STS Url through my web browser, I see the following exception:

STS Url: https://accounts.accesscontrol.windows.net/tokens/OAuth/2

{"error":"invalid_request","error_description":"ACS90004: The request contains 1 tokens separated by \u0027=\u0027 instead of a single key value pair.\r\nTrace ID: 6540924b-7656-47ae-818b-d179b38d11d5\r\nCorrelation ID: 1093ed41-6852-4651-adb7-f876fc05ca52\r\nTimestamp: 2014-09-28 06:21:07Z","error_codes":[90004],"timestamp":"2014-09-28 06:21:07Z","trace_id":"6540924b-7656-47ae-818b-d179b38d11d5","correlation_id":"1093ed41-6852-4651-adb7-f876fc05ca52"}

And so it is quite likely, that this might be some kind of a URL Encode issue that is only surfacing through the ASP.NET Web app. To reiterate again, this program works fine when I execute the SAME code through a Console application.

I have tried searching for a solution or lead to this problem, but so far, I am drawing a blank!

Any help would be appreciated.

I have a scenario of a system that will call the customer based on his priority. initially, I've a table that integrated with a legacy system. the legacy system sends the customer#, his priority, and the table in turn creates a sequence # for that customer and this is the easiest part as long as it's ready. the hardest part is how to read customers and insert them in a gridview. My major question, is it possible to control the gridview columns' values which means first column will be for only Priority 1 and column 2 for priority 2 and so on. in case of not, what is the best tool or mechanism to implement this. Thanks

I have two checkboxlists CandidateName and Payment, and a dropdownlist. User can do multiple selections in checkboxlists and one selection at dropdownlist. I am populating those data of chechboxlists and dropdownlist to Panel nested inside UpdatePanel where gridview exist.. When I click on Add Button to open up Panel, all data is properly populating. When I tried to save multiple selected checkedboxlists through "for loop" at debugging, it is not going inside the loop to accumulate checked data with comma to save at database. Instead, after chekcing "if (cblPayment1.Items[j].Selected == true)", it skips over to another query statement. Please help me advise.

 protected void btnAddNew_Click(object sender, EventArgs e)
{
    try
    {

        string strcbl1 = string.Empty;
        string strcbl2 = string.Empty;
        compCon = new SqlConnection(strConnectionString);
        compCon.Open();


        for (int i = 0; i < cblCandidateName1.Items.Count-1; i++)
        {
            if (cblCandidateName1.Items[i].Selected ==true)
            {
                strcbl1 = strcbl1 + cblCandidateName1.Items[i].Value.ToString() + ",";
            }
        }

        for (int j = 0; j < cblPayment1.Items.Count - 1; j++)
        {
            if (cblPayment1.Items[j].Selected == true)
            {
                strcbl2 += cblPayment1.Items[j].Value.ToString() + ",";
            }
        }


       string InsertSchedule = "INSERT INTO ScheduleEmail(CANDIDATE_ID, PAYMENT_ID,     TEMPLATE_ID)VALUES(@strCID, @strPID, @strCourseID)";
        SqlCommand InsertScheduleCommand = new SqlCommand(InsertSchedule, compCon);
        InsertScheduleCommand.Connection = compCon;


        InsertScheduleCommand.Parameters.AddWithValue(@"strCID", strcbl1);
        InsertScheduleCommand.Parameters.AddWithValue(@"strPID", strcbl2);
        InsertScheduleCommand.Parameters.AddWithValue(@"strCourseID", strCourseID);

        InsertScheduleCommand.ExecuteNonQuery();
        compCon.Close();
    }
    catch (Exception ex)
    {
        ShowPopUpMsg("Data is failed to save in table. Please contact your system administrator \n" + ex.ToString());
    }
    finally
    { 
    DispalyGridViewScheduleEmail();

    compCon.Close();
    }

}

THis is my HTML Code.

<!--Panel to add new record--><asp:Panel ID="panelAddNew" runat="server" 
style="display:none; background-color:gray;"        ForeColor="Black" Width="500" Height="550">
<asp:Panel ID="panelAddNewTitle" runat="server" 
 style="cursor:move;font-family:Tahoma;                       
 padding:2px;" HorizontalAlign="Center" BackColor="Blue" ForeColor="White" Height="25">
<b>Add New</b></asp:Panel>
 <table width="100%" style="padding:5px">
            <tr>
            <td colspan="3">
                <asp:Label ID="lblStatus1" runat="server"></asp:Label>
            </td>
            </tr>
            <tr>
                <td><b>Select Candidate Name(s)</b></td>
                <td><b>:</b></td>
                <td><asp:CheckBoxList ID="cblCandidateName1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" RepeatLayout="table">
                </asp:CheckBoxList>
                </td>
            </tr>
            <tr>
                <td><b>Select Payments</b></td>
                <td><b>:</b></td>
                <td>
                   <asp:CheckBoxList ID="cblPayment1" runat="server" RepeatDirection="Horizontal" RepeatLayout="Table"></asp:CheckBoxList>
                </td>
            </tr>


            <tr>
                <td><b>Course Name</b></td>
                <td><b>:</b></td>
                <td> <asp:DropDownList ID="ddlCourseName" runat="server">      </asp:DropDownList>            


                </td>
            </tr>
        </table>
        <br />
            <div align="center">
            <asp:Button ID="btnAddNew2" runat="server" Width="70" Text="Add" OnClick="btnAddNew_Click"  ValidationGroup="add"/>
            &nbsp;

            <asp:Button ID="btnCancel1" runat="server" Width="70" Text="Cancel" CausesValidation="false" OnClick="Cancel_Click" ValidationGroup="add"/>
        </div>
    </asp:Panel>   
        <!--End of Panel to add new record-->

I have the following form within an ASP.NET MVC 5 application

@model ProjectOasis.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Admin", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label"})
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label"})
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
        </div>
    </div>
    //more form stuff
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Create" />
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

How do I make it so that whenever a value is entered into the m.Email textbox that the value is immediately copied into the m.UserName textbox? (I will be making the UserName textbox un-editable after I have this working).

Thanks.

I have a custom implementation of IUserStore because I want to use my repository layer. All of my database tables stores the user’s name who inserted or last updated the row. I get user name from HttpContext.Current, which works well, except when repository is called via UserManager, I get null in HttpContext.Current. When my own business layer call the repository everything works well. (I am using async version of methods.)

Have anybody an idea what happening in UserManager, why losing current httpcontext?

Thx Attila

I am using MVC 5 with Identity 2. I have created two roles, one for administrators, and one for vendors. The problem I have is that the registration form must use properties that are defined in the vendor role. I cannot figure out how to make MVC use those role properties for register purposes. I've tried assigning the appropriate role to the applicationuser but, after assigning it the role it still says it doesn't exist. Is there anyway of doing this, or am I going to have to split this into two register screens (ie one to handle initial user creation and a second one to handle role specific implementation)?

Thanks in advance.

        public async Task<ActionResult> Register(RegisterVendorViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName = model.Email, 
                    Email = model.Email,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    PhoneNumber = model.PhoneNumber,
                    CompanyName = model.CompanyName,
                    Address = model.Address,
                    City = model.City,
                    State = model.State,
                    PostalCode = model.PostalCode
                };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)