Quantcast
Channel: CodeProject Latest postings for ASP.NET
Viewing all 3938 articles
Browse latest View live

Importing Rows Into a List

$
0
0
Hi,
The Data I Write on the Textbox is Inserted into the Table with the Insert Button

https://i.hizliresim.com/4pnb8Q.jpg[^]

When the Complete Button is Triggered, I Need to Import All Rows on the DataTable into the List I Created
How can I do this?
My Source Code is as follows

<%@PageTitle=""Language="C#"MasterPageFile="~/TemsilciIslemleri.Master"AutoEventWireup="true"CodeBehind="TemsilciSiparisIslemleri.aspx.cs"Inherits="BilgiYonetimSistemi.TemsilciSiparisIslemleri"%><asp:ContentID="Content1"ContentPlaceHolderID="ContentPlaceHolder1"runat="server"><divclass="container-fluid px-xl-5"><sectionclass="py-5"><divclass="row"><divclass="col-lg-12 mb-4"><divclass="card"><divclass="card-header"><h6class="text-uppercase mb-0">Satış Temsilci Sipariş İşlemleri</h6></div><divclass="card-body"><divstyle="overflow-x: auto;"><tableid="SatisTemsilcisiSiparisListesi"class="table table-striped card-text"><div><asp:TextBoxID="TextBox1"runat="server"CssClass="form-control"></asp:TextBox><br/><asp:TextBoxID="TextBox2"runat="server"CssClass="form-control"></asp:TextBox><br/><asp:TextBoxID="TextBox3"runat="server"CssClass="form-control"></asp:TextBox><br/><asp:ButtonID="BTNSatisIslemleri"runat="server"CssClass="btn btn-primary shadow px-5 shadow form-control-range"Text="Ekle"OnClick="BTNSatisIslemleri_Click"OnClientClick="return false"/><br/><br/></div><thead><tr><thscope="col">Name and Surname</th><thscope="col">Age</th><thscope="col">Country</th></tr></thead></table><br/><asp:ButtonID="BTNIslemTamamla"runat="server"CssClass="btn btn-primary shadow px-5 shadow form-control-range"Text="Tamamla"OnClientClick="return false"/></div></div></div></div></div></section></div><script>
        $('#ContentPlaceHolder1_BTNSatisIslemleri').click(function () {var table = $('#SatisTemsilcisiSiparisListesi').DataTable();var rowNode = table
                .row.add([$('#ContentPlaceHolder1_TextBox1').val(), $('#ContentPlaceHolder1_TextBox2').val(), $('#ContentPlaceHolder1_TextBox3').val()])
                .draw()
                .node();
            $(rowNode)
                .css('color', 'black')  
                .animate({ color: 'black' });
        });
        $(document).ready(function () {
            $('#SatisTemsilcisiSiparisListesi').DataTable({"order": [[2, "asc"]],
                dom: 'Bfrtip',
                buttons: ['copy', 'csv', 'excel', 'pdf', 'print']
            });
        });</script></asp:Content>

ASP.Net Core Identity

$
0
0
Using VS2019 with Core 3 I am attempting to secure a web project. Web API does the validation and returns a JWT token with the user authorisation details, role only. Tihs works fine as the JWT decodes with all the correct info in it.

My problem is to get that information into MS Identity (or have I got it completely wrong).

I am NOT using EntityFrameworkCore just to service the user validation.

My login partial has the following.
@if (User.Identity.IsAuthenticated)
{<form asp-controller="Account" asp-action="Logout" method="post" id="logoutForm"><ul><li><button type="submit">Log out</button></li></ul></form>
}
else
{<ul><li><a asp-page="/Login">Log in</a></li></ul>
}


The .cs code
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    CSDUtil.PWDUtil oUtil = new CSDUtil.PWDUtil();
    try
    {
        ReturnUrl = returnUrl;
        // Verification.
        if (ModelState.IsValid)
        {
            UserDetailsDB data = UserDetails;
            UserDetailsDB oUser = await dsUserDetails.AutenticateAsync(data);
            if (oUser == null)
            {
                ModelState.AddModelError(string.Empty, "Invalid user details.");
                return Page();
            }
            JwtSecurityTokenHandler oHandler = new JwtSecurityTokenHandler();
            var key = Code.MainUI.Key;
            var handler = new JwtSecurityTokenHandler();
            var jwtToken = new JwtSecurityToken(oUser.Token);
            var validations = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
            ClaimsPrincipal oPrincipal = handler.ValidateToken(oUser.Token, validations, out SecurityToken oToken);
            int i = oPrincipal.Claims.Count();
            var authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
                IsPersistent = true,
                IssuedUtc = DateTimeOffset.Now,
                RedirectUri = "/Index"
            };
            await HttpContext.SignInAsync(
                                CookieAuthenticationDefaults.AuthenticationScheme,
                                new ClaimsPrincipal(oPrincipal),
                                authProperties);
            var B = User.Identity.IsAuthenticated;///////this is always false
            return LocalRedirect(Url.GetLocalUrl(returnUrl));
        }
    }


The ClaimsPricipal populates correctly with the details of the user in identities[0] of that collection.

How do I move the user details from the ClaimsPrincipal to the User.Identity?
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP

i want show page numbers in bottom of the page like <1 2 3 4 5.......10 11 12> but it shows <1 2 3 4 5 6 to total>

$
0
0
This my aspx code<table align="center"><tr valign="top"><td><asp:DataList ID="gv1" runat="server" RepeatColumns="1" RepeatDirection="Horizontal"><HeaderTemplate>Our Tutors List</HeaderTemplate><ItemTemplate><table width="600px" border="2" align="center"><tr align="center"><td width="100%" valign="top" style="font-size: 15px"><span class="newstext_1">Name:</span> <%#DataBinder.Eval(Container.DataItem, "FirstName")%>  <%#DataBinder.Eval(Container.DataItem, "LastName")%><%--<span class="newstext_1">Mobile:</span>        <%#DataBinder.Eval(Container.DataItem, "MobileNo")%>    <span class="newstext_1">Email Id:</span>     <%#DataBinder.Eval(Container.DataItem, "EmailId")%>    --%></td></tr><tr><td><span class="newstext_1">Qualification:</span>    <%#DataBinder.Eval(Container.DataItem, "Qualification")%>            <span class="newstext_1">Experience:</span>  <%#DataBinder.Eval(Container.DataItem, "Experience")%></td></tr><tr><td><span class="newstext_1">Subjects:</span><%#DataBinder.Eval(Container.DataItem, "Subjects")%>            <%--<span class="newstext_1">Created Date:</span> <%#DataBinder.Eval(Container.DataItem, "CreatedDate")%>--%></td></tr><tr><td><span class="newstext_1">Locations:</span><%#DataBinder.Eval(Container.DataItem, "Location")%> </td></tr><tr><td><span class="newstext_1">Description:</span><%#DataBinder.Eval(Container.DataItem, "Description")%></td></tr></table><br /><br /></ItemTemplate><FooterTemplate></FooterTemplate></asp:DataList><table width="100%" border="0"><tr bgcolor=""  align="center"><td><asp:LinkButton ID="lnkbtnPrevious" runat="server" Text="<" OnClick="lnkbtnPrevious_Click"></asp:LinkButton></td><td><asp:DataList ID="dlPaging" runat="server" RepeatDirection="Horizontal" OnItemDataBound="dlPaging_ItemDataBound"
                    OnItemCommand="dlPaging_ItemCommand" OnSelectedIndexChanged="dlPaging_SelectedIndexChanged"
                    UseAccessibleHeader="True"><ItemTemplate><asp:LinkButton ID="lnkbtnPaging" runat="server" CommandArgument='<%#Eval("PageIndex")%>'
                            CommandName="lnkbtnPaging" Text='<%#Eval("PageText")%>'></asp:LinkButton>  </ItemTemplate></asp:DataList></td><td><asp:LinkButton ID="lnkbtnNext" runat="server" Text=">" OnClick="lnkbtnNext_Click"></asp:LinkButton></td></tr></table></td></tr></table>




<aspx.cs code="">
using System;
using System.Data;
using System.Web.UI.WebControls;

public partial class MathsTutors : System.Web.UI.Page
{
    PagedDataSource pds = new PagedDataSource();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    }
    private void BindData()
    {
        ClsTutorDetails tutor = new ClsTutorDetails();
        DataTable dt = tutor.GetAllTutors("Active");



        pds.DataSource = dt.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = 12;
        pds.CurrentPageIndex = CurrentPage;
        lnkbtnNext.Enabled = !pds.IsLastPage;
        lnkbtnPrevious.Enabled = !pds.IsFirstPage;

        gv1.DataSource = pds;
        gv1.DataBind();

        if (dt.Rows.Count <= 12)
        {
            dlPaging.Visible = false;
            lnkbtnNext.Visible = false;
            lnkbtnPrevious.Visible = false;
        }
        else
        {
            dlPaging.Visible = true;
            lnkbtnNext.Visible = true;
            lnkbtnPrevious.Visible = true;
        }

        doPaging();



    }

    

    #region

    private void doPaging()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");
        for (int i = 0; i < pds.PageCount; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }

        dlPaging.DataSource = dt;
        dlPaging.DataBind();
    }

    public int CurrentPage
    {

        get
        {
            if (this.ViewState["CurrentPage"] == null)
                return 0;
            else
                return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
        }

        set
        {
            this.ViewState["CurrentPage"] = value;
        }

    }
    protected void lnkbtnPrevious_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        BindData();
    }

    protected void lnkbtnNext_Click(object sender, EventArgs e)
    {
        CurrentPage += 1;
        BindData();
    }


    protected void dlPaging_SelectedIndexChanged(object sender, EventArgs e)
    {
        CurrentPage = 0;
        BindData();

    }

    protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("lnkbtnPaging"))
        {
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
            BindData();
        }
    }

    protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
        if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkbtnPage.Enabled = false;
            lnkbtnPage.Font.Bold = true;

        }
    }
    #endregion
}

video calling in asp.net

$
0
0
i want to add video calling "one to one and one to many" function on my web page using asp.net bt i dont understand how i can add this on my web site

gridview with dynamic dropdownlist control null exception

$
0
0
I have a GridView with template fields and one of the template field is a dropdownlist which is dynamically added into the gridview control. It's working properly on page load when I click the button control to the get the values from the template fields it will throw a null reference exception. Please correct my error, I am in pathetic situation. I attached the source code.

Regards

rites|Alert Moderators
asolmduasolmdu
None

0 Points

1 Post

gridview with dynamic dropdownlist control null exception
33 minutes ago|LINK|157.50.247.59

I have a GridView with template fields and one of the template field is a dropdownlist which is dynamically added into the gridview control. It's working properly on page load when I click the button control to the get the values from the template fields it will throw a null reference exception. Please correct my error, I am in pathetic situation. I attached the source code.

Regards

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
        OnRowCreated="GridView1_RowCreated"><Columns><asp:TemplateField><ItemTemplate><asp:Label ID="id" runat="server" Text='<%# Eval("RGNO") %>'></asp:Label></ItemTemplate></asp:TemplateField></Columns><Columns><asp:TemplateField><ItemTemplate><asp:Label ID="name" runat="server" Text='<%# Eval("NAME") %>'></asp:Label></ItemTemplate></asp:TemplateField></Columns><Columns><asp:TemplateField><ItemTemplate><asp:Label ID="lastname" runat="server" Text='<%# Eval("DOB") %>'></asp:Label></ItemTemplate></asp:TemplateField></Columns><Columns><asp:TemplateField><ItemTemplate><asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder></ItemTemplate></asp:TemplateField></Columns></asp:GridView>


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindGridView();
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlResult = new DropDownList();
            ddlResult.ID = "ddlResult";
            ddlResult.Items.Insert(0, new ListItem("PASS", "0"));
            ddlResult.Items.Insert(1, new ListItem("FAIL", "1"));

            PlaceHolder p = (PlaceHolder)e.Row.FindControl("PlaceHolder1");
            p.Controls.Add(ddlResult);
        }
    }

    private void BindGridView()
    {
        GridView1.DataSource = CreateDataSource();
        GridView1.DataBind();
    }

    public DataTable CreateDataSource()
    {
        DataTable dt = new DataTable();
        DataRow dr;

        dt.Columns.Add(new DataColumn("RGNO", typeof(string)));
        dt.Columns.Add(new DataColumn("NAME", typeof(string)));
        dt.Columns.Add(new DataColumn("DOB", typeof(string)));

        dr = dt.NewRow();
        dr["RGNO"] = "1001";
        dr["NAME"] = "PRAKASH";
        dr["DOB"] = "10-10-2003";
        dt.Rows.Add(dr);
        return dt;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            DropDownList dd1 = (DropDownList)row.FindControl("ddlResult");
            Response.Write(dd1.SelectedItem.Text);
        }
    }

what is major difference between blazor server app and asp.net mvc razor app?

$
0
0
what is major difference between blazor server app and asp.net mvc razor app?
=====================================================
The grass is always greener on the other side of the fence

Retrieve Session Array variable to Array variable in Class Library Project

$
0
0
Hello Friends,

I have asp.net website and have few class libraries in the same solution.

I am trying to store a database retrieved datatable (it contains only one column) into Array variable and assigning the array into Session.
This code is in my aspx.cs page.

<b>Code is aspx.cs below:</b>
DataRow[] foundAuthors = dtPermission.Select("Value = '" + Permission + "'");
if (foundAuthors.Length != 0)
{
ArrayList permlist = new ArrayList();
foreach (DataRow dr in dtPermission.Rows)
{
permlist.Add(dr["Value"].ToString());
}
SessionHandler s = new SessionHandler();
s.SetSession(permlist, "sPermList");

I have the following code in the class library. But in this code the session value i am not sure how to assign as array list in test method. currently it is showing as string and not working. Please help.

<b>Class Library Code:</b>
public class SessionHandler : IRequiresSessionState
{
public SessionHandler() { }
public object GetSession(string key)
{
object session = HttpContext.Current.Session[key];
return session;
}
public void SetSession(object data, string key)
{
HttpContext.Current.Session.Add(key, data);
}

public bool Test(string sessionKey,string perValue)
{
string ss = GetSession(sessionKey).ToString();
--Here need to assign session value to array list and compare the perValue against array list (or) if we can directly compare session stored value and return true / false
return true;
}


}

Thanks in Advance,

Priya.

Accessing Master Page Methods in Content Page and Accessing this.Master page Control from Class Library

$
0
0
Hi Friends,

I have web application along with few Class Library Projects.

I need help in implementing the following 2 points.

i) I have method written in Master Page code behind, I need to access this method from all my content pages.

ii) I need to access Master Page (like this.Master) from my another Code library project in the same Solution.

Kindly suggest on the solution.

Thanks in Advance,

Regards,
Priya.

[Solved] Retrieve Session Array variable to Array variable in Class Library Project

$
0
0
Hello Friends,

I have asp.net website and have few class libraries in the same solution.

I am trying to store a database retrieved datatable (it contains only one column) into Array variable and assigning the array into Session.
This code is in my aspx.cs page.

<b>Code is aspx.cs below:</b>
DataRow[] foundAuthors = dtPermission.Select("Value = '" + Permission + "'");
if (foundAuthors.Length != 0)
{
ArrayList permlist = new ArrayList();
foreach (DataRow dr in dtPermission.Rows)
{
permlist.Add(dr["Value"].ToString());
}
SessionHandler s = new SessionHandler();
s.SetSession(permlist, "sPermList");

I have the following code in the class library. But in this code the session value i am not sure how to assign as array list in test method. currently it is showing as string and not working. Please help.

<b>Class Library Code:</b>
public class SessionHandler : IRequiresSessionState
{
public SessionHandler() { }
public object GetSession(string key)
{
object session = HttpContext.Current.Session[key];
return session;
}
public void SetSession(object data, string key)
{
HttpContext.Current.Session.Add(key, data);
}

public bool Test(string sessionKey,string perValue)
{
string ss = GetSession(sessionKey).ToString();
--Here need to assign session value to array list and compare the perValue against array list (or) if we can directly compare session stored value and return true / false
return true;
}


}

Thanks in Advance,

Priya.

Change datatable from column to row and bind it to gridview

$
0
0
I have a datatable like this

----------------------------
STID	NAME	DOB	SBCD
----------------------------
1001	XXX	DMY	AAAA
1001	XXX	DMY	BBBB
1001	XXX	DMY	CCCC
1001	XXX	DMY	DDDD
1002	YYY	DMY	AAAA
1002	YYY	DMY	BBBB
1002	YYY	DMY	CCCC
1003	ZZZ	DMY	AAAA
1003	ZZZ	DMY	BBBB
1003	ZZZ	DMY	CCCC
1003	ZZZ	DMY	DDDD
1003	ZZZ	DMY	EEEE

I want to convert this datatable into following format and bind it to gridview.

----------------------------------------------------------------------
| STID | NAME / DOB	| 	            SUBJECTS                 |
|------|----------------|--------------------------------------------|
|1001  | XXX		|	AAAA	BBBB	CCCC	DDDD         |
|      | DMY            |	                                     |
|------|----------------|--------------------------------------------|
|1002  | YYY   		|	AAAA	BBBB	CCCC                 |
|      | DMY            |                                            |
|------|----------------|--------------------------------------------|
|1003  | ZZZ         	|	AAAA	BBBB	CCCC	DDDD	EEEE |
|      | DOB            |                                            |
|------|----------------|--------------------------------------------|

Facing Issues while reading an excel file and inserting it's rows to a my sql tabble. Working fine in local machine but giving error after deployement

$
0
0
Error:'D:\test_data\sample_bulk_upload_File.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides

code::
path = TextBox3.Text

        s1 = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" + path + ";Extended Properties=""Excel 8.0;HDR=YES;"""

        Dim OLEcon As OleDb.OleDbConnection = New OleDb.OleDbConnection(s1)

        Dim OLEcmd As New OleDb.OleDbCommand
        Dim OLEda As New OleDb.OleDbDataAdapter
        Dim OLEdt As New DataTable
        Dim sql As String
        Dim resul As Boolean
        OLEcon.Close()

        Try
            OLEcon.Open()



            With OLEcmd
                .Connection = OLEcon
                .CommandText = "Select * from [data1$]"
            End With
            OLEda.SelectCommand = OLEcmd
            OLEda.Fill(OLEdt)

            For Each r As DataRow In OLEdt.Rows

What's so bad about webforms?

$
0
0
I've been developing in ASP.Net for over 12 years and, though it was a bit of a learning curve to start, feel the webforms environment is, for most purposes, pretty good. When MVC came on the scene (first via 3rd parties such as Castle's, then through MS's own offering) everyone pretty much jumped ship declaring it the best thing since sliced bread. As I had a commitment to supporting a number of webforms applications, I didn't initially have any need to switch; and subsequently haven't found any compelling reason to do so. I've looked (briefly, admittedly) at MVC but felt it was a steep learning curve and didn't seem to offer any advantages, and have some actual disadvantages, to what I was used to.

I answered a question in Q+A today where I mentioned Webforms, and the need to decide whether to go webforms or MVC, and a subsequent comment was "I will not recommend webforms".

So I'm curious: what is it about MVC that makes it so much better than webforms? Is it simply that it's flavour of the month and commercial requirements for webforms developers has crashed? (plug: I have a requirement for a webforms maintenance developer ... message me for more details)

Is it that MVC is a lot "better", or do people feel webforms is actively "bad"?

My applications, using webforms, successfully separate business functionality from presentation issues (and indeed database/storage access from business objects). They implement multi-level inheritance, use custom controls to implement standard functionality, incorporate AJAX-based interactive features (not using Microsoft AJAX controls); and have proven to be flexible and extensible. Not yet found anything I can't do with Webforms.

SQL Parameter Collection - Not able to assign to SQLCommand

$
0
0
Hello Friends,

i have following code. I am getting Error "The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter[] objects."
in the line
cmd.Parameters.Add(HasPermissionParams).

Please help.

Thanks in Advance.

SqlCommand cmd = GetCommand(Sql_GetPermission);
SqlParameter[] HasPermissionParams = GetInsertParameters(Sql_GetPermission);
SetHasPermissionParams(HasPermissionParams, EmpID, Permission);
cmd.Parameters.Add(HasPermissionParams);


private static void SetHasPermissionParams(SqlParameter[] parms, string EmpID, string Permission)
{
parms[0].Value = EmpID;
parms[1].Value = Permission;
}

private const string Sql_GetPermission = "[sp_Permission]";


private static SqlParameter[] GetInsertParameters(string querytype)
{
SqlParameter[] parms = null;

switch (querytype)
{
case Sql_GetPermission:
parms = new SqlParameter[]
{
new SqlParameter("@EmpID", SqlDbType.VarChar),
new SqlParameter("@PermissionName", SqlDbType.VarChar)
};
break;
}
return parms;
}

ASP.net In Visual Studio 2019

$
0
0
Hey,
I want to develop a web application with ASP.net and C# in Visual Studio 2019, but I found I have to use razor pages or MVC. Unfortunately, I am not familiar with both technologies or methods, so can I develop without use them in Visual Studio 2019? Thank you so much :)

During redirection localhost is not attached and page failed to load

$
0
0
Hi Friends,

I have migrated asp.net 2.0 VS 2005 application to VS 2015 (framework 4.5).

Site loading fine. But when i click on the menus available in the page, actually it is not adding localhost in the redirection url.

for Eg:
My Home Page : http://localhost:1087/CGP/Home/Home.aspx. This page is loading fine.
In this page I have side menus and each menu "Profile" will have hyperlink like : CGP/Emp/Profile.aspx
But when I click on the menu "Profile" it is redirecting to http://CGP/Home/Home.aspx.

The term localhost is missing. I am not sure how to handle this.

Please Suggest.

Thanks and Regards

Newbie here. Why is my array list not working?

$
0
0
I am very new to ASP.net and C#, so I am trying my best, but there are stille many things that confuse me, especially because when I am looking at various examples online they give me different answers to the same solution, which just makes it even more confusing.
I made a person class, with two subclasses (driver and admin), but I can not get the ArrayList to show up when I run my Index file. I only get a parse error.

What do I need to change to make this work?

My person class
publicclass Person
 {public Person(string firstName, string lastName, int age, string email)
 {
 FirstName = firstName;
 LastName = lastName;
 Age = age;
 Email = email;
 }publicstring FirstName { get; set; }publicstring LastName { get; set; }publicint Age { get; set; }publicstring Email { get; }publicvirtualbool ChangeEmail(string email)
 {
 Email = email;returntrue;
 }publicoverridestring ToString()
 {return $"Name: {FirstName} {LastName}, Age: {Age}, E-mail: {Email}";
 }
 }


My subclasses
publicclass Driver : Person
 {privatestring v1;privatestring v2;privatestring v3;privatestring v4;privatestring v5;public Driver(string firstName, string lastName, int age, string email, int
licenceNumber)
 : base(firstName, lastName, age, email)
 {
 LicenceNumber = licenceNumber;
 }public Driver(string v1, string v2, string v3, string v4, string v5)
 {this.v1 = v1;this.v2 = v2;this.v3 = v3;this.v4 = v4;this.v5 = v5;
 }publicint LicenceNumber { get; set; }publicoverridestring ToString()
 {return $"Role: Traindriver, LicenceNumber: {LicenceNumber}, " + base.ToString();
 }
 }publicclass Admin : Person
 {public Admin(string firstName, string lastName, int age, string email)
 : base(firstName, lastName, age, email)
 {
 }publicoverridebool ChangeEmail(string email)
 {if (!email.EndsWith("@pig.dk", StringComparison.InvariantCultureIgnoreCase))returnfalse;returnbase.ChangeEmail(email);
 }publicoverridestring ToString()
 {return $"Role: Admin, " + base.ToString();
 }
 }
}


My ArrayList
namespace Pig
{publicpartialclass Index : System.Web.UI.Page
 {publicobject ListBoxResults { get; privateset; }publicobject DriverListBox { get; privateset; }protectedvoid Page_Load(object sender, EventArgs e)
 {
 Driver d1 = new Driver("Hans", "Christensen", 32, "hans@pig.dk", 123456);
 Driver d2 = new Driver("Peter", "Jensen", 40, "peter@mail.dk", 123456);
 Admin a1 = new Admin("Lene", "Maarud", 55, "lene@pig.dk");
 ArrayList person = new ArrayList();
 ListBoxResults.Items.Add(d1.ToString());
 ListBoxResults.Items.Add(d2.ToString());
 ListBoxResults.Items.Add(a1.ToString());
 }
 }
}


My Index file
<pre><%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="index.aspx.cs"Inherits="ThePig.index"%><!DOCTYPEhtml><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title></title></head><body><formid="form1"runat="server"><div><asp:ListBoxID="ListBoxResults"runat="server"Height="800px"Width="600px"></asp:ListBox></div></form></body></html>

Should I begin with razor pages or mvc?

$
0
0
I know html, css some fundamentals of js and C#, and I have decided to delve into the world of asp.net. I have learnt that there are two options to begin with, razor pages and mvc. But Razor pages seem to have very little future at present.

Which is better, Razor pages or MVC to begin with? I am only 19 and I want to devote my life to coding

Problem with Using Directive

$
0
0
It is an ASP.NeT core razor pages solution. I have three projects in my solution "OdeToFood"
1. OdeToFood (Original Project)
2. OdeToFood.Data (.Net Core Class Library)
3. OdeToFood.Core (.Net Core Class Library)


In OdeToFood.Core, when I use the following using directive in a class in OdeToFood.Core:

using OdeToFood.Data


it works perfect.


Similarly, when I use the following in a class file in OdeToFood.Data
using OdeToFood.Core


it works perfect.

But if I go to the startup.cs file in the "OdeToFood" Project and use
using OdeToFood.Data


It gives an error: The Type or namespace 'Core' does not exist in the namespace "OdeToFood." (Are you missing an assembly reference?)

Example Needed

$
0
0
I'm looking for an article or sample project that secures a web site, both API and client using .net core 3 and razor pages. The example should NOT be using EntityFramework.

Almost every article/sample I have found is either using EF or is based on core 2.2, I have a folder full of samples where I have downloaded the code, checked the packages and abandoned the project because EF is in there.
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP

I can´t get any output from XML and Binary.

$
0
0
I have been trying to experiment with XML and Binary files.
I did so by re-writing a code I made in an ASP NET Web Application.

Keycard.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;namespace Keycard
{
    [Serializable()]publicclass Keycard : ISerializable
    {protectedstring name;protectedint mykey;public Keycard(string name, int mykey)
        {this.Name = name;this.Mykey = mykey;
        }publicstring Name
        {get { return name; }set { name = value; }
        }publicint Mykey
        {get { return mykey; }set { mykey = value; }
        }publicvoid GetObjectData(SerializationInfo info, StreamingContext context)
        {

            info.AddValue("Name", name);
            info.AddValue("Keynumber", mykey);
        }public Keycard(SerializationInfo info, StreamingContext context)
        {
            Name = (string)info.GetValue("Name", typeof(string));
            Mykey = (int)info.GetValue("Keynumber", typeof(int));
        }publicoverridestring ToString()
        {return"Name: " + name + " ---- " + " Keynumber: " + mykey;
        }
    }
}


index.aspx.cs
using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Configuration;using System.Xml.Serialization;using System.IO;using System.Runtime.Serialization.Formatters.Binary;namespace Keycard
{publicpartialclass Index : System.Web.UI.Page
    {publicvoid Main(string[] args)
        {
            Keycard d1 = new Keycard("John", 102030);

            Stream stream = File.Open("KeycardData.dat",
                FileMode.Create);

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(stream, d1);
            stream.Close();

            d1 = null;

            stream = File.Open("KeycardData.dat", FileMode.Open);

            bf = new BinaryFormatter();

            d1 = (Keycard)bf.Deserialize(stream);
            stream.Close();
            Console.WriteLine(d1.ToString());

            XmlSerializer serializer = new XmlSerializer(typeof(Keycard));using(TextWriter tw = new StreamWriter(@"L\C#\keycards.xml"))
            {
                serializer.Serialize(tw, d1);
            }

            d1 = null;

            XmlSerializer deserializer = new XmlSerializer(typeof(Keycard));
            TextReader reader = new StreamReader(@"L\C#\keycards.xml");object obj = deserializer.Deserialize(reader);
            d1 = (Keycard)obj;
            reader.Close();
            Console.WriteLine(d1.ToString());
        }

    }
}


I am not getting any error messages at all, and when I press IIS Express, I get my index page, which just has a listbox, but of course there is no data in that listbox.

I can not get any data output, and it does not save any XML file in the folder that I specified. I think the reason might be that I am trying to use this code in a Web Application, but I have never worked with any other types of projects, so I am not sure what I should use instead.

Do you guys think this is the reason? Or could there be another reason as to why I am not getting my data to show up?
As I said, I am getting new error messages, so I have no idea where the problem comes from.
Viewing all 3938 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>