Tuesday, March 29, 2011

Malformed container error in IMail server

Ah... symantec decided to start marking random emails sent through ipswitch as virus...and i was alarmed..

This was the solution on IPSwitch site

This happens when something in the message did not conform to one of the RFC's for MIME Encoding. These RFC's are 2045-2049. This is usually caused by a mail client that is improperly formatting the message. There are two options to remedy the issue. You can disable the "Malformed Container Processing" or determine a way to compose the message in a way that formats the message properly. This may mean using a different client or contacting the mail client vendor.
To disable Malformed Container Processing, follow the steps below:
1.) On the server, open https://localhost:8004  in a browser.
2.) Log in with the password created during installation, otherwise click in the password field and press the enter key.
3.) Click on the "Policies" icon on the left.
4.) Click "Filtering" located in the margin.
5.) Click on the "Container Handling" tab.
6.) In the "Malformed Container File Processing" section, uncheck the "Block malformed containers."
7.) Click Apply icon, (brown arrow, second icon in upper left corner).

But the world is not that eazy... the JRE refused to run the applet needed for antivirus interfacel...
load: class com.symantec.gui.guidelines.ScanEngineApplet not found.
java.lang.ClassNotFoundException: com.symantec.gui.guidelines.ScanEngineApplet
        at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
        at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
        at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: open HTTP connection failed:https://:8004/com/symantec/gui/guidelines/ScanEngineApplet.class
        at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
        at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
        at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        ... 7 more
Exception: java.lang.ClassNotFoundException: com.symantec.gui.guidelines.ScanEngineApplet
I went to Symentec site and looked around
They said the following
The problem is on client side.  
Remove 1.6.0_12 Jre.  It can only run with 1.5.0 JRE. 
If you have both 1.6 and 1.5 installed, then browser will use 1.6 causing you problem.
I had the same issue but solved.  Symantec has the solution listed here.
http://service1.symantec.com/support/ent-gate.nsf/docid/2008092215494254

So, I went to Java site next and they said to do the following to remove "older versions"

Windows 7 and Vista - Uninstall Programs
  1. Click Start
  2. Select Control Panel
  3. Select Programs
  4. Click Programs and Features
  5. Select the program you want to uninstall by clicking on it, and then click the Uninstall button.
You may need administrator privileges to remove programs.
Windows XP - Uninstall Programs
  1. Click Start
  2. Select Control Panel
  3. Click the Add/Remove Programs control panel icon
  4. The Add/Remove control panel displays a list of software on your system, including any Java software products that are on your computer. Select any that you want to uninstall by clicking on it, and then click the Remove button.
Am just a lowly sys admin not about to challenge the mighty java folk...So, I did as they commanded and removed JRE 1.6.0_12 from my machine and VOILA... I was able to follow the IPswitch's initial instructions to the word... 

Ah sometimes you really do have to step back to step forward....

Monday, March 28, 2011

Viewstates in C#

So, as is inevitable with any .NET admin.. (pseudo admin in my case)... I ran headfirst into a fight with the viewstates...

Between the various view state errors... I looked online and found this


 What does the EnableViewStateMac setting in an aspx page do?
Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP.NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error - Validation of viewstate MAC failed.
Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.

I also highly recommend reading this article


It is very precise explanation of the devil that is viewstate

Wednesday, March 23, 2011

Comparing dates in C#


DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Response.Write(string.format("{0} {1} {2}", date1, relationship, date2));


 The example displays the following output:
//    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM

Tuesday, March 22, 2011

Session ticker with Javascript and C#

So, I built the awesomest application in the world and was stumped by a simple conundrum..

The users didnt realize they were getting timed out

So I found this gem... and modified it to be added to the master page


  var sessionTimeout = "<%= Session.Timeout %>";
  
        function DisplaySessionTimeout()
        {

            var sessionValue = '<%= Session["userID"] %>';
            //assigning minutes left to session timeout to Label
            if ((sessionValue != "")&&(sessionTimeout > 0)) {

                document.getElementById("<%= lblSessionTime.ClientID %>").innerText =
                                                                       "Session time left: " + sessionTimeout + " minutes";
                sessionTimeout = sessionTimeout - 1;

                //if session is not less than 0

                //call the function again after 1 minute delay
                window.setTimeout("DisplaySessionTimeout()", 60000);
            }
//            else {
//                //show message box
//                alert("Your current Session is over.");
//            }
        }




after adding this to the head.. I added this label to the body

    
        < asp: Label ID ="lblSessionTime" CssClass="showGreen" runat="server" >

and VOILA !! there is a green ticker updating every min informing people of the impending doom.. I mean session timeout

AH HAAA




Monday, February 14, 2011

Could not load file or assembly 'Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.


So.. I decided to play around with AJAX...just because I run 2 years behind everyone else in the world... anyways.. the very first compile, I get this error...


Server Error in '/Ajax' Application.

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Could not load file or assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

Source Error:


Line 30:    
Line 31:      
Line 32:        
Line 33:      
Line 34:    

Source File: ***\Visual Studio 2010\Projects\Ajax\web.config    Line: 32

Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded.


=== Pre-bind state information ===
LOG: User = ***
LOG: DisplayName = System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
 (Fully-specified)
LOG: Appbase = file:///***/Visual Studio 2010/Projects/Ajax/
LOG: Initial PrivatePath = ***\Visual Studio 2010\Projects\Ajax\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: ***\Visual Studio 2010\Projects\Ajax\web.config
LOG: Using machine configuration file from ***\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
LOG: Attempting download of new URL file:///***/Temporary ASP.NET Files/ajax/10e788b7/30cb6ce9/System.Web.Extensions.DLL.
LOG: Attempting download of new URL file:///***/Temporary ASP.NET Files/ajax/10e788b7/30cb6ce9/System.Web.Extensions/System.Web.Extensions.DLL.
LOG: Attempting download of new URL file:///***/Visual Studio 2010/Projects/Ajax/bin/System.Web.Extensions.DLL.
LOG: Attempting download of new URL file:///***/Visual Studio 2010/Projects/Ajax/bin/System.Web.Extensions/System.Web.Extensions.DLL.
LOG: Attempting download of new URL file:///***/Temporary ASP.NET Files/ajax/10e788b7/30cb6ce9/System.Web.Extensions.EXE.
LOG: Attempting download of new URL file:///***/Temporary ASP.NET Files/ajax/10e788b7/30cb6ce9/System.Web.Extensions/System.Web.Extensions.EXE.
LOG: Attempting download of new URL file:///***/Visual Studio 2010/Projects/Ajax/bin/System.Web.Extensions.EXE.
LOG: Attempting download of new URL file:///***/Visual Studio 2010/Projects/Ajax/bin/System.Web.Extensions/System.Web.Extensions.EXE.

And began the painful process of debugging and screaming and kicking...

DOH !!

I did not install the AJAX extension

I need to install ASP.NET 2.0 AJAX Extensions 1.0

Once I did that... all was well in my world once more...

Wednesday, February 9, 2011

Format phone number in sql server 2008

Sometimes it is desperately required to format the phone number before displaying them in your website. In this ms sql server tutorial we will learn how to format the phone number in mssql server query.

Actually we want to convert telephone number like this 6092758415 into (609) 275-8415. Let’s have a look over how to do this, for example we have a column user_phone in our database table users, let’s look how to format the telephone number in mssql server query. It's easy and better to perform formatting of phone numbers in sql.

select case when len(ltrim(rtrim(User_Phone)))='10' then '('+SUBSTRING(User_Phone,1,3)+')'+' '+SUBSTRING(User_Phone,4,3)+'-'+SUBSTRING(User_Phone,7,4) when len(ltrim(rtrim(User_Phone)))='' then ' ' end AS User_Phone from users

Now phone number field will show data in this format (###) ###-####

nawaz dobandi


वो अपने घर की खिड़की से झाकता कम है
तालूकात अभी भी है रापता कम है 
फ़िज़ूल तेज़ हवाओं को दोष देता है 
तुझे दिया जलने का होसला कम है 
में तेरे लिए जान दे देता ऐ दोस्त 
मगर मेरी जान का मुआफ्ज़ा कम है 


अगर बिकने पे आ जाओ तो घट जाते है दाम अक्सर 
न बिकने का इरादा हो तो कीमत और बढती है 


Monday, January 31, 2011

::1 in the hosts file on windows server...

So, I decided to edit my hosts file on windows, not because I had this utter urge to break everything..but because I was using crossover cables and needed my machine to understand that...


I opened the hosts file and had a one sec "HUH" moment ... where I saw these two entries 


# Comment
127.0.0.1 localhost
::1 localhost



Now I knew about the first entry and that it was present in all hosts files.. what was the second entry.. I was curious ... This is what I discovered...




::1 Localhost is the equivalent to 127.0.0.1 Localhost but using IPv6 protocol format , ::1 localhost is valid when Internet Protocol version 6 (IPv6) is implemented on a system.

IPv4 127.0.0.1
IPv6 ::1

"::" is an abbreviation for missing zeros, so this loopback entry really means

0000:0000:0000:0000:0000:0000:0000:0001 localhost

Friday, December 17, 2010

isnull is a Saviour

I was trying to query my userName from the database...it was stored as firstname, middlename and lastname and being the dunce I am, I did the simple

Select firstName+' '+MiddleName+' '+lastName as userName from members

Right ?

WRONG !!!

If any of the cols is a null, which usually is for the middle name, the concatanation returns null...

BOOOO

So, now am doing this instead

Select ltrim(isnull(FirstName,'')+' '+isnull(MiddleName, '')+' '+isnull(LastName,'')) as userName from members

and all is well in my world again !!!

Tuesday, December 14, 2010


So I had a gridview which had no data... Now what...
AHhh.. there is empty data template for gridview ... Woo Hoo... here it goes from microsoft site :

The empty data row is displayed in a GridView control when the data source that is bound to the control does not contain any records. You can define your own custom user interface (UI) for the empty data row by using the EmptyDataTemplate property.

<%@ Page language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>GridView EmptyDataTemplate Example</title> </head> <body> <form id="form1" runat="server"> <h3>GridView EmptyDataTemplate Example</h3> <asp:gridview id="CustomersGridView" datasourceid="CustomersSqlDataSource" autogeneratecolumns="true" runat="server"> <emptydatarowstyle backcolor="LightBlue" forecolor="Red"/> <emptydatatemplate> <asp:image id="NoDataImage" imageurl="~/images/Image.jpg" alternatetext="No Image" runat="server"/> No Data Found. </emptydatatemplate> </asp:gridview> <!-- This example uses Microsoft SQL Server and connects --> <!-- to the Northwind sample database. Use an ASP.NET --> <!-- expression to retrieve the connection string value --> <!-- from the Web.config file. The following query --> <!-- returns an empty data source to demonstrate the --> <!-- empty row. --> <asp:sqldatasource id="CustomersSqlDataSource" selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers] Where CustomerID='NoID'" connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" runat="server"> </asp:sqldatasource> </form> </body> </html>

Monday, November 29, 2010

Formating dates in SQL Server 2008

Problem
There are many instances when dates and times don't show up at your doorstep in the format you'd like it to be, nor does the output of a query fit the needs of the people viewing it. One option is to format the data in the application itself. Another option is to use the built-in functions SQL Server provides to format the date string for you.
Solution
SQL Server provides a number of options you can use to format a date/time string. One of the first considerations is the actual date/time needed. The most common is the current date/time using getdate(). This provides the current date and time according to the server providing the date and time. If a universal date/time is needed, then getutcdate() should be used. To change the format of the date, you convert the requested date to a string and specify the format number corresponding to the format needed. Below is a list of formats and an example of the output:

DATE FORMATS
Format #Query (current date: 12/30/2006)Sample
1select convert(varchar, getdate(), 1)12/30/06
2select convert(varchar, getdate(), 2)06.12.30
3select convert(varchar, getdate(), 3)30/12/06
4select convert(varchar, getdate(), 4)30.12.06
5select convert(varchar, getdate(), 5)30-12-06
6select convert(varchar, getdate(), 6)30 Dec 06
7select convert(varchar, getdate(), 7)Dec 30, 06
10select convert(varchar, getdate(), 10)12-30-06
11select convert(varchar, getdate(), 11)06/12/30
101select convert(varchar, getdate(), 101)12/30/2006
102select convert(varchar, getdate(), 102)2006.12.30
103select convert(varchar, getdate(), 103)30/12/2006
104select convert(varchar, getdate(), 104)30.12.2006
105select convert(varchar, getdate(), 105)30-12-2006
106select convert(varchar, getdate(), 106)30 Dec 2006
107select convert(varchar, getdate(), 107)Dec 30, 2006
110select convert(varchar, getdate(), 110)12-30-2006
111select convert(varchar, getdate(), 111)2006/12/30
TIME FORMATS
8 or 108select convert(varchar, getdate(), 8)00:38:54
9 or 109select convert(varchar, getdate(), 9)Dec 30 2006 12:38:54:840AM
14 or 114select convert(varchar, getdate(), 14)00:38:54:840

You can also format the date or time without dividing characters, as well as concatenate the date and time string:

Sample statementOutput
select replace(convert(varchar, getdate(),101),'/','')12302006
select replace(convert(varchar, getdate(),101),'/','') + replace(convert(varchar, getdate(),108),':','')12302006004426

Next Steps
  • The formats listed above are not inclusive of all formats provided. Experiment with the different format numbers to see what others are available
  • These formats can be used for all date/time functions, as well as data being served to clients, so experiment with these data format conversions to see if they can provide data more efficiently

Wednesday, November 24, 2010

Generate Random password SQL Server 2008

Well I was transferring users from one table to another and had to add random passwords to the user table.

Could not figure out a way to save my life and then in desperation came up with this methord


SELECT [PERSON_ID]  ,'IAI'+ SUBSTRING(convert(varchar(50),NEWID()),0,6) as password from Persons


Hope the next time I dont spend hours trying to randomize characters and strings :)

Monday, November 22, 2010

javascript confirm C# button

In all good web applications, the user is asked to confirm whether he/she wants to delete something in case the delete button was pressed accidentally.

Although it seems like a pain to do, it is actually really easy if you find it acceptable to use javascript's “confirm” statement, which will popup a dialog box with a particular question with “ok” and “cancel” buttons. You have no control of the title of the popup, but in IE it says “Microsoft Internet Explorer“ and I believe it says “[Javascript Application]“ or similar in Firebird.





The javascript code for it is simple:


function confirm_delete()
{
  if (confirm("Are you sure you want to delete the custom search?")==true)
    return true;
  else
    return false;
}



and 



       < asp:Button ID="btnRemoveSchool" runat="server" CssClass="btn" Text="Remove the School/Organization" OnClientClick="javascript:return confirm_delete();" / >

Add Item to DropDownList After DataBind

We often want the first option in a drop-down list to not default to the first item in the list. Instead we would prefer the option of adding a –Select Item– at the top of theasp:DropDownList. After the DataBind, execute an Item.Insert.

ddlAuthor.DataTextField = "FullName";
ddlAuthor.DataValueField = "AuthorID";
ddlAuthor.DataSource = authorDB.GetAuthors();
ddlAuthor.DataBind();
ddlAuthor.Items.Insert(0, "-- Select Author --");

Page flicker on postback

I was working on a form where one dropdownlist is populated based on values of selected item in another dropdown and it caused the page to flicker each time.

So, Robicool from work gave me this cool piece of code to stop the annoyng page flickers


 protected void Page_PreInit(object sender, EventArgs e)
    {

        if (Request.Browser.IsBrowser("IE"))
        {
            string v = Request.Browser.Version;
            if (v.Length > 0)
                v = v.Substring(0, 1);
            if ((v == "7") || (v == "6"))
            {
                SmartNavigation = true;
                MaintainScrollPositionOnPostBack = false;
            }
            else
            {
                SmartNavigation = false;
                MaintainScrollPositionOnPostBack = true;
            }
        }
        else
        {
            SmartNavigation = false;
            MaintainScrollPositionOnPostBack = true;
        }
    }

Wednesday, November 10, 2010

Potato Pattis Reciepe

5 medium potatoes
A bunch of fresh coriander leaves, chopped
1 tsp jeera / cumin
2 green chillies, chopped
1/2 tsp red chilli powder
1 to 2 tbsp all-purpose flour
1/4 cup - Onion, chopped finely
(optional....I dont use it)
1/2 tsp - Ginger, grated (optional....I dont use it)
Salt to taste
  • Boil the potatoes and peel off the skin.
  • After cooling mash it.. Divide into two equal parts 
  • First part of potatoes get slow stir fried with cumin, chillies, coriander, chilli powder and salt. Cool down the mix and divide it into 10-12 small portions and roll into balls
  • add flour to second half of potatoes and prepare it like a dough. Pls dnt add any water.
  • To make final pattis , take flour dough in hand, make a small circle out of it, put the spiced potato ball inside it and close the ball. make sure the spiced potatos are completely covered by floured potatos else it explodes while frying....
  • Heat oil in pan and deep fry the pattis till light brown colour.
  • Serve it hot with ketch up.

Thursday, November 4, 2010

Flush Socket in .NET or C# to ensure send of acknowledgement

Today, I faced a problem regarding synchronizing a C# TCP/IP Client with a JAVA TCP/IP server. 

The problem was, client sends data and waits for acknowledgment. Server listens for data and when it gets data, it sends acknowledgment to the client and start listening for data again. Now when server starts listening for data again it gets old data i.e. it was not getting blocked on the read() function which it should, as client hasn't send any more data.


the .Net Socket Send page (http://msdn.microsoft.com/en-us/library/ms145160.aspx) has the following:


"There is also no guarantee that the data you send will appear on the network immediately. To increase network efficiency, the underlying system may delay transmission until a significant amount of outgoing data is collected. A successful completion of the Send method means that the underlying system has had room to buffer your data for a network send."

So, the problem was that the data was not being flushed. I searched for Flush method in System.Net.Sockets.Socket class but it was not there. There was a suggestion like:

1. Use the SetSocketOption function and set the value of ReceiveBuffer option to 0. It didn't work. Though the recivebuffer length was 0, the data was still being buffered.
2. Use the IOControl function to set the value for Flush option. But you won't find the integer value for Flush Option (atleast I was not able to)

I tried to use NetworkStream class. You create a new stream using socket and then you create StreamReader and StreamWrite object using NetworkStream object

NetworkStream stream = new NetworkStream(socket);
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter(stream);

Then, use Flush() method of StreamWriter to flush the data. You can also set the property called AutoFlush of StreamWriter to automatically flush the stream after write operation. 
But Flush() method is more reliable according to their site...


This is my code in case you are really really curious


Instead of doing 


 //first send an acknowledgement to client  saying we are good...Now you can stop
          const string sendData = "< response status="\" > success < / response >";
                      byte[] bytes = Encoding.UTF8.GetBytes(sendData);
                      if (listenerSocket != null)
                      {
                          listenerSocket.Send(bytes, bytes.Length, 0);
                      }



I am doing ....



     NetworkStream ns = new NetworkStream(listenerSocket);
            StreamWriter w = new StreamWriter(ns);
          const string sendData = "< response status="\" > success < / response >";
            string message;
            try
            {
                w.Write(sendData);
                w.Flush();
                message = String.Format("\n\nPOST successful. bytes sent " + xml.Length);
            }
            catch (Exception ex)
            {
                message = String.Format("\n\nPOST failed. Received exception {0}", ex);
            }
            finally
            {
                w.Dispose();
                ns.Dispose();
            }

And yet the server does not receive any acknowledgment. I am very clueless at this point and any suggestion would be more than welcomed.

Update:

I think I have figured out a solution

This send code seems to be working in my case


 //--trying the asynchronous thing
IAsyncResult ar = listenerSocket.BeginSend(asen.GetBytes(xml), 0, xml.Length, SocketFlags.None, null, null);
listenerSocket.EndSend(ar);
string message = String.Format("\n\nPOST successful. bytes sent " +ar.ToString()+"\n"+ xml.Length);


Hope it works for you as well

Source Control Explorer Accidental deletion and file recovery

Sometimes, you do stupid things. But VSS is definitely more forgiving than real life and totally and completely saved me hours of rework.

1) Tried to copy files in Visual Studio 2010.
2) It moved the aspx file but not cs file
3) Deleted the original files

So, now I had a aspx file sitting around without a cs file... And I cried...

But then I tried this...

1) Shut down all VSS clients / VS IDEs.
2) Open Visual SourceSafe Explorer and login into VSS database.
3) Undo all the checkouts of any projects or the solution.
4) If the projects were modified by a check-in, roll it back.
5) Go to the parent folders, show properties, and undelete any accidentally deleted files.
6) Do a GET with VSS and make sure the project file as well as the "project's files" are correct in your working folder.
7) Shut down VSS explorer.
8) Try an Open of the project with Visual Studio.

And it worked... YES it totally did....