Thursday, November 28, 2013

How to get the number of weeks in a month?




Recently I were in a need to findout and print the number of weeks in a given month. For sometime I was totally confused how can i do this.
I belive in approach called discuss and find solution of your problem. I applied the same approach, I called some of my juniors and told them the problem "How to find number of weeks in a given months and print the week start date and week end date?"
They all started working on the problem but none of them could come up with a solution, finally I told them, let me share you something with regards to this problem. I told them something and discussed with them. I left for the lunch, when I was coming back to office, immediately whatever I discussed with my collegues i tried implementing it.
The idea was successfull and I implemented the solution and called my collegues, see this is the solution.
I am just providing you the code, it might be useful for certain functionality life timesheet etc.

Working with HttpContext

The static property Current on the HttpContext class can be useful whenever the flow of control leaves the code in your Page derived web form. Using this property you can reach out and magically grab the current Request, Response, Session, and Application objects (and more) for the request you are servicing. Take the following code as an example.

private void Page_Load(object sender, System.EventArgs e)
{
MyClass myClass = new MyClass();
myClass.DoFoo();
}
And - in some other assembly…
class MyClass
{
public void DoFoo()
{
HttpContext.Current.Response.Write("Doing Foo");
}
}
The ability to grab the context for the current request from any code inside the same application domain is powerful, but can also be misused. You can break the boundaries of your architectural layers using HttpContext.Current from a business object, and easily tie classes to ASP.NET that would otherwise work without change in Windows Forms or on a PDA with the Compact Framework.

The curious among us will wonder just how HttpContext.Current can find the context for the current request. In addition, does it always find the current request? For example, what is the behavior in the following code?

private void Page_Load(object sender, System.EventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork));
}

public void DoWork(object state)
{
HttpContext context = HttpContext.Current;
context.Response.Write("Do Work");
}
Answer: the above code generates a System.NullReferenceException because HttpContext.Current returns null. From a design point of view there are at least two problems in the above code, but let’s see how HttpContext.Current works before we discuss them.

A quick peek with a decompiler shows the implementation for the Current property looks something like the following.

public static HttpContext get_Current()
{
return (CallContext.GetData("HtCt") as HttpContext);
}
The CallContext provides a service extremely similar to thread local storage (except CallContext can perform some additional magic during a remoting call). Thread local storage is a concept where each logical thread in an application domain has a unique data slot to keep data specific to itself. Threads do not share the data, and one thread cannot modify the data local to a different thread. ASP.NET, after selecting a thread to execute an incoming request, stores a reference to the current request context in the thread’s local storage. Now, no matter where the thread goes while executing (a business object, a data access object), the context is nearby and easily retrieved.

Knowing the above we can state the following: if, while processing a request, execution moves to a different thread (via QueueUserWorkItem, or an asynchronous delegate, as two examples), HttpContext.Current will not know how to retrieve the current context, and will return null. You might think one way around the problem would be to pass a reference to the worker thread, like the following example.

private void Page_Load(object sender, System.EventArgs e)
{
WorkerClass2 worker = new WorkerClass2();
ThreadPool.QueueUserWorkItem(new WaitCallback(worker.DoWork), HttpContext.Current);
}

//…

class WorkerClass2
{
public void DoWork(object state)
{
HttpContext context = state as HttpContext;
Thread.Sleep(15000);
context.Response.Write("Request.Url = " + context.Request.Url);
}
}
However, in my environment the above code also throws an exception, albeit this time from the depths of mscoree. Both the above code and the first example with QueueUserWorkItem suffer from another flaw: both can outlive the lifetime of the page request, and also the valid lifetime of the HttpContext object assigned to that page request. While we can keep a reference to the HttpContext of any request to prevent the garbage collector from taking it, the ASP.NET runtime is certainly free to clear some of the resources as soon as the page request has finished processing. I don’t believe there is anyway to say exactly what will happen with the above code, on some machines in different circumstances the code may actually work, but the chance of failure certainly exists and the condition should be avoided.

There are ways to guarantee the page request does not finish until the worker thread completes its work, for example, the following code.

private void Page_Load(object sender, System.EventArgs e)
{
WorkerClass worker = new WorkerClass(_resetEvent);
ThreadPool.QueueUserWorkItem(new WaitCallback(worker.DoWork),
HttpContext.Current);
try
{
_resetEvent.WaitOne();
}
finally
{
_resetEvent.Close();
}
}

AutoResetEvent _resetEvent = new AutoResetEvent(false);



class WorkerClass
{
public WorkerClass(AutoResetEvent resetEvent)
{
_resetEvent = resetEvent;
}

public void DoWork(object state)
{
try
{
HttpContext context = state as HttpContext;
Thread.Sleep(500);
context.Response.Write("Do work");
}
finally
{
_resetEvent.Set();
}
}

AutoResetEvent _resetEvent = null;
}
The above code functions correctly and “Do work” appears in the browser. However, there are still some design points to ponder. First, the ASP.NET runtime processes multiple requests using a finite number of threads. We have just completed the same amount of work, but we’ve doubled the number of threads required, generated additional context switches, and now have a synchronization primitive to manage. If you can perform additional work in the original thread while waiting for the worker task to finish, then there might be a benefit. Generally, however, you should approach the idea of using additional threads in ASP.NET with a certain amount of reservation.

In this article we’ve gained some insight into how HttpContext.Current works, and seen some scenarios where we need to exercise caution. Don’t abuse the power HttpContext.Current gives you, and examine your design and architecture whenever the call appears inside your code.



Update: Fritz Onion has an excellent article on MSDN: Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code.

To set the focus on a control like Textbox when the page loads.


1) Make a field readonly:
txtName.Attributes.Add("readonly", "readonly")

2) Keyboard enter button is pressed in the textbox and fire an event:
This is done to ensure that when the keyboard enter button is pressed in the textbox we fire the "imgBtnSearch" click event
txtAccountNumber.Attributes.Add("onkeypress", "return WebForm_FireDefaultButton(event, '" + imgBtnSearch.ClientID + "')")

3) To set the focus on a control like Textbox when the page loads.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "focus", "setTimeout(""try{ document.getElementById('" & txtApplicationNumber.ClientID & "').focus(); } catch(err){}"", 1200);", True)

4) To directly access the key and value of the resource file.
lblApplicationNumber.Text = GetGlobalResourceObject("xxx ", "ApplicationNumber") ////Where Main refers for a file "xxx.resx"


5) To disable controls of a form/page
For Each ctrl As Control In Me.Controls
                Me.EcollManager.DisableControl(ctrl)
            Next

// Below is the method definition
Public Sub DisableControl(ByVal ctrl As Control)
        For Each subctrl As Control In ctrl.Controls
            DisableControl(subctrl)
        Next

        If TypeOf ctrl Is TextBox Then
            CType(ctrl, TextBox).Enabled = True
            CType(ctrl, TextBox).ReadOnly = True
        ElseIf TypeOf ctrl Is RadioButtonList Then
            CType(ctrl, RadioButtonList).Enabled = False
        ElseIf TypeOf ctrl Is CheckBox Then
            CType(ctrl, CheckBox).Enabled = False
        ElseIf TypeOf ctrl Is RadioButton Then
            CType(ctrl, RadioButton).Enabled = False
        End If
    End Sub



Thanks and Regards,
Ashraf



Decimal byte array constructor requires an array of length four containing valid decimal bytes.

This error was very surprising for me. I spent couple of hours with my friends and even search a lot on internet to quikly fix this problem but I could not solved.
Finally I asked one of my senior and he fixed it in a second because he has faced this issue before.
Scenario: I wrote a query which consists of a column returning value like
select avg(tat) from employee.
It was returning values like
12.397339
2.00303
12.9800122
Note: This query was running perfectly in TOAD, SQL Developer while executed at Oracle Server.
When I executed the query in .Net and bind the result to the dataset, i started getting the above exception. I was so much frustrated why it is not executed in .Net when in Oracle the same query is executed.
Reason: Dataset does not support the binding of a value having more than 2 decimal places. So I have to round the values to two decimal places.
Solution: select round(avg(tat),2) from employee
Note: You might also get the message as Accessor is not a parameter accessor.
The reason if the same what I discussed here.

Thread: ORA-01795, limit on in clause

I would like to share that Oracle 10g has a limit on in clause, therefore you can only have maximum of 1000 expressions inside a in clause.
Example.
You might come accross such situtaion sometime when passing employee Ids as string inside the in clause.
Select name from temployee where Id in ('1','2','3',.....'10000')
Cause: The performance of this query will be very slow and if the number of employee ids limit reached, the oracle server will throw an error message.
Suggestions:
1) Avoid using in clause, use exists clause which is better in performance.
2) Use sub query instead of using in clause and passing id's as string
Example;
Select name from temployee where Id in (select Id from tUsers)
This will work perfectly and performance of the query will be better than the IN and EXISTS clause.
Any suggestions, please comment.

Writing to Existing PDF Templates using itextSharp.


Recently I was in need of writing to existing Pdf files. I thought of using itextsharp library in order to do the Pdf files manipulations.
A useful file can be downloaded from http://www.manning.com/lowagie2/samplechapter6.pdf
PdfReader  - Reading the existing Pdf document
PdfStamper - Starts the process of adding extra content to an existing PDF document keeping the 
document PDF/A conformant. 
PdfContentByte - PdfContentByte is an object containing the user positioned text and graphic 
contents of a page. It knows how to apply the proper font encoding.
 
Below is Example Code:
private void WriteToPdfFile(string sourceFile, string destinatationFile)
{
// Reading the source file template supplied
PdfReader reader = new PdfReader(sourceFile);
//Create the destication file supplied
PdfStamper stamper = new PdfStamper(reader, new 
FileStream(destinatationFile, FileMode.Create));
// Get the Page1 and Page2 Content -  Graphical state of the page
PdfContentByte page1 = stamper.GetOverContent(1); 
PdfContentByte page2 = stamper.GetOverContent(2); 
// Declare the Font Size
Font courier10 = new Font(Font.FontFamily.COURIER, 10f);
Font Cambria12 = FontFactory.GetFont("Cambria", 12f);
int xPosition = 30;
int yPosition = 720;
// Writing the content to specific position
ColumnText.ShowTextAligned(page1, Element.ALIGN_LEFT, 
new Phrase("Hello iTextSharp", courier10), xPosition, yPosition, 0);
// setting the file compression to file size is reduced
stamper.SetFullCompression();
stamper.Close();
reader.Close();
}
 
// Please return to me in case you find any problem.