Auto Ad Code

Showing posts with label C sharp. Show all posts
Showing posts with label C sharp. 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)

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, June 5, 2012

Directory.Delete expires the session [SOLVED]

Yet another frustrating error. That when you delete a directory the session gets expired automatically.
This is a known issue and is actually a default behavior and is defined in following words.
It is the default nature if you are deleting a subdirectory within your application, your app domain will restart. This removes all session data.
How to overcome this issue?
Here are the 3 possible solutions for this issue.

Solution 1:

Make your directory outside application directory.
Here is the explanation how to use the directory which is outside. I got this solution from the given link as well.
http://stackoverflow.com/questions/502743/asp-net-deleting-a-directory-results-in-application-restart

Solution 2:

Don't delete the directory but only delete files in directory and sub directories. This will at least release the memory. Here is my function to Delete all files (and not directories). Simply call it instead of the Directory.Delete Statement.

VB

Private Sub DeleteFiles(pDirectoryPath As String)
   For Each mFile In System.IO.Directory.GetFiles(pDirectoryPath)
       System.IO.File.Delete(mFile)
   Next

   For Each mDirectory In System.IO.Directory.GetDirectories(pDirectoryPath)
       DeleteFiles(mDirectory)
   Next
End Sub

CSharp (C#)


    private void DeleteFiles(string pDirectoryPath)
{
       foreach (object mFile_loopVariable in System.IO.Directory.GetFiles(pDirectoryPath)) {
              mFile = mFile_loopVariable;
              System.IO.File.Delete(mFile);
       }

       foreach (object mDirectory_loopVariable in System.IO.Directory.GetDirectories(pDirectoryPath)) {
              mDirectory = mDirectory_loopVariable;
              DeleteFiles(mDirectory);
       }
}

I am not stealing the credits for this solution. I got the idea of this from following article and then made my own function with little bit of modifications

Solution 3:

This will work for your local system and for dedicated/virtually dedicated hosting and for only those shared hosting which allow you to run your application/website in full trust mode.
You have to add following function in your code and then have to call it before you use the Directory.Delete method.

VB

Private Sub FixAppDomainRestartWhenTouchingFiles()
        Dim p As System.Reflection.PropertyInfo = GetType(HttpRuntime).GetProperty("FileChangesMonitor", Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static)
        Dim o As Object = p.GetValue(Nothing, Nothing)
        Dim f As System.Reflection.FieldInfo = o.GetType.GetField("_dirMonSubdirs", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.IgnoreCase)
        Dim monitor As Object = f.GetValue(o)
        Dim m As System.Reflection.MethodInfo = monitor.GetType.GetMethod("StopMonitoring", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
        m.Invoke(monitor, New Object() {})
    End Sub

CSharp (C#)

    private void FixAppDomainRestartWhenTouchingFiles()
{
       System.Reflection.PropertyInfo p = typeof(HttpRuntime).GetProperty("FileChangesMonitor", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
       object o = p.GetValue(null, null);
       System.Reflection.FieldInfo f = o.GetType().GetField("_dirMonSubdirs", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.IgnoreCase);
       object monitor = f.GetValue(o);
       System.Reflection.MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
       m.Invoke(monitor, new object[]);
}

Again I won't try to steal the credits.
Here is the link from where I got this solution.
http://dotnetslackers.com/Community/blogs/haissam/archive/2008/11/12/disable-session-expiration-when-using-directory-delete.aspx

Tuesday, December 20, 2011

a generic error occurred in gdi+ [SOLVED]

Hello folks, 
If you are reading this BLOG post then either you are facing the 
"The process cannot access the file because it is being used by another process" error 
or the
"a generic error occurred in gdi+" error
while manipulating images in ASP .Net (VB .Net/C#).
The issue may appear due to  new Bitmap([IMAGE PATH]) statement 


or by the Image.FromFile([IMAGE PATH]) statement in your code where you load the image in your code. This is because GDI+ keeps a lock on files from which an image was contructed.  To avoid the lock, construct the image from a MemorySteam. That is
C Sharp (C#)
MemoryStream ms = new MemoryStream(File.ReadAllBytes([IMAGE PATH]));
Image img = Image.FromStream(ms);

VB .Net
Dim ms As MemoryStream = New MemoryStream(File.ReadAllBytes( [IMAGE PATH]))
Dim img As Image = Image.FromStream(ms)

Hope this will solve your issue and you will not receive any of the above errors.

Also don't forget to close and dispose the MemoryStream and Image after the usage else you may get the "Out of memory" error. 




Reference:

Wednesday, August 18, 2010

Disable browser back button

Sometimes we need a functionality that user should not be allowed to go to previous page using the browser back button. Most of us then try to search that how we can disable the browser back button.
A simple and straight answer is that browser's back button can not be disabled because browser resides at user's machine and not on Server. All we can do is to prevent a page for being cached. So if a page is not being cached at client then browser back button will not allow a user to navigate to that page.
What's the procedure?
Procedure is pretty much easy and described in below.
A very important thing to remember is that you have to use this code in page1 in case you want that page1 should not be available using back button of browser. i.e. use this code in that page which you want not available at browser back button.

==================================
Use following 3 lines in HEAD section (HTML view)

<meta http-equiv="cache-control" content="no-store"/>
<meta http-equiv="expires" content="0"/>
<meta http-equiv="pragma" content="no-cache"/>


use following lines in Page_Load (Code behind)
VB
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Buffer = True
Response.ExpiresAbsolute = DateTime.Now().AddDays(-1)
Response.Expires = 0
Response.CacheControl = "no-cache"



C # (C Sharp)
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now().AddDays(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";
==================================

This should solve your issue.