Thursday, August 13, 2009

.NET Image Manipulation programmatically

Sometimes developer need to do image manipulation pro grammatically:
  1. Resizing the image width/height.
  2. Change image format.
  3. Decrease image quality to decrease image size.
Code Below will help developers to do these tasks:
  1. We will declare variable for new image width, height, Quality(1-100), extension.
  2. Create Bitmap from physical file or stream.



  3. // Create a bitmap from the stream
    Bitmap oldImage = new Bitmap(filename);

  4. Initialize new bitmap using new width and height.


  5. // Initialize new bitmap using new width and height.
    Bitmap newImage = new Bitmap(Width,Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
  6. Initialize graphic from new image.
  7. Draw old image with new width and height to new image variable.

  8. Graphics g = Graphics.FromImage(newImage);
    g.DrawImage(oldImage,0,0,newImage.Width,newImage.Height);
  9. Before we save image we need get encoder of its new type.

  10. private ImageCodecInfo GetEncoderInfo(String mimeType)
    {
    ImageCodecInfo[] encoders;
    encoders = ImageCodecInfo.GetImageEncoders();
    for(int _iLoop = 0; _iLoop<encoders.Length; ++j)
    {
    if(encoders[_iLoop].MimeType == mimeType)
    {
    return encoders[_iLoop];
    }
    }
    return null;
    }
  11. Last step will save image with its new configurations:


  12. EncoderParameters imgParams = new EncoderParameters(1);
    imgParams.Param[0] = new
    EncoderParameter(System.Drawing.Imaging.Encoder.Quality,Quality);
    ImageCodecInfo ici = GetEncoderInfo(sMime);
    ImageCodecInfo newici = GetEncoderInfo(sNewMime);
    imgBitMap.Save(newstream, newici,imgParams);




Wednesday, April 1, 2009

Javascript Get Page Height With Scroll

This javascript return width and height of a web page including the scroll.
function getSizeWithScroll()
{
if (window.innerHeight && window.scrollMaxY!=undefined)
{
// Firefox
yWithScroll = window.innerHeight + window.scrollMaxY;
xWithScroll = window.innerWidth + window.scrollMaxX;
}
else
{
var body = document.body;
if (body && body.parentElement=null&&body.parentElement.clientHeight)
{
height = body.parentElement.clientHeight;
htmlheight = body.parentElement.scrollHeight;
width = body.parentElement.clientWidth;
htmlwidth = body.parentElement.scrollWidth;
yWithScroll = height>htmlheight?height:htmlheight;
xWithScroll = height>htmlheight?width:htmlwidth;
}
else
if (body && body.clientHeight)
{
height = body.clientHeight;
htmlheight = body.scrollHeight;
width = body.clientWidth;
htmlwidth = body.scrollWidth;
yWithScroll = height>htmlheight?height:htmlheight;
xWithScroll = height>htmlheight?width:htmlwidth;
}
}
arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
return arrayPageSizeWithScroll;
}

There is another option using JQuery:
$(window).width(); //width without scroll
$(window).height(); //height without scroll
$(document).width(); //width with scroll
$(document).height();//height with scroll

Thursday, March 5, 2009

ODBC on 64 bit machine (Windows/VISTA)?

As we all database developers know that a ODBC DSN is an entry that we created through "ODBC Data Source Administrator" that we reached from Start/Control Panel/AdministrativeTools or typing "odbcad32" from Start/Run .
On a 64bit machine when you run "ODBC Data Source Administrator" and created an ODBC DSN, actually you are creating an ODBC DSN which can be reachable by 64 bit applications only(You will not see most of drivers).

To run your 32bit application on a 64 bit machine, You need to run the 32bit version of "odbcad32.exe" by running "c:\Windows\SysWOW64\odbcad32.exe" from Start/Run menu and create your ODBC DSN with this tool.

The key point here to remember is a 64bit machine should be considered as a "64 bit Windows + 32 bit Windows" at the sametime. That's why the folder that our developers put the 32bit "odbcad32.exe" under C:\Windows\SysWOW64\ . The WOW abbreviation here means "Windows on Windows"

Look at the C:\Windows\SysWOW64\ for the EXE files at least to know what sort of other EXEs/DLLs are also compiled as 32bit and shipped within your 64bit OS.

For example cscript.exe and wscript.exe are ther for your WSH (Windows Scripting Host) scripts which needs to be run as 32bit. Think about a scenario like that. Only the 32 bit version of the OLE DB Provider or ODBC Driver exists for the data source that you need to get the data from your VBScript code. If it's the case, you'll need create the ODBC DSN (assuming that you're going to use ADO + ODBC in your VBScript code) from C:\Windows\SysWOW64\odbcad32.exe and also you should call your script as
"C:\Windows\SysWOW64\wscript.exe C:\scripts\myscript.vbs".
Doubleclicking the myscript.vbs from the Windows Explorer will result your script to be executed as
"C:\Windows\System32\wscript.exe C:\scripts\myscript.vbs".

Sunday, March 1, 2009

LINQ to SQL and multiple result sets in Stored Procedures

When you want to use stored procedure return multiple results you can't depend on auto generated class. You must do it manually, following steps below:
1. Create Entities for returned types:
example: we will create 2 entities ACCOUNT, ACCOUNT_USERS to LINQ to SQL Data Context
2. Create Partail class inherited from LINQ to SQL Data Context and add your method as below:
example for stored procedure will be test.

public partial class DataClasses1DataContext
{
[Function(Name = "dbo.Test")]
[ResultType(typeof(ACCOUNT))]
[ResultType(typeof(ACCOUNT_USER))]
public IMultipleResults Test([Parameter(DbType = "Int")] System.Nullable tmp)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), tmp);
return ((IMultipleResults)(result.ReturnValue));
}
}


3. Now you can use this method as below

DataClasses1DataContext c = new DataClasses1DataContext();
var r = c.Test(null); ;
ACCOUNT a = r.GetResult();
c.Dispose();

Thursday, February 12, 2009

Installing Multiple Instances of Windows Service

To Installing Multiple Instances of Windows Service.

  • Install InstallUtil.exe.
  • Add a /name parameter to specify what the service will be named. The names have to be unique, so if you already have "Telligent Mail Gateway", you might need to name it "Telligent Mail Gateway - Site 2".
  • Specify the filename of the Windows Service, which is usually like "....Service.exe”. With Mail Gateway.

    it would be like this:
    InstallUtil /name="Telligent Mail Gateway - Site 2" Service.Service.exe

    Run this from a command prompt within the add-ons directory. The name must be in quotes if it contains spaces and must come before the filename.
How to Uninstall:

Uninstalling the service is very similiar to installing. You will still use the InstallUtil.exe program and will need to specify the name of the service to uninstall, though this time you will need to add a /u switch to specify that you intend to uninstall it. For instance:

InstallUtil /u /name="Telligent Mail Gateway - Site 2" Service.Service.exe

The name must be specified since if you have multiple instances of the same executable installed, it will need to know which one. If no name is specified, it will remove the one with the default name as opposed to a custom named one.

Again, the uninstall and name parameters must come before the filename so that it know they are for that file.

Monday, January 26, 2009

SQL Server Management Studio 2008 suggests missing indexes with actual execution plan

When you choose to Include the Actual Execution Plan in SSMS 2008 it suggest any missing indexes it thinks that are needed. Plus it also calculates the performance benefit from adding them.

And best of all this also works when you're connected to a SQL Server 2000 or 2005.

Updated Unused Index Query

To clean up and update unused index query. Query below returns a list of indexes ordered by ascending reads. If the instance has been up for a long time, it is probably safe to drop indexes with zero or close to zero reads. If the reads are low and the writes are high, this may help improve your transactions per second count. Otherwise, you are just cleaning up unused space. Use caution though. A missing index is worse than an unused index.

SELECT objectname=OBJECT_NAME(s.OBJECT_ID)
, indexname=i.name
, i.index_id
, reads=user_seeks + user_scans + user_lookups
, writes = user_updates
, p.rows
FROM sys.dm_db_index_usage_stats s JOIN sys.indexes i
ON i.index_id = s.index_id AND s.OBJECT_ID = i.OBJECT_ID
JOIN sys.partitions p ON p.index_id = s.index_id AND s.OBJECT_ID = p.OBJECT_ID
WHERE OBJECTPROPERTY(s.OBJECT_ID,'IsUserTable') = 1
AND s.database_id = DB_ID()
AND i.type_desc = 'nonclustered'
AND i.is_primary_key = 0
AND i.is_unique_constraint = 0
AND p.rows > 10000
ORDER BY reads, rows DESC

Dynamic SQL using like

Dynamic SQL was the best choice by far in terms of performance for dynamic search problems,
check article below:
http://www.sommarskog.se/dyn-search-2008.html

It takes a long time from me to write a correct sysntax with LIKE criteria

First I wrote Syntax:

DECLARE @SQL nvarchar(4000)
SET @SQL='SELECT [CategoryName]
FROM [StarterSite_productcatalog].[dbo].[Adventure Works Catalog_CatalogProducts]
where categoryname like ''%@param1%'''
DECLARE @param1 nvarchar(20)
DECLARE @paramlist nvarchar(20)
SET @param1='sl'
SET @paramlist = '@param1 varchar(20)'
EXEC sp_executesql @sql, @paramlist,@param1


I found correct syntax:

DECLARE @SQL nvarchar(4000)
SET @SQL='SELECT [CategoryName]
FROM [StarterSite_productcatalog].[dbo].[Adventure Works Catalog_CatalogProducts]
where categoryname like ''%''+@param1+''%'''
DECLARE @param1 nvarchar(20)
DECLARE @paramlist nvarchar(20)
SET @param1='sl'
SET @paramlist = '@param1 varchar(20)'
EXEC sp_executesql @sql, @paramlist,@param1

Friday, January 16, 2009

LINQ to SQL Serialization

Problem:
  • LINQ to SQL classes do not support binary serialization. Although I can manually modify them to meet my needs, it is a very time-consuming job, and difficult to maintain if the table is changed in the future.
  • LINQ to SQL classes cannot be serialized by XML serializer if there is a relationship between tables.

These articles give us work around:
http://www.west-wind.com/WebLog/posts/147218.aspx
http://www.codeproject.com/KB/linq/linqsqlserialization.aspx

LINQ and Dynamic Query Expressions and SQL Injection

When you want to create LINQ with dynamic expression you will use concatenate string like:
var query = db.Customers.Where("City = '"+country+"' and Orders.Count >="+ordersCount)
.OrderBy("CompanyName")
.Select("new(CompanyName as Name, Phone)");


To prevent SQL injection you must use parameters:
var query = db.Customers.Where("City = @0 and Orders.Count >= @1", country, ordersCount)
.OrderBy("CompanyName")
.Select("new(CompanyName as Name, Phone)");