Saturday, April 18, 2015

SSRS Report : the value expression for the query parameter refers to a non-existing report parameter

This is one nasty error which I've experienced many times. Finally got one solution for that.. Do view code of the rdl..Find the killer bug..and correct it... ex:

Only referring to the code will help..


            =Parameters!FromDate.Value
         
         
            =Parameters!ToDate.Value
         
       

Correct it to


            =Parameters!FromDate.Value
         
         
            =Parameters!Todate.Value
         
       

Whatever we do outside wont help...even if we remove all the parameters from query and redo again... :)

Thanks to this part of the report...

Hope this serves good for someone out there...

Happy programming guys!!
Regards,

Export import AX model - Dynamics AX 2012

Hey Folks,

I had to do this ax model export today and found the command quite interesting. Thought of sharing it..

Open cmd prompt and run as administrator and then

locate the folder c:\program files\microsoft dynamics ax\60\managementutilities

axutil export /model:[modelname] /file:[backupmodelname].axmodel /db:[dbname]_model /s:[servername]

Dynamics AX field lookup method.

The below lookup method is overridden in the form datasource.

 public void lookup(FormControl _formControl, str _filterStr)
{
    SysTableLookup sysTableLookup;
    Query query;
    QueryBuildDataSource qbd;

    ;
    sysTableLookup = SysTableLookup::newParameters(tablenum([tableName]),_formcontrol);

    query = new Query();
    qbd = query.addDataSource(tablenum([tablename]));
    qbd.addRange(fieldnum([tablename],[fieldname])).value(SysQuery::value([value]));

    sysTableLookup.addLookupfield(fieldnum([fieldname]));
    sysTableLookup.addLookupfield(fieldnum([fieldname1]));
    sysTableLookup.parmQuery(query);
    sysTableLookup.performFormLookup();

}

Happy Programming!!

Wednesday, December 18, 2013

Read Mails From Exchange Server - Send Mail - Move Mail

Just finished struggling around with a console application that reads mail for a particular account with a particular subject from Exchange server and re sends it to some other id with the same content.

Not much blah blah..here is the whole code.. Let you guys be saved atleast...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Office.Interop.Outlook;
using System.Runtime.InteropServices;
using Microsoft.Exchange.WebServices.Data;

namespace BTROutlookConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            MessageBody messageBody = new Microsoft.Exchange.WebServices.Data.MessageBody();
            service.Credentials = new System.Net.NetworkCredential("username", "pwd", "domain.com");
            service.AutodiscoverUrl("username@domain.com");
            object o = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
            FindItemsResults findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
            FolderView view = new FolderView(100);
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.PropertySet.Add(FolderSchema.DisplayName);
            view.Traversal = FolderTraversal.Deep;
            FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Inbox, view);
            foreach (Item item in findResults.Items)
            {
                Console.WriteLine(item.Subject);
                if (item.Subject.ToString().ToLower() == "SUBJECT1".ToLower())
                {
                    item.Load();
                    messageBody = item.Body.ToString();
                    Console.WriteLine("IsNew: " + item.IsNew);
                    Console.WriteLine("To: " + item.DisplayTo);
                    Console.WriteLine("Subject: " + item.Subject);
                    Console.WriteLine("Message Body: " + item.Body.ToString());
                    Console.WriteLine("Date & Time Received: " + item.DateTimeReceived);
                    Console.WriteLine("HasAttachments: " + item.HasAttachments);
                    string mailBody = item.Body.ToString();
                    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                    message.To.Add("salini.haridas@uniquegroup.com");
                    message.Subject = "From YesFolder";
                    message.From = new System.Net.Mail.MailAddress("username@domain.com", "Test Subject");
                    message.Body = mailBody;
                    message.IsBodyHtml = true;
                    System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("exname.domain.com");
                    smtp.Send(message);
                    item.Move(findFolderResults.Folders[0].Id);
                }
            }
        }
    }
}

This program assumes the Microsoft.Exchange.WebServices is added as reference to the project.

Happy programming guys..So good to c you after so long...Hey n between nowadays I am trying my luck in AX 2012 too.. So may be next time I can give you something from that.. :)

Wednesday, April 24, 2013

Internet Security Threat Report 2013 : Recommendations from Symantec


The Internet Security Threat Report for the year 2013 has been released by Symantec , which of-course is alarming. The report is well organized and also provides recommendations and possible solutions to the listed threats. I am quoting the recommendations from Symantec straight from the report.


Protect Yourself Against Social Engineering. 

For individuals as well as for businesses, it’s essential that people learn to spot the telltale signs of social engineering, which can include undue pressure, titillation or a false sense of urgency, an offer that is literally too good to be true, bogus “officialese” in an attempt to make something look authentic (for example, lengthy reference numbers), implausible pretexts (for example, a Microsoft  representative” calls to tell you that your computer has a virus), and false quid-proquo offers (for example, receive a free gift when you provide personal or confidential information).

Avoid Ransomware. 

Avoid marginal websites and, in particular, pirate software and adult sites. Do not install unsolicited plug-ins or executables if prompted to do so, even on legitimate websites. Consider using advertising blocker software in your browser. Ensure that your computer is up to date with the latest patches and updates to increase your resistance to drive-by Web infections. Keep backups and recovery disks so you can unlock your computer in an emergency. And, of course, have effective, up-to-date security software.

Think Before You Click. 



That unsolicited email from a known acquaintance, such as your mother or coworker, may not be legit. Their account may have been compromised, if they’ve fallen for a social engineering trick.

Antivirus on Endpoints Is Not Enough.

On endpoints (desktops/laptops), signature-based antivirus alone is not enough to protect against today’s threats and Web-based attack toolkits. Deploy and use a comprehensive endpoint security product that includes additional layers of protection, including:

•  Endpoint intrusion prevention that protects against unpatched vulnerabilities from being exploited, protects against social engineering attacks, and stops malware from ever making it onto endpoints;
•  Browser protection for protection against obfuscated Webbased attacks;
•  Heuristic file-based malware prevention to provide more intelligent protection against unknown threats;
•  File and Web-based reputation solutions that provide a risk-and-reputation rating of any application and website to prevent rapidly mutating and polymorphic malware;
•  Behavioral prevention capabilities that look at the behavior of applications and malware and prevent
malware;
•  Application control settings that can prevent applications and browser plug-ins from downloading unauthorized malicious content;
•  Device control settings that prevent and limit the types of USB devices to be used.


Note: The entire article is available at the symantec website. 

Sunday, April 21, 2013

clr20r3 P9 system.componentmodel.win32 : Handling unhandled exceptions

The problem : An Application that doesn't start


Happened to come across an older (read dot net 2.0) application which , due to some reason started to misbehave. whenever it is started it said "App has encountered a problem and needs to close. We are sorry for the inconvenience". There are no other details and the only point of hope was the windows log which said.

EventType clr20r3, P1 app_name.exe, P2 1.1.2.0, P3 4f1ea58b, P4 system, P5 2.0.0.0, P6 4889de7a, P7 3839, P8 131, P9 system.componentmodel.win32, P10 NIL.

I was also told by the dev guys that the application is having its own error log which does not show any entry of this error and also the infamous excuse of "It worked yesterday."   and "It is working fine on my machine."


The source


Going through the source code , found that all the methods had try catch blocks with exception logging configured to log everything including stack trace. Even all the line of codes inside the static Main() were enclosed in a try catch.


The Solution


Since there was no handler for unhandledexception written, the same was added just inside the Main()

           AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(delegate(object sender, UnhandledExceptionEventArgs e)
                {
                  if (e.IsTerminating)
                  {
                      object o = e.ExceptionObject;
                      MessageBox.Show(o.ToString()); // use EventLog instead
                  }
                }
            );



This snippet makes sure that no exceptions are unhandled from your side. [On a lighter note, the root cause here in this case was revealed to be an error log which grew out of size]
I suggest the usage of this handler for trapping any exception that stays unhandled.


Understanding the error log [Watson buckets]



For Breaking up the windows error log entry
EventType clr20r3, P1 app_name.exe, P2 1.1.2.0, P3 4f1ea58b, P4 system, P5 2.0.0.0, P6 4889de7a, P7 3839, P8 131, P9 system.componentmodel.win32, P10 NIL.
The entries P1 ,P2 ,P3 etc are the details collected by the system regarding the exception that went unhandled. They are known as Watson buckets. They include the following information


  1. Executable
  2. Assembly version number
  3. File Stamp
  4. Full assembly name
  5. Faulting assembly version
  6. Faulting assembly timestamp
  7. Faulting assembly method def
  8. IL Offset within the faulting method
  9. Exception type




Hopes this helps someone, someday, some time...
Happy Programming...



Thursday, December 8, 2011

Map Network Drive using C# / Vb.net code

This post will show you an easier way to map a network drive using dot net code. you are free to use any .net language of your choice. I will be mostly sticking to C# though.

We will be relying on COM Interop for this and we will be referencing the Windows Script Host Object Model for this task. Lets get going....

  • Step 1.
Open your choice of application project. In this case I am opening a new Windows Forms Application in C#. And you are there on the default form :Form1.

  • Step 2.
Add a new reference.
In Solution Explorer, right click on References and Click on Add reference.

Select the COM tab.

Scroll down and select Windows Script Host Object Model
Now the solution explorer will look like this with an IWshRuntimeLibrary added.

Now you are ready to go.

  • Step 3.
Write Code.
Go to the code window. select your required event [button click or form load or just anything].
Create an instance of the class IWshNetwork_Class
Call the MapNetworkDrive method and you are done.

  • Sample Code
IWshNetwork_Class network = new IWshNetwork_Class();
network.MapNetworkDrive("k:",@"\\192.168.20.35\MyShare", Type.Missing, "user1", "password1");

you can use the following code to UnMap or remove the mapping.

network.RemoveNetworkDrive("k:");

Hope this saves some time for you....
Happy Programming...

Sunday, October 17, 2010

Multiline Textbox Character Limit

Giving character limit to a multiline textbox can be done using a regular expression validator. Add a regular expression validator to theaspx page and set the control to validate as the multiline text box. Then in the validation expression give

^[\s\S]{0,2000}$
This solution limits the character length to 2000 characters including blank spaces and tabs.

Cheers

Saturday, January 2, 2010

Are GSM phone calls secure?

Its 2010 and its time to double check the security of GSM phone calls. GSM (Global System for Mobile communications: originally Groupe Spécial Mobile) is the most widely used standard for mobile communication . The GSM encryption algorithm which was designed 20 years back is of no match to today's computing power or technological advances. GSM's A5/1 function uses a 64 bit encryption key to secure the phone calls which is too insecure considering the cpu power and storage of todays machines.

The algorithm must have seemed a lot more secure twenty years back when cpu cycles were expensive. Nobody cared to replace the A5/1 function when researchers first discusssed practical attacks on GSM.

German security expert Karsten Nohl demonstrated how easy it really is to hack into GSM cell phones,(Read news here) including those used by AT&T and T-Mobile customers in the U.S. He had launched an open-source, distributed computing project designed to crack GSM encryption and have successfully compiled it into a code book that can be used to eavesdrop on gsm phone calls. It is open source and is open to public. This can also mean that your neighbor might be already listening to your calls.

Anyone including you can listen to someone else's phone call. According to the German security expert "All you need is Two USRP radios, a beefy gaming computer, and a handful of USB sticks can already decrypt many calls". Here it goes. You record a call and then decrypt it. Recording requires some radio equipment, which can cost you $1,500[will get cheaper now] . The device is called a Universal Software Radio Peripheral device. One direction of a call can potentially be intercepted from a kilometer away while catching both directions requires you to be in the vicinity of the victim. Decryption is then done using the code book the community produced. The more you spend on the hardware, the faster you can decrypt the call. Commercial interceptors can decrypt within seconds [means less than the time taken by someone to answer an incoming call].

This post is just to make people aware about the insecurities of using a GSM network and is not intended to encourage hacking into it. if more people are aware about this they can force the operators to do something to enhance their security levels. The next generation function : The A5/3 which is used in 3G networks are still considered more secure as they have not been cracked yet.

So in this new year keep your confidential matters in 3G. Happy 3Ging.

TechiSolutions wishes you all a Happy and secure year ahead
L1F3, k33p 1t 51mpL3


References
A5/1 Security Project
Insecurity Complex

Monday, June 8, 2009

Coolite : ExtJS + ASP.Net

Every one agrees that using Ajax in ASP.Net is cool. And even cooler if you can use third party javascript/Ajax frameworks. A number of people had asked me whether there is an easy solution to use extJs framework in ASP.Net. So I thought of writing something about that here.

ExtJS is an excellent framework by itself , But a cooler way to integrate it with ASP.Net exists. Enter Coolite Toolkit. Coolite toolkit is A suite of professional ASP.NET AJAX Web Controls
built on the ExtJS JavaScript Framework. The project is in development phase and the current release [as of June 2009] is version 0.8. The control kit is dual licensed and is available in GPL and also with a commercial license.

The Library consists of a vast collection of UI components starting from buttons and datepickers to treeviews, Grid panels , Messageboxes and a Desktop control. You can see them live at Coolite Example Explorer. The controls are easy to use [you need to have a look at their examples to know how to use them and better if you can find time to read the documentation] and intuitive and they offer community help through their forum also.

Another interesting thing that i found with the library is the use of [AjaxMethod] Attribute . By using it you can call any server side method from a javascript function without any flicker/postback and the same is done using Ajax and JSON.

Do find some time to explore this toolkit.


Wednesday, June 11, 2008

Host Headers: Hosting multiple websites on IIS with a single ip


Most web developers are not aware that IIS can host multiple websites on a single ip address. Here is some help on how to do that.

You have two available options to do the same. One is to assign different port numbers to each of the websites (which i don't recommend). The second option is to use host headers. By using host headers we assign domain names to the websites hosted on iis. For example if you have two websites on iis both sharing a single ip, then you can set two different host headers(abc.com and xyz.com) for them. then you will be able to browse both the websites with the domain names specified. when you request for the web page at www.abc.com, the request is sent to iis and iis will resolve the host header(abc.com) and route it to the corresponding website.

Lets have a look on how to implement it.

  • Go to iis mmc (enter inetmgr in the run window and click ok) click here for more Run window shortcuts
  • Right click on the website and select properties.
  • Select the Websites tab and click on Advanced.







  • On this screen , Edit the default entry and delete the All Unassigned entry and enter the ipaddress of your site.
  • specify the TCP Port [let it be 80]
  • The third entry is the (much awaited) Host Header.
  • Enter the exact string that you want the website to respond to. If you want the site to respond to www.abc.com give that as the host header. You can make multiple entries in this window. if you want the same site to respond to www.thisisalsoabc.com then add that also as the next entry. Make sure you give the same ip address and port number.

Thats It and you are ready with your website with host headers enabled.
Now you can configure your other sites and give different host headers to them. Make sure you enter the same ip address and port number for them too.

Now you can browse your websites with the host header names.
Please Note that these host headers has to be registered with some naming servers. ie you have to register your website name to map to youir ip address from a name resolution system. In case you are on the local intranet Please edit the hosts file to do the same.

The hosts file is a file located on each Windows machine and is used to resolve names to an IP address, and this file can be modified to resolve any valid name to an IP address.

Here is howyou can edit the hosts file.

  • The hosts file is located in the \system32\drivers\etc directory and can be opened with Notepad.
  • You can see that the last line maps an ip to localhost
  • Press enter to start a new line after that and enter the ipaddress of the iis machine followed by a tab and enter the host header name.
  • you can make multiple entries to map each of the host headers to the ipaddress.
  • Save the file (make sure that notepad is not adding the .txt extension)

Now you are ready to browse the websites with the hostheader on your local network. If you want to browse the site from different machines on the intranet , you have to edit the hosts file on each machine. If you are on a larger network you can rely on your DNS server to handle host headers.

Hope this post helps you...

Saturday, March 29, 2008

Google Map API

Ever wondered how to keep a map to show your current location in your site.If you know the longitude and latitude of your location..then the Google maps will serve this purpose.You can place markers on the map,set route paths..and what not...

These are widely used for GPS tracking systems now a days.Including just a sample code to explain the same would be a sin as you will never be able to explore its full features if you really dont go around this.This link will help you find the full documentation for the same..

http://code.google.com/apis/maps/documentation/

Hope this helps..Cheers..

Sunday, March 9, 2008

Send and Receive Mail from C# (SMTP and POP)


Today we shall see both sending of mails from a domain and reading mails from a domain.

Some domains wont allow mails to be send from them from an application if no mail is popped from it,ie;read from it. That means , to send a mail we first need to get pop access to the domain.Once we authenticate that we can start sending mails from that domain.

Include the following code bit in any page.

public class Pop3Exception : System.ApplicationException
{
public Pop3Exception(string str)

: base(str)
{

}
};

public class Pop3Message
{

public long number;

public long bytes;

public bool retrieved;

public string message;

};
public class Pop3 : System.Net.Sockets.TcpClient
{
public void Connect(string server, string username, string password)
{
string message;
string response;

Connect(server, 110);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

message = "USER " + username + "\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

message = "PASS " + password + "\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}
}

private void Write(string message)
{
System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding();
byte[] WriteBuffer = new byte[1024];
WriteBuffer = en.GetBytes(message);
NetworkStream stream = GetStream();
stream.Write(WriteBuffer, 0, WriteBuffer.Length);
Debug.WriteLine("WRITE:" + message);
}

private string Response()
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] serverbuff = new Byte[1024];
NetworkStream stream = GetStream();
int count = 0;
while (true)
{
byte[] buff = new Byte[2];
int bytes = stream.Read(buff, 0, 1);
if (bytes == 1)
{
serverbuff[count] = buff[0];
count++;
if (buff[0] == '\n')
{
break;
}
}
else
{
break;
};
};
string retval = enc.GetString(serverbuff, 0, count);
Debug.WriteLine("READ:" + retval);
return retval;
}

public void Disconnect()
{
string message;
string response;
message = "QUIT\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}
}

public ArrayList List()
{
string message;
string response;

ArrayList retval = new ArrayList();
message = "LIST\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

while (true)
{
response = Response();
if (response == ".\r\n")
{
return retval;
}
else
{
Pop3Message msg = new Pop3Message();
char[] seps = { ' ' };
string[] values = response.Split(seps);
msg.number = Int32.Parse(values[0]);
msg.bytes = Int32.Parse(values[1]);
msg.retrieved = false;
retval.Add(msg);
continue;
}
}
}
public Pop3Message Retrieve(Pop3Message rhs)
{
string message;
string response;

Pop3Message msg = new Pop3Message();
msg.bytes = rhs.bytes;
msg.number = rhs.number;

message = "RETR " + rhs.number + "\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "+OK")
{
throw new Pop3Exception(response);
}

msg.retrieved = true;
while (true)
{
response = Response();
if (response == ".\r\n")
{
break;
}
else
{
msg.message += response;
}
}

return msg;
}
}

Now calling PopMail(),

private static void PopMail()
{
try
{
Pop3 obj = new Pop3();
obj.Connect("pop.rediffmailpro.com", "full@email.address", "password");
ArrayList list = obj.List();
foreach (Pop3Message msg in list)
{
Pop3Message msg2 = obj.Retrieve(msg);
System.Console.WriteLine("Message {0}: {1}",
msg2.number, msg2.message);
break;
}
obj.Disconnect();
}
catch (Pop3Exception pe)
{
System.Console.WriteLine(pe.ToString());
}
catch (System.Exception ee)
{
System.Console.WriteLine(ee.ToString());
}
}

will do the tricks.

No we'll see the sending of mails.For that we use a button click event on our application.

private void _sendButton_Click(object sender, EventArgs e)
{
System.Data.Odbc.OdbcConnection connect = new System.Data.Odbc.OdbcConnection();
...
{
..
}
foreach (DataGridViewRow row in grid.Rows)
{
count++;
if (row.Cells[0].Value != null)
{
if (row.Cells[0].Value.ToString() == "True")
{
..
if (count % 300 == 0)
PopMail();
sendMail(row);
..
}
}
}
MessageBox.Show("Mails sent Successfully");
}

bool sendMail(DataGridViewRow row)
{
MailMessage message = new MailMessage();

string getToAddress = row.Cells[4].Value.ToString();
try
{
if (getToAddress == "")
message.To.Add("default@email.id");
else
message.To.Add(row.Cells[4].Value.ToString());
}
catch (Exception ex)
{
message.To.Add("default@email.id");
}
try
{
message.From = new MailAddress("emailid", "domain");
message.IsBodyHtml = true;
string messageBody = GetMessageBody(row);
message.Body = messageBody;
message.Subject = "Hi";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.rediffmailpro.com");
System.Net.NetworkCredential smtpAuthen =
new System.Net.NetworkCredential("emailid", "password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = smtpAuthen;
smtp.Send(message);
return true;
}
catch (SmtpException se)
{
Console.WriteLine(se.Message);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return true;
}
}

In the code you might have noticed that,the PopMail() is called in a loop during limited time interval.That is because,the authentication time expires after sending a couple of mails.So the PopMail is called after sending every 300 mails.

Hope this is useful..

Friday, March 7, 2008

Strongly Typed Dataset C#

Have you ever struggled to generate a Strongly Typed Dataset from an xml File.

Most of you guys might be knowing this technique.

This post is for my friends who dont know how to implement that.I shall explain that to you with the help of two batch files.

One for converting and xml file to its corresponding schema file,ie;xsd and next to generate its class file.

Before that..just a slight introduction.

There are generally two types of dataset.

1.Untyped Dataset
2.Typed Dataset

In an untyped dataset we access a table as,

dataSet.Tables[0]

But in a Typed Dataset it can be accessed by giving,

dataSet.TableName

ie; direct access.

There are many other features.This was just to give a slight idea.

Now we shall see the batch file to convert xml file into xsd.

Type the following code in notepad

c:
cd %VS2003DIR%\SDK\v1.1\Bin
xsd C:\xmlConverter\abc.xml /out:K:\dotnet\csharp\dialogs
pause

and
save this file as xmlToSchema.bat

Now run this batch file.

A new file called abc.xsd will be now available in K:\dotnet\csharp\dialogs

Now create the next batch file.

c:
cd %VS2003DIR%\SDK\v1.1\Bin
xsd K:\dotnet\csharp\dialogs\abc.xsd /c /out:K:\dotnet\csharp\dialogs
pause

Save this file as schemaToCS.bat

On running this file the corresponding class file for the xsd will be generated.Now if we read the xml file to a dataset, the dataset will be a typed dataset.

Very simple right? Hope this is of use to somebody or the other.

Cheers...

Tuesday, March 4, 2008

Image Serialization C#

Serialization is the process of saving an object onto a storage medium (such as a file, or a memory buffer) or to transmit it across a network connection link in binary form. The series of bytes or the format can be used to re-create an object that is identical in its internal state to the original object (actually, a clone).The reverse process of Serialization is called Deserialization.
Refer : wikipedia - serialization

For explaining one feature of Serialization I shall quote an example.

There are some cases in which we don't want to expose our images used in a project but have to use them.Here we can implement serialization.

We keep these images needed in the serialized form and use this after deserializing the same.All the images can be stored as a single serialized file.

To illustrate the same with example code, we shall start with the ImageClass.cs file, which contains

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace serializationProject
{
[Serializable()]
public class ImageClass
{
private Image _imageObject;
private string _imageName;

public ImageClass()
{ }

public Image ImageObject
{
get
{
return _imageObject;
}
set
{
_imageObject = value;
}
}

public string ImageName
{
get
{
return _imageName;
}
set
{
_imageName = value;
}
}

public ImageClass(SerializationInfo info, StreamingContext cntxt)
{
this._imageObject = (Image)info.GetValue("ImageObject", typeof(Image));
this._imageName = (string)info.GetValue("ImageName", typeof(string));
}
}
}

Now we require a serialize object class to store the images generated from the Image Class.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace serializationProject
{
[Serializable()]
public class ObjectToSerialize : ISerializable
{
private List _images;

public ObjectToSerialize()
{ }

public List Images
{
get
{
return _images;
}
set
{
_images = value;
}
}

public ObjectToSerialize(SerializationInfo info, StreamingContext cntxt)
{
this.Images=(List)info.GetValue("Images",typeof(List));
}

public void GetObjectData(SerializationInfo info, StreamingContext cntxt)
{
info.AddValue("Images", this.Images);
}
}
}

This class returns the images as a List Object.

Now the next task is to write the functions to perform the serialization and the deserialization of the images.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace serializationProject
{
public class Serializer
{
public void SerializeObject(string filename,
ObjectToSerialize objectToSerialize)
{
Stream stream = File.Open(filename, FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Close();
}

public ObjectToSerialize DeSerializeObject(string filename)
{
ObjectToSerialize objectToSerialize;
Stream stream = File.Open(filename, FileMode.Open);
BinaryFormatter bFormatter = new BinaryFormatter();
objectToSerialize =
(ObjectToSerialize)bFormatter.Deserialize(stream);
stream.Close();
return objectToSerialize;
}
}
}

In our windows application our form contains 2 buttons.A serialize button and a deserialize button.

When we click serialize, all the 'jpg' files in a said folder will be serialized to one file.In our example we are also considering one condition.We assume that we already have a serialized version of our images.If we are making a new serialized file then the condition

if(count==1)
{}

can be ignored.The rest will do the job.

The button click event which does the serialization of the images is written as,


private void _serializeButton_Click(object sender, EventArgs e)
{
List imageList = new List();
ImageClass imageClass;

int count = 1;

DirectoryInfo directory = new DirectoryInfo("D:\\Serialize\\Temp");
///serializing all 'jpg' files in the
///temp folder of the directory.
foreach (FileInfo file in directory.GetFiles())
{
if (file.Name.Contains("jpg"))
{
///if we already have a serialized file in the directory then
///get the already existing images to the images list and
///then add the new image to the list.
///In our case we are adding files to already existing serialized
///file.If that is not required then the below given
///if condition can be ignored.
if (count == 1)
imageList = DeserializeImages();
imageClass = new ImageClass();
Image image = Image.FromFile(file.FullName);
imageClass.ImageName = file.Name;
imageClass.ImageObject = image;
imageList.Add(imageClass);
count++;
}
}

ObjectToSerialize objectToSerialize = new ObjectToSerialize();
objectToSerialize.Images = imageList;
Serializer serializer = new Serializer();
///the biggest advantage of serialization is that we can
///save a serialized file with any extension.
serializer.SerializeObject("D:\\Serialize\\imagesTemp.abc", objectToSerialize);
MessageBox.Show("Serialized");
}

Now we are going to display the images in an imagebox based on timer tick after we deserialize the images.

private void _deserializeButton_Click(object sender, EventArgs e)
{
List images = DeserializeImages();

_images = images;

Timer timer = new Timer();
timer.Enabled = true;
timer.Interval = 1000;
timer.Start();
_imageCount = 0;
timer.Tick += new EventHandler(timer_Tick);
}

private static List DeserializeImages()
{
List images = new List();
ObjectToSerialize objectToSerialize = new ObjectToSerialize();
objectToSerialize.Images = images;

Serializer serializer = new Serializer();
objectToSerialize = serializer.DeSerializeObject("D:\\Serialize\\imagesTemp.abc");
images = objectToSerialize.Images;
return images;
}

void timer_Tick(object sender, EventArgs e)
{
_imageCount++;
int imageCount = 0;
foreach (ImageClass cls in _images)
{
if (imageCount == _imageCount)
{
_imagelabel.Text = cls.ImageName;
_imageBox.Image = cls.ImageObject;
}
imageCount++;
}
}

This does the tricks.So now on each timer tick and image from the list will be displayed in the ImageBox.The image can be retrieved with the image name even from the list box.The various manipulations with this code are all based on your tactics.. I've just included a basic example with the images.

I hope this code might be of use to somebody or the other.To people who have no idea about serialization do develop some initial idea about serialization and then refer to this code.

Cheers..

Sunday, March 2, 2008

Excel To SQL

Transferring Excel sheet cell values to SQL server is never a tough job now.

Here is how we can transfer all the cell contents from an excel file to a database in a single click.

private void button1_Click(object sender, EventArgs e)
{
System.Data.Odbc.OdbcConnection con = new System.Data.Odbc.OdbcConnection();
string strConnString;
strConnString = "Driver={Microsoft Excel Driver
(*.xls)};DriverId=790;Dbq=c:\\test1.xls;DefaultDir=c:\\";
con.ConnectionString = strConnString;
con.Open();
string select = "select a,x from [sheet1$]";
System.Data.Odbc.OdbcDataAdapter odbcdataAdapter = new
System.Data.Odbc.OdbcDataAdapter(select, con);
DataSet excelDataset = new DataSet();
try
{
odbcdataAdapter.Fill(excelDataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = "server=abc;database=test1;uid=user;pwd=passwd;Connection Timeout=200;";
try
{
cnn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlCommand cmm = new SqlCommand();
cmm.Connection = cnn;

foreach (DataRow row in excelDataset.Tables[0].Rows)
{
cmm.CommandText = "insert into testWriteTable values('" + row[0].ToString() + "','" +
row[1].ToString() + "')";
cmm.ExecuteNonQuery();
}
cnn.Close();
}

Hope this helps somebody out there.

Cheers....

Monday, February 25, 2008

Unzip File From C#

Unzipping a file from C# would always have been a tough job for me,if I had not found this utility in .Net.The java utility.To add this utility to our application,

Add reference to,

vjslib - version : v2.0.50727 in our project.

To make use of this utility add the following namespaces to application.

using java.util;
using java.util.zip;
using java.io;

This makes the unzipping features available in our application.

I shall include the code which I used to unzip a file below.

private List GetZipFiles(ZipFile zipfil)
{
List lstZip = new List();
Enumeration zipEnum = zipfil.entries();
while (zipEnum.hasMoreElements())
{
ZipEntry zip = (ZipEntry)zipEnum.nextElement();
lstZip.Add(zip);
}
return lstZip;
}

private void Extract(string zipFileName, string destinationPath)
{
ZipFile zipfile = new ZipFile(zipFileName);
List zipFiles = GetZipFiles(zipfile);
foreach (ZipEntry zipFile in zipFiles)
{
if (!zipFile.isDirectory())
{
InputStream s = zipfile.getInputStream(zipFile);
try
{
Directory.CreateDirectory(destinationPath + "\\backUp");
FileOutputStream dest = new
FileOutputStream(Path.Combine(destinationPath + "\\backUp\\",
Path.GetFileName(zipFile.getName())));
try
{
int len = 0;
sbyte[] buffer = new sbyte[7168];
while ((len = s.read(buffer)) >= 0)
{
dest.write(buffer, 0, len);
}
}
finally
{
dest.close();
}
}
finally
{
s.close();
}
Console.WriteLine("File Extraction Complete.");
}
}
}

Now to unzip the file just call,

Extract("[ZipFileName]","[UnzippedFilename]");

Hope this helps...

Sunday, February 24, 2008

AutoCompleteMode TextBox

Hey Guys!!

Today I thought I shall give you a slight introduction about the possibilities of the AutoCompleteMode property of TextBoxes.

This is the property which helps in displaying the words similar to the one we are typing in the textbox in a dropdown below.Normally we see this feature while trying to login or so in any webpage.There are ofcourse other places were we can use this feature.

Today we shall see how to display the usernames similar to the one being typed in the textbox right below the textbox.We are using a MySQLConnection for the same.

To start with,

Place a textbox on a form and set its properties,

AutoCompleteMode to Suggest
and
AutoCompleteSource to CustomSource

Now as usual we require the connection,command and all to retrieve the data from MySQL

MySQL.Data.MySqlClient.MySqlDataReader read;

comm.Connection = connect;

comm.CommandText = "select * from users";
BindingSource bSource = new BindingSource();
read = com.ExecuteReader();
bSource.DataSource = read;
read.Close();

string usernameField = "username";//the field name from table
AutoCompleteStringCollection filterUsers = new AutoCompleteStringCollection();
foreach (object userItem in bSource.List)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(userItem);
PropertyDescriptor propDesc = props.Find(usernameField, true);
string fieldUserVal = propDesc.GetValue(userItem).ToString();
filterUsers.Add(fieldUserVal);
}

_searchTermUserText.AutoCompleteCustomSource = filterUsers;

This does the job.

Its very simple.We get the collection of fields from the bSource one row at a time.
Then filter just the username field from that and get the value of the field in this row.

We append each of these obtained values one by one to our string collection.Finally add that to the textbox.

I hope you were able to understand the things that I explained.

So...bye for now...Will come back soon with something more exciting. :)

Cheers....

Thursday, February 21, 2008

MD5CryptoServiceProvider C#

System.Security.Cryptography.MD5CryptoServiceProvider is a class that derives from MD5 and helps create hashes.

To create a hash of a string for storing in a data store, we make use of either the CryptoServiceProvider classes in the System.Security.Cryptography namespace, or the FormsAuthentication.HashPasswordForStoringInConfigFile method. Today we'll have a look at how to create a hash for a zip file using the MD5 algorithm.

In our case we are comparing a php generated md5 with a new md5 that we create.This function checks the download completion status of a zip file.

We already have an md5 for the whole zip file.Once we have downloaded the file we again check if the file has been downloaded completely generating an md5 for the downloaded file and then comparing with the md5 that we already have in hand.

private bool Comparemd5()
{
Console.WriteLine("Checking md5 Strings");

string gotmd5String = "";
gotmd5String = _md5String;//got md5 value from server along with the zip

MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
FileStream f = new FileStream(
Application.StartupPath + "\\abc.zip",
FileMode.Open, FileAccess.Read, FileShare.Read, 8192);

md5.ComputeHash(f);

f.Close();

///calculating the md5 of the abc.zip
Byte[] hash = md5.Hash;
StringBuilder buff = new StringBuilder();

foreach (Byte hashByte in hash)
buff.Append(hashByte.ToString("X2").ToLower());

if (gotmd5String.Contains(buff.ToString()))
return true;
else
return false;
}

MD5 are normally irreversible.So when we have to check the new value with an already saved md5 value then we always generate the md5 for that and compare both.

Like for example : a password string.In some applications the password will be stored as md5.So when the user comes back to login.We generate md5 for the password that he/she enters and then compare that with the value that we already have in hand.

Hope this example provides you an easy access for the md5 comparison.

Cheers...

Monday, February 18, 2008

Multidimensional Array in C#

Showing a simple example of a multidimensional array in c# because people coming from c++ background and all find it very difficult to make a multidimensional array in c#.

Here I am using a 2 dimensional array whose size is given in two textboxes,and later the values in the array is displayed in the listbox in the same form.

private void _addToArrayButton_Click(object sender, EventArgs e)
{
int total = 0;
int x, y = 0;
x = int.Parse(_firstPosText.Text);
y = int.Parse(_secondPosText.Text);
string[,] mulArray = new string[x, y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
total = i + j;
mulArray[i, j] = total.ToString();
}
}
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
_arrayList.Items.Add(mulArray[i, j].ToString());
}
}
}

A simple small example just to show the input to and output from a multidimensional array.