Im working on an Mvc app and im still a newbie..and im trying to experiment something but its not working

is it correct to loop my "using()" so that it can store a data in every loop

this is my post code here

 [HttpPost]
    public ActionResult Index(EntityFramework.Table1 a,Class1 b)
    {
        b.Letter1 = new Boolean[3];
        for (int x = 0; x <= 3; x++)
        {
            if (b.Letter1[x] == true)
            {
                a.checkAnswers = "correct";
                b.sum = b.sum + 1 ;
            }
            else
            {
                a.checkAnswers = "wrong";
                b.sum = b.sum + 0;

            }
            a.Total = b.sum;
            using (var c = new EntityFramework.Database1Entities1())
            {
                c.Table1.AddObject(a);
                c.SaveChanges();
            }
        }
        return RedirectToAction("Index");
    }

it says an error to c.Table1.AddObject(a); :The EntityKey property can only be set when the current value of the property is null.

i think its updating instead of adding..am i doing it wrong?

I have created a sample Web API that returns some sample data from an SQLite database which is included in the project.

I am able to browse and run the API on my local computer. This is all good.

I am also able to publish that API on Azure, all files are getting deployed I am getting "Publish successful" message as expected.

After, whenever I try to browse the azurewebsites.net domain, it doesn't browse it at all.

Once I create empty web site/web app, I am able to browse the welcome page on azurewebsites.net. But once I publish the API, I am getting 404 not found error, 503 error or IIS 502.5 error.

I tried to change settings from Azure portal, all settings seems good, .NET framework version is set to 4.7, as well as my project is too. Anyone has any idea?

Is it possible to make prepaid internet accessing project in. NET? In which user first notify when any open WiFi is available or not.when it is available then user can access it but in limited(reduced speed or some limited mb). For full access to open wifi user need to register themselves then they can access open wifi. Is this idea practically possible to implement in. NET???

I already an asp.net application A use Web API and identity.

Now I would like to create another asp.net application B use SingalR, host on different server

So how the application B use the authentication in A?

Currently, my idea is to do something like OAuth, so if this is correct, how to do it in Asp.net identity? Or I have to write all things myself.

Thank you

I am learning ASP.Net MVC 5 and I am stuck with one basic DB Design. So, I have one User which can refer many person in job Also, many person can apply to get themselves Referred. I have created two roles and all of that is taken care. Now, I have on class called Referral which will keep track of every instance of Referral that needs to be done.

Referral Model:

Public class Referral
{
     [Key]
        public int ReferralId { get; set; }
        public Company Company { get; set; }
        public int CompanyId { get; set; }
        public ApplicationUser User { get; set; }
        public string CandidateId { get; set; } // Application User ID of person asking for referral
        public string ReferrerId { get; set; } // Application user ID of person referring the candidate
}

ApplicationUser Model

  public class ApplicationUser : IdentityUser
    {
        public ICollection<Referral> Referrals { get; set; }
        // rest prop removed for brevity sake
    }

Now, suppose A(Referrer) refers B(Candidate). My Table row will look like below.

ReferralId     CompanyId     CandidateId   ReferrerId

1              1             B             A

So, far so good. But I want to establish FK relationship on Referral table. I am new to Fluent API but I tried like below.

    // one candidate can have many referrals
    dBModelBuilder.Entity<ApplicationUser>()
    .HasMany(u => u.Referrals)
    .WithRequired(u => u.User)
    .HasForeignKey(u => u.CandidateId)
    .WillCascadeOnDelete(false);

    //one referrar can have many referrals
    dBModelBuilder.Entity<ApplicationUser>()
    .HasMany(u => u.Referrals)
    .WithRequired(u => u.User)
    .HasForeignKey(u => u.ReferrerId);

But EF respects only one relationship. Why both the foreign key relationhip is not getting set. If I comment out one then other works, and vice versa. But keeping them together as shown never works.

Expected Behaviour: I expected to have two FK relationship. Once I have that then I can work accordingly. Please guide me here. I am new to all this.

enter image description here

I have a data structure which looks something like this: foo 1:* bar 1:* baz

It could look something like this when passed to the client:

{
    id: 1,
    bar: [{
            id: 1,
            baz: []
        },
        {
            id: 2,
            baz: [{
                id: 1
            }]
        }
    ]
}

In my UI, this is represented by a tree structure, where the user can update/add/remove items on all levels.

My question is, when the user has made modifications and I'm sending the altered data back to the server, how should I perform the EF database update? My initial thought was to implement dirty tracking on the client side, and make use of the dirty flag on the server in order to know what to update. Or maybe EF can be smart enough to do an incremental update itself?

I have a dummy webisite where I want to run a task in a while(true) loop and I want it to run forever. I'm in a school project about soccer bets and I need this (sort of) cloud website to automatically update games and results for me everyday, insert them in the database and send emails, depending on eacher users bets (if they gots points in the game or not).

Although, I can't seem to keep it alive. This is my code:

private static string LigacaoBD = @"connectionString";
    private static ApiMethods sportRadar = new ApiMethods();
    private static Jogo jogo = new Jogo(LigacaoBD);
    private static List<SportRadar.ClassesCliente.Jogo> jogos;
    private static List<SportRadar.ClassesCliente.Competicao> competicoes;

    protected void Page_Load(object sender, EventArgs e)
    {
        // Iniciates a new asynchronous task
        Task.Factory.StartNew(() => Actualizacoes());

    }


    public void Actualizacoes()
    {
        bool verif = true;

        while (true)
        {
            // Time in which I want the task to run the task on the method
            if (DateTime.UtcNow.ToLocalTime().Hour == 1 && DateTime.UtcNow.ToLocalTime().Minute == 30 && DateTime.UtcNow.ToLocalTime().Second == 0)
                verif = true;


            // quando voltar a ficar online será actualizar.
            if (verif)
            {
                // I want the games 7 days from now
                DateTime dt = new DateTime(DateTime.UtcNow.ToLocalTime().Year, DateTime.UtcNow.ToLocalTime().Month, DateTime.UtcNow.ToLocalTime().Day + 7);
                // This is due to the providers limitation to trial accounts
                Thread.Sleep(1000);
                // Makes the request for the tournaments to the API
                competicoes = sportRadar.Competicoes();

                Thread.Sleep(1000);
                // Makes the request for the daily schedules to the API
                jogos = sportRadar.JogosDoDia(dt);

                // Saves each game in each tournament to the database
                foreach (SportRadar.ClassesCliente.Jogo j in jogos)
                {
                    foreach (SportRadar.ClassesCliente.Competicao c in competicoes)
                        if (j.Id_Torneio == c.Id)
                        {
                            jogo.Guardar(j.Clube_Casa, j.Clube_Visitante, c.Nome, c.Pais, j.Data);
                            break;
                        }
                }
                // I want the results from the day before
                dt = new DateTime(DateTime.UtcNow.ToLocalTime().Year, DateTime.UtcNow.ToLocalTime().Month, DateTime.UtcNow.ToLocalTime().Day-1);

                Thread.Sleep(1000);
                // Makes the request for the daily results to the API
                jogos = sportRadar.ResultadosDoDia(dt);

                // Updates the results on the database and sends e-mails according to the points aquried but each user
                foreach (SportRadar.ClassesCliente.Jogo j in jogos)
                {
                    foreach (SportRadar.ClassesCliente.Competicao c in competicoes)
                        if (j.Id_Torneio == c.Id)
                        {
                            List<Utilizador> utilizadores = jogo.AlterarResultado(j.Clube_Casa, j.Clube_Visitante, c.Nome, c.Pais, j.Data, j.Golos_Casa, j.Golos_Visitante);

                            if (utilizadores.Count > 0)
                            {
                                foreach (Utilizador u in utilizadores)
                                    Verificacoes.EnviarEmail("smtp.live.com", "betmagnum@hotmail.com", "Senha098!", u.Email,
                                        "BetMagnum - Ganhou pontos num jogo!", "Parabéns, " + u.Nickname + ". Ganhou " + u.Pontuacao + " pontos no jogo " +
                                        j.Clube_Casa + " - " + j.Clube_Visitante + ".<br/><br/>Resultado do jogo:<br/>" +
                                        j.Clube_Casa + " " + j.Golos_Casa + " - " + j.Golos_Visitante + " " + j.Clube_Visitante + "<br/><br/>" +
                                        "Pontos ganhos: "+u.Pontuacao, 587);
                            }
                            break;
                        }
                }

                verif = false;

            }
            Thread.Sleep(1000);
        }
    }

So, if I open the page, it will be active and will go to the page load and run the task. Everything goes smoothly. But on the next day, I don't get any updates to the database or emails unless I open the page again, which is not what I want.

How can this be achieved?

Thanks for the help, in advance.

I developed an asp.net web application with VS 2017 and .net framework 4.5 but I don't know why the URL is appeared like the below attached image IP Address/App Name/ (Some thing strange)/page name

ASP.NET application URL

I want to pass a collection of skills id from my view to controller action, i have a dropdownlist of SKILLS :

         <select name="skills">
           <option value="0">Java</option>
           <option value="1">C++</option>
           <option value="2">Fortran</option>
           <option value="3">ASP</option>
         </select>

i want that user can select many skills from dropdown and store their value in a collection ,i.e an array, and then post that array to action in controller as follow [employee and skills have a manytomany relationship]:

 [HttpPost]
 public ActionResult AddEmp(Employee emp ,IEnumerable<Skills> skills )

 {

   DBCtx db=new DbCtx();
   db.employees.Add(emp);
   var emp_id=db.SaveChanges();

   var employee=db.employees.Find(emp_id);

   foreach(item in skills)
   {
      var skill = db.skills.Find(item);
      employee.skills.Add(skill);
   }
   db.SaveChanges();

   return View();
   } 

How can i achieve this ,thanks in advance ....

I have been reading these two functions and considering to pick up the one which is much more secure. I want to use Server.Transfer because its executes at server side in a sense. Is it better??

Server.Transfer("myUrl.aspx?id=1");

or

Response.Redirect("myUrl.aspx?id=2");

I'm new to .NET and SQL so bear with me here.

So, here's my SQL query:

      SELECT [Gender], count(*)
      FROM [UsersDB].[dbo].[vwUser]
      WHERE Gender='M'
      GROUP BY Gender

In SMSS, this returns

      M 5298

I want to print out that value (5298) in a div or a header on my webpage.

So, in my Index.cshtml I tried

      @using WebMatrix.Data;
      @{
      var db = Database.Open("usersdbconnectionstring"); 
      var selectQueryString = "SELECT [Gender], count(*) FROM [UsersDB].[dbo].[vwUser] WHERE Gender='M' GROUP BY Gender"; 
      }

I ripped that off from an example on W3C schools and it worked for printing out a table but not for this.

This didn't work either:

      @WebMatrix.Data
      @{
      var db = Database.Open("usersdbconnectionstring");
      var selectedData = db.Query("SELECT [Gender], count(*) FROM [UsersDB].[dbo].[vwUser] WHERE Gender='M' GROUP BY Gender");
      var grid = new WebGrid(source: selectedData);
       }
       <div>
       @grid.GetHtml()
       </div>

Any ideas on how to get this to work?

I am using ASP.NET and IIS for my website. Recently, I found Varnish Cache software via Google, an excellent caching HTTP reverse proxy.

Varnish Cache is installed on Ubuntu 16.04.1 and then I configure IIS connect to it. That's great.

Varnish Cache has function Purge to clear all cache of a specify page or all site. On ASP.NET, I wrote code create a Request to Varnish Cache Server with method PURGE and error occur: The remote server returned an error: (405) Method Not Allowed.

Here is my code:

  HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://IP-Address-Varnish-Cache-Server");
  req.Method = "PURGE";
  using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
  {
    // get the page data
    using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
    {
      string html = sr.ReadToEnd();
    }
  }

Please help me how to fix above error ? Thanks.

I'm trying to trigger a jQuery AJAX post to my ASP.NET webservice. However, even though the subscribeToSearch method is executed, when I access the strSubscriber.email variable in that method it's empty. Why?

These are the varaible values I'm logging before they get posted:

email: YES@NO.COM
objecttype: 15
provinceid: 7
city: "test"
distance: 0
minprice: 0
maxprice: 0
frequency: 0
rooms: 0
surface: 0

Here's the AJAX call:

   $.ajax({
        type: "POST",
        url: '/api/subscribetosearch',
        async: true,
        data: JSON.stringify({
            str: {
                'objecttype': objecttype,
                'email': email,
                'provinceid': provinceid,
                'city': city,
                'distance': distance,
                'minprice': minprice,
                'maxprice': maxprice,
                'frequency': frequency,
                'rooms': rooms,
                'surface': surface
            }
        }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function () {
        },
        success: function (msg) {


        }
    }); 

The webmethod signatures:

Ihouse.vb

    <OperationContract()>
    <Web.WebInvoke(Method:="POST", ResponseFormat:=Web.WebMessageFormat.Json, BodyStyle:=Web.WebMessageBodyStyle.WrappedRequest,
UriTemplate:="subscribetosearch")>
    Function subscribeToSearch(ByVal str As GlobalFunctions.SearchSubscriber) As Stream 

house.svc.vb

Public Function subscribeToSearch(ByVal strSubscriber As GlobalFunctions.SearchSubscriber) As Stream Implements Ihouse.subscribeToSearch
    LogError("subscribeToSearch hit")
    LogError("subscribeToSearch email: " + strSubscriber.email)
End Function

I checked out the headers in Google Chrome dev console and this is the request payload:

enter image description here

Here's the SearchSubscriber class.

Public Class GlobalFunctions

    <Runtime.Serialization.DataContract>
    Public Class SearchSubscriber
        <Runtime.Serialization.DataMember>
        Private _objecttype As Integer
        Public Property objecttype() As Integer
            Get
                Return _objecttype
            End Get
            Set(ByVal value As Integer)
                _objecttype = value
            End Set
        End Property

        Private _email As String
        Public Property email() As String
            Get
                Return _email
            End Get
            Set(ByVal value As String)
                _email = value
            End Set
        End Property

        Private _provinceid As Integer
        Public Property provinceid() As Integer
            Get
                Return _provinceid
            End Get
            Set(ByVal value As Integer)
                _provinceid = value
            End Set
        End Property

        Private _city As String
        Public Property city() As String
            Get
                Return _city
            End Get
            Set(ByVal value As String)
                _city = value
            End Set
        End Property

        Private _distance As Integer
        Public Property distance() As Integer
            Get
                Return _distance
            End Get
            Set(ByVal value As Integer)
                _distance = value
            End Set
        End Property

        Private _minprice As Integer
        Public Property minprice() As Integer
            Get
                Return _minprice
            End Get
            Set(ByVal value As Integer)
                _minprice = value
            End Set
        End Property

        Private _maxprice As Integer
        Public Property maxprice() As Integer
            Get
                Return _maxprice
            End Get
            Set(ByVal value As Integer)
                _maxprice = value
            End Set
        End Property

        Private _frequency As Integer
        Public Property frequency() As Integer
            Get
                Return _frequency
            End Get
            Set(ByVal value As Integer)
                _frequency = value
            End Set
        End Property

        Private _rooms As Integer
        Public Property rooms() As Integer
            Get
                Return _rooms
            End Get
            Set(ByVal value As Integer)
                _rooms = value
            End Set
        End Property

        Private _surface As Integer
        Public Property surface() As Integer
            Get
                Return _surface
            End Get
            Set(ByVal value As Integer)
                _surface = value
            End Set
        End Property

    End Class
End Class   

I create asp page and add aspxcombobox then i set datasource to it as:

 <dx:ASPxComboBox ID="flStudentState" runat="server" DataSourceID="dcStudentState"  TextField="Value" ValueType="System.Guid" ValueField="LookUpValueId" >
                                                                        <ValidationSettings>
                                                                            <RequiredField IsRequired="True" />
                                                                        </ValidationSettings>
                                                                    </dx:ASPxComboBox>

but when run my page the result is shown as: enter image description here

I am trying to return a csv file from an MVC Controller derived from a List. I came up with the following code for controller based on combining what I read from docs and SO questions. I must be missing something because I am getting yellow screen of death with "Cannot access a closed stream"...

public class ConsumersFileController : Controller
{
    private readonly TDCContext _db = new TDCContext();


    public ActionResult Index()
    {
        IEnumerable<Consumer> list = _db.Consumers.ToList();

        //put List in memory stream object
        MemoryStream memoryStream = new MemoryStream();
        using (memoryStream)
        {
            //return memory stream as file stream result:
            using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, System.Text.Encoding.UTF8, true))
            {
                foreach (var item in list)
                {
                    var itemBytes = item.Serialize();
                    binaryWriter.Write(itemBytes.Length);
                    binaryWriter.Write(itemBytes);

                }

                FileStreamResult fileStream =
                    new FileStreamResult(memoryStream, "application/txt") {FileDownloadName = "zips.csv"};

                return fileStream;
            }
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _db.Dispose();
        }
        base.Dispose(disposing);
    }

}

Here is the stack trace:

[ObjectDisposedException: Cannot access a closed Stream.]
   System.IO.__Error.StreamIsClosed() +59
   System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count) +14731549
   System.Web.Mvc.FileStreamResult.WriteFile(HttpResponseBase response) +93
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +88
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +831
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +607
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +134

How can the stream get closed if I am returning the result inside the using block of the stream?

I have a BeginForm to populate all properties of the model. Then I use the property values to pass the action method(Model binding).

Now I have a drop down outside of the BeginForm, I want to add one more property to the model. The property value is picked up from the selected value from the drop down.

So

  1. I modified the model AddQuestionModel, Added one more property SelectedLanguage.
  2. Added a hidden textbox inside the BeginForm.

    @using (Html.BeginForm("AddSurveyQuestion", "Country", FormMethod.Post, new { enctype = "multipart/form-data", id = "AddQuestionForm" }))
    {
         <div class="modal-header">
             <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
             <h3>Add New Question</h3>
         </div>
         <div class="modal-body">
         @Html.TextBox("SelectedLanguage",new { value = "English", @class = "hidden" })
    
  3. Listen the change event.

    $("#Model_SelectedLanguage").change(function () {
            var selectedValue = $(this).find('option:selected').text();
            $("#SelectedLanguage").val(selectedValue);
            location.reload();
    });
    

Now the question is that I still can't get the select value in the action method

[HttpPost]
public ActionResult AddSurveyQuestion(AddQuestionModel model)`.

I mean model.SelectedLanguage = null.

Also I found the input element rendered by the TextBox is not hidden at all.

I am working on an ASP.NET MVC 5 application and using tinymce editor to store HTML formatted data (for certain fields) to a SQL Server 2014 database.

The data is being returned to the page using a foreach loop, but the tags/markup are not being rendered as HTML and instead are showing up in the page as text.

CODE EX:

@foreach (var item in Model) {
    <div>@Html.DisplayFor(modelItem => item.Category)</div>
    <div>@Html.DisplayFor(modelItem => item.Name)</div>
    <div>@Html.DisplayFor(modelItem => item.Description)</div>
}

How do I get the stored HTML to render properly when returned to the page?

I am working on some blog website in asp.net. Using razor layout pages to present all content data from database. First paragraph in content part is reserved for some sub Title and got style rules for first letter like font-size, color etc.

<section id="post-content" class="b-container">

    <div class="blog-post">
        @*first paragraph reserved for title*@
        <p>
            @Model.PostSubhead1

        </p>
        @*first paragraph end*@
        <p>
            @Model.PostText1
        </p>
        <figure>
            <img src="@Url.Content(Model.PostBigImage1)" class="big-image" />
            <em class="img-text">
               @Model.PostBigImageText1
            </em>
        </figure>

    </div>
</section>

Style rules.

    #post-content .blog-post p:first-child{
    font-size:1.85em;
    line-height:1.4em;
}

#post-content .blog-post p:first-child:first-letter{
    color:#43464b;
    float:left;
    font-size:2.85em;
    font-weight:700;
    margin:6px 8px -5px 0;
    line-height:60px;
}

How can i set color of first-letter from database ? Because every post got different color for first letter in title.

I'm trying to build an HTML table in razor code where I put two items on each row. I thought of the aproach underneath. However, the compiler won't match the correct brackets with one another. Is there some way to get around this?

 for (int i = 0; i < items.Length; i++)
    {
        if (i == 0 || i % 2 == 0)
        { //this bracket matches...
            <tr>
        }

//<td>plot item data here</td>

        if (i % 2 == 1 || i == items.Length - 1)
        {
            </tr>
        } //... with this bracket
    }

I'm transferring my IIS-based API projects to a landline server in Germany with IPv4 and IPv6 addressing. After IIS has been installed and set up as the old server continues to receive this error.

APIs are developed in C # Visual Studio and are mostly .aspx pages

New server configurations: - Windows Server 2012 R2 - Microsoft .NET Framework: 4.0.30319; Version of ASP.NET:4.7.2053.0

This is the error.

I would like to write and equals sign which has a question mark above. How can I write this symbol in my asp.net web form?

From what I understand the language used is MathJax. How can I use MathJax language in my webform?

$\stackrel{?}=$