Subscribe: Web Forms
http://forums.asp.net/rss.aspx?ForumID=18
Added By: Feedage Forager Feedage Grade B rated
Language: English
Tags:
addwithvalue  cmd parameters  cmd  colspan  data  end  net  new  parameters addwithvalue  parameters  return  service  string 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Web Forms

All Forums



All Forums



Last Build Date: Sat, 18 Nov 2017 08:50:05 -0800

 



Error while Adding new data

2017-11-18T14:23:30.04-08:00

In my ASP.net+VB+SQL web i have this following code to add/ edit/ delete data VB Code Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Me.BindGriddoc() End IfEnd subPrivate Sub BindGriddoc() Dim constr As String = ConfigurationManager.ConnectionStrings("BaijuEP").ConnectionString Using con As New SqlConnection(constr) Using cmd As New SqlCommand("DocType_CRUD") cmd.Parameters.AddWithValue("@Action", "SELECT") Using sda As New SqlDataAdapter() cmd.CommandType = CommandType.StoredProcedure cmd.Connection = con sda.SelectCommand = cmd Using dt As New DataTable() sda.Fill(dt) GridView5.DataSource = dt GridView5.DataBind() End Using End Using End Using End Using End Sub Protected Sub OnRowEditingdoc(ByVal sender As Object, ByVal e As GridViewEditEventArgs) GridView5.EditIndex = e.NewEditIndex Me.BindGriddoc() End Sub Protected Sub Insertdoctype(ByVal sender As Object, ByVal e As System.EventArgs) Handles btndocty.Click Dim DocType As String = txtdoctype.Text Dim constr As String = ConfigurationManager.ConnectionStrings("BaijuEP").ConnectionString Using con As New SqlConnection(constr) Using cmd As New SqlCommand("DocType_CRUD") cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@Action", "INSERT") cmd.Parameters.AddWithValue("@DocType", DocType) cmd.Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() End Using End Using Me.BindGriddoc() End Sub Protected Sub OnRowUpdatingdoc(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Dim row As GridViewRow = GridView5.Rows(e.RowIndex) Dim Id As Integer = Convert.ToInt32(GridView5.DataKeys(e.RowIndex).Values(0)) Dim docType As String = TryCast(row.FindControl("txtdoctype"), TextBox).Text Dim constr As String = ConfigurationManager.ConnectionStrings("BaijuEP").ConnectionString Using con As New SqlConnection(constr) Using cmd As New SqlCommand("DocType_CRUD") cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@Action", "UPDATE") cmd.Parameters.AddWithValue("@Id", Id) cmd.Parameters.AddWithValue("@DocType", docType) cmd.Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() End Using End Using GridView5.EditIndex = -1 Me.BindGriddoc() End Sub Protected Sub OnRowCancelingdoc(ByVal sender As Object, ByVal e As EventArgs) GridView5.EditIndex = -1 Me.BindGriddoc() End Sub Protected Sub OnRowDeletingdoc(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs) Dim Id As Integer = Convert.ToInt32(GridView5.DataKeys(e.RowIndex).Values(0)) Dim constr As String = ConfigurationManager.ConnectionStrings("BaijuEP").ConnectionString Using con As New SqlConnection(constr) Using cmd As New SqlCommand("DocType_CRUD") cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@Action", "DELETE") cmd.Parameters.AddWithValue("@Id", Id) cmd.Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() End Using End Using Me[...]



Authorization with asp.net identity and web api

2017-11-01T19:57:20.32-07:00

Hi,

I've web api application which is being used by mobile client application.
I am using asp.net identity and want to use authorization based on token.
So I want
1. Generate token when user login on one mobile device and send back to it for subsequent requests
2. Validate/authorize token on every other api request
3. Invalidate token on first mobile device if same user is trying to login in app on another device, so that he can be logged in only one device at a time
4. Invalidate token if user logs out

Please tell me how to do all above 4 things, I am not using external login (facebbok/google/twitter) rather I am using simple login by username and password.

Thanks
Vinod K.




How to handle seo friendly routing in asp.net core like asp.net mvc ?

2017-11-18T12:27:14.12-08:00

I have seo friendly routing in asp.net mvc which basically ads title along with id but upon called it passes id to action but show title + id in url. Here is the code. routes.Add("ClinicDetails", new SeoFriendlyRoute("veterinary-clinics/{id}/details", new RouteValueDictionary(new { controller = "clinics", action = "details" }), new MvcRouteHandler())); public class SeoFriendlyRoute : Route { public SeoFriendlyRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler) { } public SeoFriendlyRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler, IEnumerable namespaces) : base(url, defaults, routeHandler) { DataTokens = defaults; defaults["Namespaces"] = namespaces; } public override RouteData GetRouteData(HttpContextBase httpContext) { var routeData = base.GetRouteData(httpContext); if (routeData == null) return null; if (routeData.Values.ContainsKey("id")) routeData.Values["id"] = GetIdValue(routeData.Values["id"]); return routeData; } private object GetIdValue(object id) { if (id == null) return null; var idValue = id.ToString(); var regex = new Regex(@"^[\w|\W]+-(?\d+).*$"); var match = regex.Match(idValue); return match.Success ? match.Groups["id"].Value : id; } } How i can get this same functionality in asp.net core. https://stackoverflow.com/questions/47219941/seo-friendly-routing-in-asp-net-core [...]



Import plain text data from an api to a table

2017-11-16T19:02:03.177-08:00

Hi, I am trying to import data from an api into a SQL Server table. The below code works for a text file. How do I read plain text data and write it to a table.

public class DataController : ImportController
    {
        private IList errors = new List();

        [HttpPost]
        [Route("data/import", Name = "DataImport")]
        public IHttpActionResult Post()
        {
            var content = parse(this.Request.Content);
            
            postdata(content.lines);
            if (errors.Count == 0)
                return Ok("Inserted");
            else
                return Ok(errors);
        }

        private Models.DataImportFormat parse(HttpContent content)
        {
            var stream = content.ReadAsStreamAsync().Result;

            var parser = new MultipartParser(stream);

            if (parser.Success)
            {
                var newDataImportFormat = new Models.DataImportFormat
                {
                    fileData = parser.FileContents,
                    contentType = parser.ContentType,
                    fileName = parser.Filename,
                    lines = Encoding.UTF8.GetString(parser.FileContents).Split(new string[] { Environment.NewLine, @"\r" }, StringSplitOptions.None).ToList()
                };

                return newDataImportFormat;
            }

            return new Models.DataImportFormat();
        }

       private void importdata(IList lines)

        {

            string connectionString = @"Data Source=localhost;Initial Catalog=TEST_DB;Integrated Security=True";



            var Data = from line in lines

                        let data = line.Split(',')

                        select new filedata

                        {

                            ID = data[0],
                            Type = data[1],
                            Status = data[2],
                            Description = data[3]

                        };

                

            using (SqlConnection sqldbConnection = new SqlConnection(connectionString))

            {

                        sqldbConnection.Open();                       

                            foreach (var i in Data)

                            {

                                try

                                {

                                    using (SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[testImport] ([ID], [Type], [Status], [Description]) VALUES (@ID, @Type, @Status, @Description)", sqldbConnection))

                                    {

                                        cmd.Parameters.AddWithValue("@ID", i.ID);                                      
                                        cmd.Parameters.AddWithValue("@Type", i.Type);
                                        cmd.Parameters.AddWithValue("@Status", i.Status);
                                        cmd.Parameters.AddWithValue("@Description", i.Description);

                                        cmd.ExecuteNonQuery();

                                    }

                                }

                                catch (Exception ex)

                                {

                                    Console.WriteLine(ex.Message);

                                }



                            }                     

            }

        }


    }

Thank you in advance.




how to create a controls(mostly label and text box) dynamically and read their input data in asp.net

2017-11-18T11:25:34.54-08:00

Hi Greetings to all,

I have set of Questions defined in SQL Server Database table. i want the Questions to be displayed by filtering the data in SQL Server based upon the users team or Specialty.a label has to be created for displaying the question selected from the table and a text box to take the input for the Question. is there any control or add in is there for this functionality kindly help on this. How can i achieve this functionality in asp.net. thanks in advance.




Adding JWT security conflicts with existing authentication

2017-11-16T07:15:08.76-08:00

I'm writing my first ASP.NET app (Core 2). My goal is to have an ASP.NET app, that users can log into (login page, cookies, credentials stored in SQL Database), *and* have an API using JWT authentication.

I managed to do the first bit - create a simple app which allowed users to log in.

Then I found out how to use JWT security, and made a simple (second) app using this.

But when I tred to put the JWT authentication into my existing app, I get problems. It wont start up at all. Or rather, it does, but there is no logon page - just a  blank browser page.

By process of elimination, I think I have worked out that some lines of code are conflicting with each other.

In the Startup.ConfigureServices() method, I have a new snipped of code (added for JWT):

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
            services
                .AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

                })
                .AddJwtBearer(cfg =>
                {
                    cfg.RequireHttpsMetadata = false;
                    cfg.SaveToken = true;
                    cfg.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidIssuer = Configuration["JwtIssuer"],
                        ValidAudience = Configuration["JwtIssuer"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
                        ClockSkew = TimeSpan.Zero // remove delay of token when expire
                    };
                });

Which seems to be conflicting with this existing snippet (after the new code):

            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            });

If I take out the second snippet (the existing code), the app starts up, and shows a login page, but login  attempts fail. No error - I just dont get logged in.

Whats going on here? Do these not work together?

Any help would be appreciated. Thanks.




Avoid https while download

2017-11-17T19:23:59.35-08:00

How to avoid https while downloading in asp.net

While downloading files i want to use http instead of https because app fails to download when i use 2GB files. is it possible.

Thanks




Consuming Web Service with SSL .p12 cert

2017-11-18T04:59:27.09-08:00

Hello to all I have a c# .net client that consumes a web service that uses a .p12 cert, but yesterday started to send a "Could not establish a trust relationship for the SSL/TLS secure channel" message, it had been working fine 2 years with the code:                 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); public bool AcceptAllCertifications(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)         {             return true;         }  Has something change about accepting all kind of certs? (Note: I have no problem consuming it with ApacheJmeter or Java client) I apreciate your help [...]



.asmx webservice calling a wcf webservice

2017-11-18T01:01:16.797-08:00

I just recently modified a WCF service and added two fields to the returning result set.   One of the new fields is an integer the other a string,  The WCF Service  is hosted in IIS  as a  website. when I invoke the service from a browser it works fine. 

In this solution there is  a .asxm service that is calls  the  WCF service . When I run it I get the following error

 System.ArgumentException: Encountered unexpected namespace 'http://schemas.datacontract.org/DataAccessLayer.Entities' The namespace must be empty. Parameter name: ns

I then  changed the WCF service to remove one of the new parameters  the string variable and recompiled it . it worked when called from the .asmx and .wcf service. I then changed the service to return a string rather than an integer  and  yet again failed. The old resultset from the service does have string and numeric results and it also works along with the new field when it is an integer but not a string!

My Question is there something that I need to do to link the WSDL result set to what the .asxm is expecting so it can return a json result set?

Can anyone help me understand how I could do this without needing the .asxm service I want to return a return json from my WCF Service.

This is the code in the .asmx file that is calling the WCF Service . The error occurs when it hits statement   serializer.WriteObject(ms, d);

public string GetCourseRosterDetailByRosterId(int rosterId)
    {
        Services cmService = new Services();
        VEnterpriseCourseRosterDetail[] d = cmService.GetCourseRosterDetailByRosterId(rosterId);
        if (d != null)
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(d.GetType());
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            serializer.WriteObject(ms, d);
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
        else
            return string.Empty;
    }




date picker is not working

2017-09-23T14:38:55.653-07:00

i have following code in mvc 4 and put date picker in div ,but when i click textbox of datepicker its not opening @{ ViewBag.Title = "EmployeeRosterCreate"; }

EmployeeRosterCreate

@{ //ViewBag.Title = "Employee Roster Create"; } @*@using CallCenterCRM.Models @model CallCenterCRM.Models.ViewModel.EmployeeViewModel*@

Select the mode of operation you want

@Html.RadioButton("operationmode","addmode") Add new Record @Html.RadioButton("operationmode","editmode") Modify new Record