Friday, December 30, 2022

Bootstrap Modal popup for Error Show or hide - OnAsyncPostBackError ASP.NET C# - Show and hide modal popup javascript

   <!-- Modal -->

          <div class="modal fade" id="myModal" role="dialog">

            <div class="modal-dialog modal-sm">

              <div class="modal-content">

                <div class="modal-header">

                  <button type="button" class="close" data-dismiss="modal">&times;</button>

                  <h4 class="modal-title">Error</h4>

                </div>

                <div class="modal-body">

                  <p>This is a small modal.</p>

                </div>

                <div class="modal-footer">

                  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                </div>

              </div>

            </div>

          </div>


javascript


$('.modal-body').html('Enter body');

               $('#myModal').modal('show');

//$('#myModal').modal({ show: false});


reference:- https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal_lg&stacked=h

Thursday, December 29, 2022

How to send null integer or string values to database SQL ASP.NET C#

 There are two ways

either you can send null value from C#


 public static bool UpdateOpenVacancy(int id, string cadreName, int? cadreID, string instituteName, int? instituteID, string disciplineName, int? disciplineID, int? sanctionedStrength, int? inPosition, int? vacancy, int openVacancy)

        {

            SqlParameter[] param = {

                new SqlParameter("@id", id),

                new SqlParameter("@cadreName", cadreName),

                new SqlParameter("@cadreId",cadreID),

                new SqlParameter("@instituteName", instituteName),

                new SqlParameter("@instituteId", instituteID==null?Convert.DBNull:instituteID),

                new SqlParameter("@disciplineName", disciplineName),

            };

using Convert.DBNull


or in stored procedure pass null value to parameters

ALTER PROCEDURE [dbo].[UpdateOpenVacancy]

@id int,

@cadreName VARCHAR(100),

@cadreID INT = null,

@instituteName VARCHAR(100) = null,


END

or 

int? counts1 = string.IsNullOrEmpty(yarncounts.Text) ? (int?)null : int.Parse(yarncounts.Text);


Wednesday, December 28, 2022

How to use scriptmanager master page to content page(other page)- ASPX C#

 System.Web.UI.ScriptManager.GetCurrent(this.Page);


Exception handling update panel script manager - ASP.NET C# - onAsyncPostBackError

 catch (Exception ex)
    {
        string message = string.Format("Message: {0}\\n\\n", ex.Message);
        message += string.Format("StackTrace: {0}\\n\\n", ex.StackTrace.Replace(Environment.NewLine, string.Empty));
        message += string.Format("Source: {0}\\n\\n", ex.Source.Replace(Environment.NewLine, string.Empty));
        message += string.Format("TargetSite: {0}", ex.TargetSite.ToString().Replace(Environment.NewLine, string.Empty));
        ClientScript.RegisterStartupScript(this.GetType(), "alert""alert(\"" + message + "\");"true);
    }


 reference:- https://www.aspsnippets.com/Articles/Display-Exception-Error-Message-details-using-JavaScript-Alert-MessageBox-in-ASPNet.aspx


or


<script type="text/javascript">

              //function pageLoad() {

       //    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

       //}

OrderBy LINQ ASP.NET C#



 dtOpenVacancy.AsEnumerable().OrderByDescending(a => a.Field<int>("id"));


IF WANT TO USE WITH GRID DATABASE:-

dtOpenVacancy.AsEnumerable().OrderByDescending(a => a.Field<int>("id")).CopyToDataTable()


or


gridview

private void BindOpenVacancy()

        {

            DataTable dtOpenVacancy = Repository.GetAllOpenVacancy();


            if (dtOpenVacancy.Rows.Count > 0)

            {

                ViewState["vwOpenVacancy"] = dtOpenVacancy.AsEnumerable().OrderByDescending(a => a.Field<int>("id")).CopyToDataTable();


                grdOpenVacancy.DataSource = dtOpenVacancy.AsEnumerable().OrderByDescending(a => a.Field<int>("id")).CopyToDataTable(); 

            }

            grdOpenVacancy.DataBind();

        }


reference:- https://www.tutorialsteacher.com/linq/linq-sorting-operators-orderby-orderbydescending

Script manager OnAsyncPostBackError ASP.NET C# - Error handling in Scriptmanager

 If you are not using scriptmanager in master page, and try and catch is not used in the page,

than you can use OnAsyncPostBackError event in Webpage.

if you are using scriptmanger in webpage without master pager, than you can easily use OnAsyncPostBackError , but you don't have to use try and catch


<asp:ScriptManager runat="server" ID="ScriptManager" 

EnablePartialRendering="true" OnAsyncPostBackError="OnAsyncPostBackError">

  </asp:ScriptManager>


references:- http://etutorials.org/Programming/aspnet+ajax/Chapter+5+Using+the+ScriptManager/Error+Handling/

https://stackoverflow.com/questions/5944481/error-handling-in-updatepanel-with-customerrors-mode-on

https://www.oreilly.com/library/view/aspnet-ajax-updatepanel/0596527470/ar01s06.html

To prevent After saving on button click on refresh button saving data - ASP.NET C#

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
     <ContentTemplate>            
           <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
           <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />      
     </ContentTemplate>
</asp:UpdatePanel>

reference:-  https://www.aspsnippets.com/questions/184293/Prevent-Page-refresh-on-Button-Click-in-ASPNet/

Tuesday, December 27, 2022

Custom Errors Web.config Script manager ASP.NET C# Ajax

<form id="form1" runat="server">

 <asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError" AllowCustomErrorsRedirect="true"></asp:ScriptManager>

</form>


web.config


<system.web>

<customErrors mode="On" defaultRedirect="ErrorPage.aspx">

      <error statusCode="404" redirect="ErrorPage.aspx"/>

      <error statusCode="500" redirect="ErrorPage.aspx"/>

    </customErrors>

</system.web>


reference:- http://www.codedigest.com/Articles/ASPNETAJAX/115_Error_Handling_in_ASPNet_Ajax_Applications.aspx

SQLdatasource with Gridview - ASP.NET C#

 reference:- https://learn.microsoft.com/en-us/previous-versions/aspnet/bb398890(v=vs.100)?redirectedfrom=MSDN

If website is working slow ASP.NET C#

 If website is working slow, then it is due to heavy UI


Grid visible to false will increase performance.



or



If we use html controls instead of asp.net controls than site will be fast and use jquery ajax for click events

How to insert and remove all elements from dropdown list - ASP.NET

 For Insert


ddlDiscipline.Items.Insert(0, new ListItem("--Select--", "--Select--"));


For Remove:-


ddlDiscipline.Items.Clear();

 ddlDiscipline.Items.Insert(0, new ListItem("--Select--", "--Select--"));


reference:- https://meeraacademy.com/how-to-use-clear-remove-and-removeat-in-dropdownlist-in-asp-net/

Monday, December 26, 2022

Removing elements from var LINQ ASP.NET

 var exceptionList = 

                 allData.AsEnumerable().Where(a => dtOpenVacancy.AsEnumerable().Select(q => q.Field<string>("disciplinename")).Contains(a.Field<string>("discipline")) && dtOpenVacancy.AsEnumerable().Select(q => q.Field<string>("institutename")).Contains(a.Field<string>("institute")) && dtOpenVacancy.AsEnumerable().Select(q => q.Field<int>("cadreid")).Contains(int.Parse(ddlCadreType.SelectedItem.Value))).ToList();

                

                ViewState["dt2"]= allData.AsEnumerable().Except(exceptionList.AsEnumerable()).CopyToDataTable();


Use Tolist somewhere

or you can use removeall from List.

Error in converting viewstate to var ASP.NET C# - Erro same key has already been added

 ViewState["dt2"] = 

                 allData.Where(a => dtOpenVacancy.AsEnumerable().Select(q => q.Field<string>("disciplinename")).Contains(a.Field<string>("discipline")) && dtOpenVacancy.AsEnumerable().Select(q => q.Field<string>("institutename")).Contains(a.Field<string>("institute")) && dtOpenVacancy.AsEnumerable().Select(q => q.Field<int>("cadreid")).Contains(int.Parse(ddlCadreType.SelectedItem.Value))).CopyToDataTable()

Compare List with string LINQ

DataTable dtOpenVacancy = ViewState["vwOpenVacancy"] as DataTable;

                var allData = dt3.AsEnumerable().Where(p => p.Field<string>("institute") != null);


 allData.Where(a => dtOpenVacancy.AsEnumerable().Select(q => q.Field<string>("disciplinename")).Contains( a.Field<string>("discipline")) && dtOpenVacancy.AsEnumerable().Select(q => q.Field<string>("institutename")).Contains(a.Field<string>("institute"))  && dtOpenVacancy.AsEnumerable().Select(q => q.Field<int>("cadreid")).Contains(int.Parse( ddlCadreType.SelectedItem.Value))).Count();



reference:- https://stackoverflow.com/questions/14257360/linq-select-objects-in-list-where-exists-in-a-b-c

Basic Update Insert Stored Procedure SQL

Also table should have primary key and identity column(id)


Note: You can pass null values to stored procedure parameters, which columns are null in database table

 /USE [PMS]

GO

/****** Object:  StoredProcedure [dbo].[UpdateOpenVacancy]    Script Date: 29-12-2022 15:29:06 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO




ALTER PROCEDURE [dbo].[UpdateOpenVacancy]

@id int,

@cadreName VARCHAR(100),

@cadreID INT = null,

@instituteName VARCHAR(100) = null,

@instituteID INT = null ,

@disciplineName VARCHAR(100) = null,

@disciplineID INT = null,

@sanctionedStrength INT = null,

@inPosition INT = null,

@vacancy INT = null,

@openVacancy INT

AS

BEGIN

IF (@id > 0)

UPDATE OpenVacancy

SET 

[CadreName] = ISNULL(@cadreName, CadreName)

      ,[CadreID] = ISNULL(@cadreId, [CadreID])

      ,[InstituteName] = ISNULL(@instituteName,[InstituteName])

      ,[InstituteID] = ISNULL(@instituteID,[InstituteID])

      ,[DisciplineName] = ISNULL(@disciplineName,[DisciplineName])

      ,[DisciplineID] = ISNULL(@disciplineID,[DisciplineID])

      ,[SanctionedStrength] = ISNULL(@sanctionedStrength, [SanctionedStrength])

      ,[InPosition] = ISNULL(@inPosition,[InPosition])

      ,[Vacancy] = ISNULL(@vacancy,[Vacancy])

      ,[OpenVacancy] = ISNULL(@openVacancy,[OpenVacancy])

WHERE ID =@id;

ELSE

INSERT INTO OpenVacancy

           ([CadreName], [CadreID],[InstituteName],[InstituteID],[DisciplineName],[DisciplineID],[SanctionedStrength],[InPosition],[Vacancy]

           ,[OpenVacancy])

     VALUES(@cadreName,@cadreID,@instituteName,@instituteID,@disciplineName,@disciplineID,@sanctionedStrength,@inPosition,@vacancy,@openVacancy)

END


Create identity column when table is already created SQL

 ALTER TABLE [UserName] DROP COLUMN [ID];


ALTER TABLE [UserName] 
    ADD [ID] integer identity not null;

This will add the id column to last

or

drop the table and create table and add identity in id

CREATE TABLE [dbo].[OpenVacancy](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[CadreName] [varchar](100) NULL,
	[CadreID] [int] NULL,
	[InstituteName] [varchar](100) NULL,
	[InstituteID] [int] NULL,
	[DisciplineName] [varchar](100) NULL,
	[DisciplineID] [int] NULL,
	[SanctionedStrength] [int] NULL,
	[InPosition] [int] NULL,
	[Vacancy] [int] NULL,
	[OpenVacancy] [int] NULL,
 CONSTRAINT [PK_OpenVacancy] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Friday, December 23, 2022

Insert Update stored procedure with Scope_Identity() SQL

reference:-  https://www.aspsnippets.com/Articles/Return-Identity-value-from-Stored-Procedure-in-SQL-Server.aspx

LINQ get selected fields without Entity or modal

 var ssIPVac = allData.Where(s => s.Field<string>("institute") == ddlInstitute.SelectedItem.Text && s.Field<string>("discipline") == ddlDiscipline.SelectedItem.Text).Select(d => new { ss = d.Field<int>("ss"), ip = d.Field<int>("ip"), vacancy = d.Field<int>("vacancy") }).First();


                    txtSanctionedStrength.Text = ssIPVac.ss.ToString();

                    txtInPosition.Text = ssIPVac.ip.ToString();

                    txtVacancy.Text = ssIPVac.ip.ToString();

How to use session in Login ASP.NET C#

Passing session value


 Session["AccessType"] = "Institute"


using session value

 if (Session["AccessType"].ToString() == "ReadOnly")

                {

                    linkNewEmployee.Visible = false;

                    linkNewEmployee.Enabled = false;

                }


or



 int UserID = Convert.ToInt32(Session["UserID"]);

            InstituteID = Convert.ToInt32(Session["InstituteId"]);

            if (UserID > 0 || (InstituteID > 0)) { }

            else { Response.Redirect("login.aspx"); }

HTML Control not found in aspx.cs but it is present in asp page

 If HTML Control with runat= server (not asp.net control), in aspx.cs giving error, => (Control not found) , but control is present in aspx page


Solution:- Change aspx page CodeBehind property to CodeFile.

AppSettings ASP.NET C# Web.Config

 Add key in asspsettings in web.config and use it in C#


web.config


<configuration>

<appSettings>

    <add key="RetirementAge" value="62"/>

  </appSettings>

</configuration>


--------------

aspx.cs

WebConfigurationManager.AppSettings["RetirementAge"]


Thursday, December 22, 2022

Unauthorized access access denied redirect to URL ASP.NET C#

web.config



<customErrors mode="On" defaultRedirect="~/GenericErrorPage.htm" >

  <error statusCode="401" redirect="~/unauthorized.htm"/>

 </customErrors>





aspx.cs code

protected void Page_Load(object sender, EventArgs e)

{



if (!Page.IsPostBack)

{

if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))

Response.Redirect("~/unauthorized.aspx");

}

}


or


public static bool CheckPageAccess(string uRL, long roleCode)
        {
            bool IsAllow = false;

            if (HttpContext.Current.Session[Constants.UserInformation] != null)
            {
                IsAllow = MenuService.MenuAccess(uRL, roleCode);
            }

            return IsAllow;
        }

if (!PageUtils.CheckPageAccess(Request.Url.AbsolutePath, CurrentUser.RoleMasterId))
                {
                    Response.Redirect("~/UnauthorizedAccessError.aspx?contentPage=" + Request.RawUrl);
                }

                if (!string.IsNullOrWhiteSpace(Request.QueryString["ApplicationId"]))
                {
                    ApplicationId = Convert.ToInt64(CryptologyFunctions.Decrypt(Request.QueryString["ApplicationId"]));

                }

Forms Authentication Roles ASP.NET C# - Web.config

 > First We have to create Folders, For example publishers, Admin

Than we have to paste the following code:-

<location path="ADMIN">

    <system.web>

      <authorization>

        <allow roles="ADMIN"/>

        <deny users="*"/>

      </authorization>

    </system.web>

  </location>

  <location path="Publishers">

    <system.web>

      <authorization>

        <allow roles="PUBLISHER,ADMIN"/>

        <deny users="*"/>

      </authorization>

    </system.web>

 </location>

references:- https://itecnote.com/tecnote/redirect-user-to-mulitple-login-pages-using-asp-net-membership/

http://www.codedigest.com/Articles/ASPNET/176_Using_Roles_in_Forms_Authentication_in_ASPNet_20.aspx

FTP Client and FTP Server

 FileZilla and WinSCP are FTP Client and Server.


 Its main function is file transfer between a local and a remote computer

Wednesday, December 21, 2022

What is Angular.JS

 It is a javascript framework.

Dropdown client side event ASP.NET C#

 <!DOCTYPE html>

<html>

<body>


<p>Select a new car from the list.</p>


<select id="mySelect" onchange="myFunction()">

  <option value="Audi">Audi</option>

  <option value="BMW">BMW</option>

  <option value="Mercedes">Mercedes</option>

  <option value="Volvo">Volvo</option>

</select>


<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>


<p id="demo"></p>


<script>

function myFunction() {

  var x = document.getElementById("mySelect").value;

  document.getElementById("demo").innerHTML = "You selected: " + x;

}

</script>


</body>

</html>

reference:- https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onchange


Tuesday, December 20, 2022

ViewState datatable ASP.NET C#

  (DataTable) ViewState["dt2"] = dt.copy();

Clone and copy difference in datatable ASP.NET C#

 Clone will copy only the structure(only the columns name)


Copy will copy all the data and structure.

How to add blank value to 0th index of Dropdown list ASP.NET c#

  public void BindCadreTypeDropdownlist()

        {

            DataSet ds = new DataAccess().Read("read_cadreType");

            ddlCadreType.DataSource = ds.Tables[0];

            ddlCadreType.DataBind();

            ddlInstitute.Items.Insert(0, new ListItem("--Select--", "--Select--"));

        }

Remove records from LINQ ASP.NET C#

 var institutes = dt.AsEnumerable().Select(d => new { Institute = d.Field<String>("institute") }).Distinct();

            

            string json = js.Serialize(institutes.Where(a => a.Institute != null));


reference:- https://stackoverflow.com/questions/38381612/c-sharp-linq-remove-null-values-from-an-array-and-return-as-not-nullable

Monday, December 19, 2022

Get value from master page string data members ASPX C#

master page file

 public partial class Site2 : System.Web.UI.MasterPage

    {

        public int TransferDriveID = 0;

        public string TransferDriveName = "";

}


other apsx file

 ((Site2)this.Master).TransferDriveID 


or

string val = Request[((SiteMaster)Master).txtSearchName.UniqueID];

or
DropDownList ddlTest = this.Master.FindControl("ddlTest") as DropDownList;

https://stackoverflow.com/questions/17783165/pass-master-page-control-values-on-content-page-on-page-load


https://stackoverflow.com/questions/7536843/master-page-is-adding-additional-text-in-textbox-id


https://www.c-sharpcorner.com/UploadFile/301dc3/accessing-control-of-master-page-from-the-content-page-in-as/

Get and update text value and date value from and to database - ASP.NET C#

Get from database

 <div runat="server" id="medical_govt_date" visible="false">

            <b>4 (b). Date of issue of medical certificate &nbsp; (MM/DD/YYYY)</b><br />

            <asp:Label runat="server" ID="lblMedicalCertificateDate" />

        </div>



<div>

        <br />

            <b>9. Number Of Award(s)

    </b>

    </div>

    <div>

        <asp:Label runat="server" ID="lblNumberOfAwards"></asp:Label>

    </div>


asp.cs 

Textbox with number field - numeric field - Ajax ajaxToolkit:NumericUpDownExtender - with max length

  <div>

            <ajaxToolkit:NumericUpDownExtender runat="server" Maximum="10" Minimum="1"   TargetControlID="txtNumberOfAwards" Width="200" />

            <asp:TextBox ID="txtNumberOfAwards" runat="server" CssClass="form-control" MaxLength="2" Text="0"></asp:TextBox>

            

            <asp:RangeValidator runat="server" ControlToValidate="txtNumberOfAwards" ErrorMessage="Enter number between 0 to 10" Type="Integer" MinimumValue="0" MaximumValue="10" ForeColor="Red" ValidationGroup="transfer_request" SetFocusOnError="true"></asp:RangeValidator>


        </div>


aspx.cs



 protected void Page_Load(object sender, EventArgs e)

        {

          

            if (!IsPostBack)

            {

txtNumberOfAwards.MaxLength = 2;

}

}

Pattern in Textbox HTML

  <input type="text" id="country_code" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code"><br><br>

This means only three characters  

This will only used on click button(submit)



reference:- https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_pattern

How to find ram slots and disk space in windows

 You can also see disk read or write speed.

> Open task manager, Click on Performance tab.

> Click on memory> You can find slots used.


Or you can click on Device manager

> and check for different devices.


Thursday, December 15, 2022

Textbox with date validations ASP.NET C#

  <div>

            <span class="h4">4. (b)</span> <span class="text-danger h3">*</span>

            

                    <b>Date of Issue of Medical Certificate (MM/DD/YYYY)</b></div>

                <div>

                    &nbsp&nbsp&nbsp<asp:TextBox runat="server" ID="txtDOIMC" ClientIDMode="Static" MaxLength="10" CssClass="form-control"

                        placeholder="eg. 02/30/1978"></asp:TextBox>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txtDOIMC"

                        CssClass="text-danger" Display="Dynamic" ErrorMessage="Can't leave blank." SetFocusOnError="True"

                        ValidationGroup="transfer_request"></asp:RequiredFieldValidator>

                    <asp:RegularExpressionValidator ID="regcheckdate" runat="server" ControlToValidate="txtDOIMC"

                        Display="Dynamic" ErrorMessage="Invalid Date Format" SetFocusOnError="True" ValidationGroup="transfer_request"

                        CssClass="text-danger" ValidationExpression="^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$"></asp:RegularExpressionValidator>

                </div>

        </div>