Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, September 14, 2023

How to locate and replace special characters in an XML file with Visual C# .NET

We can use the SecurityElement.Escape method to replace the invalid XML characters in a string with their valid XML equivalent. The following table shows the invalid XML characters and their respective replacements

Character Name Entity Reference Character Reference Numeric Reference
Ampersand & & &
Left angle bracket < < <
Right angle bracket > > >
Straight quotation mark " " '
Apostrophe ' ' "

Sample Usage of this Escape method.

//Usage
srtXML = SecurityElement.Escape(strXML);
  

For this you need to import System.Security namespace. Alternatively you can also use this simple replace method with all special characters in a single method like below

public string EscapeXml(string s)
{
    string toxml = s;
    if (!string.IsNullOrEmpty(toxml))
    {
        // replace special chars with entities
        toxml = toxml.Replace("&", "&");
        toxml = toxml.Replace("'", "'");
        toxml = toxml.Replace("\"", """);
        toxml = toxml.Replace(">", ">");
        toxml = toxml.Replace("<", "&lt;");
    }
    return toxml;
}
  

Hope this is useful!

Tuesday, June 20, 2023

About Monolithic and Micro-services Architecture?

Monolithic and micro-services architecture are two different approaches to software design. While monolithic design is a traditional approach where the entire application is developed as a single unit, micro-services architecture is a modern and modular approach where the application is broken down into smaller, interconnected services.

Monolithic Architecture:

In monolithic architecture, the complete application runs as a single unit. In simpler terms, the application is built as a monolithic block where all the components are tightly coupled. The codebase is large and complex and can be difficult to manage and maintain.

Monolithic architectures have been tried and tested for decades and have proven to be reliable, robust, and easily understandable. It is widely used in industries where real-time performance is required, such as finance, aviation, and healthcare.

Micro-services Architecture:

In micro-services architecture, the application is broken down into smaller, more manageable services. Each service focuses on a specific task or feature and can be developed and deployed independently. This modular approach ensures that services are loosely coupled, enabling them to be scaled or replaced individually.

Micro-services architecture is widely used in industries where agility is of utmost importance, such as the e-commerce and social media industries, where rapid innovation is critical. Micro-services architecture allows developers to cater to specific customer requests without affecting other services.

49395813-cd094980-f737-11e8-9e9a-6c20db5720c4

 

Pros and cons:

Both monolithic and micro-services architecture have their advantages and disadvantages. Monolithic architecture is simple and easy to understand, provides efficient performance, and requires little to no overhead. However, monolithic architecture can be difficult to manage and does not offer much flexibility.

On the other hand, micro-services architecture provides developers with better agility, scalability and offers better fault tolerance. However, micro-services architecture requires a considerable amount of overhead, and the system's complexity increases exponentially with the number of services.

Conclusion:

Both monolithic and micro-services architecture have their pros and cons. Choosing the right architecture depends on the specific needs of the organization and its business goals. While monolithic architecture remains a reliable and well-established option, organizations looking for a modern and agile approach often opt for micro-services architecture. Whatever the choice may be, it is essential to evaluate the requirements carefully before adopting a specific architecture.

Friday, May 21, 2021

How to: Looping through reader count dynamically C#

Here is how this can be done once you have the data call via Read methods
   
using (var reader = await sqlDbContext.ExecuteReaderAsync(command))
{
   
    while (await sqlDbContext.ReadAsync(reader))
    {
        // when count greaterthan 1
        if (reader.FieldCount > 1)
        {
            if (!string.IsNullOrEmpty(reader["ItemD"].ToString()))
            {
                mobilityChangeOrdersItem.ItemID= reader["ItemID"] == null ? 0 : Convert.ToInt32(reader["ItemID"].ToString());
            }
            if (!string.IsNullOrEmpty(reader["ID"].ToString()))
            {
                mobilityChangeOrdersItem.ID = reader["ID"] == null ? 0 : Convert.ToInt32(reader["ID"].ToString());
            }
        }
    }

    //Looping through complete list of return variables to find out requrired column
    string errorMessge = " SQL Message: -- *Start* ItemD -- :: " + mobilityChangeOrdersItem.ItemD;
    while (await reader.NextResultAsync())
    {
        var fieldvalues = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();

        while (await reader.ReadAsync())
        {
            if (fieldvalues.Contains("ErrorMessage"))
            { 
                errorMessge += Environment.NewLine + " ErrorMessage : " + reader["ErrorMessage"].ToString();
            }
            if (fieldvalues.Contains("ErrorProcedure"))
            {
                errorMessge += Environment.NewLine + " ErrorProcedure : " + reader["ErrorProcedure"].ToString();
            }
        }
        errorMessge += Environment.NewLine + " SQL Message: -- *End*";
        mobilityChangeOrdersItem.StatusMessage = errorMessge;
    } 
    mobilityChangeOrdersList.Add(mobilityChangeOrdersItem);
}

Hope this helps 😀

How to : Check if a column exists in a datareader in C#

 Here is how we can do in  C# supported Frameworks!!

var fieldvalues = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();

//get column name here
if (fieldvalues.Contains("ErrorMessage"))
{
    errorMessge += Environment.NewLine + " ErrorMessage : " + reader["ErrorMessage"].ToString();
}
//get column name here
if (fieldvalues.Contains("ErrorProcedure"))
{
    errorMessge += Environment.NewLine + " ErrorProcedure : " + reader["ErrorProcedure"].ToString();
}

BTW, ErrorMessage will return the value after checking these fields 

Hope this helps 😀

Tuesday, February 20, 2018

Paste JSON as Code - quicktype

quicktype infers types from sample JSON data, then outputs strongly typed models and serializers for working with that data in your desired programming language. To use this extension, just copy some JSON and use Edit/Paste JSON as Code.

This extensions works only in VS2017 as of now.

For a more powerful experience, including custom options and the ability to generate code from JSON Schema or multiple JSON samples, try app.quicktype.io.

Download here

Wednesday, January 31, 2018

How to get the IP Address of a Remote Socket Endpoint

Here is how we can IP address, you need to use below namespace library

using System.Net.Sockets;

IPHostEntry ipHostInfo1 = Dns.GetHostEntry(Dns.GetHostName());
// loop through list of system IP address 
// get the IP4 Address of the current machine
foreach (IPAddress ipaddr in ipHostInfo1.AddressList)
{
    if (ipaddr.ToString() == ConfigurationManager.AppSettings["SystemIPAddress"].ToString())
    {
        strIpAddress = ipaddr.ToString();
        break;
    }

}

                
IPAddress ipAddress = IPAddress.Parse(strIpAddress);

Hope this helps!

Monday, March 13, 2017

Can't locate Microsoft.Office.Interop.Word

Microsoft Office primary interop assemblies (PIAs) are used for development purpose when you are working with Word or Excel.

Usually Microsoft Interop libraries are installed automatically at the time of Microsoft Office in development computer. However, in some cases you might need to install PIAs separately.

Download : Microsoft Office 2010: Primary Interop Assemblies Redistributable

Thursday, October 20, 2016

Types of exception in c#

A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another.

C# exception handling is built upon four keywords: try, catch, finally, and throw.

  • try: A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.

  • catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

  • finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

  • throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

Types of Exceptions in C#

Exception Class

Description

System.IO.IOException

Handles I/O errors.

System.IndexOutOfRangeException

Handles errors generated when a method refers to an array index out of range.

System.ArrayTypeMismatchException

Handles errors generated when type is mismatched with the array type.

System.NullReferenceException

Handles errors generated from deferencing a null object.

System.DivideByZeroException

Handles errors generated from dividing a dividend with zero.

System.InvalidCastException

Handles errors generated during typecasting.

System.OutOfMemoryException

Handles errors generated from insufficient free memory.

System.StackOverflowException

Handles errors generated from stack overflow.

Tuesday, October 20, 2015

C# Character Escape Sequences

Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant.

In C# you can use the backslash to put special characters to your string. For example, to put ", you need to write \". There are a lot of characters that you write using the backslash: Backslash with a number:

  • \000 null
  • \010 backspace
  • \011 horizontal tab
  • \012 new line
  • \015 carriage return
  • \032 substitute
  • \042 double quote
  • \047 single quote
  • \134 backslash
  • \140 grave accent

Backslash with other character

  • \' - single quote, needed for character literals
  • \" - double quote, needed for string literals
  • \\ – backslash
  • \0 - Unicode character 0
  • \a - Alert (character 7)
  • \b - Backspace (character 8)
  • \f - Form feed (character 12)
  • \n - New line (character 10)
  • \r - Carriage return (character 13)
  • \t - Horizontal tab (character 9)
  • \v - Vertical quote (character 11)
  • \uxxxx - Unicode escape sequence for character with hex value xxxx
    \xn[n][n][n] - Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
  • \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates

Hope this helps!!

Friday, February 20, 2015

How to get Cookies reference is getting in ashx file

Here is how you can do it if you set Cookies in different pages. Below code will help you get Cookies in ASHX file

  public void ProcessRequest(HttpContext context)
        {
            context.Response.AddHeader("Pragma", "no-cache");
            context.Response.AddHeader("Cache-Control", "private, no-cache");

            if (context.Request.Cookies["UserID"] != null && 
                context.Request.Cookies["UserID"].Value != null 
                && context.Request.Cookies["UserID"].Value.Trim() != "")
            {
                UserID = Convert.ToInt32(context.Request.Cookies["UserID"].Value);
            }

            HandleMethod(context);
        }
Hope this helps !!

Tuesday, January 27, 2015

How to access ViewState of one page in another page in Asp.Net?

You can't access ViewState of one page from another page directly. If you want to access a particular ViewState value then you can pass the value in Context collection and then access the value in other page.

In Page 1:

Context.Items.Add("employee" ,ViewState["employee"].ToString());


In Page 2:


string employeeName = Context.Items["employee"].ToString();

Hope this helps!

How to: Disable Button after Click while maintaining CausesValidation and an OnClick-Method

Here is how you can do it by adding these two lines in your code behind to prevent multiple clicks on a button.

string strProcessScript = "if (!Page_ClientValidate()){ return false; } else{ this.value='Processing...';this.disabled=true; }";
CheckOutButton.Attributes.Add("onclick", strProcessScript + ClientScript.GetPostBackEventReference(CheckOutButton, "").ToString());

If you have ASP.NET Validation controls in your page, then you might need to do this by adding specific validation group to Page_ClientValidate method.

string strProcessScript = "if (!Page_ClientValidate('PaymentValidationGroup')){ return false; } else{ this.value='Processing...';this.disabled=true; }";
CheckOutButton.Attributes.Add("onclick", strProcessScript + ClientScript.GetPostBackEventReference(CheckOutButton, "").ToString());
 
Only thing you need to change in ASPX is to add following attribute in ASP Button code UseSubmitBehavior="false"
 
<asp:Button runat="server" ID="PaymentCheckOutButton" ValidationGroup="PaymentValidationGroup"                                          
Text="Proceed to Checkout" UseSubmitBehavior="false" class="btn btn-primary btn-cons pull-right" OnClick="PaymentCheckOutButton_Click" />
 
Hope this helps!!

Tuesday, August 12, 2014

How to Parse datetime in multiple formats

Here is how we can parse different date formats get validated using one function.

In VB.NET

'''Validate method for Date format
  Private Function validateDate(ByVal strDate As String, ByVal strColumnName As String) As String
        Dim strError As String = ""
        Dim provider As CultureInfo = CultureInfo.GetCultureInfo("en-us")
        Dim formatStrings As String() = {"MM/dd/yyyy", "yyyy-MM-dd", "d"}
        Dim dateValue As DateTime
        Try
            If DateTime.TryParseExact(strDate, formatStrings, provider, DateTimeStyles.None, dateValue) Then
                strError = "Success"
            Else
                strError = "Failed"
            End If
        Catch ex As Exception

        End Try
        Return strError
    End Function

In C#

///Validate method for Date format
private string validateDate(string strDate, string strColumnName)
{
    string strError = "";
    CultureInfo provider = CultureInfo.GetCultureInfo("en-us");
    string[] formatStrings = {
        "MM/dd/yyyy",
        "yyyy-MM-dd",
        "d"
    };
    DateTime dateValue = default(DateTime);
    try {
        if (DateTime.TryParseExact(strDate, formatStrings, provider, DateTimeStyles.None, out dateValue)) {
            strError = "Success";
        } else {
            strError = "Failed";
        }

    } catch (Exception ex) {
    }
    return strError;
}

Add as many as formatters to the formatStrings array and use this funtion. Happy Coding ☺☻

Thursday, March 27, 2014

How to change or add script tag source from C#?

Here is how we can add script to page header from code behind in c#. The reason why I am doing this is I have these JavaScript files included in master page. And when I try to give path of these files I am getting issues with absolute page when I got to other pages since I have these in master page.

and one more reason why I did is I don’t want to change this every time if deploy to different environment from QA, Stage and Production.

This is how we can do it in your master page.

string js1 = HttpContext.Current.Request.ApplicationPath + "/Scripts/jquery.cycle2.js";
string js2 = HttpContext.Current.Request.ApplicationPath + "/Scripts/jquery.countdown.js";

Literal js1script = new Literal();
js1script.Text = string.Format(
@"<script src=""{0}"" type=""text/javascript""></script>", js1);
Page.Header.Controls.Add(js1script);

Literal js2script = new Literal();
js2script.Text = string.Format(
@"<script src=""{0}"" type=""text/javascript""></script>", js2);
Page.Header.Controls.Add(js2script);

Hope this is useful!!

Monday, March 10, 2014

How to access a div or HTML controls is inside a gridview?

Here is an example of how to access a div inside the TemplateColumn of a Grid:

aspx:

<asp:TemplateField HeaderText="Pick" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemStyle Width="60px" />
<ItemTemplate>
<div id="divpickstatus" runat="server">
</div>
</ItemTemplate>
</asp:TemplateField>



codebehind



protected void gridview_schedule_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HtmlGenericControl divpickstatus = (HtmlGenericControl)e.Row.FindControl("divpickstatus");
}
}
Hope this helps.

Thursday, July 18, 2013

How to get username from email address c#

Here is sample code snippet that I have used to get username from the email address. You can use MailAddress Class to get few built in properties for our use.

   1: string FromEmail = ConfigurationManager.AppSettings["NotifyEmail"].ToString();
   2: MailAddress FromAddress = new MailAddress(FromEmail);
   3: objEmail.From = FromAddress;
   4:  
   5: NetworkCredential NetworkCredential = new NetworkCredential(FromAddress.Address, "XXXXXXX");
   6: smtpclient.Credentials = NetworkCredential;
   7:  
   8: // Alternately you want you can try few different properties from MailAddress class.
   9:  
  10: Debug.WriteLine("DisplayName:  " +  FromAddress.DisplayName);
  11: Debug.WriteLine("Host:  " + FromAddress.Host);

This worked for my scenario. Happy coding.

Saturday, April 20, 2013

How to Remove Css Style from codebehind?

Here is how we can achieve this from codebhind in c#. Here is the sample code snippet I am here removing CssSytle from DIV but I works for any Control

   1: // Removing Div class when we have only transaction details
   2: divTransactionSummary.Attributes.Add("class", divTransactionSummary.Attributes["class"].ToString().Replace("prodiv", ""));
   3:               

Here “prodiv” is the class of div I have used in my aspx page for this DIV


Hope this helps!!

Saturday, March 23, 2013

SMTP Server Error: Bad sequence of commands. The server response was: you must authenticate first (#5.5.1)

This error occurs due to lock down of default mail server (127.0.0.1) by web hosting companies due to SPAM or what ever other security reasons. But if you use “localhost” or default server “127.0.0.1” on your local machine it should not be an issue. But if you have a situation where you need to relay e-mail to a remote mail server that is secured you get this exception.

So you need to handle well using built in classes provided by .NET. This is take care by NetworkCredential Class. This class provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.

Here is a fully working quick code sample that you can use to get started on your own SMTP-Authentication supporting e-mail code.

   1: try
   2: {
   3:     SmtpClient smtpclient = new SmtpClient();
   4:     NetworkCredential NetworkCredential = new NetworkCredential(smtpUserName, smtpPassword);
   5:     smtpclient.Credentials = NetworkCredential;
   6:     string MailServer = ConfigurationManager.AppSettings["SMTPServer"].ToString();
   7:     MailMessage objEmail = new MailMessage();
   8:  
   9:     string FromEmail = ConfigurationManager.AppSettings["ErrorReportEmailFrom"].ToString();
  10:     if (FromEmail.IndexOf(";") > 0)
  11:     {
  12:         FromEmail = FromEmail.Replace(";", ",");
  13:     }
  14:     MailAddress FromAddress = new MailAddress(FromEmail);
  15:     objEmail.From = FromAddress;
  16:  
  17:     string ToEmail = ConfigurationManager.AppSettings["ErrorReportEmailTo"].ToString();
  18:     if (ToEmail.IndexOf(";") > 0)
  19:     {
  20:         ToEmail = ToEmail.Replace(";", ",");
  21:     }
  22:     objEmail.To.Add(ToEmail);
  23:  
  24:     string CcEmail = ConfigurationManager.AppSettings["CcEmail"].ToString();
  25:     if (CcEmail.IndexOf(";") > 0)
  26:     {
  27:         CcEmail = CcEmail.Replace(";", ",");
  28:     }
  29:     objEmail.CC.Add(CcEmail);
  30:  
  31:     string BccEmail = ConfigurationManager.AppSettings["BccEmail"].ToString();
  32:     if (BccEmail.IndexOf(";") > 0)
  33:     {
  34:         BccEmail = BccEmail.Replace(";", ",");
  35:     }
  36:     objEmail.Bcc.Add(BccEmail);
  37:  
  38:     objEmail.Subject = strSubject;
  39:     try
  40:     {
  41:         objEmail.Body = strBody;
  42:         objEmail.IsBodyHtml = true;
  43:         smtpclient.Host = MailServer;
  44:         smtpclient.Send(objEmail);
  45:     }
  46:     catch (Exception ex)
  47:     {
  48:         throw ex;
  49:     }
  50:     finally
  51:     {
  52:         objEmail.Dispose();
  53:     }
  54: }
  55: catch (Exception ex)
  56: {
  57:      
  58: }

Enjoy coding!!

Sunday, February 17, 2013

How to Set default button from C# to a Content Page

Here is how we can use default button property of the form to set Default Button for a content page from Code behind using C#
 
// Setting default button
this.Master.Page.Form.DefaultButton = this.btnSubmit.UniqueID;
 
Here is how we can set default button for the page which doesn’t have Master Page
// Setting Default Button           
this.Page.Form.DefaultButton = btnSubmit.UniqueID;
 
Hope this helps!!

Friday, July 20, 2012

C#: How to Get Machine name of the webserver

Here is how you can do using C#,

Response.Write("machinename " +System.Environment.MachineName +"<BR>" )


This gives you name computer where your webserver is located.


If you need with the domain name here is how you can achieve using the following code snippet:


You need to import following namespace to use this,


using System.Net; 


public static string GetServerMachineName()
{
string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
string sysdn = "";
if (!hostName.Contains(domainName))
sysdn = hostName + "." + domainName;
else
sysdn = hostName;

return sysdn;
}

Happy Coding Smile