Welcome to Adi's Web World

Good things don't come to those who wait; they come to the people who go out and try to get them.

Home
Pictures
Video Collection
Fun Zone
Blogs
Lafayette
pixGENE
Contact Me
Site Map
BLOG's
Aditya's Blog - My own personal blog.
March 04

Custom Paper Size & Orientation Problem in Crystal Reports 2008

I had a situation where I had to print shipping labels from a label printer. I created a report using crystal reports with No Printer option checked and Dissociate Formatting Page Size and Paper Size option checked since I had to print on a paper with custom size (4”X2.3”).

When I tried to print the report from ASP.NET using ReportDocument.PrintToPrinter method it would take the default paper size of the printer which in my case was 3.5”X1”. To set the paper size to the custom size mentioned above following code helped me solve the problem.

ReportDocument oRpt = new LabelReport() // here LabelReport is the name of the report
or you can load the report with the following statement also
ReportDocument oRpt = new ReportDocument();
oRpt.Load(Server.MapPath(“LabelReport.rpt”));
PrintOptions boPrintOptions = oRpt.PrintOptions;
// The paper size used for this report is '4x2.3'.
string PrinterName = " "; //put in your printer name here.
System.Drawing.Printing.PrinterSettings oPrinterSettings = new System.Drawing.Printing.PrinterSettings();
oPrinterSettings.PrinterName = PrinterName;
foreach (System.Drawing.Printing.PaperSize oPaperSize in oPrinterSettings.PaperSizes)
{
if ("30256 Shipping" == oPaperSize.PaperName)
// “30256 Shipping” is the paper type. You can find the available paper types in the printer properties shown below
{
       boPrintOptions.PaperSize = (CrystalDecisions.Shared.PaperSize) oPaperSize.RawKind;
       break;
}
}
CrystalReportViewer1.ReportSource = oRpt;
oRpt.PrintOptions.PrinterName = PrinterName;
oRpt.PrintToPrinter(1, false, 0, 0);
 

image



2:16 PM GMT  |  Read comments(0)

February 18

Convert table to CSV string in SQL Server

There doesn’t seem to be a native function in SQL Server to collapse a table of row values into a comma-separated string, for example:

Animal
Llama
Manatee
Pygmy Marmoset
Okapi

Result CSV: “Llama, Manatee, Pygmy Marmoset, Okapi”

In mySQL there’s a built-in aggregate function called group_concat, but no equivalent in SQL Server unless you build your own .NET function, like in this TechNet article Invoking CLR User-Defined Aggregate Functions. That’s quite a chunk of coding and is restricted to SQL Server 2005 or later, so here’s a handy SQL snippet that does a similar job without the fuss.

select Name from Animal

declare @csv varchar(max)
select @csv = coalesce(@csv + ‘, ‘, ”) + Name from Animal
select @csv

If you use the code regularly then consider creating a scalar user-defined function (UDF) that returns the CSV string as varchar.

Note that the string being appended to @csv above -> ‘, ‘, ” is:
1) a single quote
2) a comma
3) a space
4) a single quote
5) a comma
6) a space
7) two single quotes

NOTE: single quotes are used to delimit strings in SQL



1:29 PM GMT  |  Read comments(0)

April 27

VS 2005 Debugger crashing with IE 8

IE 8 has a feature called Loosely-Coupled Internet Explorer (LCIE) which results in IE running across multiple processes.
http://www.microsoft.com/windows/internet-explorer/beta/readiness/developers-existing.aspx#lcie
Older versions of the Visual Studio Debugger get confused by this and cannot figure out how to attach to the correct process.  You can work around this by disabling the process growth feature of LCIE.  Here's how:
1)  Open RegEdit
2)  Browse to HKEY_LOCALMACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main
3)  Add a dword under this key called TabProcGrowth
4)  Set TabProcGrowth to 0
If you run into the same problem on Vista or newer, turn off protected mode.

3:39 PM GMT  |  Read comments(0)

August 08

How Long Until My Password Expires?

Here is a quick and dirty way to figure out when your account (or anyone else's) will expire on the domain.
Prerequisites:
1.  You must be running this from a computer joined to the domain.
2.  You must be running this with valid domain credentials.

How does it work:
There is no attribute that directly holds when your password expires.  It is a calculation done based on two factors -

1. When you last set your password (pwdLastSet), and

2. What your domain policy for the maximum password age (MaxPwdAge) is.

Here is a simple command line app to demonstrate how this is done:

using System;
using System.DirectoryServices;
using System.Reflection;
class Invoker
{
    [STAThread]
    static void Main(string[] args)
    {
        try
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: {0} username", Environment.GetCommandLineArgs()[0]);
                return;
            }
            PasswordExpires pe = new PasswordExpires();
            Console.WriteLine("Password Policy: {0} days", 0 - pe.PasswordAge.Days);
            TimeSpan t = pe.WhenExpires(args[0]);
            if(t == TimeSpan.MaxValue)
                Console.WriteLine("{0}: Password Never Expires", args[0]);
            else if(t == TimeSpan.MinValue)
                Console.WriteLine("{0}: Password Expired", args[0]);
            else
                Console.WriteLine("Password for {0} expires in {1} days at {2}", args[0], t.Days, DateTime.Now.Add(t));
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString()); //debugging info
        }
    }
}
class PasswordExpires
{
    DirectoryEntry _domain;
    TimeSpan _passwordAge = TimeSpan.MinValue;
    const int UF_DONT_EXPIRE_PASSWD            = 0x10000;
    public PasswordExpires()
    {
        //bind with current credentials
        using (DirectoryEntry root = new DirectoryEntry("LDAP://rootDSE", null, null, AuthenticationTypes.Secure))
        {
            string adsPath = String.Format("LDAP://{0}", root.Properties["defaultNamingContext"][0]);
            _domain = new DirectoryEntry(adsPath, null, null, AuthenticationTypes.Secure);
        }
    }
    public TimeSpan PasswordAge
    {
        get
        {
            if(_passwordAge == TimeSpan.MinValue)
            {
                long ldate = LongFromLargeInteger(_domain.Properties["maxPwdAge"][0]);
                _passwordAge =  TimeSpan.FromTicks(ldate);
            }
            
            return _passwordAge;
        }
    }
    public TimeSpan WhenExpires(string username)
    {
        DirectorySearcher ds = new DirectorySearcher(_domain);
        ds.Filter = String.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", username);
        SearchResult sr = FindOne(ds);
        int flags = (int)sr.Properties["userAccountControl"][0];
        if(Convert.ToBoolean(flags & UF_DONT_EXPIRE_PASSWD))
        {
            return TimeSpan.MaxValue; //password never expires
        }
        //get when they last set their password
        DateTime pwdLastSet = DateTime.FromFileTime((long)sr.Properties["pwdLastSet"][0]);
        
        if(pwdLastSet.Subtract(PasswordAge).CompareTo(DateTime.Now) > 0)
        {
            return pwdLastSet.Subtract(PasswordAge).Subtract(DateTime.Now);
        }
        else
            return TimeSpan.MinValue;  //already expired
    }
    private long LongFromLargeInteger(object largeInteger)
    {
        System.Type type = largeInteger.GetType();
        int highPart = (int)type.InvokeMember("HighPart",BindingFlags.GetProperty, null, largeInteger, null);
        int lowPart  = (int)type.InvokeMember("LowPart",BindingFlags.GetProperty, null, largeInteger, null);
            
        return (long)highPart << 32 | (uint)lowPart;
    }
    private SearchResult FindOne(DirectorySearcher searcher)
    {
        SearchResult sr = null;
        using (SearchResultCollection src = searcher.FindAll())    
        {
            if(src.Count>0)
            {
                sr = src[0];
            }
        }
        return sr;
    }
}
 
References: 
  1. http://msdn.microsoft.com/en-us/library/ms974598.aspx
  2. http://dunnry.com/blog/WhenDoesMyPasswordExpire.aspx


11:53 AM GMT  |  Read comments(1)

July 01

ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

SYMPTOMS

If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception.

CAUSE

The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.
This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

RESOLUTION

To work around this problem, use one of the following methods:

  • For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
  • For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example: Response.Redirect ("nextpage.aspx", false);
    If you use this workaround, the code that follows Response.Redirect is executed.
  • For Server.Transfer, use the Server.Execute method instead.

Reference: http://support.microsoft.com/kb/312629/EN-US/



1:05 PM GMT  |  Read comments(0)

 
Scott Guthrie's Blog - For all those people working in .NET Technologies this blog would be really helpful in learnign TIPS & TRICKS in .NET Technology.
 
Socratees Blog - Lot of new stuff posted in this blog.