Currently the system downloads onto the server, how would I edit the ;

using (var fileStream = System.IO.File.OpenWrite(????))

To download onto the client machine instead of the server?

public EmptyResult Download(string id)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            CloudConfigurationManager.GetSetting("filestorageideagen_AzureStorageConnectionString"));

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference("documentuploader");

            DocumentUps documentUps = db.DocumentUps.Find(id);

            string fileName = id.ToString() + documentUps.RevisionId.ToString() + documentUps.Attachment.ToString();

            CloudBlockBlob blob = container.GetBlockBlobReference(fileName);


            using (var fileStream = System.IO.File.OpenWrite(????))
            {
                blob.DownloadToStream(fileStream);
            }


            return new EmptyResult();
        }

I'm trying to write a function in an MVC C# controller into which I can pass in the table name, server name, database name, username and password. This function is being called from an Ajax call, so it needs to return JSON. I'm using to using entity framework, so I'm sort of new to this - I've been trying to use SqlDataReader, and then automatically put all data return into a list of objects, which I can then return to the Ajax, but I'm not even getting close - all of the methods using SqlDataReader seem to require knowing what rows you want to select in advance, so I have no real clue what do to or try next. Has anybody got any advice on how to achieve this?

I have to check target, causing web form validation, is there any way to do this in a crossbrowser way without accessing window.event ? It's unavailable in FF.

script type="text/javascript">
    function myValidate(source, args)
    {
      var id = window.event.target.id;
      if( id == "Button1")
      alert('a');
      else if(id == "Name")
      alert('b');
    }
</script>
<form id="form1" runat="server">
<div>
    <asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="myValidate();" ErrorMessage="CustomValidator"></asp:CustomValidator>
    <asp:TextBox ID="Email" runat="server"></asp:TextBox>
    <asp:TextBox ID="Name"  runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
</div>
</form>

For now I see two ways:

  1. override entire chain of WebForm_DoPostBackWithOptions, Page_ClientValidate, ValidatorValidate, CustomValidatorEvaluateIsValid
  2. save target in window.target in custom onclick functions, but it is unreliable, because there may be tons of form submitters and window.target will not "unsave" itself

I'm very new to programming and are trying hard to learn. I've been struggling with an issue for a few hours without understanding what I'm doing wrong.

My goal is to save text (article with a lot of line breaks) to a database, and then retrieve the text and view the output as it was written, with all line breaks preserved.

The text is part of an object named KaseriInfo.

I've read some topics regarding this and tried the following:

Before saving to the Db I use the inputText.Replace("\r\n", "<br />"); After retrieving from Db I user the inputText.Replace("<br />", "\r\n");

I've been mixing with the .Replace-methods in different ways but I won't get the result I wish for.

This is my code for adding to the database using a local web service:

public bool AddKaseri(KaserierInfo kaseri)
    {
        bool successOrNot = false;
        Kaserier kaseriToBeAdded = new Kaserier();
        kaseriToBeAdded.Title = kaseri.Title;
        kaseriToBeAdded.Content = kaseri.Content.Replace("\r\n", "<br />");
        kaseriToBeAdded.About = kaseri.About;
        kaseriToBeAdded.Uploaded = DateTime.Now;

        db.Kaseriers.Add(kaseriToBeAdded);
        try
        {
            db.SaveChanges();
            successOrNot = true;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        return successOrNot;
    }

And this is the code for retrieving the data from the Db:

public KaserierInfo GetOneKaseri(int id)
    {
        var result = from row in db.Kaseriers
                     where row.Id == id
                     select row;

            KaserierInfo kaseri = new KaserierInfo();

        var kas = result.FirstOrDefault();
        if (kas != null)
        {
            kaseri.Id = kas.Id;
            kaseri.Title = kas.Title;
            kaseri.About = kas.About;
            kaseri.Content = kas.Content.Replace("<br />", "\r\n");
            kaseri.UploadedDateOnly = kas.Uploaded.ToString();
            kaseri.Uploaded = kas.Uploaded;
            kaseri.UploadedDateOnly = kaseri.Uploaded.ToLongDateString();
        }
        return kaseri;
    }

What is stored in the Db

The HTML-output won't come with line breaks for some reason. This is what is displayed:

Output on website

I would be glad to solve this so that the line breaks will be rendered correctly. Please keep in mind that my skills are low.

Best /J

I'm trying to obtain a data from a ASP.NET file who return me not all the data, but just the result acording to the data i send to him.

The web-service is working fine and i already do the necesary test to see if is working properly.

Here is the code of the method i use to get the data (who used to work just fine) but now i also use it to send a string to obtain certain specific data, and doesn't seems to work:

namespace AndroidApp.REST
{
    public static class Client
    {
        public async static Task<T> GetRequest<T>(this string url)
        {
            try
            {
                HttpClient client = new HttpClient();
                //Preparing to have something to read
                var stringContent = new StringContent("someHardCodedStringToTellTheServerToPublishTheDataTheAppWillConsume");
                var sending = await client.PostAsync(url, stringContent);

                //Reading data
                var response = await client.GetAsync(url);
                var json = await response.Content.ReadAsStringAsync();
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
            }
            catch
            {
                return default(T);
            } 
        }
    }

}

Any question, comment, request for clarification or anything than helps to obtain an answer or improve the clarity of the question would be much apreciated too

Thanks in advance

I want to create a application in which if there is Ajax call it return Partial view and if it is a page refresh it return with layout and render script. But the problem is partial view won't render sections, for that I have created a MVC helper in APP_Code as :

 @helper AddSection(Func<object, object> content)
 {
   if (IsAjaxRequest)
   {
        @content(null);
   }
   else
   {
        @section scripts {
            @content(null);
        }
   }
}

When I am calling it in my view I am getting the bellow error :

CS0103: The name 'DefineSection' does not exist in the current context
Line 71: #line hidden
Line 72: DefineSection("scripts", () => {
Line 73: 

I tried many things but this error is still there, I also searched a lot but couldn't found the solution.

Could you please take a look if you can do needful?

Thanks, Sombir

I have themes layer which is an area named theme(name of the folder) in my project. and i read my Layout from this Layer by using default view engine like what you see below:

   public class CustomViewEngine : RazorViewEngine
{

    public CustomViewEngine() : base()
    {

        AreaViewLocationFormats = new[] {
        "~/Modules/{2}/Views/{1}/{0}.cshtml",
        "~/Modules/{2}/Views/{1}/{0}.vbhtml",
        "~/Modules/{2}/Views/Shared/{0}.cshtml",
        "~/Modules/{2}/Views/Shared/{0}.vbhtml"
    };

        AreaMasterLocationFormats = new[] {

        "~/Modules/{2}/Views/{1}/{0}.cshtml",
        "~/Modules/{2}/Views/{1}/{0}.vbhtml",
        "~/Modules/{2}/Views/Shared/{0}.cshtml",
        "~/Modules/{2}/Views/Shared/{0}.vbhtml"
    };




        AreaPartialViewLocationFormats = new[] {

        "~/Modules/{2}/Views/{1}/{0}.cshtml",
        "~/Modules/{2}/Views/{1}/{0}.vbhtml",
        "~/Modules/{2}/Views/Shared/{0}.cshtml",
        "~/Modules/{2}/Views/Shared/{0}.vbhtml"
    };




        ViewLocationFormats = new[] {

        "~/Themes/Default/Views/{1}/{0}.cshtml",
        "~/Themes/Default/Views/{1}/{0}.vbhtml",
        "~/Themes/Default/Views/Shared/{0}.cshtml",
        "~/Themes/Default/Views/Shared/{0}.vbhtml"

    };




        MasterLocationFormats = new[] {

        "~/Themes/Default/Views/{1}/{0}.cshtml",
        "~/Themes/Default/Views/{1}/{0}.vbhtml",
        "~/Themes/Default/Views/Shared/{0}.cshtml",
        "~/Themes/Default/Views/Shared/{0}.vbhtml"

    };



        PartialViewLocationFormats = new[] {

        "~/Themes/Default/Views/{1}/{0}.cshtml",
        "~/Themes/Default/Views/{1}/{0}.vbhtml",
        "~/Themes/Default/Views/Shared/{0}.cshtml",
        "~/Themes/Default/Views/Shared/{0}.vbhtml"

    };
    }

      //I never knew this override methods benefit but i did it because i copied this part from another source!
    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {

        var nameSpace = controllerContext.Controller.GetType().Namespace;

        return base.CreatePartialView(controllerContext, partialPath.Replace("%1", nameSpace));

    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {

        var nameSpace = controllerContext.Controller.GetType().Namespace;

        return base.CreateView(controllerContext, viewPath.Replace("%1", nameSpace), masterPath.Replace("%1", nameSpace));

    }


    protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
    {
        var nameSpace = controllerContext.Controller.GetType().Namespace;

        return base.FileExists(controllerContext, virtualPath.Replace("%1", nameSpace));

    }

}

by this solution my project will start form _ViewStart.cshtml of theme layer. and its no problem!. my only problem is _ViewStart.cshtml of my Module Areas!i i want them to use _ViewStart.cshtml of theme layer not their own ViewStart!

because in this case i have to change _ViewStart of my All layers From this: @{Layout = "~/Views/Shared/_Layout.cshtml";} to this: @{Layout = "~/Themes/Default/Views/Shared/_Layout.cshtml";}

and for more illustrating i show you the related part of my solution in this Pic

I have a JavaScript file in which I need to generate an action link via Razor syntax. Here's my code so far.

@{
  int ID = @:cardId;
  @:row.insertCell(0).innerHTML = @Url.Action("Details", "Cards", new { Id = ID});
}

I want to nest my own text in the link. ie. <a>MyText</a> However, the Url.Action method is the only method I know of to create a link via Razor and I don't see an overload method that allows me to customize the text of the link.

How to generate ComboBox in Grid row cell with dynamic row data values in EXT.NET MVC?C?

Model format

public class JobCustomField{
        public int CustomFieldTypeId { get; set; }        
        public string CustomFieldTypeValue { get; set; }
        public string CustomFieldTypeName { get; set; } 
        public string FieldType { get; set; }
        public string DefaultValue { get; set; }
        public bool Required { get; set; }
        public List<JobCustomFieldTypePickList> JobCustomFieldTypePickList { get; set; }
}    
public class JobCustomFieldTypePickList
    {

        public string JobCustomFieldTypePickListName { get; set; }
        public int DisplayOrder { get; set; }
    }

Sample Data

List<JobCustomField> ModelData = new List<JobCustomField>(){
                                    new JobCustomField(){
                                            CustomFieldTypeId = 1,
                                            CustomFieldTypeValue ="SA",
                                            CustomFieldTypeName ="CFA",
                                            FieldType="SINGLE",
                                            DefaultValue="A",
                                            JobCustomFieldTypePickList = new List<JobCustomFieldTypePickList>(){
                                                            new JobCustomFieldTypePickList(){
                                                                JobCustomFieldTypePickListName = "AA",
                                                                DisplayOrder = 1
                                                            }  
                                                        }
                                    },
                                     new JobCustomField(){
                                            CustomFieldTypeId = 2,
                                            CustomFieldTypeValue ="SB",
                                            CustomFieldTypeName ="CFB",
                                            FieldType="MULTI",
                                            DefaultValue="B",
                                            JobCustomFieldTypePickList = new List<JobCustomFieldTypePickList>(){
                                                            new JobCustomFieldTypePickList(){
                                                                JobCustomFieldTypePickListName = "BA",
                                                                DisplayOrder = 1
                                                        },
                                                            new JobCustomFieldTypePickList(){
                                                                    JobCustomFieldTypePickListName = "BB",
                                                                    DisplayOrder = 1
                                                            },
                                                            new JobCustomFieldTypePickList(){
                                                                    JobCustomFieldTypePickListName = "BC",
                                                                    DisplayOrder = 1
                                                            }
                                                        }
                                    }
            };

ViewPage Code

@(Html.X().GridPanel().Padding(5).Title("Custom Field(s)")
       .ID("CustomFieldList")
       .EmptyText("No Custom Field(s) found")
       .AutoRender(false)
       .Layout("fit")
       .Height(530)
       .Scroll(ScrollMode.None)
       .Border(true)
       .Store(Html.X().Store().ID("CustomFieldStore")
          .Model(Html.X().Model().IDProperty("RowId")
          .Fields(
               new ModelField("FieldType") { Mapping = "FieldType" },
               new ModelField("CustomFieldTypeName") { Mapping = "CustomFieldTypeName" },
               new ModelField("CustomFieldTypeValue") { Mapping = "CustomFieldTypeValue" },               
               new ModelField("DefaultValue ") { Mapping = " DefaultValue " },
               new ModelField("Required") { Mapping = "Required" },
 new ModelField("JobCustomFieldTypePickList", ModelFieldType.Object) { IsComplex = true },
              )
          )
          .DataSource(Model)
)
    .ColumnModel(
            column =>
            {
         column.Add(
                        Html.X().Column()
                            .Text("Custom Field")
                            .DataIndex("CustomFieldTypeName")
                            .Width(150));
                column.Add(
                        Html.X().Column()
                            .Text("Field Type")
                            .DataIndex("FieldType")
                            .Width(150));
                column.Add(
                        Html.X().ComponentColumn()
                            .Editor(true)
                            .ID("CustomFieldValue")
                            .DataIndex("JobCustomFieldTypePickList")
                            .Width(150)
                            .Text("Value")
                             .Component(
                    Html.X().Container()
                      .Items(
                                  Html.X().ComboBox()
                         .ItemID("CustomFieldValueMultiDrop")
                                       .ID("CustomFieldValueMultiDrop")
                                        .Flex(1)                         
                                        .QueryMode(DataLoadMode.Local)                        
                                        .ValueField("JobCustomFieldTypePickListName")
                                        .EmptyText("(All)")
                                        .DisplayField("JobCustomFieldTypePickListName")
                                         .Store(Html.X().Store().ID("PickListValuestore")
                                             .AutoLoad(true)
                                             .Model(Html.X().Model()
                                             .IDProperty("JobCustomFieldTypePickListName")
                                             .Fields(
                                                 new ModelField("JobCustomFieldTypePickListName", ModelFieldType.String) { Mapping = "JobCustomFieldTypePickListName" }
                                  )
                             )
                })

need to display Combo box in third column and fill comboBox items JobCustomFieldTypePickList

Result

We getting combobox in grid but combobox data not filled.

I'm trying to save an html table which created from excel reader in my MVC project. This is code of uploading excel and display it in HTML table in the browser:

Upload function:

    public ActionResult Upload()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Upload(HttpPostedFileBase upload)
    {
        if (ModelState.IsValid)
        {

            if (upload != null && upload.ContentLength > 0)
            {
                // ExcelDataReader works with the binary Excel file, so it needs a FileStream
                // to get started. This is how we avoid dependencies on ACE or Interop:
                Stream stream = upload.InputStream;

                // We return the interface, so that
                IExcelDataReader reader = null;


                if (upload.FileName.EndsWith(".xls"))
                {
                    reader = ExcelReaderFactory.CreateBinaryReader(stream);
                }
                else if (upload.FileName.EndsWith(".xlsx"))
                {
                    reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }
                else
                {
                    ModelState.AddModelError("File", "This file format is not supported");
                    return View();
                }

                reader.IsFirstRowAsColumnNames = true;

                DataSet result = reader.AsDataSet();
                reader.Close();

                return View(result.Tables[0]);
            }
            else
            {
                ModelState.AddModelError("File", "Please Upload Your file");
            }
        }
        return View();
    }

And this is my View Code:

@model System.Data.DataTable
@using System.Data;

<h2>Upload File</h2>

@using (Html.BeginForm("Upload", "ImportData", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <div class="form-group">
        <input type="file" id="dataFile" name="upload" />
    </div>

    <div class="form-group">
        <input type="submit" value="Upload" class="btn btn-default" />
    </div>

    if (Model != null)
    {
        <table>
            <thead>
                <tr>
                    @foreach (DataColumn col in Model.Columns)
                    {
                        <th>@col.ColumnName</th>
                    }
                </tr>
            </thead>
            <tbody>
                @foreach (DataRow row in Model.Rows)
                {
                    <tr>
                        @foreach (DataColumn col in Model.Columns)
                        {
                            <td>@row[col.ColumnName]</td>
                        }
                    </tr>
                }
            </tbody>
        </table>
    }
}

After using the previous code the html will browsed in the view like the below image :

enter image description here

Finally, I need to save this HTNL table as a new table:

CREATE TABLE ExcelSheet_name(
   ID varchar(50),
   FirstName varchar(50),
   LastName varchar(50),
   .....
   XColumn varchar(50));

the table name depending on the excel sheet name and the column will be depending on the displayed column in the HTML table

This question already has an answer here:

On clicking a menu button, my view appears. Once the user enter the details on the page, and click submit button it should show reportsection div and display the data returned by model. view

 @model MyStoreReports.ViewModels.SalesByBrandParentVM

@{
    ViewBag.Title = "Sales by Brand Page";
}
@section Styles {
    <link href="@Url.Content("~/css/report.css")" rel="stylesheet" type="text/css" />

}

@section Scripts{
<script type="text/javascript" src="~/js/reportsales.js">

</script>
}


<div class="row" >
    <div class="col-lg-2">
        <form method="post">
            <h2>Sales by Brand</h2>

            <input asp-for="ReportSalesByBrandModel.FromDate" class="form-control" type="date"/>
            <div class="form-group">
                <label asp-for="ReportSalesByBrandModel.FromDate">FromDate</label>
                <span asp-validation-for="ReportSalesByBrandModel.FromDate" class="text-muted"></span>
            </div>

            <input asp-for="ReportSalesByBrandModel.ToDate" class="form-control"type="date"/>
            <div class="form-group">
                <label asp-for="ReportSalesByBrandModel.ToDate">ToDate</label>
                <span asp-validation-for="ReportSalesByBrandModel.ToDate" class="text-muted"></span>
            </div>

            <input asp-for="ReportSalesByBrandModel.Category" class="form-control" />

            <div class="form-group">
                <a asp-controller="App" asp-action="Index" class="btn btn-default">Cancel</a>
                <input id="submitReport" type="submit" value="Submit" class="btn btn-success" />
            </div>
        </form>
    </div>
</div>



    <div id="reportsection">
        <table>
            <tr>
                <th>ClientCode</th>
                <th>TrxAmount</th>

            </tr>
            @foreach (var item in Model.SpSalesByBrandModel)
            {
                <tr>
                    <td>@item.ClientCode</td>
                    <td>@item.TrxAmount</td>

                </tr>
            }
        </table>
    </div>

reportsales.js

(function () {
    document.getElementById("reportsection").style.display = 'block';
    document.getElementById("submitReport").addEventListener("click", myFunction);
})();

function myFunction() {
    document.getElementById("reportsection").style.display = 'none';
}

controller:

 [HttpPost]
        public IActionResult ReportSalesbyBrand(SalesByBrandParentVM model)
        {
            if(ModelState.IsValid)
            {
                fdate = model.ReportSalesByBrandModel.FromDate;
                edate = model.ReportSalesByBrandModel.ToDate;
                category = model.ReportSalesByBrandModel.Category;
                return View(_totalSalesRepository.GetSalesbyBrand());
            }

            throw new Exception("Model state not valid");
        }

It doesn't work as expected and returns NullReferenceException. The point is how to display the div section on clicking submit button.

I have this HTML code with a div whose contents I want to pass to the controller. The div basically contains some span items of the label-primary class (link). I want to be able to get the names of the labels in this div in the controller. My idea was, as soon as the submit button is clicked, get the list of items that are inside the label-container div and pass their names to the controller as the List<string> OwnerTerminals value. How do I do that?

HTML + JS code:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    ...
    <div id="register-terminal-panel" class="panel panel-default" style="max-width: 450px;">
        <div class="panel-heading" style="color:#003F8B">
            Add terminals to client
        </div>
        <div class="panel-body">
            <div id="label-container"></div>
            <div class="input-group input-group pull-right">
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                </span>
                <input id="register-terminals-search" type="text" class="form-control" placeholder="Search terminals" aria-describedby="search-addon" onkeyup="searchTerminals()">
            </div>
        </div>
        <ul id="register-terminal-list-container" class="list-group">
            @foreach (Point p in terminals)
            {
                <li id="list-item-@p.Name"><a href="javascript:void(0)" class="list-group-item" onclick="createLabel('@p.Name')">@p.Name</a></li>
            }
        </ul>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

<script>
    function closeLabel(item) {
        item.parentElement.remove();
        var listItem = '\n<li id="list-item-' + item.parentElement.id + '"><a href="javascript:void(0)" class="list-group-item" onclick="createLabel(\'' +
            item.parentElement.id + '\')">' + item.parentElement.id + '</a>';
        $('#register-terminal-list-container').append(listItem);
        sortUnorderedList("register-terminal-list-container");
    };

    function createLabel(name) {
        var label =
            '<span id="' + name + '" class="label label-primary terminal-label"><span class="glyphicon glyphicon-remove" onclick="closeLabel(this)" id="terminal-label-close-btn"></span> ' + name + '</span>\n'
        $('#label-container').append(label);
        $('#list-item-' + name).remove();
    };
</script>

Model:

public class RegisterViewModel
{
    ...
    public List<string> OwnerTerminals { get; set; }
}

In a controller I serialized form data to json and saved to database:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(IFormCollection formData)
{
    var json = JsonConvert.SerializeObject(formData);
    var doc = new Doc()
    {
        Subject = formData["subject"],
        Content = json
    };

    _context.Docs.Add(doc);
    _context.SaveChanges();

    return RedirectToAction("Edit", new { Id = doc.Id });
}

Now, I'd like to deserialize form data and reconstruct the form:

public IActionResult Edit(int id)
{
    var doc = _context.Docs
        .Where(o => o.Id == id).FirstOrDefault();

    if (doc == null)
    {
        ViewData["ErrorMessage"] = "Not found";
        return View("Error");
    }

    var formData = JsonConvert.DeserializeObject<IFormCollection>(doc.Content);
    ViewData["FormData"] = formData;

    return View(doc);
}

The above will throw an exception at deserialization:

JsonSerializationException: Cannot create and populate list type Microsoft.AspNetCore.Http.IFormCollection. Path '', line 1, position 1.

If I do not specify type, then deserialization succeeds; but I prefer it to be deserialized to IFormCollection. What is the proper way to deserialize IFormCollection?

Also, the reason I'm saving json is because, I'm dealing with 30 or so types of forms, and I do not want to create strongly typed model objects for each of them. Any advice is welcome.

Here is my problem, I have this function:

Private Function GetCalendarData(ByVal start As Date, ByVal [end] As Date) As DataTable
        Dim rfTecnico As Integer = ddlTecnicoCal.SelectedValue 'Session("idUtente")
        Dim da As New SqlDataAdapter("Select statoric.id, (case when clienti.IDCliente = 796 then richieste.descr else clienti.RagSociale end) as RagSociale, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraDalle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraDalle % 100)),'04:00') as eventstart, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraAlle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraAlle % 100)),'04:30') as eventend
        From StatoRic 
        INNER Join 
        (Richieste INNER JOIN Clienti 
        On clienti.IDCliente=Richieste.RFCliente) 
        On StatoRic.RFRic=Richieste.IDRic
        WHERE(RFStato = 11 or RFStato = 12 Or rfstato = 13 Or rfstato = 41) And Attuale=1 and StatoRic.DataAss is not null And RFTecnico=" & rfTecnico, ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString)

        Dim dt As New DataTable()
        da.Fill(dt)

        Return dt
    End Function

I use it to fill a daypilot week calendar with to-do tasks. A task can be an appointment or not (meaning: the statoric.datass value can contain the date of appointment or it can be null). OraDalle is the start time, OraAlle is the end time (if dataass not null, of course). For convention when a task is not an appointment I want to show it anyway on the scheduler with fake start-end times, so I added the ISNULL function you can see above. If no OraDalle is found it returns 4:00, if not oraAlle is found it returns 4:30.

This is ok if there's only 1 non-appointment task, but what if there are more of them? I'd like to increment 4:00 and 4:30 by half an hour for each non-appointment task found by the query (so series like 4:00-4:30 / 4:30-5:00 / 5:00-5:30 and so on), how can I do it?

My online exam application test in asp.net gets split when multiple users take the test. my 20 question test gets split into 10 10 question to each user who is taking the test simultaniously. I am using session in my appliaction here is the code please help.

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

namespace OnlineExamDesign
{
    public partial class Exam : System.Web.UI.Page
    {
        static int index = 0;
        static int selection = 0;
        static int QuestionNums = 0;
        clsExam examObj = new clsExam();
        DataSet ds; DataTable dt;

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {

                index = 0;
                selection = 0;
                string set = Session["CandidateSet"].ToString();
                ds = examObj.getQuestion(set);
                Session["Ques"] = ds;
                displayQuestion(index);
                btnPrevious.Enabled = false;
                if (Session["candidateName"] != null)
                    lblCandidateName.Text = Session["candidateName"].ToString();
                clearResultData();
            }


        }

        private void clearRadioButtons()
        {
            rbtnOption1.Checked = false;
            rbtnOption2.Checked = false;
            rbtnOption3.Checked = false;
            rbtnOption4.Checked = false;
        }

        private void clearResultData()
        {
            for (int n = 0; n < clsExam.AnsList.Length; n++)
            {
                clsExam.AnsList[n] = 0;
            }

        }

        private void saveCandidateData()
        {
            Candidate obj = new Candidate();
            obj.Fname = Session["CandidateFName"].ToString();
            obj.Lname = Session["CandidateLName"].ToString();
            obj.Contact = Session["CandidateContact"].ToString();
            obj.Domain = Session["CandidateDomain"].ToString();
            obj.Team = Session["CandidateTeam"].ToString();
            obj.Set = Session["CandidateSet"].ToString();
            obj.ExamStartTime = (DateTime)Session["strttime"];
            obj.ExamEndTime = System.DateTime.Now;
            obj.Score = examObj.score;
            obj.actionCandidateDetails("save");
            Session["Score"] = obj.Score;

        }

        private int displayQuestion(int index)
        {
            ds = (DataSet)Session["Ques"];
            dt = ds.Tables[0];
            int num = dt.Rows.Count;

            if (index <= num)
            {
                lblQuestionNum.Text = Convert.ToString((index+1));

                lblQuestion.Text = dt.Rows[index]["questions_question_nvc"].ToString();
                rbtnOption1.Text = dt.Rows[index]["questions_option1_nvc"].ToString();
                rbtnOption2.Text = dt.Rows[index]["questions_option2_nvc"].ToString();
                rbtnOption3.Text = dt.Rows[index]["questions_option3_nvc"].ToString();
                rbtnOption4.Text = dt.Rows[index]["questions_option4_nvc"].ToString();
            }
            else if (index > num - 1)
                btnNext.Enabled = false;
            else if (index <= 0)
                btnPrevious.Enabled = false;

            return num;
        }

        private void retainChoice()
        {
            if ((clsExam.AnsList[index]).Equals(1))
            {
                rbtnOption1.Checked = true;
            }
            else if ((clsExam.AnsList[index]).Equals(2))
            {
                rbtnOption2.Checked = true;
            }
            else if ((clsExam.AnsList[index]).Equals(3))
            {
                rbtnOption3.Checked = true;
            }
            else if ((clsExam.AnsList[index]).Equals(4))
            {
                rbtnOption4.Checked = true;
            }
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {

            btnPrevious.Enabled = true;
            rbtnOptionCheckedChanged(sender, e);
            examObj.storeAns(index, selection);
            selection = 0;
            clearRadioButtons();
            index++;
            int QuestionNums = displayQuestion(index);
            retainChoice();
            if (index >= QuestionNums - 1)
                btnNext.Enabled = false;
        }

        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            if (index > 0)
            {
                rbtnOptionCheckedChanged(sender, e);
                examObj.storeAns(index, selection);
                selection = 0;
                clearRadioButtons();
                index--;
                displayQuestion(index);
                retainChoice();
                btnNext.Enabled = true;
            }
            else if (index <= 0)
            {
                btnPrevious.Enabled = false;
            }
            else if (index < QuestionNums - 1)
            {
                btnNext.Enabled = true;
            }
            else
            {
                btnPrevious.Enabled = false;
                btnNext.Enabled = true;
            }
        }

        protected void btnExit_Click(object sender, EventArgs e)
        {
            int i = 0;
            examObj.storeAns(index, selection);

            ds = (DataSet)Session["Ques"];
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (dr["questions_answer_nvc"].Equals(clsExam.AnsList[i]))
                {

                    examObj.countScore();
                    i++;
                }
            }
            Response.Write(examObj.score);
            saveCandidateData();
            index = 0;
            clearResultData();
            Response.Redirect("ThankYou.aspx");

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int i = 0;
            examObj.storeAns(index, selection);

            ds = (DataSet)Session["Ques"];
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (dr["questions_answer_nvc"].Equals(clsExam.AnsList[i]))
                {

                    examObj.countScore();
                    i++;
                }
            }
            Response.Write(examObj.score);
            saveCandidateData();
            index = 0;
            clearResultData();
            Response.Redirect("ThankYou.aspx");

        }

        protected void rbtnOptionCheckedChanged(object sender, EventArgs e)
        {
            if (rbtnOption1.Checked)
                selection = 1;
            else if (rbtnOption2.Checked)
                selection = 2;
            else if (rbtnOption3.Checked)
                selection = 3;
            else if (rbtnOption4.Checked)
                selection = 4;
        }

    }
}

using ClosedXML.Excel string constr = ConfigurationManager.ConnectionStrings["GroceryDB"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Select RTRIM(Order_Code) as [Order Code],Order_Time as [Order Date],RTRIM(Productname) as [Product Name],RTRIM(OrderedProducts.Price) as [Price ($)],RTRIM(Qty) as [Qty],RTRIM(Unit) as [Unit],RTRIM(Name) as [Customer name],RTRIM(Address + ',' + City + ',' + State + ',' + PostalCode) as [Address],RTRIM(TotalAmount) as [Total Amount ($)] from [Order],OrderedProducts,Product where product.ProductID=Orderedproducts.Prod_ID and [Order].Order_Code=OrderedProducts.OrderCode and Status='Confirmed' order by Order_Time")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt, "Order");

                        Response.Clear();
                        Response.Buffer = true;
                        Response.Charset = "";
                        string FileName = "Report-" + System.DateTime.Now + ".xlsx";
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        Response.AddHeader("content-disposition", "attachment;filename= " + FileName);
                        using (MemoryStream MyMemoryStream = new MemoryStream())
                        {
                            wb.SaveAs(MyMemoryStream);
                            MyMemoryStream.WriteTo(Response.OutputStream);
                            Response.Flush();
                            Response.End();
                        }
                    }
                }

I have an ongoing C# ASP.NET MVC 5 project, we have the site running only with view and controller yet.

My boss suggested that maybe we can use a good template to start with, rather than the default template provided by VS 2015.

He suggests this : https://marketplace.visualstudio.com/items?itemName=RehanSaeed.ASPNETMVCBoilerplate

However, I can't seem to make a successful build from that project.

Will the default project template provided by VS 2015 suffice?

Or there are better project templates to start with?

Thank you!

I noticed that when I use Launch Without Debugging (Ctrl+F5 instead of F5) in VS2017, it always works. From desktop applications, I'm used to it failing to build if the application is already running because it can't overwrite the .exe file.

But in my C# ASP.NET WebApi project, when I hit Ctrl+F5, I can make changes to the code and hit Ctrl+F5 again and it will build and run. So I assume Visual Studio manages to close or kill the web application somehow so it doesn't fail to overwrite the file.

Is that how it works?

I am using phantomjs in asp.net application to convert html to PDF.

First i used this c# code to generate a html page.

using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("~/Phantomjs/" + HTMLfileName), FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(GiveBodyText);
                }
            }

then using phantom command i executed this code.

ExecuteCommand(string.Format("cd {0} & phantomjs rasterize.js  {1} {2} \"A4\"", serverPath, HTMLfileName, filename));

but the main problem is that i want PDF to be landscape oriented and by default PDFs are portrait and to change that i tried to edit following properties in rasterize.js:

page.viewportSize = { width: 1000, height: 600 };

Orientation: 'landscape'

but this is not working.

I have the following GridView and ObjectDataSource:

<asp:TemplateField>
    <ItemTemplate>
        <asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" />
    </ItemTemplate>
</asp:TemplateField>

In my TemplateField I only want to display the button if screenshotId evaluates to a non-null non-zero value.

If screenshotId is DbNull or 0 then I want to leave the cell blank.

I have tried this code behind on RowDataBound without success because in GridView I have only cell blank, also if screenshotId evaluates to a non-null non-zero value.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
            int screenshotId = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "screenshotId"));
            ImageButton btnShowImage = e.Row.FindControl("imgbtnEdit") as ImageButton;

            if (screenshotId > 0)
            {
                btnShowImage.Visible = true;
                Response.Write(screenshotId + "<br />"); //here the value are 1
            }
            else
            { 
                btnShowImage.Visible = false;
            }

    }

}

What's the best way?

I've got a piece of JavaScript on a webpage that allows a user to scan in serial numbers and then it should send those to a webmethod where a database records it and a txtfile gets made.

It doesn't matter what's in the webmethod, because the code never runs. (Even removing the entire method and just make it change a bool to true as an example returns the same error). Here is the Js:

function sendingReady() {

  saveSerialNumbers();

  var employeeNr = document.getElementById("userCode").textContent;
  var productNr = document.getElementById("productCode").textContent;
  var cnt = {
    employeeNumber: employeeNr,
    productNumber: productNr
  };
  $.ajax({
    type: "POST",
    url: "WebServices.asmx/sendingReady",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify({
      'cnt': cnt
    }),
    success: function() {
      console.log("Success sendingReady")
    },
    error: function() {}
  });
  var succes = "succes";
  localStorage.setItem("SuccesVerzenden", succes);
}

function saveSerialNumbers() {

  var scannedserials = [];
  var errorchoises = [];

  var Table = document.getElementById("SerialListContainer");
  var rowLength = Table.rows.length;

  for (i = 0; i < rowLength; i++) {
    var row = Table.rows[i];

    var serialnumber = row.childNodes[0].textContent;
    scannedserials.push(serialnumber);

    var errorChoice = row.childNodes[1].childNodes[0].value;
    errorchoises.push(errorChoice);
  }

  var cnt = {
    serialNumber: scannedserials,
    sendingErrorcode: errorchoises,
    personalNumber: document.getElementById("userCode").textContent,
    productNumber: document.getElementById("productCode").textContent
  };
  $.ajax({
    type: "POST",
    url: "WebServices.asmx/createSendingCeetisFile",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify({
      'cnt': cnt
    }),
    success: function() {
      console.log("Success saveSerialNumbers")
    },
    error: function() {}
  });

}

To top function works, I get the "success SendingReady" message in my log. But the bottom function, called by the top one, does not. I've tried everything from sending the data as 4 separate instances, to changing the options in the Ajax call, to changing the recipient webmethod. This is said webmethod:

[System.Web.Services.WebMethod]
public void createSendingCeetisFile(SendingErrors cnt)
{
//unimportant code that doesn't ever run anyway; 
}

with sendingErrors being:

public class SendingErrors
{
    public string[] serialNumber { get; set; }
    public string[] sendingErrorcode { get; set; }
    public string[] dollies { get; set; }
    public string personalNumber { get; set; }
    public string productNumber { get; set; }
}

Dollies isn't being used yet. I'm using IIS and I haven't found any way to debug the server-side; All the IIS logs show is a generic '500' with no further detail.

I'm really hoping I'm missing something obvious, but after trawling through these forums and other sites looking for an answer for slightly over a day I'm kind of losing hope.