I have a web-site with asp.net web pages on the backend, and javascript with jQuery and bootstrap on the client side. I have a serious issue playing video on safari iPhone and iPad devices. Mostly videos are inside bootstrap carousel. This is the example of the video in page

<div class="resp col-xs-12 col-sm-4 col-lg-3">
        <div class="mob-xs-1x1 mob-hover-style mob-video-style">
            <div class="video- mob" data-autoplay="@IsAutoplay.ToString().ToLower()" data-poster-desktop="@Html.SomeUrl(Image)" data-poster-mobile="@Html. SomeUrl (Image)"
                 data-poster-tablet="@Html. SomeUrl (Image)" data-disable-sound="@DisableSound.ToString().ToLower()">
                <video loop="true" preload="auto " playsinline="playsinline">
                    <source src="@Html. SomeUrl(SomeUrl)"></source>
                </video>
                <div class="poster" style="background: url('@Html. SomeUrl(Image)') no-repeat center center; background-size: cover; display: none;">
                    <img src="" />
                </div>
                <div class="container-wrap">
                    <div alt="loading" class="loading" style="display: none;"></div>
                    <div class="container-flex">
                        @if (ShowButtons)
                        {
                            <div class="controls">
                                <div class="play" data-play="@Html. SomeUrl("/icons/misc/video-playerOn.svg")" data-stop="@Html.SomeUrl("/icons/misc/video-playerOff.svg")">
                                    <img src="@Html.SomeUrl("/icons/misc/video-playerOn.svg")" />
                                </div>
                                <div class="sound" data-on="@Html.SomeUrl("/icons/misc/volumeOn.svg")" data-off="@Html.SomeUrl("/icons/misc/volumeOff.svg")">
                                    <img src="@Html.SomeUrl("/icons/misc/volumeOff.svg")" />
                                </div>
                            </div>
                        }
                    </div>
                </div>
            </div>
        </div>
    </div>

In the client side we have multiple bootstrap carousels in which those videos are playing. All those carousels are in jQuery widgets like

$.widget('sm.someWidget, {

_create: function () { var widget = this; var div = this.element; widget.options.isMobile = window.matchMedia("screen and (max-width: 767px)").matches; widget.options.isTablet = window.matchMedia("screen and (min-width: 768px) and (max-width:999px)").matches; widget.options.iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; widget.options.disableSound = $(div).attr("data-disable-sound") === "true"; if (widget.options.iOS) { widget._hideSound(); } widget._setPoster(); widget._setSrc(); widget.options.isAutoplay = div.data('autoplay'); widget.options.canPlay = false; var playImage = widget._getPlayImage(); playImage.unbind('click'); playImage.bind('click', function(){ if (widget.options.isPlaying) { console.log('stop playing video'); widget._stop(); } else { widget._play(); } }); var soundImage = widget._getSoundImage(); soundImage.unbind('click'); soundImage.bind('click', function(){ widget._sound(!widget.options.soundOn); }); var videoElement = widget._getVideoElement(); videoElement.unbind('canplay'); videoElement.bind('canplay', function(e){ widget._getLoadingIcon().hide(); if (widget.options.isPlaying) { widget._getPosterElement().hide(); } widget.options.canPlay = true; }); var source = videoElement.find('source'); source.bind('error', function (e) { widget._getPlayControl().hide(); widget._getSoundControl().hide(); widget._getLoadingIcon().hide(); }); if (widget.options.isAutoplay && !widget.options.isMobile && !widget.options.isTablet && $(div).is(":visible")) { $(widget.element).show(); setTimeout(function () { widget._play(); }, 150); } else { } widget._setSoundIcon('off'); if(widget.options.disableSound) { widget._sound(true); } else { widget._sound(false); } $(widget.element).show(); widget._getVideoElementNative().addEventListener('ended', function(){ widget._stop(); } , false); if(widget.isPlaying){ widget._getVideoElementNative().addEventListener('pause', function() { widget._stop(); }, false);} widget._getVideoElementNative().addEventListener('webkitendfullscreen', function() { widget._stop(); }, false); },

My problem is that on iPhone and iPad devices video just don’t want to play. When I push play on my custom play button it changes on stop button, but that’s all, video doesn’t play. Can you help me? On the Chrome console i have an error like Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().

I'm thinking of putting an autocomplete feature for one of my input fields in Asp.net view so I tried out the example from Jquery UI and pasted the code inside one of the .cshtml views:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data = ["Boston Celtics", "Chicago Bulls", "Miami Heat", "Orlando Magic", "Atlanta Hawks"];
$("#seed_one").autocomplete({source:data});
});
</script>
</head>

<body>
<input id="seed_one" type="text" name="seed_one" />
</body>
</html>

However, when I run the application and start typing something in the input field, no suggestions show up. What's the problem with the code?

I want to export .frx report that designed by FastReport as an pdf or excel file on a c# web form application like code below:

    public static bool ShowReport(string ReportFileName, DataTable ReportData, string DBObjectName, string ExportType, out string Message, params string[] AdditionalParams)
    {
        FastReport.Utils.Config.WebMode = true;
        string ReportFile = HttpContext.Current.Server.MapPath(WPResources.ReportsRoot) + string.Format("{0}_{1}.frx", ReportFileName, ExportType.ToUpper());

        FastReport.Report objReport = new FastReport.Report();
        objReport.Load(ReportFile);
        objReport.Dictionary.Connections.Clear();
        System.Data.DataTable resultTable = new DataTable();

        objReport.RegisterData(ReportData, DBObjectName);
        objReport.GetDataSource(DBObjectName).Enabled = true;


        int ParamsCount = AdditionalParams.Length;
        if ((ParamsCount % 2) != 0)
            ParamsCount--;

        for (int i = 0; i < ParamsCount; i += 2)
        {
            var DynamicControl = (objReport.FindObject(AdditionalParams[i]) as FastReport.TextObject);
            if (DynamicControl != null)
            {
                DynamicControl.Text = AdditionalParams[i + 1];
                DynamicControl.Visible = !string.IsNullOrEmpty(AdditionalParams[i + 1]);
            }
        }

        (objReport.FindObject("rptData") as FastReport.DataBand).DataSource = objReport.GetDataSource(DBObjectName);

        string fileName = Path.GetFileNameWithoutExtension(ReportFile);
        fileName += "_" + WPFarsiDate.Today.ToString().Replace("/", ".") + "_" +
            DateTime.Now.Hour.ToString() + "." +
            DateTime.Now.Minute.ToString();

        if (ExportType == "Excel")
        {
            using (MemoryStream objMemoryStream = new MemoryStream())
            {
                objReport.Prepare(false);
                FastReport.Export.OoXML.Excel2007Export objExcel2007Export = new FastReport.Export.OoXML.Excel2007Export();
                objExcel2007Export.OpenAfterExport = false;
                objExcel2007Export.Export(objReport, objMemoryStream);
                byte[] buffer = objMemoryStream.ToArray();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("inline;filename={0}.xlsx", fileName));
                HttpContext.Current.Response.BinaryWrite(buffer);
                HttpContext.Current.Response.End();
            }
        }
        else if (ExportType == "Pdf")
        {
            using (MemoryStream objMemoryStream = new MemoryStream())
            {
                objReport.Prepare(false);
                FastReport.Export.Pdf.PDFExport objPDFExport = new FastReport.Export.Pdf.PDFExport();
                objPDFExport.EmbeddingFonts = true;
                objPDFExport.OpenAfterExport = false;
                objPDFExport.Export(objReport, objMemoryStream);
                byte[] buffer = objMemoryStream.ToArray();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.pdf", fileName));
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.BinaryWrite(buffer);
                HttpContext.Current.Response.End();

            }
        }

        Message = string.Empty;
        return true;
    }

When I export it to excel, that is no any matter and it will be done successfuly. But when I export it to pdf, I get this error:

Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

It should be noted that mentioned error just occurs in the main server and the job can be done successfully in localhost. It would be very helpful if someone could explain solution for this problem.

I have listbox in asp.net tools with 20 items. now i want to select multiple items and change order of items by mouse drag and drop in same listbox, so please suggest me any solution ..

I have a dropdown list of Tests(Diagnostic) on my view and selecting any Test from that list it should load corresponding Fee into a readonly textbox. Here is my View:

 <select name="TestId" id="TestId" style="width: 171px;">
                <option value="">Select...</option>
                @foreach (var tests in ViewBag.allTests)
                {
                    <option value="@tests.TestId">@tests.TestName</option>
                }
            </select>
 <input type="text" id="TestFee" name="TestFee" readonly="readonly" />

<script>
        $(document).ready(function() {
            $("#TestId").change(function() {
                var testid = $("#TestId").val();

                //$("#fees").empty();

                var json = { testId: testid };
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("GetFeesById", "TestRequest")',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(json),
                    success: function(data) {
                        $("#TestFee").val(data.Fee);

                    }
                });
            });
        });

And there is controller:

public class TestRequestController : Controller
{
   SaveTestManager manager=new SaveTestManager();
    public ActionResult SaveTestRequest()
    {
        ViewBag.allTests = manager.AllTestViews();
        return View();
    }

    [HttpPost]
    public JsonResult GetFeesById(int testId)
    {
        var testlist = manager.AllTestViews().Where(m => testId==m.TestId);
        return Json(testlist, JsonRequestBehavior.AllowGet);


    }
} 

I used Debugger on my JsonResult, It returns corresponding Data on change of dropdown item. But, my textbox does not get Fee which returned from controller. Is there any wrong with this code? how could be assign value on textbox? NB: I never Used Json before, I just trying with the help of some blogs and tutorials. If is there any better way please suggest this as well. Thanks

I have the following SQL Server stored procedure (declared parameters are missing but I don't have problems with that):

DECLARE @TotalRegistros AS INT = 0
DECLARE @ShowMsg AS NVARCHAR(50)    

SELECT @TotalRegistros = COUNT(*) 
FROM Tbl_Productos 
WHERE IdProducto = @Producto

IF @TotalRegistros < 3
BEGIN
    INSERT INTO Tbl_Productos (IdProducto, UnidadMedida, Precio, Activo) 
    VALUES (@Producto, @Medida, @Precio, @Activo)

    SET @ShowMsg = 'All fine!'
END
ELSE
BEGIN
    SET @ShowMsg = 'Error, you already have 3 rows.!'
END

SELECT @ShowMsg

I execute this stored procedure with this C# code:

public string ExecuteSP(Producto prod)
{
    int res = 0;
    string resp = "";

    SqlCommand cmd = new SqlCommand("SPName", conn);

    try
    {
        Open();
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@Producto", prod.Id);
        cmd.Parameters.AddWithValue("@Medida", prod.Tipo);
        cmd.Parameters.AddWithValue("@Precio", prod.Precio);
        cmd.Parameters.AddWithValue("@Activo", prod.Active);

        //CodeUpdated
        SqlParameter returnMessage = new SqlParameter("@ShowMsg", SqlDbType.NVarChar);
        returnMessage.Direction = ParameterDirection.ReturnValue;

        cmd.Parameters.Add(returnMessage);

        res = cmd.ExecuteNonQuery();

        resp = returnMessage.Value.ToString();
    }
    finally
    {
        Close();
    }

    return resp;
}

I know that I need to add something like OutputParameter and add the @ShowMsg but I don't know exactly how to do it! and the main problem is that I execute this code from a WebMethod with this code:

[WebMethod]
public string ExecuteC#Code(int id, string medida, string precio, string activo)
{
    string respuesta = "Error";

    try
    {
        Producto prod = new Producto(id, medida, precio, activo);
        //Code updated
        string resp = conn.ExecuteSP(prod);

        if (resp == "All fine!")
            respuesta = "Operacion realizada existosamente";
        else
            respuesta = "Already 3 rows with same Id..."
    }
    catch (Exception ex)
    {
        respuesta = "A ocurrido un error: " + ex.Message;
    }

    return respuesta;
}

Like I said, I have an idea of what I need to do to get the message after execute the stored procedure, but then I don't have any idea of how can I send that message to my web method. I know that I need to change the data type of my methods because I'll expect a string instead of an int.

I am using some 3rd party library that uses razor syntax to render the gui 'widget' that is used the client. It seems that this library creates some div and javascript that is then sent to the client. However, some issues are arising when trying to integrate it with Angular. If I create a traditional MVC layout, in which the call is made to the controller which then renders the view, it renders fine:

~/Views/MyEditor/MyPage.cshtml: (
@model ...
<div class="col-md-7">
   @Html.{3RDPARtY}.Editor()
   .Render()
</div>

Other html elements on this page are decorated by ng tags and meant to be used as a template with Angular's 1.x ng-route.

in the angular routing controller...

$routeProvider.when('/MyEditor' {
    templateUrl: "~/Views/MyEditor/MyPage.cshtml"
    controller: "..."
}

In this scenario, when Angular routing loads up this route, the page comes back with all the angular tags intact and functions fine as an angular application. However, we find that the 3rd party has not loaded and has not rendered the html and scripts that it is meant to generate.

If we move the @Html.3rdParty.Render() to the main Index.cshtml, that is, the one that is by default without any Angular routing, it then renders and functions fine. Only when the angular router makes the request to that cshtml file does it crap out. It there any way to get it to render the razor properly when the router makes the call for the file?

Any help would be much appreciated. Thank you.

I need to build a Org Chart that prints from a web page and I have something like 19 to 32 entities on the second level and 3-7 entities on the third level.

I tried a solution called OrgChart component from Team Improver at http://www.orgchartcomponent.com/default.aspx but they are in England and don't respond to their email. I also tried a solution from https://www.codeproject.com/Articles/18378/Organization-Chart-Generator that has the basic tree org chart. I populate from a database via Ling to SQL, No Problem.

Parent Entity - Level 1
|
|
---Child Entity Level 2
|
|
---Child Entity Level 2
|
|
---Child Entity Level 2
|
|
---Child Entity Level 2
|
|
---Child Entity Level 2
|
|
---Child Entity Level 2
          |
          |
          Child Entity Level 3
          |
          |
          Child Entity Level 3
          |
          |
          Child Entity Level 3
          |
          |
          Child Entity Level 3

This script reads QR code and stores the resulting string in txtcodigo. Upon clicking the textbox (or pressing enter), msgentrada is called. But this needs to be automatic - it should not require a label click, but instead invoke the server-side method immediately when the JavaScript function acquires the QR code.

I'm wondering if there's some way to send an event to programmatically press the label, or something. I hoped onTextchanged would work, but it doesn't.

ASP Markup:

 <asp:TextBox ID="txtCodigo" AutoPostBack="True" ReadOnly="false"     runat="server" Width="371px" OnTextChanged="msgSalida" ></asp:TextBox>

Frontend JavaScript:

 <script>
    $(document).ready(function () {
        $('#reader').html5_qrcode(function (data) {
            $('#<%=txtCodigo.ClientID%>').val(data);

        },
  . 
  . 
  .

  </script>

Backend code:

protected void msgEntrada(object sender, EventArgs e)
    {

        if (txtCodigo.Text!=null || txtCodigo.Text!="")
        {

    .
    .
    .

I know there is a lot of topic here talks about this problem , but before i posted i tried all the solution and nothing works with me !

Anyway my problem is when i try to open my admin panel path :

xoxo.com/admin

i got this error :

You do not have permission to view this directory or page.

But when i request this path :

xoxo.com/admin/create

it's working 100%

with known i did not made any change on the files or server .

anyway here is the controller content of admin page:

public class AdminController : Controller
{
    private SmartBookLibraryModel db = new SmartBookLibraryModel();

    // GET: Admin/Index
    public ActionResult Index()
    {
        var vm = new admin_DashBoard();
        vm.Book = db.Books.ToList();
        vm.Category = db.Categories.ToList();
        vm.Group = db.Groups.ToList();
        vm.AspNetUser = db.AspNetUsers.ToList();

        return View(vm);
    }

Also the Actual path for the page as the follow :

Admin/Admin/Index

But i used routing :

 public class AdminAreaRegistration : AreaRegistration 
{
    public override string AreaName 
    {
        get 
        {
            return "Admin";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context) 
    {

        context.MapRoute(
             "Admin",
             "Admin",
             new { controller = "Admin", action = "Index" }
            );


        context.MapRoute(
            "Admin_default",
            "Admin/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }

}

and my

thanks and wish someone help me with that !

This is my first ASP.NET Core project. I have a single page application where I have a search box and a button in the Index.cshtml page. If the search box text is empty then nothing is displayed else the records corresponding to pId is retrieved and displayed in the Index.cshtml page.So far this is working great.

I am looking to extend this view by aggregating the weight for a given day and display it at the top.So once the user enters a PId and submits the page, I would like to display

 pId    total_weight   create_dt

Below it, would be the current view which I already have

 pId   bIdc   rule_id   weight   create_dt

I am not sure where I should be aggregating the scores? How do I update my current view to display the aggregated values?

Controller

public IActionResult Index(string pId)
{
        var scores = from ts in _context.Scores
                          select ts;

        if (!string.IsNullOrEmpty(pId))
        {
            scores = scores.Where(p => p.p_id.Equals(pId)).OrderByDescending(p => p.create_dt);

            return View(scores.ToList());
        }
        else
            return View();
    }

Index.cshtml

<div id="p-form">
<form asp-controller="Score" asp-action="Index" method="get">
    <p>
        <b> P Id:</b> <input type="text" name="pId">
        <input type="submit" value="Submit" />
    </p>
</form>
</div>
@if (Model != null)
{
    <div id="p-scores">
        <table class="table">
            <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.p_id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.b_idc)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.rule_id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.weight)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.create_dt)
                </th>
            </tr>
        </thead>
            <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(model => item.p_id)
                    </td>
                    <td>
                        @Html.DisplayFor(model => item.b_idc)
                    </td>
                    <td>
                        @Html.DisplayFor(model => item.rule_id)
                    </td>
                    <td>
                        @Html.DisplayFor(model => item.weight)
                    </td>
                    <td>
                        @Html.DisplayFor(model => item.create_dt)
                    </td>
                </tr>
            }
        </tbody>
        </table>
    </div>
}

I'm unable to build a VB.NET site I've inherited due to a nebulous error.

Without a clue as to what might be causing it, I turned the hounds of the Czech Republic loose on it (otherwise known as Resharper). It ended up showing me 20 errors and upwards of a thousand other "issues" with the solution:

enter image description here

Okay, so I'm going after the errors first; ASP Errors first. The first one pointed to this:

<telerik:RadButton ID="ExportButtonRad" DisabledButtonCssClass="rbDownload' UseSubmitBehavior="false" EnableViewState="false" AutoPostBack="true" CommandName="ExportToExcel" Skin="Default" Visible="false" OnClientClick="document.body.style.cursor = 'wait';" ButtonType="StandardButton" HoveredCssClass="goButtonClassHov" ToolTip="Export" runat="server" Text="Export">

...and flagged the following portion:

UseSubmitBehavior="false" 

...as an "Unexpected token"; so I removed that, and re-ran the Resharper > Inspect > Code Issues in Solution.

Now there are more (not less) ASP Errors, and that same element ("ExportButtonRad") is red-flagged again for the same supposed infraction ("Unexpected token"); this time EnableViewState="false" is the culprit or scapegoat.

So I'm afraid that if I remove that, I will have 11 ASP Errors and it will finger some other property set to false as being bogus. I have suspicions this is not the real problem. Does anybody know about any "gotchas" with this that might be the underlying cause of this whack-a-moliation?

If I click "Design" the code still shows (but is not selectable). If I minimize and maximize it shows the below instead of the designer.

I have tried repairing VS2015 and safe mode, still doesn't work. I also tried setting the default "Open With" program, but nothing changed no matter what I set.

HTML files have the same problem. I have tried rebooting as well. Running Windows 10

Nothing has been changed recently.

What is causing this?

enter image description here

Auto-wire Insert to SQLDataSource

Is it possible to auto-wire a button command in a gridview to SQLDataSource Insert? What do I mean by that

Example

This is a sample SQLDataSource.

<asp:SqlDataSource ID="SQLDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" SelectCommand="[dbo].[GetUsers]" SelectCommandType="StoredProcedure" UpdateCommand="[dbo].[UpdateUser]" UpdateCommandType="StoredProcedure" DeleteCommand="[dbo].[DeleteUser]" DeleteCommandType="StoredProcedure" InsertCommand="[dbo].[CreateUser]" InsertCommandType="StoredProcedure"></asp:SqlDataSource>

All the fields in the GridView are bound using <%# Bind("<parameter name>") %>. I use link buttons Edit, Update and Delete to perform the respective operations. I do not have to code a thing! I use the same parameter names for all the Stored Procedures.

The Insert Command

Unlike other commands, the only way I seem to be able to use Insert is if I create an event handler to call SQLDataSource1.Insert(). Is there a way to auto-wire the Insert similar to other commands?

Note: I did not even have to configure the parameter names manually for the other commands in the SQLDataSource definition.

How can i hide grid-view columns when exporting to excel file using ClosedXML i tried to hide grid-view columns by using below code but it didn't work.

any suggestions ?

Code

gridsales.Columns[0].Visible = false;
gridsales.Columns[1].Visible = false;
gridsales.Columns[2].Visible = false;
gridsales.Columns[3].Visible = false; 
using (ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook())
{
    //Loop through the GridView pages.
    for (int i = 0; i < gridsales.PageCount; i++)
    {
        DataTable dt = new DataTable("Daily Sales Report");
        foreach (TableCell cell in gridsales.HeaderRow.Cells)
        {
            dt.Columns.Add(cell.Text);
        }
        foreach (GridViewRow row in gridsales.Rows)
        {
            dt.Rows.Add();
            for (int j = 0; j < row.Cells.Count; j++)
            {
                dt.Rows[dt.Rows.Count - 1][j] = row.Cells[j].Text;
            }
        }
        wb.Worksheets.Add(dt);
    }
    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=DailySalesReport.xlsx");
    using (MemoryStream MyMemoryStream = new MemoryStream())
    {
        wb.SaveAs(MyMemoryStream);
        MyMemoryStream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.End();
    }
}

I currently create a wizard and its steps programmatically and I am trying to show the default side bar with its links to each step on the top instead of the side. Is this possible?

Wizard wiz = new Wizard();
//Do stuff with wizard steps

An event in my global.asax, calls a method in the class which return an integer. I would like to hold this integer in a session variable in global.asax which later I would like to use in a controller. I tried HttpContext.Current.Session.Add, but it gives "Object reference not set to an instance of object". I am not sure how to resolve this and any help is highly appreciated.

Thanks.

I'm trying to figure out the amount of HTTP requests that my application perform when using a regular for loop with a method that performs the request vs PLINQ or using the "regular" parallel for loop. So for example, lets imagine we have a method called DoRequest() which performs 1 http request at a time when called.

When using it with regular for loop:

for(int i=0; i<100;i++){
DoRequest();
}

With Parallel for loop:

Parallel.For(0,100,i=> DoRequest());

And with PLINQ:

MyList.AsParallel().WithDegreeOfParallelism(18).ForAll(i=>DoRequest());

With the regular for loop, I'm guessing that my application does 1 request at a time, the counter will move forward when the first call is done?

The question that I have here is, how many requests is my application doing in 2nd and 3rd case??

I'm shooting in dark but I'll say that with 3rd method it does 18 parallel requests at a time if I'm correct?

What is the logic behind it ?

C# with Microsoft SQL Server 2014

Hi,

Just say I have a table with both Male & Female genders (PK (Id), PersonsName, IsMale). I wish to get a random name but for both genders. Example:

Select Top 1 PersonsName 
From MyTable 
Where IsMale = '1' 
Order by NewID()

Select Top 1 PersonsName 
From MyTable 
Where IsMale = '0' 
Order by NewID()

How can I combine those statements so I return 2 records (1 male and 1 female name) from the one SQL statement?

I have seen on here in the past that someone just seperated the two statements in the same SQL query, like so:

Select Top 1 PersonsName 
From MyTable 
Where IsMale = '1' 
Order by NewID();

Select Top 1 PersonsName 
From MyTable 
Where IsMale = '0' 
Order by NewID()

Each time the code is run I wish to have two totally random names and not two records of the same gender so I can populate the dataset and bind it to a ListView control. I just need the SQL statement

Any help would be great

The Markup:

<div class="form-group">
<table class="table table-bordered" id="tblSavingColl" style="width: 97%; margin-left:1.5%;">
                            <thead>
                                <tr>
                                    <th>Client Code</th>
                                    <th>Name</th>
                                    <th>Bal</th>
                                    <th>Due</th>
                                    <th>Received <br/>G S</th>
                                    <th>Adj Y/N</th>
                                    <th><input type="checkbox" id="selectall" /> All</th>
                                    <th>GS Adj Amt</th>
                                    <th>Bal</th>
                                    <th>Due</th>
                                    <th>Received SS</th>
                                    <th>Adj Y/N</th>
                                    <th><input type="checkbox" id="selectAll2" /> All</th>
                                    <th>SS Adj Amt</th>
                                    <th>Bal</th>
                                    <th>Deposit</th>
                                    <th>Withdraw</th>
                                    <th>Rcvd</th>
                                    <th>Prst</th>
                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
</div>
<div class="form-group">
  <input type="button" class="button" id="btnSaveSaving" value="Save Saving Details" />
</div>

Javascript to load the table rows:

<script type="text/javascript">
  $(document).ready(function(){
   var savAcList = []; // to store ac infos

   $.ajax({
        type: 'GET',
        url: '@Url.Action("GetSavingCollSheet", "CollectionSheetTranscation")',
        dataType: 'json',
        data: { adDate: $('#adDate').val(), centerCode: $('#centerCode').val(), collnSheetNo: $('#collnSheetNo').val() },
        success: function (data) {
            $.each(data, function (i, dets) {
                var $row = $('<tr>' +
                    '<td>' + dets.clientNo + '</td>' +
                    '<td>' + dets.clientName + '</td>' +
                    '<td>' + dets.MSBal + '</td>' +
                    '<td>' + dets.MSDue + '</td>' +
                    '<td><input type="text" value = "' + dets.MSRec + '" class="chkBox" /></td>' +
                    '<td class="GSCol">' + msadjCheckBox + '</td>' +
                    '<td>' + msadjCode + '</td>' +
                    '<td>' + msadjAmount + '</td>' +
                    '<td>' + dets.PSBal + '</td>' +
                    '<td>' + dets.PSRec + '</td>' +
                    '<td><input type="text" value = "' + dets.PSRec + '" class="chkBox" /></td>' +
                    '<td class="SSCol">' + psadjCheckBox + '</td>' +
                    '<td>' + psadjCode + '</td>' +
                    '<td>' + psadjAmount + '</td>' +
                    '<td>' + dets.OSBal + '</td>' +
                    '<td>' + dets.OSDep + '</td>' +
                    '<td>' + dets.OSWithdraw + '</td>' +
                    '<td>' + recFlag + '</td>' +
                    '<td>' + prFlag + '</td>'
                    );
                $('#tblSavingColl > tbody').append($row);

                savAcList.push(dets.SavAcCode);

                totMSDue += Number(dets.MSRec);
                totPSDue += Number(dets.PSRec);
                totOSDep += Number(dets.OSDep);
                totOSWith += Number(dets.OSWithdraw);
                totUFDue += Number(dets.UFRec);
                psTransfer += Number(dets.PSAdjAmt);
                msTransfer += Number(dets.MSAdjAmt);
                if (dets.PresentFlag == "Y")
                    totPresent++;
            });
            var totalCollectionAmt = (totPSDue + totMSDue + totOSDep + totUFDue + 0 - (totOSWith + psTransfer + msTransfer));
            $('#txttotalpensav').val(totPSDue);
            $('#txttotaloptsav').val(totOSDep);
            $('#txttotalwithdraw').val(totOSWith);
            $('#txtpresent').val(totPresent);
            $('#txttotalmonthsav').val(totMSDue);
            $('#txttotunitfund').val(totUFDue);
            $('#txttotalcolln').val(totalCollectionAmt);
            $('#txtwelfarefundamt').val("0");
            $('#txttotpentrans').val(psTransfer);
            $('#txttotmontrans').val(msTransfer);
            $('#txttotaltransfer').val(Number(psTransfer) + Number(msTransfer));

            //alert(savAcList[0]);
        },
        error: function () {
            alert("Error");
        }
    })
  });
</script>

Now after the table is loaded, we have checkbox in 6th column and 12th column. I needed to handle the checkbox event to

  1. When the checkbox in 6th column is checked, i must load a value in the dropdown in 7th column and the value of 5th column to 8th column.
  2. Similarly, when the checkbox in 12th column is checked, i must load a value in the dropdown in 13th column and the value of 11th column to 12th column.

For the value to load in dropdown i previously created an array called "savAcList" in jquery and fetched the value while loading table with data.

I am unable to find the checkbox column for doing the above. What I did is shown below, but the javascript below does a little bit of mis-steps like i need to check the first checkbox that is in 6th column then only the 12th column checkbox. And I when unchecking the checkbox, if the 12th column checkbox is unchecked it clears the value for 6th column and vice versa.

The javascript I did is :

 var meroIndex = 0; var meroRow = 999;

$('#tblSavingColl').on('click', 'tr', function (e) {

    //var myIndex = $('#tblSavingColl tr input[type="checkbox"]:checked').parent().index();   // get the index of the checkbox i.e. colIndex

    var myIndex = $('#tblSavingColl tr input[type="checkbox"]').parent().index();           // get the index of the checkbox i.e. colIndex
    var myRow = $(this).index();                                                            // get the rowIndex

    if (meroIndex == myIndex && myRow == meroRow)
        myIndex = 12;

    if (meroIndex == myIndex && myRow != meroRow)
        myIndex = myIndex;

    //alert("My Index " + myIndex + "   MeroIndex = " + meroIndex);

    meroIndex = myIndex;
    meroRow = myRow;

    var myTIndex = myIndex + 2;
    var mySelIndex = myIndex + 1;

    var ReceivedGS = $(this).find('td:nth-child(' + (Number(myIndex) - 1) + ') input').val();
    var myAcCode = savAcList[Number(myRow)];

    if ($(e.target).is('input[type=checkbox]')) {

        var option = document.createElement("option");            // create a new element option [this here is created for a new option to be appended in the dropdownlist]
        option.value = myAcCode;                                  // associate the option element with value attribute
        option.text = myAcCode;                                   // associate the option element with text attribute

        if ($(e.target).is(':checked')) // if the checkbox is checked
        {

            $(this).find('td:nth-child(' + myTIndex + ') input').val(ReceivedGS);                      // sets the textbox to the value in "ReceivedGS" variable
            $(this).find('td:nth-child(' + mySelIndex + ') select').removeAttr("disabled");              // removes the disabled property of the dropdownlist
            $(this).find('td:nth-child(' + mySelIndex + ') select').append(option);                      // append the option variable to the dropdownlist
            $(this).find('td:nth-child(' + mySelIndex + ') select>option:eq(1)').attr('selected', true); // selects the newly created option of the dropdownlist
        }
        else    // if the checkbox is not checked
        {

            $(this).find('td:nth-child(' + myTIndex + ') input').val("0");                                             // sets the textbox value to 0
            $(this).find('td:nth-child(' + mySelIndex + ') select').find("option[value='" + myAcCode + "']").remove();   // removes the appended item from dropdownlist
            $(this).find('td:nth-child(' + mySelIndex + ') select').prop("disabled", "disabled");                        // applies the disabled property to the dropdownlist
        }
    }
});

I need the help for above.

And when I want to save the table data. I did stored all the rows and columns in an array and wanted to pass to the controller. This is all I did:

 $('#btnSaveSaving').click(function () {
    var myTableArray = [];

    $('#tblSavingColl tbody tr').each(function () {
        var arrayOfThisRow = [];

        var tableData = $(this).find('td');
        if (tableData.length > 0) {
            tableData.each(function () {
                if ($(this).find("input[type=text]").length) {
                    var myText = $(this).find("input[type=text]").val();
                    arrayOfThisRow.push(myText);
                }
                else if ($(this).find("input[type=checkbox]").length) {
                    var myText = $(this).find("input[type=checkbox]");
                    if ((myText).prop('checked') == true)
                        arrayOfThisRow.push('Y');
                    else arrayOfThisRow.push('N');
                }
                else if ($(this).find("select").length) {
                    var myText = $(this).find("select :selected").text();
                    arrayOfThisRow.push(myText);
                }
                else arrayOfThisRow.push($(this).text());
            });

            myTableArray.push(arrayOfThisRow);
        }
    });

    var params = [];

    /*for (var i = 0; i < myTableArray.length; i++) {
        var dataValue = myTableArray[i].split(',');

            params = {
                collSheetNo: $('#collnSheetNo').val(),
                clientNo: dataValue[0],
                clientCode: dataValue[0],
                clientName: dataValue[1],
                UFAcNo: dataValue[6],
                UFBal: dataValue[2],
                UFDue: dataValue[3],
                UFRec: dataValue[4],
                MSAcNo: dataValue[6],
                MSBal: "a",
                MSDue: "a",
                MSRec: "a",
                MSAdjFlag: "a",
                MSAdjACNo: "a",
                MSAdjCode: "a",
                MSAdjAmt: "a",
                PSAcNo: "a",
                PSBal: "a",
                PSDue: "a",
                PSRec: "a",
                PSAdjFlag: "a",
                PSAdjAcNo: "a",
                PSAdjCode: "a",
                PSAdjAmt: "a",
                OSAcNo: "a",
                OSBal: "a",
                OSDep: "a",
                OSWithdraw: "a",
                ReceivedFlag: "a",
                PresentFlag: "a"
            };
    }*/

    $.ajax({
        type: 'POST',
        url: '@Url.Action("SaveSavingColln", "CollectionSheetTranscation")',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ savingColln: params}), 
        success: function (result) {
            alert(result);
        },
        error: function () {
            alert("Error while saving Saving Collection Sheet");
        }
    });
});

The commented lines fills the params variable. But infact it does not execute after

  var dataValue = myTableArray[i].split(',');

So, i am having a problem while sending the data to controller as well. well i even tried the following way to pass the data to the controller.

 data: JSON.stringify({ savingColln: myTableArray}), 

I put a breakpoint on the controller to know whether or not the data is going to the controller or not. It actually reaches the controller and the length of the myTableArray but no value is fetch. My controller is as follows:

 public JsonResult SaveSavingColln(List<SavingCollectionModel> savingColln)
    {
        string result = iCollService.SavingCollnSave(savingColln);
        return Json(result, JsonRequestBehavior.AllowGet);
    }

Image

I'm developing a solution that uses ASP.NET MVC 5, C#, Razor.

Problem:

I have a view that after saving it doesn't view the content of the partial view, I only see the Textbox control for Description field.

View

@Html.HiddenFor(m=>m.Items)
@Html.Partial("~/Areas/Checks/Views/Shared/_ViewerItems.cshtml", Model.Items)

@Html.TextBoxFor(m => m.Description, new { @class = "form-control" })



@{
    var len = Request.RawUrl.Split('/').Count();
    var viewname = Request.RawUrl.Split('/')[len - 1];
    var _newprefixbuttoname = "Salva"+viewname;
    var _newprefixbuttonameProsegui = "Salva" + viewname+"Prosegui";
    //
    if (SessionManager.IsUserConnected(Xanta.ServiceLayer.BO.Ruoli.IsRole411))
    {
        <!-- saving buttons -->
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10 text-right">
                <input type="submit" name="@_newprefixbuttoname" value="Salva" class="btn btn-lg btn-info" />
                <input type="submit" name="@_newprefixbuttonameProsegui" value="Salva e prosegui" class="btn btn-lg btn-success" />
            </div>
        </div>
    }


}

-

-

P.S.: the post method used is the same used in the other views but in this case occurs this problem. Anyway I show it to you

Source

[HttpPost]
[ValidateAntiForgeryToken]
[HttpParamAction]
public ActionResult SaveData(Valutation mv)
{
    return savingDataValutation(mv);
}

private ActionResult savingDataValutation(Valutation mv, bool goon = false)
{
    if (!ModelState.IsValid)
        return View(mv);

    var responseData = manager.savingDataValutation(base.getCurrentCompany(), mv);
    if (responseData.Error)
        ModelState.AddModelError("", responseData.Message);

    if (goon)
        return RedirectToAction(nextpage);

    setSuccessMessage();
    return View(mv);
}

PartialView

@using System.Web.UI.WebControls
@model Xanta.Areas.Checks.ViewModels.ViewerVerificheViewModel
@{
    bool allrespnull = Model.Items.Count() == Model.Items.Count(x => x.RispostaValue == null);
    var dropDownBMMA = new List<ListItem> 
        { 
              new ListItem { Text = "Bassa", Value = "B" }, 
              new ListItem { Text = "Medio Bassa", Value = "MB" } ,
              new ListItem { Text = "Medio Alta", Value = "MA" } ,
              new ListItem { Text = "Alta", Value = "A" } 
        };
}
<style>
    .colrisp{
        width: 100px;
        text-align:center;
    }
    .norisp{
        color:red;
    }
</style>

<table class="table table-bordered table-hover table-striped">
    <tbody>
        @for (int i = 0; i < Model.Items.Count; i++)
        {
            if (Model.Items[i].Visible)
            {
                <tr @{ if (!allrespnull && Model.Items[i].TipoRisposta != 1 && Model.Items[i].TipoRisposta != 6 && Model.Items[i].RispostaValue == null) { <text> class="norisp" </text>         } }>
                    <td>
                        <b>&#8226;</b>
                        @*@Html.DisplayFor(m => m.Items[i].VerificaTesto)*@
                        @Html.Raw(Model.Items[i].VerificaTesto)
                        @Html.HiddenFor(m => m.Items[i].idVerifica)
                        @Html.HiddenFor(m => m.Items[i].VerificaTesto)
                    </td>
                    @if ((Model.Items[i].TipoRisposta == 2) || (Model.Items[i].TipoRisposta == 3) || (Model.Items[i].TipoRisposta == 5))
                    {
                        <td class="colrisp">
                            @Html.Label("Si")
                            @Html.RadioButtonFor(m => m.Items[i].RispostaValue, "S", new { @id = "rbSi" + i.ToString() })
                        </td>
                        <td class="colrisp">
                            @Html.Label("No")
                            @Html.RadioButtonFor(m => m.Items[i].RispostaValue, "N", new { @id = "rbNo" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 3)
                    {
                        <td class="colrisp">
                            @Html.Label("Non pert")
                            @Html.RadioButtonFor(m => m.Items[i].RispostaValue, "NP", new { @id = "rbNP" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 4)
                    {
                        <td class="colrisp">
                            @*@Html.EditorFor(m => m.Items[i].RispostaValue, "NP", new { @id = "txt" + i.ToString(), @class = "form-control" })*@
                            @Html.TextBoxFor(m => m.Items[i].RispostaValue, new { @class = "form-control", @id = "txt" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 5)
                    {
                        <td class="colrisp">
                            @Html.Label("Non valutabile")
                            @Html.RadioButtonFor(m => m.Items[i].RispostaValue, "NV", new { @id = "rbNV" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 7)
                    {
                        <td class="colrisp">
                            @Html.DropDownListFor(m => m.Items[i].RispostaValue, new SelectList(dropDownBMMA, "Value", "Text", Model.Items[i].RispostaValue), "", new { @id = "ddl7_" + i.ToString() })
                        </td>
                    }
                    @if (Model.Items[i].TipoRisposta == 8)
                    {
                        <td class="colrisp">
                            @Html.CheckBoxFor(m => m.Items[i].CheckBoxValue, new { @id = "chk8_" + i.ToString() })
                        </td>
                    }

                </tr>
                if (Model.Items[i].TipoRisposta == 6)
                {
                    <tr>
                        <td class="colrisp">
                            @Html.TextAreaFor(m => m.Items[i].RispostaValue, new { @class = "form-control", @rows = 8, placeholder = @Model.Items[i].PlaceHolder, style = "max-width:100% !important;" })
                        </td>
                    </tr>
                }

            }
        }
    </tbody>
</table>

The partialview works very well in other contexts! But I don't understand what's wrong.

Any suggestions? Thanks

(why you decrease my reputation...I'll have fear next time to write a new post! )