How To Implement Custom Rounding Procedures
There are a number of different rounding algorithms available in Microsoft products. Rounding algorithms range from Arithmetic Rounding in Excel’s Worksheet Round() function to Banker’s Rounding in the CInt(), CLng(), and Round() functions in Visual Basic for Applications.
The Round() function is not implemented in a consistent fashion among different Microsoft products for historical reasons.
I had an issue where in my .net code the number would be round down and in sql server the number would be round up. so I set out to write my own algorithm.
Friend Function Round(ByVal val As Decimal, ByVal Count As Integer) As Decimal
Dim retVal As Decimal = 0.0
Dim value As String = val
If Not String.IsNullOrEmpty(value) Then
Dim lenghtOfString As Integer = value.Length
Dim IndexOfPoint As Integer = value.IndexOf(“.”)
If IndexOfPoint > 0 Then
Dim ValueBeforePoint As String = value.Substring(0, IndexOfPoint)
Dim ValueAfterPoint As String = value.Remove(0, IndexOfPoint + 1)
Dim LenghtOfAfterPoint As Integer = ValueAfterPoint.Length – 1
Dim newValue As Integer
If LenghtOfAfterPoint + 1 <= Count Then
retVal = ValueBeforePoint & “.” & ValueAfterPoint
Else
For i As Integer = LenghtOfAfterPoint To 0 Step -1
Dim strchar As String = ValueAfterPoint(i)
If strchar >= “5″ Then
‘Increase next value
Dim NextValue As String = ValueAfterPoint(i – 1)
newValue = CInt(NextValue) + 1
Dim indexOfNextVal As Integer = ValueAfterPoint.LastIndexOf(NextValue)
If indexOfNextVal = ValueAfterPoint.Length – 1 Then
indexOfNextVal = indexOfNextVal – 1
End If
ValueAfterPoint = ValueAfterPoint.Remove(indexOfNextVal, 2)
ValueAfterPoint = ValueAfterPoint.Insert(indexOfNextVal, newValue)
Else
‘decrease next values
Dim NextValue As String = ValueAfterPoint(i – 1)
newValue = CInt(NextValue)
Dim indexOfNextVal As Integer = ValueAfterPoint.LastIndexOf(NextValue)
If indexOfNextVal = ValueAfterPoint.Length – 1 Then
indexOfNextVal = indexOfNextVal – 1
End If
ValueAfterPoint = ValueAfterPoint.Remove(indexOfNextVal, 2)
ValueAfterPoint = ValueAfterPoint.Insert(indexOfNextVal, newValue)
End If
If ValueAfterPoint.Length = Count Then
retVal = ValueBeforePoint & “.” & ValueAfterPoint
Exit For
End If
Next
End If
Else
retVal = val
End If
End If
Return retVal
End Function
How to count # of character occurrences in a string .NET vERSION
A quick way to find the number of occurrences of a character in a string could go something as shown below.
Dim x As String = “aa:bb:cc:dd”
How to count # of character occurrences in a string
A quick and dirty way would be to use an expression like
length(x) – length(replace(x, “:”, “”))
Here’s some code that I actually ran:
set @x = “aa:bb:cc:dd”;
set @colons = length(@x) – length(replace(@x, “:”, “”));
select @x , @colons;
Example 2:
try to count how many times p appears in word ‘Mississippi’
select len(‘Mississippi’) – len(replace(‘Mississippi’, ‘p’, ”))
Easier way to manage your ASP.NET Cache
I was recently told by a client of mine that the ASP.NET app I developed was WAY TOO SLOW! I had to agree; the site was pinging the database twice on every load of the home page. So I said, “Give me a week… I’ll make it work better”. I went home feeling bad… my app was slow and I really didn’t know where to begin. I had a lot of code that depended on pinging the database and I didn’t want to sift through it all. What I ended up doing was using the cache object.
I started to look at other open source projects and their approaches to caching. Than DotNetKicks’ cache manager caught my eye! I went off that idea and created my own way of implementing an object to interface with the cache object, making it more manageable.
The Cache manager I wrote has 3 methods (Grab, insert, clear), a constructor and 2 properties (CacheKey, CacheDuration). So here’s my code in VB and C#:
using System.Web;
using System.Web.Caching;
namespace MainSite.Cache
{
public class CacheManager<T>
{
private string m_cachekey = “”;
public string CacheKey {
get { return m_cachekey; }
set { m_cachekey = value; }
}
private int m_cacheduration;
public int CacheDuration {
get { return m_cacheduration; }
set { m_cacheduration = value; }
}
public CacheManager(string Key, int duration)
{
this.CacheKey = Key;
this.CacheDuration = duration;
}
public T Grab()
{
return (T)HttpContext.Current.Cache(this.CacheKey);
}
public void Insert(T obj, System.Web.Caching.CacheItemPriority priority)
{
DateTime expiration = DateTime.Now.AddMinutes(this.CacheDuration);
HttpContext.Current.Cache.Add(this.CacheKey, obj, null, expiration, TimeSpan.Zero, priority, null);
}
public void Clear()
{
HttpContext.Current.Cache.Remove(this.CacheKey);
}
}
}
So what I do is create a class and have a grab method that makes an instance of the cache manager object and calls the cache manager class’ grab method. If the cache returns null, I have a private method in my class that does the nesessary things to put the info into the cache object. Here’s an example:
namespace MainSite.Cache
{
public class ReviewsCache
{
public static ReviewsCollection Grab()
{
CacheManager<ReviewsCollection> man = new CacheManager<ReviewsCollection>(GetKey(), 90);
ReviewsCollection cont = man.Grab();
if (cont == null) cont = Insert(man);
return cont;
}
private static ReviewsCollection Insert(CacheManager<ReviewsCollection> man)
{
ReviewsCollection cont = MainSite.Logic.Reviews.GetAll();
man.Insert(cont, Web.Caching.CacheItemPriority.Default);
return cont;
}
public static void Delete(string sectionname)
{
CacheManager<ReviewsCollection> man = new CacheManager<ReviewsCollection>(GetKey(), 90);
man.Clear();
}
private static string GetKey()
{
return “Reviews”;
}
}
}
The cache object is a great thing to utilize in ASP.NET. But to make the caching manageable, you need to have a structure for managing the cache object and add logic to delete, grab, etc. Interfacing with a class is easier and follows the MVC pattern better than just saying Cache["MyKey"] in your logic or UI.
Working with Dates and Time in ASP.NET
First we set the initial DateTime variable as follows:
Dim dtNow As DateTime = DateTime.Now
Now we can use this variable to manipulate today’s date to give us the exact format that we need.
| 6/25/2008 |
| litDate.Text = dtNow.Date |
| 6/25/2008 |
| litToday.Text = dtNow.Today |
| 6/25/2008 |
| litToShortDateString.Text = dtNow.ToShortDateString |
| 8:26 AM |
| litToShortTimeString.Text = dtNow.ToShortTimeString |
| Wednesday, June 25, 2008 |
| litToLongDateString.Text = dtNow.ToLongDateString |
| 8:26:46 AM |
| litToLongTimeString.Text = dtNow.ToLongTimeString |
| 6/25/2008 1:26:46 PM |
| litToUniversalTime.Text = dtNow.ToUniversalTime |
| 177 |
| litDayOfYear.Text = dtNow.DayOfYear |
| 3 |
| litDayOfWeek.Text = dtNow.DayOfWeek |
| 6 |
| litDay.Text = dtNow.Month |
| 25 |
| litDay.Text = dtNow.Day |
| 2008 |
| litDay.Text = dtNow.Year |
| 6/26/2008 8:26:46 AM |
| litAddDays.Text = dtNow.AddDays(1) |
| 6/25/2008 9:26:46 AM |
| litAddHours.Text = dtNow.AddHours(1) |
| 6/25/2008 8:26:56 AM |
| litAddMilliseconds.Text = dtNow.AddMilliseconds(10000) |
| 6/25/2008 8:27:46 AM |
| litAddMinutes.Text = dtNow.AddMinutes(1) |
| 7/25/2008 8:26:46 AM |
| litAddMonths.Text = dtNow.AddMonths(1) |
| 6/25/2008 8:26:47 AM |
| litAddSeconds.Text = dtNow.AddSeconds(1) |
| 6/26/2008 12:13:26 PM |
| litAddTicks.Text = dtNow.AddTicks(1000000000000) |
| 6/25/2009 8:26:46 AM |
| litAddYears.Text = dtNow.AddYears(1) |
| 6/24/2008 8:26:46 AM |
| litAddNegDays.Text = dtNow.AddDays(-1) |
| 6/25/2007 8:26:46 AM |
| litAddNegYears.Text = dtNow.AddYears(-1) |
How to invoke events across User Controls in ASP.NET
I want my code to avoid all the middle men, to be foolproof with clear and visible usage, and to be simple to use. That suggests we should declare our events the usual way, all listeners should register themselves the usual way, there should be no more than one line of code to forward the event, and the forwarding should happen once.
So we need something to expose the events and methods to invoke them:
- Events and notification methods come in pairs.
- Notifiers and listeners use the same object.
- The object will keep track of the event handler delegates in
Context.Items.
In the provided code, I have one User Control with two buttons to invoke events, and another User Control to receive them. I used a regular Button and an ImageButton to demonstrate event handlers with different argument types.
The sender control uses the following code to invoke the events:
private ButtonEvents events; private void Page_Load (object sender, EventArgs e) { events = new ButtonEvents(Context.Items); } private void uxButton_Click (object sender, EventArgs e) { events.ClickButton(sender, e); } private void uxImage_Click (object sender, ImageClickEventArgs e) { events.ClickImageButton(sender, e); }
The receiver control uses this code to register to those events:
private void Page_Load (object sender, EventArgs e) { ButtonEvents events = new ButtonEvents(Context.Items); events.ImageButtonClicked += new ImageClickEventHandler(events_ImageButtonClicked); events.ButtonClicked += new EventHandler(events_ButtonClicked); }
The ButtonEvents class needs a little more work than usual to implement, but not much:
internal class ButtonEvents { private CachedEvent buttonEvent; private CachedEvent imageButtonEvent; public ButtonEvents (IDictionary items) { buttonEvent = new CachedEvent(items, "Button"); imageButtonEvent = new CachedEvent(items, "ImageButton"); } public event ImageClickEventHandler ImageButtonClicked { add { imageButtonEvent.Add(value);} remove { imageButtonEvent.Remove(value);} } public event EventHandler ButtonClicked { add { buttonEvent.Add(value);} remove { buttonEvent.Remove(value);} } public void ClickButton (object sender, EventArgs e) { buttonEvent.Invoke(sender, e); } public void ClickImageButton (object sender, ImageClickEventArgs e) { imageButtonEvent.Invoke(sender, e); } }
The ButtonEvents class makes use of the CachedEvent helper object. This is the object which implements the real solution. The CachedEvents takes a dictionary and a key in its constructor, so it knows where to store the event handlers. The event handlers are delegates, and are stored as such:
public CachedEvent (IDictionary items, object key) { this.items = items; this.key = key; } private Delegate Listeners { set { items [key] = value; } get { return (Delegate) items [key]; } }
There are two helper methods to register and unregister event listeners:
public void Add (MulticastDelegate newListener) { Listeners = Delegate.Combine(Listeners, newListener); } public void Remove (MulticastDelegate formerListener) { Listeners = Delegate.Remove(Listeners, formerListener); }
And finally, the method to invoke the event:
public void Invoke (object sender, EventArgs arguments) { Delegate listeners = Listeners; if (listeners != null) listeners.DynamicInvoke(new object[] {sender, arguments}); }
HttpCacheVaryByParams Class
Provides a type-safe way to set the VaryByParams property.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(False)
Response.Cache.VaryByParams(“Category”) = True
If Response.Cache.VaryByParams(“Category”) Then
‘…
End If
-
Recent
- How To Implement Custom Rounding Procedures
- How to count # of character occurrences in a string .NET vERSION
- How to count # of character occurrences in a string
- Easier way to manage your ASP.NET Cache
- Working with Dates and Time in ASP.NET
- How to invoke events across User Controls in ASP.NET
- HttpCacheVaryByParams Class
-
Links
-
Archives
- July 2009 (1)
- February 2009 (2)
- June 2008 (3)
- December 2007 (1)
-
Categories
-
RSS
Entries RSS
Comments RSS