I'm trying to implement device specific views in a ASP.NET MVC application, as described e.g. here: https://www.simple-talk.com/dotnet/asp-net/multiple-views-and-displaymode-providers-in-asp-net-mvc-4/ or here: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/aspnet-mvc-4-mobile-features

Although the articles above are geared towards ASP.NET MVC4, their content is relevant for later versions of the framework (my app is using ASP.NET MVC 5.2).

I've stumbled on an issue. I have the following controller:

public class TestController: Controller
{
    public ActionResult Test()
    {
        return View(new TestModel());
    }
    public ActionResult Test2()
    {
        return View("~/Views/Test/Test.cshtml", new TestModel());
    }
}

The Test model is really basic:

public class TestModel
{
    public string TheDate
    {
        get
        {
            return DateTime.Now.ToString();
        }
    }
}

And I have two views in the "~/Views/Test" folder:

Test.cshtml

@model MyNamespace.Models.TestModel
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<h1>This is the desktop view</h1>
<p>model data: @Model.TheDate</p>
</body>
</html>

Test.Mobile.cshtml

@model MyNamespace.Models.TestModel
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<h1>This is the mobile view</h1>
<p>model data: @Model.TheDate</p>
</body>
</html>

I've implemented the solution described in the links above.

When asking for /test/test, I get the proper view (Test.cshtml when requesting it through my desktop browser and Test.Mobile.cshtml when requesting it from a mobile emulator). However, when asking for /test/test2, i get the desktop view all the time.

I've searched for a solution to my problem, but everyone seems to be reproducing the same scenario over and over (i.e. the "/test/test" scenario) and nobody seems to have tried to do the "/test/test2" scenario. Is it even possible to override that functionality? I'm not afraid to get my hands dirty with overriding default razor/MVC functionality, but I don't really know where to start with this.

Any help is appreciated.

I create application, and when i sent data from multiple forms i have a problem with Date which need to send data to second table have value 01.01.0001 in model and controller, but from the browser sending correct data:

Broser Data Controller Data

here is code of Model:

   [Key]
        public int rID { get; set; }
        public int AgentID { get; set; }
        [StringLength(10)]
        public string karta_br { get; set; }
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        [DataType(DataType.Date)]
        public DateTime Datum { get; set; }
        public int patnikID { get; set; }
        public int stanicaOD { get; set; }
        public int stanicaDO { get; set; }
        public decimal cena { get; set; }
        public bool povratna { get; set; }
        public virtual tbl_agenti tbl_agenti { get; set; }
        public virtual tbl_patnici tbl_patnici { get; set; }
        public virtual ICollection<tbl_povratni> tbl_povratni { get; set; }
        public virtual tbl_stanici tbl_stanici { get; set; }
        public virtual tbl_stanici tbl_stanici1 { get; set; }
        [NotMapped]
        public virtual tbl_povratni povratniLST { get; set; }

The model receive null value, i don`t know where is the problem. Anyone have solution?

I am creating webm/video of users' web-camera using Video.JS my goal is to save the generated video to a file in a designated folder on the server. I have tried different methods such as: BinaryWritter, MemoryBuffer, StreamWritter but unfortunately only 1 KB of the video gets written to the file.

According to Video.JS on GitHub in a Chrome Browser Video.JS generates objects containing properties for both Audio and Video whereas in Firefox Video.JS generates a blob object

The desired outcome is as follows:

  • Capture users' webcam Done
  • Save users' video to server without using FileUploadControl that is the video should get uploaded to the server automatically I haven't found a solution yet.

Could you please help me to achieve the second goal.

Default.aspx

<form id="form1" runat="server">
    <div class="container">
        <div class="row">
            <div class="col-xs-12">
                <video id="myVideo" class="video-js vjs-default-skin"></video>

                <!-- Video.js & AJAX POST -->
                <script type="text/javascript">
                    var player = videojs("myVideo",
                    {
                        controls: true,
                        width: 320,
                        height: 240,
                        plugins: {
                            record: {
                                audio: true,
                                video: true,
                                maxLength: 10,
                                debug: true
                            }
                        }
                    });

                    player.on('deviceError', function () {
                        console.log('device error:', player.deviceErrorCode);
                    });
                    player.on('error', function (error) {
                        console.log('error:', error);
                    });

                    player.on('startRecord', function () {
                        console.log('started recording!');
                    });

                    player.on('finishRecord', function () {
                        console.log('finished recording: ', player.recordedData);

                        $.ajax({
                            type: 'POST',
                            url: 'Default.aspx/GetVideo',
                            data: "{recordedVideo:" + JSON.stringify("testName") + "}",
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            success: function (r) {
                                /*alert(r.d.Name);
                                alert(r.d.Population);*/
                                alert(r.d);
                            }
                        });
                    });
                </script>
                <!-- END OF Video.js & AJAX POST -->
            </div>
        </div>
    </div>
</form>

WebMethod

    [System.Web.Services.WebMethod]
    public static string GetVideo(RecordedVideo recordedVideo)
    {
        var binFormatter = new BinaryFormatter();
        var stream = new MemoryStream();
        binFormatter.Serialize(stream, recordedVideo.Video);

        byte[] b = new byte[stream.Length];
        b = stream.ToArray();

        MemoryStream ms = new MemoryStream(b);

        using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(".\\uploadedVideos\\test.webm"), FileMode.Create, System.IO.FileAccess.Write))
        {
            ms.Read(stream.ToArray(), 0, (int)ms.Length);
            fs.Write(stream.ToArray(), 0, (int)ms.Length);
            fs.Close();
            ms.Close();
        }
    }

RecordedVideo Class

namespace WebApplication1
{
    public class RecordedVideo
    {
        private object name;

        public object Name
        {
           get { return name; }
           set { name = value; }
       }
    }
 }

Your help is much appreciated.

Best Regards

I have a problem with this ASP.NET API controller.

response.Content = new PushStreamContent(video.WriteToStream, 
                                         new MediaTypeHeaderValue("video/" + ext));

And I get this error :

Error CS0121 The call is ambiguous between the following methods or properties: 'PushStreamContent.PushStreamContent(Action, MediaTypeHeaderValue)' and 'PushStreamContent.PushStreamContent(Func, MediaTypeHeaderValue)'
TVStream G:\TVStream\TVStream\Controllers\Api\VideosController.cs 19 Active

And here is the signature of my WriteToStream method:

public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)

When creating a website in C# .NET how can I implement a stack or a queue?

I have a GridView with a TemplateField column that has an asp:Button in the ItemTemplate. The text of the button is <%# Bind("Active") %> while the datasource selectcommand is

"SELECT col1, col2, col3, CASE WHEN [Active] = 'true' THEN 'Active' ELSE 'Inactive' END AS [Active] FROM table

I want to change the CssClass of the button to one thing when the text says "Active" and set the CssClass to something else when it says "Inactive". Yet when I debug the GridView registers "" for the Cell on load. Right now my IF check is in the RowDataBound event. Does it need to be in a different event?

Below is my connection string and I don't know where I am getting error.

<appSettings>

<!-- Default database to use... -->
<add key="Database_default" value="DB_Servername"/>

<!-- Datamart database connection to use -->
<add key="Database_datamart" value="MED_PROD"/>

<!--  Development Datamart Database Server -->
<add key="MED_PROD" value="Initial Catalog=REPORT_MED;Data Source=DB_Servername;UID=app_UID;PWD=******;"/>

<!--  Dev Server - Port Reference-->
<add key="va3fin01" value="Initial Catalog=acc;Data Source=DB_Servername;UID=med_UID;PWD=*******;"/>

<!-- MEDFIN_DEV -->
<add key="MED_DEV" value="Initial Catalog=MED_DEV;Data Source=DB_Servername;UID=med_UID;PWD=********;"/>

 </appSettings>

I don't have any back end code. They asked me to change server. After changing servers I am getting "The connectionstring property has not been initialized" on a working app. Please let me know if there is anything I could take care of only on web.config

Please help! Thanks

I'm trying to upload a basic web application from visual studio on Windows 7 to an IIS environment on Windows Server 2007.

Though launching it from IIS displays the Login page, trying to navigate past it to the main menu returns this error:

Server Error in Application "PARKING/PARKING ASSIGNMENTS WEB"Internet Information Services 7.0
Error Summary
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. Detailed Error Information
Module IIS Web Core 
Notification MapRequestHandler 
Handler StaticFile 
Error Code 0x80070002 
Requested URL http://localhost:81/Parking Assignments Web/Home 
Physical Path C:\ParkingAssignmentsWeb\Home 
Logon Method Anonymous 
Logon User Anonymous 
 Most likely causes:
•The directory or file specified does not exist on the Web server.
•The URL contains a typographical error.
•A custom filter or module, such as URLScan, restricts access to the file.
 Things you can try:
•Create the content on the Web server.
•Review the browser URL.
•Create a tracing rule to track failed requests for this HTTP status code and see which module is calling SetStatus. For more information about creating a tracing rule for failed requests, click here. 
 Links and More InformationThis error means that the file or directory does not exist on the server. Create the file or directory and try the request again. 
View more information »

This is the code I used for navigation:

Response.Redirect("Home.aspx");

Why would this navigation work on Visual Studio but not on IIS?

UPDATE: I tried the variations of the Redirect command you guys showed me but all of them gave a 404 error, which leads me to believe that the problem isn't with the command but with something else. Any idea what?

I've got a method in my control page that displays 4 images with their 4 labels. What I am trying to achieve is to have these 4 images with their corresponding labels displayed randomly each time the page is loaded.

The control page has a panel with set locations for each label and each image. How do I randomize it? This is what I have:

        Label1.Text = DBTable.WText1;
        Label2.Text = DBTable.WText2;
        Label3.Text = DBTable.WText3;


        Image1.ImageUrl = DBTable.WImage1;
        Image2.ImageUrl = DBTable.WImage2;
        Image3.ImageUrl = DBTable.WImage3;

        Label4.Text = DBTable.CorrectText;
        Image4.ImageUrl = DBTable.CorrectImage;

Any advice or help is appreciated

I use Apache Ignite .NET EntityFramework second level caching in my ASP.NET MVC 5 website. Everything work as expected on my development machine, but things get complicated when I try to publish the website using Web Deploy on the production IIS.

I always get a class org.apache.ignite.IgniteException: Ignite instance with this name has already been started: GridName when I publish or restart the website on IIS. The error is pretty clear, Ignite is already running.

The only way I found to get away this error is restarting the application pool of the website. However, I don't want to do this every time I publish the website in production (which happens several times a week).

I tried stopping the Ignite instance in the global.asax Dispose() or Application_End(), but the thing is that the AppDomain takes many seconds to stop. Ignite therefore has the time to try starting itself before it is stopped and causes the error mentioned above.

I also tried to call Ignition.TryGetIgnite() to retrieve the running instance instead of trying to start it, but it always return null. Looking at the source code of this function in the Apache Ignite Github repository, I see that the Ignition object simply keeps a static list of nodes in memory and perform operations on this list. Since the AppDomain restarted at this point, the list is empty but the Ignite node is still running in the JVM.

Is there a way to retrieve the Ignite instance or to stop it reliably, so I don't need to restart the application pool each time?

I have code in controller that write data from View to table

Here is code

[HttpGet]
    public ActionResult WelcomeScreen()
    {
        // Формируем список команд для передачи в представление
        SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
        ViewBag.Teams = teams;
        SelectList teams2 = new SelectList(db.Companies, "CompanyID", "CompanyName");
        ViewBag.Teams2 = teams2;
        return View();
    }


    [HttpPost]
    public ActionResult WelcomeScreen(Interview interview)
    {
        db.Interview.Add(interview);
        db.SaveChanges();
        int id = interview.Interview_Id;
        return RedirectToAction("Index", "Questions");
    }

Here is model

   [Key]
    public int Interview_Id { get; set; }
    public string Greeting { get; set; }
    public string Detail { get; set; }
    public Nullable<int> VacancyId { get; set; }

    public virtual Vacancy Vacancy { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Interwier> Interwiers { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<InvitationMail> InvitationMails { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<MassLink> MassLinks { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<QuestionBlock> QuestionBlocks { get; set; }
}

I need to have Interview_Id

I try to make it like this, but it not works int id = interview.Interview_Id;

How I can write id to variable?

OK, so I'm having an issue with either Visual Studio or ASP.NET - I've laid out controls in an html table but the TextBox and DropDownList controls appear out of place in the table and just hog the bottom of the screen. https://i.stack.imgur.com/o2Zvb.png

Here's the markup, as you can see the textboxes "should" all be within the elements:

<table>
   <thead>
       <tr>
           <th colspan="6">
               <asp:Label ID="Search_Header" runat="server" Font-Bold="True" meta:resourcekey="Search_HeaderResource1" Font-Size="16pt"></asp:Label>
           </th>
       </tr>
   </thead>
   <tbody class="controls">
       <tr>
           <td style="height: 22px">
                  <asp:Label ID="Destination" runat="server" meta:resourcekey="DestinationResource1" ></asp:Label>
           </td>
           <td style="height: 22px">
               <asp:TextBox ID="Destination_Text" runat="server" meta:resourcekey="TextBox1Resource1"></asp:TextBox>
           </td>
           <td style="height: 22px">
               <asp:Label ID="Check_In" runat="server" Text="Label" meta:resourcekey="Check_InResource1"></asp:Label>
           </td>
           <td style="height: 22px">
<asp:TextBox ID="Check_In_Date" runat="server" meta:resourcekey="Check_In_DateResource1" TextMode="DateTime" AutoPostBack="True"></asp:TextBox>
    <ajaxToolkit:CalendarExtender ID="Check_In_Date_CalendarExtender" runat="server" TargetControlID="Check_In_Date" BehaviorID="Check_In_Date_CalendarExtender" />
           </td>
           <td style="height: 22px">
                 <asp:Label ID="Check_Out" runat="server" Text="Label" meta:resourcekey="Check_OutResource1"></asp:Label>
           </td>
           <td style="height: 22px">
                <asp:TextBox ID="Check_Out_Date" runat="server" meta:resourcekey="Check_Out_DateResource1" TextMode="DateTime" AutoPostBack="True"></asp:TextBox>
    <ajaxToolkit:CalendarExtender ID="Check_Out_Date_CalendarExtender" runat="server" TargetControlID="Check_Out_Date" BehaviorID="Check_Out_Date_CalendarExtender" />
           </td>
       </tr>
       <tr style="margin-bottom: 5px">
           <td></td>
           <td>
                <asp:RequiredFieldValidator ID="Destination_Validator" runat="server" ErrorMessage="<%$ Resources:Resource, Required_Field %>" ControlToValidate="Destination_Text" Font-Size="8pt" ForeColor="Red"></asp:RequiredFieldValidator>
           </td>
           <td></td>
           <td>
               <asp:RequiredFieldValidator ID="Check_In_Validator" runat="server" ErrorMessage="<%$ Resources:Resource, Required_Field %>" ControlToValidate="Check_In_Date" Font-Size="8pt" ForeColor="Red" ></asp:RequiredFieldValidator>
           </td>
           <td></td>
           <td>
               <asp:RequiredFieldValidator ID="Check_Out_Validator" runat="server" ErrorMessage="<%$ Resources:Resource, Required_Field %>" ControlToValidate="Check_Out_Date" Font-Size="8pt" ForeColor="Red" ></asp:RequiredFieldValidator>
           </td>
       </tr>
       <tr>
           <td>
               <asp:Label ID="Adults" runat="server" Text="Label" meta:resourcekey="AdultsResource1"></asp:Label>
           </td>
           <td>
               <asp:TextBox ID="Adult_Count" runat="server" type="number" TextMode="Number" meta:resourcekey="Adult_CountResource1" ForeColor="Black" MaxLength="2" Width="20px" Font-Size="10pt" ReadOnly="True" ViewStateMode="Enabled"></asp:TextBox>
    <ajaxToolkit:NumericUpDownExtender ID="Adult_Count_NumericUpDownExtender" runat="server" TargetControlID="Adult_Count" Minimum="1" Width="50" BehaviorID="Adult_Count_NumericUpDownExtender" Maximum="10" RefValues="" ServiceDownMethod="" ServiceDownPath="" ServiceUpMethod="" Tag="" TargetButtonDownID="" TargetButtonUpID="" ViewStateMode="Enabled" />
           </td>
           <td>
                <asp:Label ID="Children" runat="server" Text="Label" meta:resourcekey="ChildrenResource1"></asp:Label>
           </td>
           <td>
               <asp:TextBox ID="Child_Count" runat="server" type="number" TextMode="Number" meta:resourcekey="Child_CountResource1" ForeColor="Black" MaxLength="2" Width="20px" Font-Size="10pt" ReadOnly="True" ViewStateMode="Enabled"></asp:TextBox>
    <ajaxToolkit:NumericUpDownExtender ID="Child_Count_NumericUpDownExtender" runat="server" TargetControlID="Child_Count" Minimum="0" Width="50" BehaviorID="Child_Count_NumericUpDownExtender" Maximum="10" RefValues="" ServiceDownMethod="" ServiceDownPath="" ServiceUpMethod="" Tag="Child" TargetButtonDownID="" TargetButtonUpID="" ViewStateMode="Enabled" />
           </td>
           <td>
               <asp:Label ID="Room_Size" runat="server" Text="Label" meta:resourcekey="Room_SizeResource1"></asp:Label>
           </td>
           <td>
               <asp:DropDownList ID="Room_Size_List" runat="server" meta:resourcekey="Room_Size_ListResource1">
                <asp:ListItem meta:resourcekey="ListItemResource1">1 adult</asp:ListItem>
                <asp:ListItem meta:resourcekey="ListItemResource2">2 adults</asp:ListItem>
            </asp:DropDownList>

           </td>
       </tr>
   </tbody>
</table>

after include a routine to check if an user "Usuario" is Registered at database i'm getting error message below from any navigator:

error '80020009' /novo.asp, line 31

The routine basic is

set verificar = conexao.execute ("select Usuario from empresas")
while not verificar.eof

verificar.movenext

if  Cadastrar_CodEmpresa = verificar("Usuario")   Then
              response.Redirect("index.asp?pagina=login") 



if not verificar.eof Then

verificar.movenext
    End if


 set cadastrar_cadastro = conexao.execute("insert into Empresas (Usuario,Telefone) Values ('" & Cadastrar_CodEmpresa & "' , '" & Cadastrar_Telefone & "')")



    End if  Wend

Following My full code:

 if request.Form("commentForm") = "sim" then



Cadastrar_CodEmpresa = request.Form("CodEmpresa")
Cadastrar_Segmento = request.Form("Segmento")
Cadastrar_Endereco = request.Form("Endereco")
Cadastrar_Bairro = request.Form("Bairro")
Cadastrar_Cidade = request.Form("Cidade")
Cadastrar_CEP = request.Form("CEP")
Cadastrar_Pais = request.Form("Pais")
Cadastrar_Contato = request.Form("Contato")
Cadastrar_Telefone = request.Form("Telefone")
Cadastrar_Email = request.Form("email")


set verificar = conexao.execute ("select Usuario from empresas")
while not verificar.eof

verificar.movenext

if  Cadastrar_CodEmpresa = verificar("Usuario")   Then
              response.Redirect("index.asp?pagina=login") 



if not verificar.eof Then

verificar.movenext
    End if


 set cadastrar_cadastro = conexao.execute("insert into Empresas (Usuario,Telefone) Values ('" & Cadastrar_CodEmpresa & "' , '" & Cadastrar_Telefone & "')")



    End if  Wend

This question morphed from a previous one here.

It seems that the problem is actually this failure to recognize checkboxes as such - whether there's really a problem with updating the database once this conundrum is solved remains to be seen.

So here's the code:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim connStr As String = "SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=entenhausen;PWD=pondscum"
    Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Exploding' WHERE Unit = @Unit And MemberNo = @MemberNo AND Custno = @CustNo"

    Dim coName As String
    Dim argVals(2) As String
    Dim _Unit As String
    Dim _MemberNo As String
    Dim _CustNo As String
    Dim curCheckboxIDVal As String
    Label2.Text="label 2 text from button1_click"
    LabelDebug.Text="label debug text from button1_click"

    For Each cntrl As Control In Me.Controls
            Label2.Text="label 2 text from foreach"
            If TypeOf cntrl Is CheckBox Then
                Label2.Text="label 2 text from is checkbox"
                If DirectCast(cntrl, CheckBox).Checked = True Then
                    Label2.Text="label 2 text from checked"
                    curCheckboxIDVal = CStr(DirectCast(cntrl, CheckBox).ID)
                    coName = GetLabelTextForID(curCheckboxIDVal)
                    argVals = GetArgValsForCompanyName(coName)
                    _Unit = argVals(0)
                    _MemberNo = argVals(1)
                    _CustNo = argVals(2)
                Label2.Text=_Unit
                LabelDebug.Text=_MemberNo
                    Using conn As New SqlConnection(connStr), _
                        cmd As New SqlCommand(upd8DML, conn)
                        cmd.Parameters.Add("@Unit", SqlDbType.VarChar, 50).Value = _Unit
                        cmd.Parameters.Add("@MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
                        cmd.Parameters.Add("@CustNo", SqlDbType.VarChar, 50).Value = _CustNo
                        conn.Open
                        cmd.ExecuteScalar()
                    End Using
                End If
            End If
        Next
End Sub

I am updating Label2.Text to see how far the code gets - and it only gets to the "foreach" - this is the last value of Label2.Text: "label 2 text from foreach"

So this line:

If TypeOf cntrl Is CheckBox Then

...fails to equate to true.

Yet, not only do I have many dynamically-created Checkboxes on the form when the button is clicked, there is also one that I dropped there at design-time. NONE of these checkboxes are seen as checkboxes, obviously.

Why not? Why is the type of the checkbox control not evaluating to CheckBox?

NOTE: When I prepend "the whole shebang" like so:

System.Web.UI.WebControls.CheckBox

...it makes no difference; in fact, it grays out the "System.Web.UI.WebControls." portion.

UPDATE

That idea from Perry Mason inspirited me to try this:

For Each cntrl As Control In Me.Controls
    Label2.Text = "label 2 text from foreach"
    LabelDebug.Text = LabelDebug.Text+" "+cntrl.GetType().ToString+" "
    If TypeOf cntrl Is System.Web.UI.WebControls.CheckBox Then

...which shows this:

enter image description here

So a Checkbox (among other things) is seen simply as a "LiteralControl" apparently. Seems rather vague...

UPDATE 2

In response to Bradley Uffner, here is the code that adds the checkboxes:

For i As Integer = 0 To categoryDT.Rows.Count - 1
    ' for testing, limit count
    If i > 3 Then 'There are thousands...just grab enough to fit on the page without scrolling for now...
        Exit For
    End If
    Dim coName = New Label()
    ' Must prepend with something, as controls cannot share the same ID
    coName.ID = "lbl" + i.ToString()
    coName.Text = categoryDT.Rows(i)(0).ToString()
    formCustCatMaint.Controls.Add(coName)

    Dim chk = New CheckBox()
    chk.ID = "ckbx" + i.ToString()
    chk.Checked = True
    formCustCatMaint.Controls.Add(chk)

    ' Add a "line break" after each checkbox
    Dim l = New Label()
    l.Text = "<br>"
    formCustCatMaint.Controls.Add(l)
Next

UPDATE 3

On third thought, it may be that it is not that the Checkboxes are being seen as System.Web.UI.LiteralControl, but that they are not being seen at all - not even the one dropped on the form/page at design time.

Why do I propose this radical idea? Because only the following controls are enumerated:

LiteralControl
HtmlHead
LiteralControl
HtmlForm
LiteralControl

Yet thre are many more controls than that, even discounting the dynamically-generated Checkboxes. There is no button, unless it is one of the "LiteralControl"s.

Something is rotten as all get-out here.

UPDATE 4

Changing Page_Load to Page_Init (at Perry Mason's suggestion) did make a difference; I get this:

Multiple controls with the same ID 'lbl0' were found. Trace requires that controls have unique IDs. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Web.HttpException: Multiple controls with the same ID 'lbl0' were found. Trace requires that controls have unique IDs.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

UPDATE 5

I really don't get why there are multiple "lbl0"s because the i in the loop should automatically increment, right? This is the code:

For i As Integer = 0 To categoryDT.Rows.Count - 1
    ' for testing, limit count
    If i > 3 Then 'There are thousands...just grab enough a few for now...
        Exit For
    End If
    Dim coName = New Label()
    ' Must prepend with something, as controls cannot share the same ID
    coName.ID = "lbl" + i.ToString()
    coName.Text = categoryDT.Rows(i)(0).ToString()
    formCustCatMaint.Controls.Add(coName)

    Dim chk = New CheckBox()
    chk.ID = "ckbx" + i.ToString()
    chk.Checked = True
    formCustCatMaint.Controls.Add(chk)

    ' Add a "line break" after each checkbox
    Dim l = New Label()
    l.Text = "<br>"
    formCustCatMaint.Controls.Add(l)
Next

...and i is obviously incrementing because otherwise the "If i > 3" would never be true, which it is, because the number of Label/CheckBox pairs are indeed curtailed.

Could it be that Page_Init is called multiple times, and the second time it tries to add a second lbl0, and then the above occurs?

UPDATE 6

That must indeed be true (that Page_Init) is reached multiple times, because the following code prevented the err from occurring:

Dim PageAlreadyInitted As Boolean = False

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If PageAlreadyInitted = True Then Exit Sub
    PageAlreadyInitted = True

...but it makes no difference as far as Checkboxes being found in the loop through the controls - I still get only LiteralControls, no Buttons, Checkboxes, etc.

We have some ASP.NET web application which used in 2 ways:

  • enterprise solution (msi-like installer)
  • cloud solution (use same installer)

Currently we use home-grown installer, but consider if we can replace it with something more convenient and suitable for CI/CD development cycle.

What technologies/products can be used? Currently I think about webdeploy, but not sure how it can be applied for enterprise setup...

I am working on a graph that I have to show as drill down with dynamic data. First I tried to load static drill down data and graph worked perfectly fine. But I need to load data dynamically, for that, I am using JSON calls to fetch data from Server with given "point name" (selected point of pie chart). When it loads the first time, it is working fine to show series data in a pie chart. But when I am clicking on pie chart objects, I receive a server call and gets data as JSON response but it's not updating pie chart. Also, I need to keep navigation, so I can go forward or backwards at any point.

I am using below code but it is not working as multiple level pie chart, does anybody has done same, who can review below code and suggest how can I do this.

        var options = {
            chart: {
                renderTo: 'chart_divDrillDownGraph',
                type: 'pie',
                events: {
                    drilldown: function (e) { 
                        if (!e.seriesOptions) {
                            if (!e.seriesOptions) {
                                $.get("http://localhost:54877/GetStats.aspx?key=drilldownGraph&selectedPointName=" + e.point.name, function (data) {
                                    this.addSeriesAsDrilldown(e.point, data); 
                                });
                            }
                        }
                    }
                }
            },
            title: {
                text: 'Report of March 2017'
            },
            subtitle: {
                text: 'Click the slices to view details.'
            },
            plotOptions: {
                series: {
                    dataLabels: {
                        enabled: true,
                        format: '{point.name}: {point.y:.1f}<span style="unicode-bidi: bidi-override;">%</span>'
                    }
                }
            },

            tooltip: {
                headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
                pointFormat: '<span style="color:{point.color}">{point.name}</span><span style="unicode-bidi: bidi-override;">: <b>{point.y:.2f}%</b> of total</span><br/>'
            },
            series: [{}],

            drilldown: {
            }
        };

        if (this.name != "undefined" && this.name != null)
            selectedlevelName = this.name;
        else
            selectedlevelName = "";

        var url =  "http://localhost:54877/GetStats.aspx" + "?key=drilldownGraph&selectedPointName=" + selectedlevelName;
        $.getJSON(url,  function(data) {
            options.series[0].data = data; 
            var chart = new Highcharts.Chart(options);
        });

But I am getting below error

TypeError: this.addSeriesAsDrilldown is not a function

I am using following JS of high charts http://code.highcharts.com/highcharts.js http://code.highcharts.com/modules/drilldown.js

enter image description here

We have a pretty big projet splitted into an MVC part and an old ASP.NET part, we are willing to migrate ASP.NET pages to MVC but this is not the point. We are using bundles on the MVC part of the project but we just register separate files on the ASP part, the problem is pretty confusing since MVC pages are OK on all navigators, ASP pages are OK on all navigators EXCEPT Internet Explorer and its clearly not a problem of compatibility since the same CSS is rendering OK on MVC pages.

I tried to remove the "only" and such potentiel fixes from my media queries definitions but stills not resolving the problem.

Here is are captures, for the same DOM element :

MVC page

ASP.NET Page

Does any one have any idea or suggestion or even has ever faced the same problem ?

Note 1: The css file core.css on MVC is the file produced by the bundle which includes between others ark.css on ASP. Note 2: All style sheets are correctly registered and rendered on the ASP project.

Any hint is welcomed, Thanks in advance.

I have Gridview full with data and I need when some of rows are checked i can be able to press the button and change the data accordingly, I can do it when all rows are checked but i can't find a way to connect my queries with id of one or many rows.

    protected void UsedForButton_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            var chk = row.FindControl("InStockCbx") as CheckBox;
            if (chk.Checked)
            {
                //using (WorkDBEntities db = new WorkDBEntities())
                //{

                //    WorkTable table = new WorkTable();
                //    table.InStock = 0;

                //    db.WorkTables.Add(table);
                //    db.SaveChanges();    
                //}
                string query = "UPDATE WorkTable SET InStock = 0 WHERE Id = " ???;

                SqlCommand comm = new SqlCommand(query, conn);
                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
            }

When setting up an application with TradeKing, you get:

  • A Consumer Key
  • A Consumer Secret
  • A Oauth Token
  • A Oauth Token Secret

For accessing TradeKing's API, that's apparently all you need to build personal applications. However, I can't find a way to build the correct Oauth headers in C#/.NET.

The examples seem fairly simple, like this Node.js sample. The Oauth library for Node.js takes care of generating the appropriate headers. There are similar samples for a few other languages, but they all seem to have libraries to build the proper header from the provided keys and tokens. I can't find a library to do this with C#/.NET.

I'm trying to wrap my head around what's going on in this SO question that builds the headers from scratch, but it's pretty advanced. I'm poking around in the ASP.NET Security repo, because they must be handling this somewhere. But I can't quite find what I'm looking for.

How can I generate an Oauth header from these keys with .NET?

I want to pass a model to the controller after klicking on a row.

this is my code which doesn't work.

<table class="table">
<tr>
    <th>
        <p>Sender</p>
    </th>
    <th>
        <p>Subject</p>
    </th>
    <th>
        <p>Received</p>
    </th>
    <th>
        <p>HasAttachment</p>
    </th>
    <th></th>
</tr>

@foreach (var item in Model.Inbox) {
<tr class="mail-row" onclick="location.href = '@(Html.ActionLink   ("", "MailViewer", "Profile", new { mail = item }, null ))'">
    <td>
        @Html.DisplayFor(modelItem => item.Sender)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Subject)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Received)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.HasAttachment)
    </td>
</tr>
}

</table>

I tried to use Url.Action but i got only the Object Type in the url and not the actual object.

I try to send this object:

public class Mail
{
    public string Sender { get; set; }
    public string Subject { get; set; }
    public DateTime Received { get; set; }
    public bool HasAttachment { get; set; }

    public string content { get; set; }
}