I'm learning ASP.NET MVC 4. I'm finding documents to learn about Razor and MVC. I google and read Razor tutorial at w3schools, codeproject but I don't find full document to learn all about Razor controls and its syntax.

Can someone know where I can find it ?

Thank you

I've got a div element which I am using as a popup which does not update itself. I'll use the picture below to explain:

Popup problem

When I click on each row in the grid, the right hand side updates to show the details, part of which is a potentially lengthy Note field. The button View Note triggers a popup with the full text inside. Here, I have previously selected Donor 2000000, which displayed the correct note. However, when I select another Donor(2000002 as highlighted) the information in the popup retains the info for the first selected Donor. So, essentially it sets it once and then does not update.

The (partial) code for the main View is:

  <div class="col-md-4 col-md-push-8">
        <h4>
            Donor Details
        </h4>
        <div id="donor-details">
            <p class="muted">
                Select donor to display detailed infomation
            </p>
        </div>
    </div>
    <div class="col-md-8 col-md-pull-4">
        @Html.Action("DonorSummaryGrid") @* configure grid in a partial view *@
    </div>
</div>

<script>
    $(function () {
        pageGrids.donorSummaryGrid.onRowSelect(function (e) {
            $.post("/Donor/GetDonorDetails?donorId=" + e.row.DonorId, function (data) {
                if (data.Status <= 0) {
                    alert(data.Message);
                    return;
                }
                $("#donor-details").html(data.Content);
            });
        });
    });
</script>

The code for the partial view - which contains the details - is:

@if (!String.IsNullOrWhiteSpace(Model.CurrentNoteText)) {

    <div id="note-dialog" title="Note for Donor @Model.DonorId">
        <p>@Html.DisplayTextFor(model => model.CurrentNoteText)</p>
    </div>
    <br />
}
@Scripts.Render("~/Scripts/NoteDialogue.js")

When I debug, the value of Model.CurrentNoteText and @Model.DonorId do reflect the correct data.

NoteDialogue.js is:

$(function() {
    $("#note-dialog").dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 500
        },
        hide: {
            effect: "blind",
            duration: 200
        }
    });

    $("#opener").click(function() {
        $("#note-dialog").dialog("open");
    });
});

I hope this is clear :)

Oh, there are no errors shown in the browser, and everthing functions as expected, except for updating the info in the popup.

I have tried

<script>
    $("#note-dialog").html("@Model.CurrentNoteText");
</script>

with no success.

I have a single-tenant ASP.NET web application which is deployed on a Windows 2008R2 web server and DB is on another server.

My application uses at-least 20 3rd party DLLs, and the total size of these DLLs is around 150MB. Assuming we have 20 customer sites running in IIS, these 20+ DLLs hog a lot of memory space as they get loaded in each individual IIS process. My problems:

Very slow site load times: a fresh customer single-tenant install takes around 3-5 min to load the home page. I am assuming it takes that much time to load all these DLLs in memory space.

RAM hogging: My RAM is being used up like crazy, as we scale (get more customer installs), precious memory space will get used up for these same DLLs. These 3rd party DLLs will not change much in future (no upgrades).

So given these conditions, should I go ahead and install these assemblies in GAC? From what I read, I find developers advising me against GAC for various reasons (which I do understand), but I still feel that given my conditions, installing these assemblies in GAC will not only improve my load times significantly, but also save precious RAM.

Any inputs would be great.

Note that I have already profiled the application performance using ANTS and dotTrace, and there are no significant bottlenecks which would cause the app to load so slow during the first hit. Also note that application performance is acceptable AFTER the first hit. It loads all pages within 3 seconds, but the first hit takes 3-5 min.

I have an old asp classic VB script that was converted to run in VB .NET long ago that is a mess but I can't get approval to rewrite it yet.

In there it had a function that takes a string and attempts to handle it properly based on its content.

It was originally written as:

Public Shared Function fx(ByVal _str As String) As String
    If IsDate(_str) Then
        'Dates have to be formated just right for MySQL to accept them
        fx = DatePart("yyyy", _str) & "-" & DatePart("m", _str) & "-" & DatePart("d", _str)
    ElseIf IsNumeric(_str) Then
        'Numbers go in just fine
        fx = _str
    ElseIf Len(_str) > 0 Then
        'If it's not a date and not a number then treat it as a text field and filter it so that MySQL will take it
        _str = Trim(_str) 'First trim off any leading and trailing spaces
        _str = Replace(_str, "\", "\\") 'Change all \ to \\  
        _str = Replace(_str, "'", "''") 'Change all ' to ''         
        fx = _str
    Else
        fx = ""
    End If
End Function

My problem comes when I use pass fx the value "11.16" and it says "Oh yes, that's a date - 2015/11/16"

I tried using success = DateTime.TryParse(_str,tempDate) but it behaves the same.

What is the best way to do this if _str being passed in can be anything from a blank string to a date to a dollar amount to a street address? The obvious is to rewrite the calling code but with the legacy code that's not terribly practical. Any suggestion appreciated.

Thanks!

I received a userid and comment in uri from a user on a website. On button click I want to submit it but I want to make conditional so if the URI doesn't contains userid and password then I dont want to apply the URI analysis and allowing the user to type the userid and comment and press the button manually. I hope I explain correctly with my limited knowledge. The question first part is here

I am using ASP.NET and Entity Framework Code First approach! I changed the Role table of EF to add a Priority column and i also added a Many-Many relationship between Role table and another table called Controls ! I have page that want to assing each User Control (one or more ) Roles! so that they can only be visible by that roles. Here's the code that i used to add Many-Many relationship ! the VS gives me this error:

An exception of type 'System.NullReferenceException' occurred in TestFinal.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

i am absoulty sure that both of the Objects are not Null ! here is the code:

 ApplicationDbContext context = new ApplicationDbContext();
        context.Controls.Find(Convert.ToInt32(ControlDropDown.Text)).Roles.Add(UserAndRole.findRole(RoleDropDown.Text));//(ApplicationRole)context.Roles.Find(RoleDropDown.Text));
        var role = UserAndRole.findRole(RoleDropDown.Text);
      //  context.myRole.Find(RoleDropDown.Text).controls.Add(context.Controls.Find(Convert.ToInt32(ControlDropDown.Text)));
       // context.Roles.Find
       // role.controls.Add(context.Controls.Find(Convert.ToInt32(ControlDropDown.Text)));
        Contorl control = context.Controls.Find(Convert.ToInt32(ControlDropDown.Text));
        context.Roles.Find(RoleDropDown.Text).controls.Add(control);
        context.SaveChanges();

The Error appears in 9th Line !

NOTE

Since it is the first item that i am adding a Many-Many relationship both controls and Roles collections are NUll !

I need to add functionality to an existing form in ASP.NET. I would like to fire a Javascript function after the existing validations have cleared and the form is submitted and change as little of the existing code as possible.

My question:
Is there a success callback with HTML.BeginForm()?
I am trying to replicate the functionality from this SO answer which uses Ajax.BeginForm().

My constraints:
All of the validation and rendering is already in place, so I would like to do this with HTML.BeginForm() instead of Ajax.BeginForm() at the view level without messing with the controller at all, if possible.

Existing form:

 @using (Html.BeginForm("SignUp", "Location", FormMethod.Post))
    {
        <div class="clearfix">
            <input type="hidden" name="Member.Page" value="@(ViewBag.PageType)" />
            <input id="inputMemberType" type="hidden" name="Member.Type" value="@(Enumeration.Subscription.Global)" />
            @Html.TextBoxFor(model => model.Member.Email, new { id = "textEmail", @class = "left", placeholder =  (LanguageManager.GetText(LanguageConst.SIGNUP_PH_EMAIL)) })
            <input id="buttonSignUp" type="submit" class="left" value="@(LanguageManager.GetText(LanguageConst.SIGNUP_BTN_SIGNUP))" />
            <div class="left">
                @Html.ValidationMessageFor(model => model.Member.Email, string.Empty, new { @class = "container-error", style = "color:white;" })
            </div>
        </div>
    }

I am rather unfamiliar with ASP.NET, so any help is appreciated.

Related:
BeginForm Documentation

Right now, I have a web API that receives emails via a POST to a URL of the web API.

The controller setup is basically: mypage/api/email. The email comes in fine.

However, there is a problem: it comes in packed inside a form framework. I need to get the email into its raw form to parse it as an email from OpenPop. Is there an easy way to convert the email from the FormDataCollection format to a raw email? Or a way to convert it to OpenPop (or MailMessage)? I feel like there must be.

The language is C#. It is an ASP.NET web API.

how to solve Failed to load resource: the server responded with a status of 503 (Service Unavailable) while running an web application on localhost

I have:

    List<string> dates1 = new List<string>();
    List<string> values1 = new List<string>();

    List<string> dates2 = new List<string>();
    List<string> values2 = new List<string>();

That will accept my data ranges from a datasource. Dates1 and Values1 have 128 values in each list.

The dates1 data looks like this {"5/29/2015 11:02",....,"5/30/2015 11:02",....,"5/31/2015 11:02",....,"6/1/2015 11:02",....,"6/2/2015 11:02",....,"6/3/2015 11:02"} with the in between data points being different times within that day for a total 128 values.

The dates2 data looks like this {"5/29/2015 9:05","5/30/2015 9:05","5/31/2015 9:05","6/1/2015 9:05","6/2/2015 9:05","6/3/2015 9:05"} with 7 total values.

The two graphs separately look correct and like this: Both Graphs

The problem is getting both graphs on the same chart correctly.

If I create 2 series on the chart I will get this: firstTry

I have seen some advice to use Chart1.AlignDataPointsByAxisLabel(); and this is what I get: secondTry

The two graph should be spread out evenly over each other but the x-axis for the 2nd series is being disrupted for some reason. Is this even possible to do? I would greatly appreciate any help you can spare.

Here is the c# code if interested:

    List<string> dates = new List<string>();
    List<string> values = new List<string>();

    List<string> dates2 = new List<string>();
    List<string> values2 = new List<string>();

//*****SQL connection and code that populates the Lists is here*****


    Chart1.Series.Add(new Series());
    Chart1.Series[0].Points.DataBindXY(dates, values);

    Chart1.Series[0].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.StepLine;
    Chart1.Series[0].Color = Color.Red;
    Chart1.Series[0].BorderWidth = 1;
    Chart1.Series[0].ToolTip = "#VALY, #VALX";

    //BIND THE DATA TO THE CHART
    Chart1.Series.Add(new Series());
    Chart1.Series[1].Points.DataBindXY(dates2, values2);


    Chart1.Series[1].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.StepLine;
    Chart1.Series[1].Color = Color.Green;
    Chart1.Series[1].BorderWidth = 2;
    Chart1.Series[1].ToolTip = "#VALY, #VALX";

    //SET THE IMAGE OUTPUT TYPE TO BE JPEG
    Chart1.ImageType = System.Web.UI.DataVisualization.Charting.ChartImageType.Jpeg;

    //ADD A PLACE HOLDER CHART AREA TO THE CHART
    Chart1.ChartAreas.Add(new ChartArea());
    Chart1.AlignDataPointsByAxisLabel();  // THIS IS THE COMBINING OF AXES
    Chart1.ChartAreas[0].Area3DStyle.Enable3D = false;
    Chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.FromArgb(50, 200, 200, 200);
    Chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.FromArgb(50, 200, 200, 200);

    //ADD A PLACE HOLDER LEGEND TO THE CHART
    //SHOW THE LEGEND
    Chart1.Legends.Add(new Legend());
    Chart1.Legends[0].Enabled = true;

I am creating an asp.net web application that uses the linkedin api. It requests for access from user and posts to LinkedIn on their behalf. But the problem is that whenever the user logs out of the application and logs in later,the Linkedin api gives error "unauthorized" and the user has to grant access again to the app. I have my api key and secret and am passing that with tokenmanager along with the user's accesstoken. I am storing the accesstoken as well as accesstokensecret in database. I read somewhere that the problem occurs because linkedin requires both the accesstoken and accesstokensecret for authentication. If that is the case, then how should i pass these values for authentication? Kindly help. Thanks.

I have some legacy code I've inherited and am trying to figure out whether or not this code is causing a connection to stay open to my database. I'm not too familiar with ADO.net but from what I can see this should be causing a problem.

I have a function to get a data reader:

Public Shared Function ExecuteDataReader(ByRef ObjSqlCmd As SqlCommand, ByVal CSTRING As String) As IDataReader
    Try
        Dim cn As New SqlConnection(CSTRING)
        cn.Open()
        ObjSqlCmd.Connection = cn
        Return ObjSqlCmd.ExecuteReader(CommandBehavior.CloseConnection)
    Catch ex As Exception
        If ObjSqlCmd.Connection.State = ConnectionState.Open Then ObjSqlCmd.Connection.Close()
        Return Nothing
    End Try
End Function

And then code using this to read:

Dim cmd As New SqlCommand
'set up command
Dim idr As IDataReader = ExecuteDataReader(cmd, "database")

    If idr Is Nothing Then
        If cmd.Connection.State = ConnectionState.Open Then cmd.Connection.Close()
        Return arrResult
    End If

    While idr.Read
        'read
    End While

    If cmd.Connection.State = ConnectionState.Open Then cmd.Connection.Close()

I can see it closing the connection at the end (assuming nothing goes wrong and an exception is thrown) but from MSDN they say you should always clsoe the data reader. Does that get closed when the connection is closed?

Also from what I understand, the code

 ObjSqlCmd.ExecuteReader(CommandBehavior.CloseConnection)

Will not close the connection unless the data reader is closed. Can someone explain what is happening here and if everything might be closing correctly? I know the best practice is to use "using" and then try/catch/finally to close the reader, the the original developers did not seem to follow these practices.

Say I have got 10 button/Links in aspx page. I need to maintain a session variable on only ONE button click and for all other 9 click/action I need to change the value in session variable. How can I get this in a best way, instead of writing in those 9 click actions. Please suggest

I created an MVC3 project in Visual Studio 2013. The view engine is razor.First I write jquery.ajax in @section Scripts {} in view(cshtml) it works fine. But I seperate script in .js file and debugging I get error : (debugging IIS Express)

IIS 8.0 Detailed Error - 404.0 - Not Found ... More Information: This error means that the file or directory does not exist on the server. Create the file or directory and try the request again.
..

My jquery function(archive.js) :

jQuery.AjaxGetProjects = function (dropdownId, detailDropDownId, authorized) {

var projectId = $(dropdownId).val();
if (projectId != null && projectId != '') {
    var url =
    $.ajax({
        type: "POST",
        url: '@Url.Action("GetProjects", "Archive")',
        data: {
            'projectId': projectId,
            'authorized': authorized
        },
        success: function (departman) {
            var length = 0;
            $(detailDropDownId).empty();
            $.each(departman, function (index, proje) {
                length = length + 1;
                $(detailDropDownId).append($('<option/>', {
                    value: proje.Value,
                    text: proje.Text,
                    selected: proje.Selected
                }));
            });
            if (length == 2) {
                $(detailDropDownId).trigger('change');
            }

        },
        error: function (xhr, ajaxOptions, thrownError) {
            // bu kısımda eğer ajax işlemi başarısız ise
            // hata mesajı verebiliriz.
            alert(xhr.responseText);
        }
    });
}

}

Controller :

public class ArchiveController : BaseController
{
   ...
   public ActionResult GetProjects(int projectId, bool authorized)
    {

        IArchive arch = WcfServiceHandler.GetDmsService<IArchive>();

        List<Poco> list = arch.GetProjects(UserManager.GetUserInfo(), projectId);
        var t = MvcHelper.GetDropDownList<Poco>(list, "NAME", "ID", "");
        return Json(t, JsonRequestBehavior.AllowGet);
    }

I tried this but not work (I got a new error: resource cannot be found ):

  <system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

please help..

I'm trying to communicate with my ASP.net web service through another C# program. But there's an Internal Server Error returned to me in client, though the web service is working via web browser (returning a JSON properly). Any advice on how to make it work?

My Web Service Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace WebApplication2
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class WebService : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void Callme(string x)
        {
            string[] Response = new string[3];
            Response[0] = x;
            Response[1] = "this";
            Response[2] = "Workd!";
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            this.Context.Response.ContentType = "application/json; charset=utf-8";
            this.Context.Response.Write(serializer.Serialize(Response));
        }
    }
}

My Client Code:

 public partial class Form1 : Form
    {
        private string URL = "http://localhost:49532/WebService.asmx/Callme";
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
            string json = "{\"ReqType\":\"0\"}";
            httpWebRequest.ContentType = "application/json; charset=utf-8";
            httpWebRequest.ContentLength = json.Length;
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {

                streamWriter.Write(json);
                streamWriter.Flush();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                label1.Text = result;
            }
        }
    }

And Here's the Error: Error Screenshot

I have a single-tenant ASP.NET web application which is deployed on a Windows 2008R2 web server and DB is on another server.

My application uses at-least 20 3rd party DLLs, and the total size of these DLLs is around 150MB. Assuming we have 20 customer sites running in IIS, these 20+ DLLs hog a lot of memory space as they get loaded in each individual IIS process. My problems:

  1. Very slow site load times: a fresh customer single-tenant install takes around 3-5 min to load the home page. I am assuming it takes that much time to load all these DLLs in memory space.

  2. RAM hogging: My RAM is being used up like crazy, as we scale (get more customer installs), precious memory space will get used up for these same DLLs. These 3rd party DLLs will not change much in future (no upgrades).

So given these conditions, should I go ahead and install these assemblies in GAC? From what I read, I find developers advising me against GAC for various reasons (which I do understand), but I still feel that given my conditions, installing these assemblies in GAC will not only improve my load times significantly, but also save precious RAM.

Any inputs would be great.

This question already has an answer here:

I am trying to re-code the following razor syntax to be workable code and am stuck:

    var ServiceIndex = @ViewBag.ServiceID ;
    var ServiceName = @ViewBag.ServiceName ;
    var ServiceNotes = @ViewBag.ServiceNotes ;

My problem is that right now the ViewBag for those 3 arrays is empty and so it pukes on the lone semicolon.

i have a problem. i have dropdown as shown below.

enter image description here

so the add button allows users to add more country dropdown. the problem is that here, i have chosen two countries. but only the first one is inserted into the database after i clicked on save button.

enter image description here

In my dropdown, id of brazil is 28. so there are supposed to be another row where user_scheme_master_id 30 chose brazil for 2nd choice as well. below is my dropdown code

<div id="jj">
    @Html.DropDownListFor(model => model.Memberc, ViewBag.lCountry as SelectList, "--select--", new { @id = "tid0" })

below is how my controller looks like for this operation

try
{
    // TODO: Add insert logic here
    List<CommonEntities> ICountry = CommonDAL.GetICountry();
    ViewBag.ICountry = new SelectList(ICountry, "ID", "Description");
    ListOfItems objListOfItemss = new ListOfItems();
    objListOfItemss = ARSharedDAL.CreateSchemeInsert(objListOfItems);
    return RedirectToAction("IndexMitiBranch");
}
catch
{
    List<CommonEntities> ISharedUI = CommonDAL.GetARSharedReference();
    ViewBag.ISharedUI = new SelectList(ISharedUI, "ID", "Description");
    List<CommonEntities> ICountry = CommonDAL.GetICountry();
    ViewBag.ICountry = new SelectList(ICountry, "ID", "Description");
    return View();
}

My stored procedure

Insert into [dbo].[APP_Specific_Scheme_Country] 
(user_scheme_master_id, country_id)
Values (@schemeid,@Country_id)

finally the link to stored procedure.

public static ListOfItems CreateSchemeCInsert(ListOfItems objListOfItems)
{
    SqlDataReader rdrDataAccess = null;
    ListOfItems objListOfItemsDetails = null;
    SqlConnection database = new SqlConnection(MyCOODataConn.MyCOOConnectionString);
    //Insert Data in DB
    database.Open();
    SqlCommand databaseCmd = new SqlCommand("SP_APP_Specific_SchemeCInsert", database);//name SP in database
    databaseCmd.CommandType = CommandType.StoredProcedure;
    databaseCmd.Parameters.Add(new SqlParameter("@User_scheme_master_id", objListOfItems.msi));
    databaseCmd.Parameters.Add(new SqlParameter("@Country_id", objListOfItems.Memberc));
    rdrDataAccess = databaseCmd.ExecuteReader();
    objListOfItemsDetails = new ListOfItems();
    return objListOfItemsDetails;

I've check declaration for stored procedure. everything is right. Why does it only insert the first value of dropdown?

ps: if the javascript for adding dropdown helps, please let me know.

edit: as requested

the method for adding dropdown and controller

enter image description here

controller

enter image description here

I am adding menu items programmatically so I can control which ones appear based on the role of the user. My problem is that every menu item I add behaves as if it has been clicked on during the load. Stripped to bare bones, here is the simplified code:

Public Class test2
Inherits System.Web.UI.Page

Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
    If Not IsPostBack Then
        CreateMenu()
    End If
End Sub
Private Sub CreateMenu()
    MainMenu.Items.Add(New MenuItem("Home", "", "/Peak.aspx"))
End Sub
End Class

The test2.aspx contains:

<form id="form1" runat="server">
    <asp:Menu ID="MainMenu" runat="server" >
        <Items>
        </Items>
    </asp:Menu>
</form>

This is all the code in Peak.aspx.vb:

Public Class Peak
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As
                System.EventArgs) Handles Me.Load
        MsgBox("This should not appear but does!!")
    End Sub

End Class

The Peak.aspx Page_Load is being loaded and the message box displayed, when test2 is set as the start up page. My real code has several menu items added and CreateMenu causes ALL the page_Loads to be being triggered with a large overhead!

Is this a bug or something I can switch off, and is there a workaround?

I've a Stored Procedure that insert some record then update it

CREATE PROCEDURE [dbo].[InsertSponsors]
@Someparameters  nvarchar(100),
@Anotherparameter int,
AS

Begin

DECLARE @ID int,

 @RowCount int

    insert into Clients (Name,Photo,PolicyID,BirthDay,
    Gender,Title,Nationality,Relationship,ClassID,HRID,Active,
    StartingDate,EndingDate,AddingDate,CreationOwner,UniqueID,PassportNo)
    values (@Name,@Photo,@PolicyID,@Birthday,@Gendar,@Title,@Nationality,@RelationShip,
    @ClassID,@HRID,@Active,@StartingDate,@EndingDate,@AddingDate,@CreationOwner,@UniqueID,@PassportNo)

    SELECT @RowCount = @@ROWCOUNT;

    Select @ID=SCOPE_IDENTITY();
    update Clients set SponsorID=@ID where ID=@ID;


End

I'm Calling this StoredProcedure from DataAdapter like below

Notice: I've tried all the commented code but with no luck

internal static int UpdateInsertAdapter(string query,DataTable dt, SqlParameter[] sqlParameters, bool SP)
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = openConnection();
            cmd.CommandText = query;
            if (SP)
            {
                cmd.CommandType = CommandType.StoredProcedure;
            }
            cmd.UpdatedRowSource = UpdateRowSource.None;
            foreach (SqlParameter parameter in sqlParameters)
            {
                cmd.Parameters.Add(parameter);
            }

            SqlDataAdapter adpt = new SqlDataAdapter();
            //adpt.AcceptChangesDuringFill = true;
            //adpt.AcceptChangesDuringUpdate = true;  
            //SqlCommandBuilder cmdb = new SqlCommandBuilder(adpt);
            //adpt.InsertCommand = cmdb.GetInsertCommand();
            adpt.InsertCommand = cmd;

            **//////Should i've select command to select the @RowCount**

            adpt.UpdateBatchSize = 10;

            int recordsInserted = adpt.Update(dt);
            return recordsInserted;
        }

Notice:

This Datatable is modified as i read it using ExcelDataReader then i've added two DataColumns to that Datatable

Questions

what can i do to bulk insert Datatable and select the inserted rows.

In this article Code Project Multiple Ways to do Multiple Inserts the author wrote a Stored Procedure just to insert can i insert then update

Errors:

1.Update requires a valid UpdateCommand when passed DataRow collection with modified rows

2.The DataAdapter.SelectCommand property needs to be initialized.

For a while now I have been implementing a RESTful API in the design of my project because in my case it is very useful for others to be able to interact with the data in a consistent format (and I find REST to be a clean way of handling requests). I am now trying to not only have my current REST API for my resources, but the ability to expose some pieces of information via a bidirectional websocket connection.

Upon searching for a good .net library to use that implements the websocket protocol, I did find out about SignalR. There was a few problems I had with it (maybe specific to my project?)

I want to be able to initialize a web socket connection through my existing REST API. (I don't know the proper practice to do this, but I figured a custom header would work fine) I would like them (the client) to be able to close the connection and get a http response back (101?) to signify its completion.

The problem I had with SignalR was:

  • that there was no clean way outside of a hub instance to get a user's connection id and map it to a external controller where the rest call made affects what piece of data gets broadcasted to the specific client (I don't want to use external memory)
  • the huge reliance on client side code. I really want to make this process as simple to the client and handle the majority of the work on the server side (which I had hoped modifying my current rest api would accomplish). The only responsibility I see of a client is to disconnect peacefully.

So now the question..

Is there a good server side websocket library for .net that implements the latest web socket protocol? The client can use any client library that adheres to the protocol. What is the best practice to incorporate both web socket connections and a restful api?