Sunday, 26 December 2010

old "dbo" database owner prevents service broker from working properly - SQL 2005

I have cloned a virtual copy of Win2003 server that has SQL2005 already installed. The new server is planned to be disconnected from the domain of the original server and run separately.

 

In SQL2005 I dropped all databases and restored my database that has service broker already enabled, the restored database was running very well on another server inside my old domain "AWQAF", this database also has a notification service running on top of a message queue called "messageQueue".

 

Service broker then didn't working as supposed or as it should to work like.

 

I tried to check the status of the service broker using the following statement:

SELECT is_broker_enabled FROM sys.databases WHERE name = 'AfaqCMS';

 

It gives me 0 result, a mean of service broker is disabled.

 

So, I tried to enable service broker using the following statement:

ALTER DATABASE [AfaqCMS] SET NEW_BROKER WITH ROLLBACK IMMEDIATE;

 

By trying to SEND/RECIVE messages using the following statements, I got dialog created without messages transmission:

DECLARE @NotificationDialog uniqueidentifier;

SET QUOTED_IDENTIFIER ON;

BEGIN DIALOG CONVERSATION @NotificationDialog

FROM SERVICE ChangeNotifications

TO SERVICE 'ChangeNotifications'

ON CONTRACT [http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]

WITH ENCRYPTION = OFF;

SEND

ON CONVERSATION @NotificationDialog

MESSAGE TYPE [http://schemas.microsoft.com/SQL/Notifications/QueryNotification] (N'CommentHits');

SELECT @NotificationDialog;

RECEIVE * FROM ChangeMessagesQueue ;

 

By checking transmission queue of the system I found some errors around the original owner of the restored database.

SELECT * FROM sys.transmission_queue

 

A filed called "transmission_status" is containing the following exception:

An exception occurred while enqueueing a message in the target queue.

Error: 15404, State: 11.

Could not obtain information about Windows NT group/user 'AWQAF\adm_walghool', error code 0x534.

 

By deleting 'AWQAF\adm_walghool' from all locations it can be existed in, I got another status:

An exception occurred while enqueueing a message in the target queue.

Error: 15517, State: 1.

Cannot execute as the database principal because the principal "dbo" does not exist,

this type of principal cannot be impersonated, or you do not have permission.

 

Now I realized that it is the database owner that prevents service broker from working properly, So I run the following statement to get every things working successfully again:

ALTER AUTHORIZATION ON DATABASE::[AfaqCMS] TO [SA]

 

Anthother statement can be used also:

 

USE AfaqCMS

GO

EXEC dbo.sp_changedbowner @loginame = N'zakauser', @map = false

 

 

 

 

Monday, 2 August 2010

What is the difference between ISO 9660, Joliet and UDF?

CD-ROM File Systems

An ISO 9660 file system is a standard CD-ROM file system. Full ISO format requires all upper case characters or numbers, no spaces, very limited special characters, and no more than 30 characters in the name.

Joliet is the name of an extension to the ISO 9660 file system. Joliet format permits 64-character file names with lower-case alpha and other relaxed restrictions. It also relaxes the ISO requirement for directory nesting to no more than eight levels. It doesn't hurt to include the Joliet Directory if the names conform.

UDF is a hybrid filesystem that uses both UDF and ISO 9660. Also called a UDF bridge, it was commonly used until Microsoft incorporated support for UDF in its operating system. UDF permits 127 16-bit Unicode characters, or 254 8-bit Unicode characters. If any character in any name is not in the list of legal 8-bit Unicode characters, all names will be represented in 16-bit Unicode.

However Joliet is no longer needed since the ISO 9660 standard has been extended in 3 different levels:
Level 1: Filename cannot be longer than 8 chars , Filename extention cannot be longer than 3 chars.
Level 2: Filename can be up to 255 chars long.
Level 3: Same as level 2 but files can be written in multiple extents (-> Packet writing).


Normally a Mac can read both ISO 9660 and Joliet CDs.

Monday, 28 June 2010

ClickOnce does not install fonts - Install fonts using C#

ClickOnce does not install fonts. ClickOnce is designed to be a non-impactful install, and installing fonts is considered impactful to a user's computer. ClickOnce is only a deployment technology, it does not offer any support for font installation, so this operation requires extra coding. We have to code the font installation logic in the application. To install font on client machines, we have to create code just like the following.

ClickOnce deloyment normally does not touch the system directories. This is an important difference with MSI deployment technology. ClickOnce deployment does not cover:
· "Install to GAC"(GAC is another system directory)
· "Write to Registry"
· "Install for All Users" etc... While these can all be done with MSI:

Take a look to "Key Differences" between ClickOnce and MSI:
http://msdn.microsoft.com/en-us/library/142dbbz4(VS.90).aspx

So we have to code ourselves for the font installation, first: write file from embedded resource, second: add font to windows resources, third: add registry entry so the font is also available next session, finally: solve GDI+ bug, where GDI+ must be notified with this new added font, so, a scalable font resource file needs to be created, this scalable font resource file stores the name of a TrueType font file so that GDI knows where to find the file. To create a scalable font resource file, call the GDI function CreateScalableFontResource with an integer flag, the name of the font resource file to be generated, an existing TrueType font file name, and the path to the files if they do not contain a complete path.

First: Special thanks for following threads:

http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic52983.aspx
http://www.daniweb.com/forums/thread231795.html
http://www.dotnetmonster.com/Uwe/Forum.aspx/winform/18215/ClickOnce-deployment-include-font

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Drawing.Text;
using System.Windows.Forms;
namespace myNameSpace

{
class InstallFonts
{
// PInvoke to look up fonts path
[DllImport("shfolder.dll", CharSet = CharSet.Auto)]
private static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);

private const int CSIDL_FONTS = 0x0014;
private const int MAX_PATH = 260;
private static string GetFontsPath()
{
StringBuilder sb = new StringBuilder(MAX_PATH);
SHGetFolderPath(IntPtr.Zero, CSIDL_FONTS, IntPtr.Zero, 0, sb);
return sb.ToString();
}

// PInvoke to 'register' fonts and broadcast addition

[DllImport("gdi32.dll")]
private static extern int AddFontResource(string lpszFilename);

[DllImport("gdi32", EntryPoint = "RemoveFontResource")]
private static extern bool RemoveFontResourceW(string lpFileName);

[DllImport("gdi32.dll")]
private static extern int CreateScalableFontResource(uint fdwHidden, string lpszFontRes, string lpszFontFile, string lpszCurrentPath);

private static IntPtr HWND_BROADCAST = new IntPtr(0xffff);
private const uint WM_FONTCHANGE = 0x001D;

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

public static void InstallFont()
{

string fontsPath = GetFontsPath();
string ttfFile9 = System.IO.Path.Combine(fontsPath, "V100009_.TTF"); ;
string fotFile9 = System.IO.Path.Combine(fontsPath, "V100009_.FOT"); ;

int ret;
if (!System.IO.File.Exists(ttfFile9))
{
//Write file from embedded resource
System.IO.File.WriteAllBytes(ttfFile9, MyFonts.V100009_);
//Allow GDI+ to be notified and determines the new fonts
//to install a TrueType font, a scalable font resource file needs to be
//created. This scalable font resource file stores the name of a TrueType
//font file so that GDI knows where to find the file. To create a scalable
//font resource file, call the GDI function CreateScalableFontResource with
//an integer flag, the name of the font resource file to be generated, an
//existing TrueType font file name, and the path to the files if they do not
//contain a complete path.
ret = CreateScalableFontResource(0, fotFile9, ttfFile9, String.Empty);
//Add font resource
ret = AddFontResource(fotFile9);
//Add registry entry so the font is also available next session
Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", "C39HrP36DlTt (TrueType)", "V100009_.TTF", RegistryValueKind.String);

//Broadcast to let all top-level windows know about change
ret = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, new IntPtr(0), new IntPtr(0));
//Work around to use font after installing without restarting the installing application
//It is GDI+ bug not .NET bug,
PrivateFontCollection oPFC9 = new PrivateFontCollection();
oPFC9.AddFontFile(ttfFile9);
}
}
}
}

Tuesday, 22 June 2010

An error occurred creating the configuration section handler for system.serviceModel/bindings

Suddenly I got a problem when trying to access a web service,
the problem only occurred on my PC that has "Vista SP1 x64"
operating system, my workmates hasn't this problem at all, this is the exception
string appeared:


System.TypeInitializationException: The type initializer for
'my internal class name' threw an exception. --->
System.Configuration.ConfigurationErrorsException: An error occurred creating
the configuration section handler for system.serviceModel/bindings: Could not
load type
'System.Security.Authentication.ExtendedProtection.Configuration.ExtendedProtectionPolicyElement'
from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
(D:\Projects\Hajj1431\Sources\Desktop\Hajj\bin\Release\Hajj.exe.Config line 38)
---> System.TypeLoadException: Could not load type
'System.Security.Authentication.ExtendedProtection.Configuration.ExtendedProtectionPolicyElement'
from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.


I googled and found some thing similar

here
,

here
,

here
and

here
. All of them points to a corrupted windows update with code KB982168, I
spend long time searching about KB982168 or any thing similar but nothing. Where
all of the previous threads were talking about Win2003 and WinXP updates.


I tried to restore my operating system to old date but Windows
Restore was disabled by group policy created by Domain Admin.


I tried to go deep in the problem to find which assembly cause
the problem but it seems it is some thing larger than a single assembly.


After long time of try and error I reached a solution by
installing Vista Service Pack 2.


Where, I noticed that Microsoft announced it will not support
Vista without SP2, so, I realized that any update my not work properly without
SP2, again searching, I found x64 version of mentioned SP2, it takes an hour to
download and another hour or more to install, but finally web-services is back
to work again.


Thanks god ...


Service Pack 2 (KB948465):



It is 745MB size and can be downloaded from this link:


http://www.microsoft.com/downloads/details.aspx?FamilyID=8ad69826-03d4-488c-8f26-074800c55bc3&displaylang=en&displaylang=en

Tuesday, 18 May 2010

The remote server returned an error: (502) Bad Gateway.

The remote server returned an error: (502) Bad Gateway.

Simply I want to access internet-world from inside my web-application using the following code.

public static string BrowseURL(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "GET";
request.Credentials = CredentialCache.DefaultCredentials;
//
request.Proxy = WebProxy.GetDefaultProxy();
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
//
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet));
string responseData = reader.ReadToEnd();
return responseData;
}

On my development machine it works fine, but on production server I faced a problem of "Bad Gateway" when reaching GetResponse(), I realized that it was an authentication problem, and after some google_ing, I found a good thread that speaks about solving Proxy problems with authentication. Now, the following code is working properly on my production environment.

public static string BrowseURL(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "GET";
request.Credentials = CredentialCache.DefaultCredentials;
//that is the solution
WebProxy proxy = new WebProxy("proxy ");
proxy.Credentials = new NetworkCredential("userName", "Password", "Domain");
request.Proxy = proxy;
//
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet));
string responseData = reader.ReadToEnd();
return responseData;
}

Saturday, 15 May 2010

Conditional buidl Events using Viusal Studio 2008

Sometimes you need some extra actions to be trigged after build, eg. copy exe files. To add an extra action, go to project properties and select “Build Events” tab. You can add the additional actions before and after build process.

But what if some conditions are needed to check before performing your action. !

Two things you have to investe in order to know how to make conditional build event in VS2008, first, is the command macros introduced by Microsoft in VS2008, second, is the batch file ".BAT" commands.


Command Macros are
here.
BAT Commands are
here.

Example:

IF NOT $(ConfigurationName) == Release GOTO end
Copy "$(SolutionDir)\$(ConfigurationName).exe" "$(TargetPath)"
:end

Wednesday, 5 May 2010

C++ Macro Concatination

You can use ## operator (double number sign) to concatinate two tokens (text or arguments) in macro invocation.

Example:

enum Types {T1,T2};
#define MakeDrivedClass(name, type) class name##type : public type##Base{}
MakeDrivedClass(CMy,t1);

Output:
class CMyT1 :  public T1Base {};

Saturday, 3 April 2010

500.19 IIS7 ERROR

After createing a new ASP.NET application, and after publishing to certain folder, IIS7 refused to open the published site because of 500.19 error, IIS7 said that the requested page cannot be accessed because the related configuration data for the page is invalid.



But, in fact it is a security issues that prevent mister IIS7 from accessing web.config file. Particularly, it was computername\IIS_IUSRS that must take some permisions, read this article for more information.

Solution:
Simply add the following groups into security tab to solve this problem:
1- Authenticated Users
2- Users (computername\Users)



Tuesday, 16 March 2010

Allow only one instance of any Windows Form, C#

The ability to load forms once, is something essential in many applications. But, this is a simple way to do that:

public Boolean IsFormAlreadyLoaded(string formToLoadName)
{
    //Allow only one instance of any MDI child form in your MDI application
   
foreach (Form frmChild in this.MdiChildren)
    {
        if (frmChild.Name == formToLoadName)
        {
            frmChild.Activate();
           
return true;
        }
    }
   
return false;
}

Monday, 15 March 2010

Printer capabilities

This is an excelent article about printing essentials, and,  here is my own experiments using some different printers:

HP Officejet Pro All-in-One


HP Color LaserJet 3800
KONICA MINOLTA mc7450 PS

Tuesday, 9 March 2010

ClickOnce signing error and its solution :)

This is the error:
error: 0x80880253
The signer's certificate is not valid for signing.
SignTool Error: An error occurred while attempting to sign: bin\Debug\app.publish\\setup.exe

A very good work but not work with me: http://www.may.be/renewcert/

A very good comment that brings me to the road and solve the problem:
http://social.msdn.microsoft.com/Forums/en/winformssetup/thread/cebc2dff-1418-4be4-b3f7-9e158ed6b573

This the magic comment:
Are you signing your ClickOnce deployment? If you go to the Signing tab for your project, do you have a certificate selected?

If you are just pushing updates for the same application, you will want to track down the certificate file (pfx) you used to use and sign with it instead of creating a new one, so the deployment does not think you created a new certificate.
If you are just deploying something new, you can create a test certificate and use that.
RobinS.
GoldMail.com

Sunday, 7 March 2010

Identify yourself with Certificates

What is PFX file?
This file type is an acronym of "Personal Information Exchange" that can be opened with "Microsoft Certificate Manager or Certificate Import Wizard".

This file is an Encrypted security file that stores SSL secure certificates used to authenticate a person or device, such as a computer or Web server; requires a password to be opened; can be installed by right-clicking the file and selecting "Install PFX."

More than one certificate can be stored in a single file in the following formats:

PFX,P12: Personal Information Exchange
P7B: Cryptographic Message Syntax Standard-PKCS#7 Certificate
SST: Microsoft Serialized Certificate Store


What SSL Is and Why You Need It?


Doing business online without SSL is like leaving customer credit card numbers on the counter or offering a dressing room without a door


An SSL certificate is a bit of code on your web server that provides security for online communications. When a web browser contacts your secured web site, the SSL certificate enables an encrypted connection. It’s kind of like sealing a letter in an envelope before sending it through the mail.


SSL certificates also inspire trust because each SSL certificate contains identification information. When you request an SSL certificate, a third party (such as Thawte or VeriSign) verifies your organization’s information and issues a unique certificate to you with that information. This is known as the authentication process.

An SSL certificate, or secure certificate, is a file installed on a secure Web server that identifies a website. This digital certificate establishes the identity and authenticity of the company or merchant so that online shoppers can trust that the website is secure and reliable. In order to verify that these sites are legitimate (they are who they say they are), the companies and their websites are verified by a third party, such as Verisign or Thawte.


Once the verification company establishes the legitimacy of an organization and the associated website, they will issue an SSL certificate (for the small fee of a few hundred dollars). This digital certificate is installed on the Web server and will be viewable when a user enters a secure area of the website. You can tell you are visiting a secure page when the URL starts with "https." To view the certificate, click the lock icon near one of the edges of your browser window.

Because digital certificates verify a company's current status, they do not last forever. SSL certificates typically expire every one to three years. If the certificate is not renewed in time, you may see an alert box pop up that says "This website's certificate has expired." This error has nothing to do with you or your computer, but is displayed because the Web server you connected to has not renewed its SSL certificate. While this does not necessarily mean the site is fraudulent, it does show that the site is less than professional.

What Happens between the Web Browser and Server?

1.A browser attempts to connect to a web site secured with SSL. The browser requests that the web server identify itself.
2.The server sends the browser a copy of its SSL certificate.
3.The browser checks whether it trusts the SSL certificate. If so, it sends a message to the server.
4.The server sends back a digitally signed acknowledgement to start an SSL encrypted session.
5.Encrypted data is shared between the browser and the server.

Continue reading ...
http://www.thawte.com/resources/ssl-information-center/get-started-with-ssl/index.html
http://www.thawte.com/resources/ssl-information-center/get-started-with-ssl/how-ssl-works/index.html

List of comercial certificate authorities
http://msdn.microsoft.com/en-us/library/ms995347.aspx

AOL (http://www.aol.com)
A-Trust (http://www.a-trust.at)
Arge Daten (http://www.signatur.rtr.at/de/providers/providers/argedaten.html)
AS Sertifitseerimiskeskuse (http://www.sk.ee)
Asociacion Nacional del Notariado Mexicano (http://www.notariadomexicano.org.mx)
Austria Telekom-Control Commission (http://www.signatur.rtr.at)
Autoridade Certificadora Raiz Brasileira (http://www.icpbrasil.gov.br)
Autoridad de Certificacion Firmaprofesional
Baltimore (http://www.baltimore.com)
Belgacom E-Trust (http://www.e-trust.be)
CC Signet (http://www.signet.pl)
CAMERFIRMA (http://www.camerfirma.com)
Certic?mara S.A. (http://www.certicamara.com/)
Certisign (http://www.certisign.com.br/)
CertPlus (http://www.certplus.com)
Colegio de Registradores
Comodo Group (http://www.comodogroup.com/)
ComSign (http://www.ComSign.co.il)
Correo
Deutsche Telekom (http://www.telekom.de)
DST (http://www.digsigtrust.com/)
Entrust (http://www.entrust.com/certificate_services/index.htm)
eSign (http://www.esign.com.au/)
EUnet International (http://www.eunet.fi/)
FESTE (http://www.feste.org/)
First Data Digital Certificates (http://www.firstdata.com/index.jsp)
FNMT (http://www.ceres.fnmt.es/)
Gatekeeper Root CA (http://www.agimo.gov.au/infrastructure/gatekeeper)
GeoTrust (http://www.geotrust.com)
GlobalSign (http://www.globalsign.com/)
GoDaddy (http://www.godaddy.com)
Hongkong Post (http://www.hongkongpost.gov.hk/product/cps/ecert/index.html))
IPS SERVIDORES (http://www.ips.es/)
KMD (http://www.kmd-ca.dk)
NetLock (http://www.netlock.hu/)
Post.Trust (http://www.post.trust.ie/)
PTT Post (http://www.ptt-post.nl)
Quovadis (http://www.quovadis.bm/)
RSA (http://www.rsasecurity.com/)
Saunalahden Serveri (http://www.saunalahti.fi/)
SECOM Trust.net (http://www.secomtrust.net)
SecureNet (http://www.securenetasia.com/)
SecureSign (http://www2.jcsinc.co.jp)
Serasa (http://www.serasa.com/)
SIA (https://ca.sia.it/)
Sonera (http://www.sonera.com/)
Spanish Property & Commerce Registry (https://www.registradores.org))
TC TrustCenter (http://www.trustcenter.de/)
TDC (http://www.tdc.dk)
Thawte (http://www.thawte.com/)
Trustis Limited (http://www.trustis.com)
TW Government Root Certification Authority
Unizeto Certum (http://www.certum.pl)
UserTRUST (http://www.usertrust.com/)
ValiCert (http://www.valicert.com/)
Verisign (http://www.verisign.com/)
Visa
Wells Fargo Root Certificate Authority (http://www.wellsfargo.com/certpolicy)
XRamp (http://www.xramp.com)

Thursday, 4 March 2010

Some Internet culture around Flash


Adob, Learn Flash Professional CS4:
Learn how to use Flash Professional CS4 with tutorials selected by experts at Adobe.There's everything from Getting Started for beginners, to New Features, Workflows, and Overviews.

http://tv.adobe.com/show/learn-flash-professional-cs4/

PixlToLife: learning made simple
Contians free flash tutorials: http://www.pixel2life.com/tutorials/adobe_flash/
Also, includes these good tutorials:
1- Making a Photoshoot Effect With jQuery & CSS: http://www.pixel2life.com/viewtutorial/76739/making_a_photoshoot_effect_with_jquery_css/
Which depends on the following tutorial:
    jQuery PhotoShoot Plugin 1.0: http://tutorialzine.com/2010/02/jquery-photoshoot-plugin/
      Where the author uses images from Flicker.
Flicker: is huge store of shared images, http://www.flickr.com/

2- Creating Ripples in the Medici Fountain: http://www.pixel2life.com/viewtutorial/76115/creating_ripples_in_the_medici_fountain/

Monday, 1 March 2010

Simplified jQuery Poll-down menu, only an anchor and a div elements


This code is adopted from another original article:

It is a simple poll down menu construct from <a> alement and <div> element, just like that:
1.<a id="anchor" onclick="return false;" href="">Menu title</a>
2.<div id="div" style="display:none;position:absolute; z-index:1000;">
3.    <a href="">element1 title</a>
4.    <a href="">element2 title</a>
5.</div>

menu

function
MakeADIVMenu(anchor,div) {    var timeoutID = -1;
    $(
'a#' + anchor)
    .hover(
       
function() {
            clearTimeout(timeoutID);
            $(
'#' + div).css('position', 'absolute');
            $(
'#' + div).css('top', $('a#' + anchor).position().top);
            $(
'#' + div).css('left', $('a#' + anchor).position().left - ($('#' + div).width()/2));
            $(
'#' + div).css({zIndex:20}).show();
        },
       
function() { timeoutID = setTimeout(function() { $('#' + div).hide(); }, 2000); }
    );
   
    $(
'#' + div)
    .hover(
       
function() {
            clearTimeout(timeoutID);
            $(
this)
            .each(
function() {
            $(
this).css('position', 'absolute');
            $(
this).css('top', $('a#' + anchor).position().top);
            $(
this).css('left', $('a#' + anchor).position().left - ($(this).width()/2));
            $(
this).css({ zIndex: 20 }).show();});
        },
       
function() { $(this).hide(); }
    );
   
//1.<a id="anchor" onclick="return false;" href="">
    //2.<div id="div" style="display:none">
    //3. <a href="">element1</a>
    //4. <a href="">element2</a>
    //5.</div>
}