Subscribe: Custom Server Controls
http://forums.asp.net/rss.aspx?ForumID=19
Added By: Feedage Forager Feedage Grade B rated
Language: English
Tags:
byval  cmd parameters  cmd  code  data  end  net mvc  net  new  object  parameters addwithvalue  public  return  string  var 
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: Custom Server Controls

All Forums



All Forums



Last Build Date: Sat, 18 Nov 2017 15:24:09 -0800

 



EF Core database

2017-11-04T19:25:06.197-07:00

hat's how I try to follow this article / guide on how to add the database to Azure DB.

That's the way I have a database at Azure, but Right now, my Dbset will not get hold of "User".

https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db

How can it be?

namespace WebsiteSiteNameDB2018Core.Models.DB
{
    public class SiteNameDB: DbContext
    {

        public SiteNameDB(DbContextOptions<SiteNameDB> options) : base(options)
        { }

        public DbSet<User> User { get; set; }

    }
}

Error with: "DbSet" say Property type

Appsettings.json.

{
  "ConnectionStrings": {
    "MvcMovieContext": "Server=tcp:Text.database.windows.net,1433;Initial Catalog=xxxxxxxxxxxx;Persist Security Info=False;User ID=xxxxxxxxxxxxxx;Password=xxxxxxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

How can I fix it?




PWA - WebP image file referenced in results in 404 not found

2017-11-18T23:08:24.003-08:00

PWA - Progressive Web App

I was made aware that some of my pictures are too big a file size and negatively impact initial page load. Recommendation was to use WebP format.

That reduces file size significantly 50-70%.

Unfortunately, I get a 404 not found in the console.  The file is there.

Not understanding why this fails.




Website Crash

2017-11-18T04:24:49.993-08:00

What is the best practice for handling website crashes during a CRUD operation. Thanks !




Will webassembly replace SPA?

2017-11-13T09:20:04.097-08:00

I saw a demo where webassembly was used for generating webpages with c# on the fly in the browser, just like if it was an wpf app. Now what will the implications be on SPA frameworks? I've started to learn React and I like it, but i've heard people talk that javascript will not be relevant when webassembly gets production ready in a couple of years. Is this really true?  I still think using SPA give a better user experience in many ways compared to the instant physics of that demo example.




Async Await and AsyncCallback Difference

2017-11-18T19:24:04.613-08:00

Hi All,

I am new to asynchronous programming. I understand Async Await and AsyncCallback (Delegates) are used to call methods asynchronously.

I would like to know the real difference between the two. Can someone help me in understanding the difference.

Thanks in advance,

Ashvin




State Server is losing sessions in between

2017-11-17T19:11:48.397-08:00

I have a .NET MVC 4.5 application. It is hosted on 2 servers and it is load balanced using a VIP. All the users access the website using the VIP.

We have used ASP.NET State Server for storing session data. 1 of the server has the app hosted and is the state server.

We have some roles specified for a user, based on which some icons are set to visible/invisible. The roles are stored in the session itself.

The problem is that the icons disappears on refresh and if I refresh it again, it loads the icons back. On frequent F5 the same happens multiple times.

Based on the research on the internet, I checked the application ID under IIS is the same (its same), same configurations are loaded on both the servers. We have session timeout set to 60 in the code itself, web.config is not updated through code and neither any other files are updated when the app runs, response.redirects are not used anywhere in the code, no logs inside my event viewer.

Sometimes, the users are logged out too. Hence, I determined that this is a session issue.

Can anyone please help me here ?




Make a json request to website that need authentication

2017-11-17T17:14:44.467-08:00

HI I'm newbie on c# and i'm trying to get a json string from a website that needs authentication with email and password. string url = "https://portalqa.***.com/test.json"; -> Json String string loginUrl = "https://portalqa.***.com/users/sign_in"; -> Login Form I'm doing this, but when i try make the second request i got ever 401 error(HTTP Error 401 - Unauthorized: Access is denied due to invalid credentials). Someone can help me? HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); requestSec.CookieContainer = Login(); HttpWebResponse resp = (HttpWebResponse)requestSec.GetResponse();    protected static CookieContainer Login()         {             string userName = "***********";             string password = "***********";             ASCIIEncoding encoding = new ASCIIEncoding();             string postData = "user[email]=" + userName + "&user[password]=" + password;             byte[] postDataBytes = encoding.GetBytes(postData);             HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://portalqa.***.com/users/sign_in");             httpWebRequest.Method = "POST";             httpWebRequest.ContentType = "application/x-www-form-urlencoded";             httpWebRequest.ContentLength = postDataBytes.Length;             httpWebRequest.AllowAutoRedirect = false;             using (var stream = httpWebRequest.GetRequestStream())             {                 stream.Write(postDataBytes, 0, postDataBytes.Length);                 stream.Close();             }             var cookieContainer = new CookieContainer();             using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())             {                 using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))                 {                     foreach (Cookie cookie in httpWebResponse.Cookies)                     {    [...]



show progress bar while downloading pdf from FTP on web application

2017-11-17T06:38:19.603-08:00

I am trying to download files from FTP. The requirement is to show a progress bar with Downloadingsize/Filesize and percentage. I am able to display progress bar on Windows Form Application but On web application hosted on Local IIS server, i am getting a problem.  I am using following code to download files from FTP on my generic handler .ashx file public void ProcessRequest(HttpContext context) { DownLoadFilesFromFTp("FileName.pdf", "MyFolder"); } public bool DownLoadFilesFromFTp(string fileName,string ftpFolder) { //Create FTP Request. try { string Ftp_Host = System.Configuration.ConfigurationManager.AppSettings["Ftp_Host"]; string Ftp_UserName = System.Configuration.ConfigurationManager.AppSettings["Ftp_UserName"]; string Password = System.Configuration.ConfigurationManager.AppSettings["Password"]; string downloadpath= System.Configuration.ConfigurationManager.AppSettings["downloadpath"]; //Fetch the Response and read it into a MemoryStream object. string ftpurl = Ftp_Host + ftpFolder + "/" + fileName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpurl)); reqFTP.Credentials = new NetworkCredential(Ftp_UserName, Password); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Proxy = null; reqFTP.UsePassive = false; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream responseStream = response.GetResponseStream(); FileStream writeStream = null; //if (fileName.Substring(fileName.Length - 3, 3) == "pdf" || fileName.Substring(fileName.Length - 3, 3) == "PDF") //{ writeStream = new FileStream(downloadpath + fileName, FileMode.Create); //} int Length = 2048; // 2048; Byte[] buffer = new Byte[Length]; int bytesRead = responseStream.Read(buffer, 0, Length); while (bytesRead > 0) { writeStream.Write(buffer, 0, bytesRead); bytesRead = responseStream.Read(buffer, 0, Length); } responseStream.Close(); writeStream.Close(); response.Close(); return true; } catch (WebException wEx) { return false; } catch (Exception ex) { return false; } } My Jquery and HTML Code Part
  [HttpPost]
        public JsonResult DeptList()
        {
            try
            {
                  var data1 =  Models.TBL_Department.GetAlldept();
                  return Json(new { Result = "OK", Records = data1 });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }







What is the difference between razor page and asp.net mvc template

2017-11-17T09:44:51.277-08:00

i have few question about razor page.

1) why Microsoft develop this razor page technology when asp.net mvc is there.

2) what is the advantage of  razor page template for which people use it instead of asp.net mvc.

3) what is the difference between razor page and asp.net mvc?

4) razor page has action, model folder etc very similar like asp.net mvc then where the difference lies?

please answer in details point wise. 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 [...]



how to use SQL Sever sys views to get table meta info. for another owner

2017-11-18T17:26:12.107-08:00

The below code connects as db1 and gets its own table meta data fine, but I need to get table meta data owned by another database called db2.  

SELECT   a.name table_name

,b.name column_name

,c.name data_type 

FROM sys.objects a

,sys.columns b

,sys.types   c

WHERE a.name = 'Table_1'

AND a.object_id = b.object_id

AND b.system_type_id = c.system_type_id

AND c.name in ('text','varchar','char' ,'ntext','nvarchar','nchar') 

AND a.type_desc in ('VIEW','USER_TABLE')

How do I get this info for Table_1 that is owned by another database without coding it in the use statement?  Thanks




New Editor Problem

2017-11-17T01:03:34-08:00

Is it true this forum has new editor update?

First time i post with new editor five minutes ago, there is problem when inserting code sample (Chrome Browser)

After click OK button in code editor, the code is blocked, i cant move the cursor below the code block

Can you make extra line under the code block just inserted, then move the cursor to the line?




My Partial View is not rendering inside the parent view after an Ajax call

2017-11-18T16:50:50.383-08:00

Hi:

I spent several days trying to figure it out why when I try refresh my partial view from an ajax call, the partial view is rendered without the layout.

My partial view is very basic, a textbox with a submit button.  When you click the button,a javascript function is called to invoke an action method via ajax.

The action returns a ActionResult using the return PartialView("_myView", model)

Then on the javascript I am replacing the content of the div with the resulting html from the ajax call as follows:

$('#dv#').html(data)

Then if you fill the textbox again and click the submit again, the partial view losses the layout.

When I inspect the data, it looks fine.

Any idea why this happens

Thanks




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") [...]



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.