Thursday, April 10, 2025

Read XMl File data With namespace and without namespace

 

Suppose xml files is avaialble like this with namespace

<?xml version="1.0" encoding="UTF-8"?> <Document xmlns="http://abcd.org/onmags/schema"> <AuthReq> <MyData> Hi How are you </MyData> </AuthReq> </Document>

.Net Sample Code looks like this

#region With Namespace XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("/Sample/request.xml")); var nms = new XmlNamespaceManager(doc.NameTable); nms.AddNamespace("nm", "http://abcd.org/onmags/schema"); XmlNode node = doc.DocumentElement.SelectSingleNode("/nm:Document/nm:AuthReq", nms); //XmlNode node = doc.DocumentElement.SelectSingleNode("/Document/AuthReq"); string request = node.InnerText.ToString(); #endregion =================================================================

Suppose xml files is avaialble like this without namespace

<?xml version="1.0" encoding="UTF-8"?> <Document> <AuthReq> <MyData> Hi How are you </MyData> </AuthReq> </Document>

.Net Sample Code looks like this

#region With Namespace XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("/Sample/request.xml")); XmlNode node = doc.DocumentElement.SelectSingleNode("/Document/AuthReq"); string request = node.InnerText.ToString(); #endregion

Monday, March 3, 2025

Get Validation Error Message, Page.Isvaild False Section

if you wanted to know the route cause of error message then we can write below code in aso.net 

 foreach (BaseValidator validator in Page.Validators)

            {

                if (validator.Enabled && !validator.IsValid)

                {

                    // Put a breakpoint here

                    string clientID = validator.ClientID;

                    string aa = validator.ErrorMessage;

                }

            }

Monday, February 24, 2025

Session Kill on Page Refresh OR On Page/Browser refresh session kill in asp.net with c#

Create a Global Variable

bool IsPageRefresh = false;

Write Below Code on Page Load

  #region To Maintain Refresh event
  //Section of code checks if the page postback is due to genuine submit by user 
  //or by pressing "refresh" or F5
  if (!IsPostBack)
  {
       //Session.Abandon(); Session.Clear();
       ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
       Session["SessionId"] = ViewState["ViewStateId"].ToString();
  }
  else
  {
      if (ViewState["ViewStateId"] != null && Session["SessionId"] != null)
        {
          if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
            {
               IsPageRefresh = true;
            }
        }

        Session["SessionId"] = System.Guid.NewGuid().ToString();
        ViewState["ViewStateId"] = Session["SessionId"].ToString();
    } 
    #endregion 

Check Global variable where you made the condition like on events

    #region To Maintain Refresh event
     if (IsPageRefresh)
        {
          Session.Abandon(); Session.Clear();
        }
    #endregion

    if (Session["MyFlag"] == null) Response.Redirect("invalid.aspx?msg=Session expired. ", true);

Friday, December 13, 2024

SecurityProtocol Setting in .Net, SSL/TLS Error Fixes

 #region SecurityProtocol Setting

                try

                { //try TLS 1.3

                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)12288

                                                         | (SecurityProtocolType)3072

                                                         | (SecurityProtocolType)768

                                                         | SecurityProtocolType.Tls;

                }

                catch (NotSupportedException)

                {

                    try

                    { //try TLS 1.2

                        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072

                                                             | (SecurityProtocolType)768

                                                             | SecurityProtocolType.Tls;

                    }

                    catch (NotSupportedException)

                    {

                        try

                        { //try TLS 1.1

                            ServicePointManager.SecurityProtocol = (SecurityProtocolType)768

                                                                 | SecurityProtocolType.Tls;

                        }

                        catch (NotSupportedException)

                        { //TLS 1.0

                            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

                        }

                    }

                }

                #endregion

Saturday, September 14, 2024

Received an invalid column length from the bcp client for colid Error while Bulk Upload in aspx c#

 I have created sample code to know the route cause of this issue.

So we can write code like this.

Sample code:-

#region bulkCopy

if (MyConnection.State == ConnectionState.Closed) MyConnection.Open();

DataTable dataTableName = GetDataTabletFromCSVFile(filenamestr1);

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(MyConnection))

{

bulkCopy.DestinationTableName = "Destination_TBL_My_Name_Temp";

try

{

bulkCopy.WriteToServer(dataTableName);

}

catch (Exception ex)

{

WriteErrorLog_Debug("My_FileExtractService " + ex.Message.ToString() + " " + ex.StackTrace.ToString() + " / " + RefNo, "testTimer_Elapsed1");


string message = "";

if (ex.Message.Contains("Received an invalid column length from the bcp client for colid"))

{

string pattern = @"\d+";

Match match = Regex.Match(ex.Message.ToString(), pattern);

var index = Convert.ToInt32(match.Value) - 1;


FieldInfo fi = typeof(SqlBulkCopy).GetField("_sortedColumnMappings", BindingFlags.NonPublic | BindingFlags.Instance);

var sortedColumns = fi.GetValue(bulkCopy);

var items = (Object[])sortedColumns.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sortedColumns);


FieldInfo itemdata = items[index].GetType().GetField("_metadata", BindingFlags.NonPublic | BindingFlags.Instance);

var metadata = itemdata.GetValue(items[index]);

var column = metadata.GetType().GetField("column", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);

var length = metadata.GetType().GetField("length", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);

message = (String.Format("Column: {0} contains data with a length greater than: {1}", column, length));

}

string aa =  message;


WriteErrorLog_Debug("My_FileExtractService Detailed Exception " + message.ToString() + " " + ex.StackTrace.ToString() + " / " + RefNo, "testTimer_Elapsed1");

}

}

#endregion

Wednesday, January 17, 2024

Get Web Request Error 500,400 Exception details in c#

WebException is a good approch to get the Real cause of 500 error,  


catch (WebException ex)

{
    using (var stream = ex.Response.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
}
catch (Exception ex)
{
    // Something more serious happened
    // like for example you don't have network access
    // we cannot talk about a server exception here as
    // the server probably was never reached
}

Thursday, January 11, 2024

Some Key to Help for Sql Optimization

 Below having some command used to get/analysis the Sql Query for optimization.

Add Below list of command at top pf the Query with ON and at the end again reset with OFF

Ex: Set NoCount ON

--Query

Set NoCount OFF

----Set Of Commands--------

Set NoExec OFF

Set ParseOnly OFF

Set Concat_Null_Yields_NULL OFF

Set Arithabort OFF

--Set Showplan_Text OFF

Set Statistics Time OFF

Set Statistics IO OFF

Set NOCount OFF


-----Mainly Used below three command only-----

SET NOCOUNT ON

SET STATISTICS TIME ON

set statistics io on