Auto Ad Code

Showing posts with label VB. Show all posts
Showing posts with label VB. Show all posts

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

Thursday, August 9, 2012

No mapping specified for the following EntitySet/AssociationSet

You can get this error when you have generated your Entity Model from a database.
This error means that due to any issue (update/delete etc) the Entity mappings are not same as the Database.

Solution

There can be seen many solutions to this problem over internet but the best solution as far as I know is
1. Double Click the edmx file to open the Entity Model in design view.
2. Press Ctrl A to select all objects within Entity Model.
3. Now press Delete to delete all objects.
4. Again generate your Entity model from Database using "Update Model from Database" option given in context menu (Right Click).
5. All done.

Hope this will help.


Happy Coding :)

Wednesday, June 6, 2012

Copy Directory without using Directory.Move [SOLVED]

Following function will copy a directory/folder from one place to another without using Directory.Move.
Q: Why we need following function if Directory.Move is there?
A: Because Directory.Move expires(deletes) the session whenever you use it.

VB


Private Sub CopyDirectory(pSourcePath As String, pDestinationPath As String)
        For Each dirPath As String In Directory.GetDirectories(pSourcePath, "*", SearchOption.AllDirectories)
            Directory.CreateDirectory(dirPath.Replace(pSourcePath, pDestinationPath))
        Next

        For Each newPath As String In Directory.GetFiles(pSourcePath, "*.*", SearchOption.AllDirectories)
            File.Copy(newPath, newPath.Replace(pSourcePath, pDestinationPath))
        Next
    End Sub


C#

    private void CopyDirectory(string pSourcePath, string pDestinationPath)
{
       foreach (string dirPath in Directory.GetDirectories(pSourcePath, "*", SearchOption.AllDirectories)) {
              Directory.CreateDirectory(dirPath.Replace(pSourcePath, pDestinationPath));
       }

       foreach (string newPath in Directory.GetFiles(pSourcePath, "*.*", SearchOption.AllDirectories)) {
              File.Copy(newPath, newPath.Replace(pSourcePath, pDestinationPath));
       }
}

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

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.

Monday, July 12, 2010

Default Button (Enter Key)

Many of us faces the issue that while typing in a textbox we press Enter and expect a button named "A" to be clicked but this doesn't happens and button "B" gets clicked.
For example you have provided a Textbox for Search and a button is given with that textbox so that when that button will be clicked your code will try to search in database for whatever written in Textbox. You expect that when user will press enter while typing in Textbox then search button will be clicked by default but this doesn't happen and instead soneother button (like login etc) get clicked. Pretty much annoyiong is this and even tab sequence don't work here.
Whats the solution?
Its pretty much easy which is to add yout HTML code for that textbox and button withing a <asp:Panel. There is a property named "DefaultButton" for <asp:Panel. You can write ID of your button in the "DefaultButton" property of <asp:Panel. Now whenever Enter key will be pressed in any textbox contained in that <asp:Panel then that button will be clicked whose ID is given against "DefaultButton" property of <asp:Panel.

Sample code
<asp:Panel runat="server" ID="pnlChild" DefaultButton="ButtonID">
    YOUR HTML CODE Including the Button to be Clicked
</asp:Panel>