Auto Ad Code

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

Tuesday, August 6, 2024

Check if string is valid JSON - C# ( C sharp - Csharp )

Please use the following function. If you don't have Newtonsoft installed then you need to add Newtonsoft first. You can do this using Visual Studio 's NuGet package manage from Tools menu.

        using Newtonsoft.Json.Linq;

        private static bool IsValidJson(string strInput)
        {

            try
            {
                if (string.IsNullOrWhiteSpace(strInput))
                {
                    return false;
                }

                strInput = strInput.Trim();

                if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || (strInput.StartsWith("[") && strInput.EndsWith("]")))
                {
                    try
                    {
                        var obj = JToken.Parse(strInput);
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }


json , valid json , string , c# , c # , csharp , c sharp , invalid json

Friday, July 22, 2022

UNIX Time to DateTime - Timestamp to DateTime - C# (C Sharp)

Unix time is the number of seconds that have elapsed since the 01 January 1970 00:00:00 UTC. 

01 January 1970 00:00:00 UTC is called Unix epoch.

Following short and simple (2 liner) C# (CSharp) function will return the DateTime for the provided Unix Time (Timestamp)

Monday, July 8, 2013

5th, 10th, nth working (business) day from today (or anydate)

Here is a little piece of code using which you can calculate 5th, 10th or nth (here n can be any number) working (business) day from today (or any given date).
Note that we are assumiung that Saturday and Sunday are weekend, you can change the code if your weekend is not on Saturday, Sunday.
btnCalc is the button on which's click we are calling the function to calculate and lblDate is the label where we are showing the nth working (business) date.

C# (CSharp)
protected void btnCalc_Click(object sender, EventArgs e)
    {
        //Here I am calculating 10th working (business) day from today. You can replace the parameter 10 with your required number of working (business) day
        //Also I am calculating from today, you can give your required Date as parameter as well at the place of DateTime.Now
        lblDate.Text = calculateNthWorkingDay(10, DateTime.Now).ToString();
    }

    public DateTime calculateNthWorkingDay(int n, DateTime pFromDate) //n=Number of working day.
    {
        int mWorkingDays = 0;
        for (int i = 1; i <= n; i++)
        {
            pFromDate = pFromDate.AddDays(1);
            if (!IsWeekEnd(pFromDate))
                mWorkingDays++;
            else
                n++;
        }
        return pFromDate;
    }

    public bool IsWeekEnd(DateTime pDateTime)
    {
        bool isWeekEnd = false;
        if ((pDateTime.DayOfWeek == DayOfWeek.Saturday) || (pDateTime.DayOfWeek == DayOfWeek.Sunday))
        {
            isWeekEnd = true;
        }
        return isWeekEnd;
    }


VB.Net
Protected Sub btnCalc_Click(sender As Object, e As EventArgs)
        'Here I am calculating 10th working (business) day from today. You can replace the parameter 10 with your required number of working (business) day
        'Also I am calculating from today, you can give your required Date as parameter as well at the place of DateTime.Now
        lblDate.Text = calculateNthWorkingDay(10, DateTime.Now).ToString()
    End Sub

    Public Function calculateNthWorkingDay(n As Integer, pFromDate As DateTime) As DateTime
        'n=Number of working day.
        Dim mWorkingDays As Integer = 0
        For i As Integer = 1 To n
            pFromDate = pFromDate.AddDays(1)
            If Not IsWeekEnd(pFromDate) Then
                mWorkingDays += 1
            Else
                n += 1
            End If
        Next
        Return pFromDate
    End Function

    Public Function IsWeekEnd(pDateTime As DateTime) As Boolean
        Dim isWeekEnd As Boolean = False
        If (pDateTime.DayOfWeek = DayOfWeek.Saturday) OrElse (pDateTime.DayOfWeek = DayOfWeek.Sunday) Then
            isWeekEnd1 = True
        End If
        Return isWeekEnd1
    End Function

Tuesday, March 5, 2013

Datagrid/GridView Paging not working if set(initialize) from codebehind

Okay, here is another frustrating issue which you may face while using Datagrid or Gridview and you want to set (initialize) paging from code behind.
Your code will looks perfect to you but still paging is not functional.
Your code may look like
C#

  gvUsers.DataSource = mDtUsers; //mDtUsers is your datasource.
  gvUsers.DataBind();

  gvUsers.AllowPaging = true;
  gvUsers.PageSize = mPageSize;
  gvUsers.CurrentPageIndex = 0;


VB.Net

  gvUsers.DataSource = mDtUsers 'mDtUsers is your datasource.
  gvUsers.DataBind()

  gvUsers.AllowPaging = True
  gvUsers.PageSize = mPageSize
  gvUsers.CurrentPageIndex = 0


Everything looks fine? Yeh it do but still paging not functional. So whats the solution?

The Solution

Solution is pretty easy and straight forward and in fact you don't have to add any extra line of code, you simply have to change the sequence of statements. That means set (initialize) the paging before the binding of Datagrid/Gridview and everything will be working perfect, it means your code should be like

C#

  gvUsers.AllowPaging = true;
  gvUsers.PageSize = mPageSize;
  gvUsers.CurrentPageIndex = 0;

  gvUsers.DataSource = mDtUsers; //mDtUsers is your datasource.
  gvUsers.DataBind();



VB.Net

  gvUsers.AllowPaging = True
  gvUsers.PageSize = mPageSize
  gvUsers.CurrentPageIndex = 0

  gvUsers.DataSource = mDtUsers 'mDtUsers is your datasource.
  gvUsers.DataBind()


Hope this simnply solution will solve your problem.
Happy Coding! :)


Friday, March 1, 2013

jQuery not working in UpdatePanel

If you are reading this then this means that you are facing the same problem which I faced and the problem is that jQuery functions are not working after any of the event occurred within the Updatepanel.

I mean suppose you are showing and hiding some DIV using jQuery .show() amd .hide(), the DIV resides in an updatepanel where you have another button as well which is a server side button and calls the Server side event using AJAX (update panel), after doing your work of this button you try to show/hide the DIV but you get surprised as the jQuery function is no more being called.

You jQuery code would be like this

<script type="text/javascript" language="javascript">
  $(document).ready(function () {
      $("#btnTest").click(function () {
       $("#dvTest").show(); //Here you could be having hide/toggle/slideToggle etc etc
    });
  });
</script>

Solution
So whats the solution? Solution is very easy and simple. Use your jQuery code as following
<script type="text/javascript" language="javascript">
  $(document).ready(function () {
     $('#btnTest').live('click', function () {
        $('#dvTest').show(); //Here you could be having hide/toggle/slideToggle etc etc
        return false;
     });
  });
</script>


Hope your issue is solved?

Happy coding :)

Tuesday, December 4, 2012

[SOLVED] Dropdownlist SelectedIndexChanged (OnSelectedIndexChanged) From GridView

You may want to implement some functionality on changing index of a drop down list which is provided within a grid for multi records. I too had to do the same and searched over internet for some suitable solution. Though there are more than one solutions but the solution I am providing is most easy of them and requires no tricks.
The Solution
Note the RED BOLD code of HTML view, which means you will have to set EnableViewState="false" for the griview and also you will have to set AutoPostBack="true" for the dropdownlist.

Here is your GridView code (The HTML)


<asp:GridView runat="server" ID="gvTest" Width="50%" AutoGenerateColumns="false" EnableViewState="false">
            <Columns>
                <asp:BoundField DataField="Gender" HeaderText="Gender" HeaderStyle-HorizontalAlign="Left" />
                <asp:TemplateField >
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlTest" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlTest_SelectedIndexChanged">
                            <asp:ListItem Value="Male">Male</asp:ListItem>
                            <asp:ListItem Value="Female">Female</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>


And here is Code behind 
1. C#

protected void Page_Load(object sender, System.EventArgs e)
{
       try {
              FillGridView();
       } catch (Exception ex) {
              Response.Write(ex.Message);
       }
}

private void FillGridView()
{
       try {
              DataTable dt = new DataTable();
              dt.Columns.Add("Gender");
              DataRow dr = null;
              dr = dt.NewRow();
              dr["Gender"] = "I am a ";
              dt.Rows.Add(dr);

              gvTest.DataSource = dt;
              gvTest.DataBind();
       } catch (Exception ex) {
              Response.Write(ex.Message);
       }
}

protected void ddlTest_SelectedIndexChanged(object sender, System.EventArgs e)
{
       try {
              Response.Write("You selected " + ((DropDownList)sender).SelectedItem.Value);
       } catch (Exception ex) {
              Response.Write(ex.Message);
       }
}



2. VB.Net

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Try
            FillGridView()
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
    End Sub

    Private Sub FillGridView()
        Try
            Dim dt As New DataTable
            dt.Columns.Add("Gender")
            Dim dr As DataRow
            dr = dt.NewRow
            dr("Gender") = "I am a "
            dt.Rows.Add(dr)

            gvTest.DataSource = dt
            gvTest.DataBind()
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
    End Sub

    Protected Sub ddlTest_SelectedIndexChanged(sender As Object, e As System.EventArgs)
        Try
            Response.Write("You selected " & CType(sender, DropDownList).SelectedItem.Value)
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
    End Sub


Wednesday, September 12, 2012

[SOLVED] Mailbox name not allowed. The server response was: sorry, your mail was administratively denied.

If your website is hosted at Godaddy.com then you may face this error while using SMTP.

Mailbox name not allowed. The server response was: sorry, your mail was administratively denied. (#5.7.1)

Whats the reason? And he solution.
the only reason of this error is that Godaddy only allows those email addresses in FROM clause which are from same domain.
Suppose your domain is mydomain.com then only those Mails will be sent which are having an Email address in their FROM clause which is from mydomain.com. Its not must that the email address should exist. You can use imaginary mail address like noreply@mydomain.com etc etc. The only restriction is that the email address should be of same domain.

Let us suppose your domain is mydomain.com
C#


MailMessage mMailMessage = new MailMessage(new MailAddress("noreply@mydomain.com", "No Reply"), new MailAddress("anybody@testdomain.com", "Test User"));
mMailMessage.Subject = "Email Subject";
string mEmailBody = "Email Body";
mMailMessage.Body = pEmailBody;
mMailMessage.IsBodyHtml = true;
SmtpClient mSMTPClient = new SmtpClient("relay-hosting.secureserver.net", 25);
mSMTPClient.Send(mMailMessage);
mMailMessage.Dispose();



VB.Net


Dim mMailMessage As MailMessage = New MailMessage(New MailAddress("noreply@mydomain.com", "No Reply"), New MailAddress("anybody@testdomain.com", "Test User"))
mMailMessage.Subject = "Email Subject"
Dim mEmailBody As String = "Email Body"
mMailMessage.Body = pEmailBody
mMailMessage.IsBodyHtml = True
Dim mSMTPClient As SmtpClient = New SmtpClient("relay-hosting.secureserver.net", 25)
mSMTPClient.Send(mMailMessage)
mMailMessage.Dispose()