Twitter Feed Popout byInfofru

Get list of installed printers using C# WMI

Well, almost about an year back I write an application which search for the available printer on the server and do some operation accordingly. Today while browsing my code library I found that small test application. So I thought it would be good to share this with the community.

Management Objects are really good, I mean when it comes to windows you can do lots of operations using Management Object. You can get the list of services installed on system, hardware and etc. And the point which is worth to mention here is you can do that by using simple query like TSQL.

To access the printer information on the local machine you can use the following code

   1:             ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
   2:             objScope.Connect();
   3:            
   4:             SelectQuery selectQuery = new SelectQuery();
   5:             selectQuery.QueryString = "Select * from win32_Printer";
   6:             ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
   7:             ManagementObjectCollection MOC = MOS.Get();
   8:             foreach (ManagementObject mo in MOC)
   9:             {
  10:                 listBox1.Items.Add(mo["Name"].ToString().ToUpper());
  11:             }

 

The above code will use the current logged on identity as the default credentials. where as following code will get the list of printer installed from a remote location.

   1: ConnectionOptions objConnection = new ConnectionOptions();
   2: objConnection.Username = "aghausman";
   3: objConnection.Password = "nightmare";
   4: objConnection.Authority = "ntlmdomain:DDI"; //Where DDI is the name of my domain
   5: // Make sure the user you specified have enough permission to access the resource. 
   6:  
   7:  
   8: ManagementScope objScope = new ManagementScope(@"\\\\10.0.0.4\oot\\cimv2",objConnection); //For the local Access
   9: objScope.Connect();
  10:  
  11: SelectQuery selectQuery = new SelectQuery();
  12: selectQuery.QueryString = "Select * from win32_Printer";
  13: ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
  14: ManagementObjectCollection MOC = MOS.Get();
  15: foreach (ManagementObject mo in MOC)
  16: {
  17:     listBox1.Items.Add(mo["Name"].ToString().ToUpper());
  18: }

 

and here is the attachment of the solution files created in Visual Studio 2008

Downloading Zip File Using Asp.net

Here is the quick code of downloading the zip file from asp.net (vb.net)

   1: Dim _strBeingViewedName As String = "MyZip"
   2: Response.ContentType = "application/x-zip-compressed"
   3: Response.AppendHeader("Content-Disposition", "attachment; filename=" + _strBeingViewedName + ".zip")
   4: Response.TransmitFile("..\\zipPath\\" & _strBeingViewedName + ".zip") 'Full Path of the zip file
   5: Response.End()

Z-Index Problem with Flash Object

From this morning I have been snatching my hairs over a very strange problem with Flash Object. Actually I am not a Flash Guru, but I just want to place a flash animation on the home page of the web site which is unfortunately using the Asp Horizontal Menu. The problem lies when the menu drops down and it goes behind the flash object. I thought it is z-index issues, that’s why I put style tag on object tag and give z-index but it didn’t tricked. After full one day of working over it as there is no comprehensive post on the Internet for this sick problem. Here is the snippet which works like a charm for me. 
   1: <div id="Container">
   2:  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="960" height="370">
   3:   <param name="wmode" value="transparent">
   4:   <param name="movie" value="../banner/banner.swf"/>
   5:   <param name="quality" value="high" />
   6:   <embed src="../banner/banner.swf" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="960" height="370" wmode="transparent"></embed>
   7:   </object>
   8:   </div>
I create new param called “wmode” and set its value to “transparent”. In embed tag I specify wmode="transparent" I take the flash object in a div and here is the style for that div.
   1: <style type="text/css">
   2:     #Container
   3:     {
   4:         position: relative; /*or absolute*/
   5:         z-index: 1;
   6:     }
   7: </style>
Now take the Asp Menu in a div and give z-index value higher then we have one in object container div. Also, it is worth to mention here that the flash script generated from Dreamweaver usually contain the following installation script as well which is not compatible to work with this.
   1: <script type="text/javascript">
   1: 
   2: AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','width','960','height','370','src','file://Path','quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','movie','file:///Path' ); //end AC code
</script><noscript>
As I said I am not a flash champ, but at least in my case this code was creating problem. So I preferred to delete this ;)

CLR Integration and Lightweight Pooling Conflict

I thought I am CLR Integration Guru in Sql Server but this morning I came to know that there are lots of things left to grab. While I was moving the local database on the new live server I run some CLR Procedure which Says these procedures required CLR Integration enabled. So to get that done.
I went on SQL Server Surface Area Configuration -> Surface Area configuration for features -> Enable CLR Integration. till here, every thing seems fine I encounter no error.
After that when I re-execute the same query I get a new error:
"Invalid connection (Common languageruntime (CLR) execution is not supported under lightweight pooling.Disable one of two options: "clr enabled or "lightweight pooling".
I really have no idea what the light weight pooling is but the need of the time is to disable it. After googling for a bit I get this link. but still no use as the query written in this page is not working infact it is giving error.
Query:sp_configure 'show advanced options', 1;GOsp_configure 'lightweightpooling', 0;GORECONFIGURE;GO
Error:The configuration option 'lightweightpooling' does not exist, or it may be an advanced option.
To find what is going wrong, I quried on sys.configurations because this table contain database configuration.
select * from sys.configurations where name like '%light%'
Finally, after running the above query I came to know that there is a space in 'lightweightpooling'. It means it is 'lightweight pooling. Now when I diagnose the problem I execute the following query which make my sql server CLR Integrated.
USE masterGOEXEC sp_configure 'show advanced options', 1GORECONFIGURE WITH OVERRIDEGOEXEC sp_configure 'lightweight pooling', 0GOEXEC sp_configure 'clr enabled', 1goRECONFIGURE WITH OVERRIDEGOEXEC sp_configure 'show advanced options', 0GO
After executing the query, we might need to restart the SQL Services to make it work.

Beta Components Detected on SQL Server 2005 Installation

This weekend, I was in Morgan Technologies as they were facing some installation problem in SQL Server 2005 enterprise edition. So they called me up with relation to the community work. So the error was
Errors occurred during the installation:Beta components detected.
It looks that there is some beta software running on the server but after looking at the Program Files and Add Remove Program It seems that there is nothing installed before. No Visual Studio Installation (as that is server) , no Beta stuff. There was .net framework 2.0 installed but to get rid of this error I did uninstall that too.But the error doesnot seems to go. still the beta components deteced comes on screen each time I try to install SQL Server.So, Finally I found Microsoft MSI Cleanup Utility which did my job perfectly. on a clean machine where there is nothing Installed I found two microsoft beta installations, No idea where it came from but this tool remove that and afterward SQL Server installed like a butter with no issue.To download the tool : http://support.microsoft.com/kb/290301

Waking up for Fajr. It Easy!

May Almight ALLAH give all of us the sprit of waking up early in the morning for fajr.

Dawah

Backup Failed : System.Data.SqlClient.SqlError: Failed to pause catalog for backup. Backup was aborted.

So, not too long ago I was regular blogger but due to builds and examinations I am getting far from this stuff. Anyway, this morning when I was taking backup of the database located on one of our dedicated server. I hunt the following error.
System.Data.SqlClient.SqlError: Failed to pause catalog for backup. Backup was aborted.
In short, you are no more able to take backups. So I googled about this error but trust me, there is no much information regarding this stuff. So, to get rid of it, you quickly need to do the following steps.
1. Jump to the services console. (Control Panel-> Administrative Tools -> Services)2. Locate the SQL Server FullText Search and verify is it running.3. If it is not running then start it .... but hold on read the next point4. If it is running then verify what account which it is using under Log On tab.  (it should be Local System Account)5. Save the settings and make sure to restart the service and you are done.

Protecting images with Response Filter

In this article we will see how we can change the email addresses written on a website to images on the fly. The general opinion about this task is to revamp the form where we are asking user to input the email address and then generate an image which will display later instead of email address.Fortunately, Asp.net provides us with a feature called Response filter which allow us to alter the response generated by web server. By using Response filter we don’t need to alter the foundation of our application. We just need to plug that response filter in and our work is done.So to create a filter we need to create a class called “EmailFilter.CS” which will inherit from Stream.
public class EmailFilter : Stream{private string _path;private Stream _response;public EmailFilter(Stream response, string path){_response = response;_path = path;}
public override int Read(byte[] buffer, int offset, int count){return _response.Read(buffer, offset, count);}
public override void Write(byte[] buffer, int offset, int count){}} 
This can easily be read that we have two local variables which are getting set by our parameterized constructor and we have overrides two functions out of which the write function is really important. We are going to play with that function throughout the tutorial.Note:It is also important to mention here that we have removed some code for clarity but to use the stream class you need to override the some other functions and properties which you can find in code attached.
Now the next step is to write the code in Write method.
 
public override void Write(byte[] buffer, int offset, int count){string html = System.Text.Encoding.UTF8.GetString(buffer);string emailPattern = @"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
Regex objRegex = new Regex(emailPattern);MatchCollection objCol = objRegex.Matches(html);
foreach (Match m in objCol){string email = m.Value;Font objFont = new Font("Arial", 12, FontStyle.Bold);int width = (int) getTextWidth(email, objFont);Bitmap objBitmap = new Bitmap(width, 20);Graphics objGraphics = Graphics.FromImage(objBitmap);objGraphics.FillRectangle(Brushes.White, new Rectangle(0, 0, width, 20)); //getting white bgobjGraphics.DrawString(email, objFont, Brushes.Black, new Point(0, 0));string relpath = "images/" + Guid.NewGuid().ToString() + ".jpg";string saveFileName = _path + relpath;objBitmap.Save(saveFileName,System.Drawing.Imaging.ImageFormat.Jpeg);objGraphics.Dispose();objBitmap.Dispose();string imgMarkup = "<img src='" + relpath + "'/>";html = html.Replace(email, imgMarkup);}buffer = System.Text.Encoding.UTF8.GetBytes(html);_response.Write(buffer, offset, count);}protected float getTextWidth(string strText, Font f){float width = 0;Bitmap objBitmap = new Bitmap(1, 1);Graphics objGraphics = Graphics.FromImage(objBitmap);try{width = objGraphics.MeasureString(strText, f).Width;return width;}catch (Exception){return 0;}finally{objBitmap.Dispose();objGraphics.Dispose();}} 
The first four lines are easy to understand we are just storing the HTML generated by web server to a variable and we have created a regular expression object to check for the email addresses in out html.
In foreach loop we are generating the images of every email address using System.Drawing and saving the images in a temp location and finally disposing the objects.Now the main stuff is here, we are creating a string variable which will hold html image tag with source and then replace the email address with the image tag.
Whereas, getTextWidth is a simple function which measure the width of our text and return it so that we can have dynamic width for different size of texts.Let's use this response filter in our aspx page. To do that we need to write the following code in Page_Load 
protected void Page_Load(object sender, EventArgs e){Response.Filter = new EmailFilter(Response.Filter, Server.MapPath("/").ToString());}
It is worth to mention here the parameter. Our Response filter is just a class file and we donot have the Server path in classes but we still want to store the images using relative path so to do that we just pass the root path as parameter which we will use in Response Filter to save the image. To understand the situation correctly we need to write the following code in the form tag of our aspx.
<div>aghausman@gmail.com </br>aghausman@ciberstrategies.com</br>me@aghausman.net</br></div>
That is nothing but three simple email addresses. Now when you run the page you will see the following output. Notice that we have write three email addresses but it is showing only two. To see what went wrotn we have let's have a look at the source given below:[singlepic=27,500,200,web20,]
Notice that there is no html after the br of second image. It means there is some thing wrong with the response.write. Now to understand what happen we need to go back and read the last line of our Write function which is as follows
_response.Write(buffer, offset, count);
here we are simply passing what we have get from Write parameter but the matter of fact is that it is now changed. Remember, we have change our email address with the image tag so to compare let's see our first email address and frst generated image. 
Email Address : aghausman@gmail.comImage Text : <img src='images/da04a458-7ff4-41cb-b982-5724c1eadb84.jpg'/>
Notice that image tag is using more then double characters. so we need to change the last parameter count according to the new condition. for that let's see the Write method code again.
  
 
public override void Write(byte[] buffer, int offset, int count){string html = System.Text.Encoding.UTF8.GetString(buffer);string emailPattern = @"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
Regex objRegex = new Regex(emailPattern);MatchCollection objCol = objRegex.Matches(html);
int totCount = 0;foreach (Match m in objCol){string email = m.Value;Font objFont = new Font("Arial", 12, FontStyle.Bold);int width = (int) getTextWidth(email, objFont);Bitmap objBitmap = new Bitmap(width, 20);Graphics objGraphics = Graphics.FromImage(objBitmap);objGraphics.FillRectangle(Brushes.White, new Rectangle(0, 0, width, 20)); //getting white bgobjGraphics.DrawString(email, objFont, Brushes.Black, new Point(0, 0));string relpath = "images/" + Guid.NewGuid().ToString() + ".jpg";string saveFileName = _path + relpath;objBitmap.Save(saveFileName,System.Drawing.Imaging.ImageFormat.Jpeg);objGraphics.Dispose();objBitmap.Dispose();string imgMarkup = "<img src='" + relpath + "'/>";totCount += imgMarkup.Length;html = html.Replace(email, imgMarkup);}buffer = System.Text.Encoding.UTF8.GetBytes(html);_response.Write(buffer, offset, count + totCount);} 
We have only create an int variable before loop and on every loop we are adding the length of image tag to the variable and finally on response.write we are adding the count with the length of image tags we have generated. that's it.Now if we run the page we will see the following output:  
[singlepic=26,500,200,web20,]That's all, we have now replace the emal addresses written on our website to images. Just in case you don't want to write the page_load stuff on every page as it is very difficult then you can also use httpModule. For the see the following code
public class EmailToImages : IHttpModule{public void Dispose(){
}public void Init(HttpApplication application){HttpContext context = HttpContext.Current;
context.Response.Filter = new EmailFilter(context.Response.Filter, context.Server.MapPath("/"));}}<httpModules><add name="EmailToImage" type="LearnWebApp.EmailToImages, LearnWebApp"/></httpModules> 
Now to remove the temperory images you might need a code which delete the images in timely fashion. That's all.
 Orignal Article and source code will be find at : http://www.highoncoding.com/Articles/468_Protecting_Email_Addresses_Using_Response_Filters.aspx

Fill Asp Menu by Folder

In this post, we will see how can we fill the Asp Menu by specifying folder instead of some other data source. Following is the folder structure which this code is supportedRoot-> Folder 1 -> Files-> Folder 2 -> Files-> Folder 3 -> FilesI mean, if there is another folder in Folder 1 or Folder 2 or Folder 3. The code will not detect because it is not recursive.So Let's get down to the code
protected void Page_Load(object sender, EventArgs e){DirectoryInfo di = new DirectoryInfo(@"C:\\agha"); //Path of folder you want get file/folder fromDirectoryInfo[] objDi = di.GetDirectories();foreach (DirectoryInfo d in objDi){MenuItem objMenuItem = new MenuItem(d.Name);FileInfo[] objfi = d.GetFiles("*.*");foreach (FileInfo f in objfi){objMenuItem.ChildItems.Add(new MenuItem(f.Name));}Menu1.Items.Add(objMenuItem);}}