Quantcast
Channel: Windows – Benohead’s Software Blog
Viewing all 24 articles
Browse latest View live

Sybase: Update TEXT/IMAGE columns using dbwritetext

$
0
0

Similar to the writetext command, you can use the dbwritetext function of the Open Client DB Library to update a text or image column.

Here is a short sample how to do it:

// Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sybfront.h>
#include <sybdb.h>

LOGINREC     *login; 
DBPROCESS    *dbproc; 
DBCHAR       mytextcol[512]; 

int _tmain(int argc, _TCHAR* argv[])
{
	if (dbinit() == FAIL) 
		exit(ERREXIT);
	
	// Create a login  record and fill it with username, password and application name.
	login = dblogin(); 
	DBSETLUSER(login, "myusername");
	DBSETLPWD(login, "mypassword"); 
	DBSETLAPP(login, "myapplicationname"); 

	// Open a connection to the server using the login record.
	dbproc = dbopen(login, "myservername"); 

	// You need to first select the text/image field in order to be able to get the pointer.
	dbcmd(dbproc, "select mytextcol from mydb..mytable where myuid = '582289'"); 
	dbsqlexec(dbproc); 
	dbresults(dbproc); 
	dbbind(dbproc, 1, STRINGBIND, (DBINT) 0, (BYTE *)&mytextcol); 
	dbnextrow(dbproc); 

	// This is the new value for the field.
	strcpy(mytextcol, "My update text value."); 

	// Now write it with dbwritetext
	dbwritetext (dbproc, "mydb..mytable.mytextcol", dbtxptr(dbproc, 1), DBTXPLEN, dbtxtimestamp(dbproc, 1), TRUE, (DBINT)strlen(mytextcol), (BYTE *)&mytextcol); 

	// The end...
	dbexit(); 
	return 0;
}

myservername is not the hostname of the server but the name in the Sybase configuration (you can see it using dsedit).
TRUE: it means that the operation should be logged. If you set it to FALSE, the operation will be minimally logged which is suboptimal in case of media recovery (but is faster and doesn’t fill the transaction log).

You need to additionally set the following in your visual C++ project:
Additional Include Directories: “C:sybaseOCS-15_0include”
Additional Library Directories: “C:sybaseOCS-15_0lib”;”C:sybaseOCS-15_0dll”
Additional Dependencies: libsybct.lib libsybdb.lib

The advantage of using dbwritetext are:

  • It’s fast.
  • It can handle large volumes of data (up to 2GB).

The disadvantages are:

  • It does not activate insert or update triggers.
  • If you have a timestamp column in the table it’s value will not be updated when using dbwritetext

If the program crashes on dbbind, check whether your SQL-Select is right (I had a typo in the selected column name and wasted half an hour wondering why it was crashing).

The post Sybase: Update TEXT/IMAGE columns using dbwritetext appeared first on Benohead.


Java: Distributing/Deploying the JRE using Windows Group Policies

$
0
0

Download the JRE you want to distribute from the Oracle Java SE Downloads page.

I used the Java SE Runtime Environment 6 Update 33.

Start the downloaded JRE installation package (in my case: jre-6u33-windows-x64.exe). When you see the following screen, the installer will have extracted the files we need to the file system:

The extracted files are stored in:

On Windows 7: C:\Users\<username>\AppData\LocalLow\Sun\JAVA\<version> e.g. C:\Users\benohead\AppData\LocalLow\Sun\JAVA\jre1.6.0_33_x64

Windows XP: C:\Documents and Settings\<username>\Local Settings\Application Data\Sun\Java\<version> e.g. C:\Documents and Settings\benohead\Local Settings\Application Data\Sun\Javajre1.6.0_33

Please copy the files there to your work directory e.g. c:\temp\staging

Note that the 32bit installer e.g. jre1.6.0_33 will not delete the files if you cancel the installation. But the 64bit installer will delete Data1.cab. So copy the files and only then cancel the installation.

If you need to update properties of the MSI package before distribution, you can use Orca database editor. It is part of the Microsoft Windows SDK (I used the Microsoft Windows SDK for Windows 7 and .NET Framework 4.

I’m not too sure to which part of the SDK Orca belongs to, so I’ve checked all packages during the installation of the SDK.

Then go to your SDK installation folder (in my case C:\Program Files\Microsoft SDKs\Windowsv7.1\Bin), you’ll find there Orca.msi:

Double-click on it to install it. Again I did a complete installation (disk space is cheap and my time too expensive to look for the exact components I really 100% need).

Start Orca now, Select “File | Open” in the menu. Select “Transform | New Transform” in the menu, so that all changes are tracked and visually indicated.

You’ll see a list of tables on the left, click there on Property (this is the table containing all the parameters you may want to change):

The following 3 changes will make sure that the check JRE updates is disabled. If the users have no admin rights, I guess the autoupdate makes no sense anyway.

AUTOUPDATECHECK 1 -> 0
JAVAUPDATE 1 -> 0
JU 1 -> 0

If you need to register the plugin as default JVM in IE and Firefox:

IEXPLORER 0 -> 1
MOZILLA 0 -> 1

(Note that the two properties above are deprecated as of Java 6U10)

To specify not to reboot the system after installation.

RebootYesNo Yes -> No

If you want to install for a single user and not for all users, remove the property ALLUSERS (which is set to 1 by default)

If you want to remove the Java coffee cup icon in the taskbar when applets run:

SYSTRAY 1 -> 0

All updated , deleted or inserted properties will be marked in green. You can then either save the transform with “Transform | Generate Transform…” in the menu. Or save an update MSI package with “File | Save Transformed As…”.

Then you need to copy your Installer (along with the CAB file to the share where it is accessible to all clients where the JRE should be installed).

Now go to your domain controller and open the Group Policy Management Editor:

Start | Run | gpmc.msc

Then navigate to:

Group Policy Management | Forests: xxxx | Domains | xxxx | Group Policy Object

There you can either use an existing policy or create a new one:

Let’s assume you want to create a new one. Click with the right mouse button in the area on the right and select New. Give it a name (e.g. “JRE Policy Object”)

Now select it in the list:

Right click and select Edit. This will open the Group Policy Management Editor.

There navigate to JRE Policy Object | Computer Configuration | Policies | Software Settings | Software installation:

In the area on the right, right click and select New | Package…

Then in the “Open” dialog, navigate to the share where the MSI package is stored, select it and click Open.

Choose Assigned as deployment method:

And there you have your new package in the group policy:

You can right click on it, choose Properties and go to the Security tab to manage who you want to distribute it to (it might be a good idea to first distribute it to your test users and then to everybody).

The post Java: Distributing/Deploying the JRE using Windows Group Policies appeared first on Benohead.

Windows: Installing the Group Policy Management Console (GPMC)

$
0
0

The Group Policy Management Console (GPMC) is a Microsoft Management Console (MMC) snap-in used to administrate group policies in a Windows domain controller. Although it’s actually part of Windows Server 2008, it’s not part of the default installation but it can be installed afterwards. Here are the steps required to install it.

Click on the Start button and go to Administrative Tools / Server Manager:

GPMC install step 1

In the Server Manager, select Features on the left hand side. This will display the list of installed features. You will see that Group Policy Management is missing:

GPMC Installation Step 2

Click on Add Feature and the following dialog will be displayed:

GPMC Installation Step 3

There select Group Policy Management and press Next. Then confirm the installation of the feature by clicking Install in the following dialog:

GPMC Installation Step 4

Then close the Server Manager when the installation is done. That’s it, now you can start the GPMC by using Windows logo key and R and executing gpmc.msc.

The post Windows: Installing the Group Policy Management Console (GPMC) appeared first on Benohead.

Securely connect to a Linux server with putty and ssh key

$
0
0

First you need to download PuTTY and PuTTYgen from the PuTTY Download Page.

Then start puttygen:

Open puttygen

Make sure the type of key to generate is SSH-2 RSA and click on the Generate button:

puttygen generate key

As instructed, you’ll have to move the mouse randomly over the grey area. After some moving around, the key will be generated:

puttygen key generated

Now copy the key from the "Public key for pasting into OpenSSH authorized_keys file" text area. We’ll add it as an authorized key for the user on the Linux machine.

Now login to the Linux server (e.g. using putty) and type the following:

cd $HOME/.ssh
vi authorized_keys

If there are no keys defined for this user yet, the file will be created, otherwise there will already be entries in this file.
Press I to enter insert mode, if it’s not the first key you’ll have to add a newline here, then paste the copied key. Press :wq for saving and exiting.

If the file was newly created, we’ll need to make sure that only the current user can write in this file:

chmod g-w $HOME $HOME/.ssh $HOME/.ssh/authorized_keys

Now, in case it’s not already done, we’ll need to allow public keys as an authentication mechanism for ssh:

vi /etc/ssh/sshd_config

There make sure the lines are in there:

  • PubkeyAuthentication yes
  • AuthorizedKeysFile .ssh/authorized_keys

These lines are most probably in there but commented out. In this case just remove the hash sign before them.

If you also want to completely disable password based authentication (e.g. only use public keys), you can also set the following:

  • ChallengeResponseAuthentication no
  • PasswordAuthentication no
  • UsePAM no

If you’re afraid to do something wrong, you can also set these 3 parameters later on.
Then press :wq to save.

Then restart your ssh daemon to activate the new settings using one of the following commands (depending on your system):

rcsshd restart

service sshd restart

service ssh restart

/etc/rc.d/sshd restart

/etc/init.d/sshd restart

We’re done on the linux side. Let’s go back to puttygen. You can define now a passphrase if you want (it’s optional). Then press "Save private key" and choose an appropriate location on the disk. Now you can open putty:

putty

Type in the user name and host name or the IP address of the Linux server (e.g. root@192.168.190.157), then open the SSH node in the tree on the left hand side, then click on Auth:

putty ssh auth

Click on Browse and choose the private key file you’ve saved using puttygen.
Then click again on Session (at the top of the tree on the left hand side). Give the connection a name (in Saved Sessions) and press Save:

putty session saved

Now you can press Open and will be automatically logged in !

The post Securely connect to a Linux server with putty and ssh key appeared first on Benohead.

Windows: Change first day of the week

$
0
0

On my machine, since I’m using the US regional settings, the week starts on Sunday:

Windows clock first day of week sunday

Windows clock first day of week sunday

It’s usual for the US and Australia but in Europe everybody considers the week to start on Monday, not Sunday. So you’d expect this:

Windows clock first day of week monday

Windows clock first day of week monday

In Windows 7 you can change it in the regional settings:

Regional settings first day of week sunday

Regional settings first day of week sunday

You can change there the first day of the week to Monday:

Regional settings first day of week monday

Regional settings first day of week monday

Now on Windows XP, you do not have this drop down list for the first day of the week. It’s automatically set based on the regional settings. But you can change it in the registry (HKEY_CURRENT_USER\Control Panel\International -> iFirstDayOfWeek):

Registry first day of week sunday

Registry first day of week sunday

There change 6 (Sunday) to 0 (Monday):

Registry first day of week monday

Registry first day of week monday

This also works on Windows 7 (but it’s easier to change it in the regional settings).

The post Windows: Change first day of the week appeared first on Benohead.

Windows: log first login and last logout (and sleep) time every day

$
0
0

Since I have to keep track of when I started working and when I stopped working (because of some legal regulations), I was using an app on my iphone to check in and out of work. But often I either was in a hurry and forgot it or forgot my phone at home or had no battery left… So I’ve decided to try and automate this.

I’d need to cover the following:

  1. Log an entry on the first login on the machine every day.
  2. Log an entry on the last logout on the machine every day.
  3. account for the fact that I usually do not logout but send the computer into sleep mode
  4. and in the morning I then wake from sleep

First we’ll create two batch files logging the times we’ve started and ended work.

Create a login.bat file somewhere with the following contents:

type %USERPROFILE%\loginlogoff.log | findstr /R "login.*%date%"
if errorlevel 1 echo login at %time% %date% >> %USERPROFILE%\loginlogoff.log

This basically checks whether the file %USERPROFILE%\loginlogoff.log already contains an entry with login and today’s date. If yes, there is nothing to do since it’s not the first login event today. If not, we write an entry in the file with the current time and date.

Then create a logout.bat file with the following contents:

type %USERPROFILE%\loginlogoff.log | findstr /v /R "logout.*%date%" > %USERPROFILE%\loginlogoff.tmp
type %USERPROFILE%\loginlogoff.tmp > %USERPROFILE%\loginlogoff.log
echo logout at %time% %date% >> %USERPROFILE%\loginlogoff.log

It first creates a copy of the file excluding all logout events which occured today, copies the file and adds a logout event. This basically will replace an logout event which occured on the same day with the latest one.

Now we need to have these scripts executed automatically. My computer at work is a Windows machine, so the obvious choice was to go some scheduled tasks. You can create a scheduled task on logon. But there’s no option for logoff. One option for the logoff issue could be to use the ONEVENT option of schtasks.exe. But it’s kind of a pain (never really worked reliably).

Here comes gpedit.msc. I can define there scripts which are to be run on logon and logoff:
gpedit logon logoff

To start it, click on the Start button, select Run… and type gpedit.msc (then press OK). You then have to navigate to Local Computer policy / User Configuration / Windows Settings / Scripts (Logon/Logoff).

There you will see two entries:

  • Logon
  • Logoff

Right click on Logon, select Properties, Then click Add, Browse and select the login.bat file created above. Press OK twice.
The do the same thing for Logoff and select the logout.bat file created above.

This takes care of the scenarios 1 and 2 above. Now we need to handle the sleep and wake triggers. There will be handled by scheduled tasks created using schtasks.exe:

SCHTASKS /Create /TN LogWake /TR %USERPROFILE%\login.bat /SC ONEVENT /EC System /MO *[System/EventID=1]
SCHTASKS /Create /TN LogSleep /TR %USERPROFILE%\logoff.bat /SC ONEVENT /EC System /MO *[System/EventID=42]

Here you’ll have to replace %USERPROFILE%\login.bat and %USERPROFILE%\logout.bat by the paths to the two batch files created above.

The event ID 1 will be triggered a few seconds after a wake from sleep. It might be trigger many times during the day but we do not care since we’ll only log the first one.
The event ID 42 will be triggered when the computer goes into sleep mode.

That’s it. You’ll then get a file at %USERPROFILE%\loginlogoff.log containing something like this:

login at  8:31:01,33 08.11.2012 
logout at  18:37:41,49 08.11.2012

The post Windows: log first login and last logout (and sleep) time every day appeared first on Benohead.

Windows: Port 80 is already in use

$
0
0

I wanted to start the Apache web server using XAMPP and got an error message that port 80 was already in use. My first thought was that IIS might be running on port 80. But on this machine I hadn’t installed IIS. So I executed the following to check which process might be using it:

c:\> netstat -nabo
...
  TCP    [::]:80                [::]:0                 LISTENING       4
 Can not obtain ownership information
...

So it’s process ID 4. I also used TCPView from Sysinternals and also saw that the process ID 4 was using this port. The process name was shown as “System”. In Task Manager, the image name for process ID 4 was System and the description was “NT Kernel & System”. It didn’t help me much either.

So I went through the list of running services and saw a service called “Web Deployment Agent Service” with the description “Remote agent service for the Microsoft Web Deploy 3.5.”. After stopping this service I was able to start Apache on port 80 successfully.

You can check the services by pressing Windows-R to get to the Run prompt, typing services.msc and pressing enter.

If this doesn’t help, I’d recommend searching for a service called “World Wide Web Publishing Service” and stop it. And of course, if IIS is running, you should stop it.

The post Windows: Port 80 is already in use appeared first on Benohead.

This file requires _WIN32_WINNT to be #defined at least to 0×0403. Value 0×0501 or higher is recommended

$
0
0

While building a product originally written with Visual Studio 6 on my machine (Windows 7 and Visual Studio 2010), I got for a few sub-projects the following error message:

c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\include\atlcore.h(35): fatal error C1189: #error : This file requires _WIN32_WINNT to be #defined at least to 0×0403. Value 0×0501 or higher is recommended.

Using findstr, I could see that _WIN32_WINNT was not set in those projects. So the solution was easy. I just had to add the following to the beginning of stdafx.h in those projects:

#ifndef WINVER				// Allow use of features specific to Windows XP or later.
#define WINVER 0x0501		// Change this to the appropriate value to target other versions of Windows.
#endif

#ifndef _WIN32_WINNT		// Allow use of features specific to Windows XP or later.                   
#define _WIN32_WINNT 0x0501	// Change this to the appropriate value to target other versions of Windows.
#endif

After that the projects could build successfully.

The post This file requires _WIN32_WINNT to be #defined at least to 0×0403. Value 0×0501 or higher is recommended appeared first on Benohead.


Java: Could not find main class. Program will exit.

$
0
0

In order to make a runnable (executable) JAR file which can be started by double clicking the JAR file, you just need to add a manifest file to the JAR file which references the main class to be executed. To do this, just create a file called manifest.txt and add the following contents:

Main-Class: com.benohead.app.Main

Replace com.benohead.app.Main by the fully qualified name of your main class (the class containing the static main method to be executed). Make sure that there is a newline after the fully qualified name since it could make problems later on if it is missing.

You can then make the JAR file using your class files and the manifest file:

jar -cvfm MyJarFile.jar manifest.txt com/benohead/app/*.class

A manifest.mf file created and added instead of the manifest.txt file.

When you double click on the create JAR file, the main class will be automatically executed.

Now, you may be able to run the JAR file like this on some machine but it might also fail on other machines, with the following error message:

Could not find main class. Program will exit.

You may also notice that the following works on some machines where the double click doesn’t work:

java -jar MyJarFile.jar

The problem is probably that you compiled your code with a new version of the JDK (e.g. JDK 6) but an old version of JRE (e.g. JRE 5) is used on double click. You may wonder why it is a problem when you double click but not when you run it from the command line. The answer is that you might be using different versions on the JRE when double clicking and when call java from the command line.

To check this, you can execute the following two commands.

To check the version used on double click:

ftype | find "jarfile"

It will return something like this:

jarfile=”C:\Program Files\Java\jre1.5.0_14\bin\javaw.exe” -jar “%1″ %*

This shows that JRE 5 is used on double click. If you compiled your code using JDK 6 it will be a problem.

To check the version used from the command line:

java -version

It will return something like this:

java version “1.6.0_20″
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) Client VM (build 16.3-b01, mixed mode)

In this case it is using JRE 6 which is the reason why it worked from the command line.

So how do you fix it ? There are two ways to do it:

  1. Reinstall the new JRE. It should then fix the file association in the OS
  2. Fix the file association manually

For the second one, you can execute the following in a command prompt:

ftype jarfile="C:\Program Files\Java\jre6\bin\javaw.exe" -jar "%1" %*

Of course you need to find the path to the new JRE and use it instead of the path above. Depending on your operating you can use the command below to find it:

where javaw

(where is some kind of Windows equivalent to the which command under Linux and is available from Windows 2003 Server onwards, so including Windows Vista, Windows 7 and Windows 8)

Note that to check whether the problem is really a java version issue, you can also start the JAR file from the command line using the same version as used in the double click scenario e.g.:

"C:\Program Files\Java\jre1.5.0_14\bin\javaw.exe" -jar MyJarFile.jar

If you have a version issue, you should get an exception along the lines:

“Exception in thread “main” java.lang.UnsupportedClassVersionError: com/benohead/app/Main (Unsupported major.minor version 50.0)”).

Here’s for your reference a mapping of java versions to major.minor versions:

Java Version    Major Version

Java 4          48.0
Java 5          49.0
java 6          50.0
java 7          51.0

The post Java: Could not find main class. Program will exit. appeared first on Benohead.

Generating new certificate in XAMPP for Windows

$
0
0

Since I had an older version of XAMPP for Windows installed, it was still using openssl 1.0.1e in which the heartbleed vulnerability was not yet fixed. So I installed the latest version and since the certificate in there was from 2013 I was not really sure whether it was safe or not so I decided to generate a new one. Here’s a short description how to do it.

Open a DOS prompt and navigate to the apache\bin directory in your XAMPP for Windows installation:

cd /D D:\Software\xampp\apache\bin

We’ll first define a couple of environment variables so that we do not need to provide them every time as parameter to openssl:

set OPENSSL_CONF=D:\Software\xampp\apache\conf\openssl.cnf
set RANDFILE=C:\Temp\.rnd

Now we’re ready to start. Generating a certificate involves 3 steps:

  1. Generating an RSA private key
  2. Generating a certificate sign request
  3. Generating a certificate

Note that since we are generating a self sign certificate, we can combine these 3 steps into 1 as described here.

Once the certificate is generated you can install it as shown here.

Generating an RSA private key

You can generate the key by executing the following:

D:\Software\xampp\apache\bin>openssl genrsa -out server.key 1024
Loading 'screen' into random state - done
Generating RSA private key, 1024 bit long modulus
............++++++
...........++++++
e is 65537 (0x10001)

This will create a file called server.key with a content similar to:

—–BEGIN RSA PRIVATE KEY—–
MIICXwIBAAKBgQDkQxjDD36nH9lfch9m+CS3TzIHYqrkEd0XGg+ki4E0QyP+Me9W
mJvPfEh8Gn9Iw18o4je9UN8gVWszm6GqBT0z3ryC10ZwQvi+hB+fRWNX3dC+cam8
EwA+NE3tVRGCHcjo73IFMixIsKfJ/1Rdj8lV0IX5PBform1hI6ao8jXH4QIDAQAB
AoGBAImgEtv5CaoGP++WRWy2DJ0heM6PJO4h/yWgpvHU0vAJ0ze+L8oMdVUiYCnD
aB8c/NEPo//XNNCv79TL7ystwXnTLlLR05n90Ta3SBFex1Pp48Rn7vLReZmiTrMc
6P7hqlKYCny+5zcx9gNzYJ73OsRoJGy0wdRRy6lRB87iiRDhAkEA9wz9Vc9vpDie
xsMVMfeEC7hOzUCHd3bX0Ye8BYBTVslQAZmrBQZv3Z59W+MSM3aJT6vPYtsMwIWH
zdvI7z/4nQJBAOyH3yuROrzrqFIe5YlyKLxeLx28T0IdYS1zwt064zfgMyi3eWG+
CAibg81cAMqlDhMzden8/CTYZYEQIhD6/xUCQQCA0tcvbdGrcpLo1kUxHv5OFjeR
M/rvwprbecoDnFzYvnTnwLe7ERY4HDMGPSv6he8oClFEHTFTGs4r/FWU3GjJAkEA
oYpeQawLOLGdoJBXZdqgtZ2BgkZ0vwu/rcIs6NjqC+RELF+6N6YIaJCFoMBgDgZS
KYzw0CCmuCdOk6nICl7RzQJBANeQEfc+FT3r3mdVLnyXraAjPxo+RFDZvWqQJiJY
MJUFZ9SPiaiNzVZhMijmAR3klnOz1XZlRhC/z9fzDJVopGk=
—–END RSA PRIVATE KEY—–

Note you can find instructions saying to use the -des3 option. Do not this will cause your key to contain a pass phrase:

D:\Software\xampp\apache\bin>openssl genrsa -des3 -out server.key 1024
Loading 'screen' into random state - done
Generating RSA private key, 1024 bit long modulus
......++++++
.........................++++++
e is 65537 (0x10001)
Enter pass phrase for server.key:
Verifying - Enter pass phrase for server.key:

Which will lead to such an error loading the key from XAMPP:

[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] AH02577: Init: SSLPassPhraseDialog builtin is not supported on Win32 (key file D:/Software/xampp/apache/conf/ssl.key/server.key)
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] AH02311: Fatal error initialising mod_ssl, exiting. See D:/Software/xampp/apache/logs/error.log for more information
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] AH02564: Failed to configure encrypted (?) private key localhost:8443:0, check D:/Software/xampp/apache/conf/ssl.key/server.key
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=RSA)
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Wed May 07 14:32:03.746107 2014] [ssl:emerg] [pid 4564:tid 252] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=PKCS8_PRIV_KEY_INFO)
AH00016: Configuration Failed

Generating a certificate sign request

You can then use the key to generate a certificate sign request using the following command:

D:\Software\xampp\apache\bin>openssl req -nodes -new -key server.key -out server.csr
Loading 'screen' into random state - done
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:.
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:localhost
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:.

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:mypassword
An optional company name []:.

You should of course use the appropriate data instead of localhost and dot (which means empty field). Also choose a different challenge password than mypassword.

This will create a file called server.csr containing something like:

—–BEGIN CERTIFICATE REQUEST—–
MIIBgjCB7AIBADAoMRIwEAYDVQQKDAlsb2NhbGhvc3QxEjAQBgNVBAMMCWxvY2Fs
aG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA5EMYww9+px/ZX3IfZvgk
t08yB2Kq5BHdFxoPpIuBNEMj/jHvVpibz3xIfBp/SMNfKOI3vVDfIFVrM5uhqgU9
M968gtdGcEL4voQfn0VjV93QvnGpvBMAPjRN7VURgh3I6O9yBTIsSLCnyf9UXY/J
VdCF+TwX6K5tYSOmqPI1x+ECAwEAAaAbMBkGCSqGSIb3DQEJBzEMDApteXBhc3N3
b3JkMA0GCSqGSIb3DQEBBQUAA4GBAKdmonasFGzPFiY8pgQThwIUvHo7her3SiPL
VkZqGbLT4NjoB2Yp7zi2qZ59qGLFHNFsfeBfnJZMFP2pGBbO1dW/2H1R0ogX95Ci
jIhwZFZD6xwpPkIWpau2dS1i5Q7kyBeGp/krfNHr/kSAUvaavq1R581yL2b5/ClY
9ARH/He/
—–END CERTIFICATE REQUEST—–

You probably do not need the -nodes option since it only applies when using openssl to generate a key using the req command. But I’d rather use it here although I do not need it than forget it when generating both the key and the certificate in a single step using the req command.

Generating a certificate

Now we need to generate the certificate using the following:

D:\Software\xampp\apache\bin>openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Loading 'screen' into random state - done
Signature ok
subject=/O=localhost/CN=localhost
Getting Private key

If you get such an error:

unable to write 'random state'

it means you forgot to set the second environment variables as shown in the beginning of this post.

Generating a self-signed certificate in one step

When generating a self-signed certificate you can combine this all to one step using only the req command:

D:\Software\xampp\apache\bin>openssl req -nodes -new -x509 -keyout server.key -out server.crt
Loading 'screen' into random state - done
Generating a 1024 bit RSA private key
............++++++
............++++++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:.
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:localhost
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:.

You should of course use the appropriate data instead of localhost and dot (which means empty field).

Installing the certificate

Now we just need to copy the key and the certificate to the apache installation:

D:\Software\xampp\apache\bin>copy /Y server.crt d:\Software\xampp\apache\conf\ssl.crt
        1 file(s) copied.

D:\Software\xampp\apache\bin>copy /Y server.key d:\Software\xampp\apache\conf\ssl.key
        1 file(s) copied.

After a restart of the Apache web server, your new certificate will be available.

The post Generating new certificate in XAMPP for Windows appeared first on Benohead.

OleViewer: STG_E_FILENOTFOUND and IDataObject interface viewer only supports IID_IDataObject

$
0
0

I had some problems loading a type library (TLB file) when building a Visual C++ project, so I wanted to have a look at the TLB file using the OleViewer. So I started the OleViewer as Administrator from C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\x64. When opening the TLB file I got the following error message:

LoadTypeLib(my tlb file) failed.
STG_R_FILENOTFOUND ($80030002)

The issue here was that I started the 64bit version of the OleViewer. With the 32bit version (present directly in C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin), this error was gone, so it could actually load the file but I got another error message:

IDataObject interface viewer only supports IID_IDataObject

Solving this was easy but kind of confusing. I went to the View menu, unchecked “Expert Mode” then opened the TLB file. And the error message was gone. After that I checked it again but could still open the TLB file. Eveb after closing the OleViewer and opening it again, I was able to load the TLB file.

I’m still not 100% sure what happened here… Another thing I did after removing the Expert Mode and before reopening my TLB file was to open a few object classes in the tree on the left. At least of them was the Microsoft Web Browser (under Controls). So if unchecking the Expert Mode alone doesn’t help, you could try this.

It looks like the error message I got above means that iviewers.dll in-process server was not properly registered. The OleViewer uses iviewers.dll to parse the type library. Somehow after the things I’ve done above, the registration was fine. Of course if it still doesn’t work for you, you can try registering it yourself using regsvr32 iviewers.dll.

Somewhere inbetween I’ve also try using but also had a problem with the same TLB file (also it worked for others). After the problem was solved with OleViewer, OleWoo was also able to open the TLB file. So I guess OleWoo parses the TLB the same way OleViewer does.

And actually after that Visual Studio 2012 wasn’t complaining anymore about the TLB file. Before that I got the following error message on the line where I import the TLB file:

error C1084: Cannot read type library file: ‘my tlb file’: Error loading type library/DLL.

So it looks like Visual Studio had the same issue with iviewers.dll as OleViewer and OleWoo but unfortunately only said it couldn’t load the type library instead of giving me a more precise error message…

Even if I don’t really get what happend here, I’m glad it’s solved :-)

The post OleViewer: STG_E_FILENOTFOUND and IDataObject interface viewer only supports IID_IDataObject appeared first on Benohead.

Visual C++: module unsafe for SAFESEH image, unable to generate SAFESEH image

$
0
0

Using Visual Studio 2012, I was building from the command line a software which was built until now using an older version (guess it was Visual Studio 2005). There were of course many things I had to change in the code itself (so much for portability…). And of course I had to upgrade the project in the solutions to VS2012 (using the devenv /upgrade command).

After converting the projects and modifying the code, I got the following error messages on a few projects:

error LNK2026: module unsafe for SAFESEH image.

fatal error LNK1281: Unable to generate SAFESEH image.

This means that the linker was started with the option meaning /SAFESEH “image has safe exception handlers” (also note that we only got this because we’re still building 32bit targets). The error occurs because some input modules were not compatible with the safe exception handlers feature of the linker. In our case it was some third party lib files for which I did not have the source code. These lib files are not be compatible with safe exception handlers is because they were created with an older version of the Visual C++ compiler.

But this is easy to fix. You just need to tell the linker not to produce an image with a table of safe exceptions handlers even if it thinks that all modules are compatible with the safe exception handling feature.

If you work in the Visual Studio Editor, you can right-click on your DLL project, go to Properties > Linker > Advanced and set “image has safe exception handlers” to No.

If like me you’re working from the command line, you can edit the .vcxproj file by opening it and searching for the <link> tags. Add the following to each <link> tag (there will be one per target e.g. one for debug and one for release):

<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>

It doesn’t matter where exactly you add it, it just needs to be between <link> and </link>.

If you call the linker yourself, you can also add /SAFESEH:NO to the command line.

After making this change, you can build your project again and the error will be gone.

The post Visual C++: module unsafe for SAFESEH image, unable to generate SAFESEH image appeared first on Benohead.

Visual Studio 2012: mspdb110.dll is missing when executing editbin.exe

$
0
0

I was having some issues using an OCX in an old application I had recompiled using Visual Studio 2012. One thing I found is that it might be related to a compatibility issue with Data Execution Prevention (DEP). Since I couldn’t recompile the OCX and didn’t have direct access to the linker settings, I went for using editbin.exe to apply a /NXCOMPAT:NO. But when I ran the following:

C:\Users\benohead>"c:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\editbin.exe" /NXCOMPAT:NO myfile.exe

I got a system error from link.exe saying:

The program can’t start because mspdb110.dll is missing from your computer. Try reinstalling the program to fix this problem.

The cause for this error is that I executed the command in the wrong DOS prompt. Not the one where I had executed vcvars32.bat. So I just executed vcvars32.bat:

"c:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\vcvars32.bat"

And gave it another try. Now no error message was displayed.

The post Visual Studio 2012: mspdb110.dll is missing when executing editbin.exe appeared first on Benohead.

Windows: Network connections timing out too quickly on temporary connectivity loss

$
0
0

If you have a rather unstable network where you tend to loose connectivity for a short time frequently, you might notice that established connections (e.g. ssh connections using putty) will get lost. You can then immediately reconnect but it’s still a pain.

The issue is not really with the software loosing the connection (e.g. putty) but rather with the Windows network configuration. A single application cannot set the network settings for the whole application or a specific session to prevent this problem. To solve this problem, you will need to tweak a few Windows network settings.

Basically tweaking these settings means increasing the TCP timeout in Windows. This can be done in the registry.

The relevant TCP/IP settings are:

  • KeepAliveTime
  • KeepAliveInterval
  • TcpMaxDataRetransmissions

These parameters are all located at the following registry location: \HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Tcpip\Parameters.

On Windows versions which are not based on Windows NT (i.e. Windows 95, Windows 98 and Windows ME), these parameters are located under: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP.

KeepAliveTime

The KeepAliveTime parameters controls how long the TCP driver waits until the a keep-alive packet is sent over an idle TCP connection. A TCP keep-alive packet is simply an ACK packet sent over the connection with the sequence number set to one less than the current sequence number for the connection. When the other end receives this packet, it will send an ACK as a response with the current sequence number. These communication is used to make sure that the remote host at the other end of the connection is still available and make sure the connection is kept open.

Since TCP keep-alives are disabled by default, the application opening the connection needs to specifically enable them.

The value is the number of milliseconds of inactivity before a keep-alive packet is sent. The default is 7,200,000 milliseconds (ms) i.e. 2 hours.

Note that the default of 2 hours might be to high in some cases. Having a high KeepAliveTime brings two problems:

  1. it may cause a delay before the machine at one end of the connection detects that the remote machine is no longer available
  2. many firewalls drop the session if no traffic occurs for a given amount of time

In the first case, if your application can handle reconnect scenario, it will take a very long time until it notices the connection is dead and it would have been able to handle it properly if it failed fast.

In the second case, it’s the opposite, the connection is articially closed by the firewall inbetween.

If you encounter one of these cases on a regular basis, you should consider reducing the KeepAliveTime from 2 hours to 10 or 15 minutes (i.e. 600,000 or 900,000 milliseconds).

But also keep in mind that lowering the value for the KeepAliveTime:

  • increases network activity on idle connections
  • can cause active working connections to terminate because of latency issues.

Setting it to less than 10 seconds, is not a good idea except if you have a network environment with with a very low latency.

KeepAliveInterval

If the remote host at the other end of the connection does not respond to the keep-alive packet, it is repeated. This is where the KeepAliveInterval is used. This parameter determines how often this retry mechanism will be triggered. This is basically the wait time before another keep-alive packet is sent. If at some point in time the remote hosts responds to the keep-alive packet, the next keep-alive packet will be again sent based on the KeepAliveTime parameter (assuming the connection is still idle).

The value is the number of milliseconds before a keep-alive packet is resent. The default is 1,000 milliseconds (ms) i.e. 1 second. If the network connectivity losses sometimes last a few minutes, it’d make sense increasing this parameter to 60,000 milliseconds i.e. 1 minute.

TcpMaxDataRetransmissions

Of course this retry process cannot go on for ever. If the connection is not only temporarily lost but lost for good, then the connection needs to be closed. This is where the parameter TcpMaxDataRetransmissions is used. This parameter defines the number of keep-alive retries to be performed before the connection is aborted.

The default value is to perform 5 TCP keep-alive retransmits. If you experience network instability and lose connections too often, you should consider increasing this value to 10 or 15.

Note that starting with Windows Vista, this parameter doesn’t exist anymore and is replaced by a hard-coded value of 10. After 10 unanswered retransmissions, the connection will be aborted. But you can still control the time frame which a connection could survive a temporary connectivity loss by adapting the KeepAliveInterval parameter.

Also note that this parameter only exists in Windows NT based versions of Windows. On old systems running Windows 95, Windows 98 or Windows ME, the corresponding parameter is HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\MaxDataRetries.

Summary

Tweaking the parameters above, one can configure the Windows TCP driver so that connections can survive small connectivity losses. Remember that after changing these settings, you’ll need to reboot the machine (it’s Windows after all…).

If you cannot modify TcpMaxDataRetransmissions because you have a newer version of Windows, you can still reach the same results by increasing KeepAliveInterval instead.

Also note that issues with lost connections in unstable networks seems to especially affect Windows Vista and later. So if you move from Windows XP to let’s say Windows 7 and you experience such issues, you should first add the KeepAliveTime  and KeepAliveInterval parameters to the registry, reboot, check whether it’s better and possibly increase the value of KeepAliveInterval if required.

All parameters above should be stored in the registry as DWORD (32bit value).

The post Windows: Network connections timing out too quickly on temporary connectivity loss appeared first on Benohead.

Microsoft Word 2007: Bullets and numbering in unprotected sections

$
0
0

Let’s assume you have a template where you only want users to be able to write to a few sections of the document but not in the rest e.g. because the rest is automatically generated, you would protect the document and make these 2 sections unprotected. In Word 2003, it is possible to write text in there and format things however you want including numbered or bulleted lists.

Now if you open a document based on this template in Word 2007, you’ll still be able to write text in the unprotected document but when you select text and right click to open the context menu, you’ll see that bullets and numbering are dimmed (disabled). Also the buttons for bullets and numbering in the toolbar are disabled.

What’s strange (apart from the fact that it worked fine in Word 2003 but not in Word 2007) is that writing a start and space (or a 1 and space) will automatically create a bulleted list. So it’s not just that bullets and numbering doesn’t work but just that it’s disabled in the context menu and toolbars.

The only solution for this is to defined quick styles  (the ones you see in the Styles group of the Home tab) with the appropriate formatting and use them to apply this formatting to the text in the unprotected section. So just define all the styles you want to use in a protected document as quick styles and the problem is solved ! This doesn’t seem to make much sense but it works. It looks like Word 2007 feels that applying existing styles in an unprotected section of a protected document is fine but using the formatting options in the context menu or toolbar is actually modifying styles.

Also if all you need are bullets, you can also use the shortcut for the bulleted list: Ctrl+Shift+L.

The post Microsoft Word 2007: Bullets and numbering in unprotected sections appeared first on Benohead.


C#: Query active directory to get a user’s roles

$
0
0

There are a few different ways to get the roles/groups of user from Active Directory. Here are 3 different ways to do it.

The first way to do it is to use UserPrincipal.FindByIdentity:

private static IEnumerable<string> GetGroupsFindByIdentity(string username, string domainname, string container)
{
	var results = new List<string>();
	using (var context = new PrincipalContext(ContextType.Domain, domainname, container))
	{
		try
		{
			UserPrincipal p = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
			if (p != null)
			{
				var groups = p.GetGroups();
				foreach (var group in groups)
				{
					try
					{
						results.Add(@group.Name);
					}
					catch (Exception ex)
					{
					}
				}
			}
		}
		catch (Exception ex)
		{
			throw new ApplicationException("Unable to query Active Directory.", ex);
		}
	}

	return results;
}

You can then print the roles using:

var groups = GetGroupsFindByIdentity("benohead", "aw001.amazingweb.de", "DC=aw001,DC=amazingweb,DC=de");
foreach (var group in groups)
{
	Console.WriteLine(group);
}

Another way to do it is to use a DirectorySearcher and fetching DirectoryEntries:

private static IEnumerable<string> GetGroupsDirectorySearcher(string username, string container)
{
	var searcher =
		new DirectorySearcher(new DirectoryEntry("LDAP://" + container))
		{
			Filter = String.Format("(&(objectClass=user)(samaccountname={0}))", username)
		};
	searcher.PropertiesToLoad.Add("MemberOf");

	var directoryEntriesFound = searcher.FindAll()
		.Cast<SearchResult>()
		.Select(result => result.GetDirectoryEntry());

	foreach (DirectoryEntry entry in directoryEntriesFound)
		foreach (object obj in ((object[]) entry.Properties["MemberOf"].Value))
		{
			string group = Regex.Replace(obj.ToString(), @"^CN=(.*?)(?<!\\),.*", "$1");
			yield return group;
		}
}

The regular expression is required in order to extract the CN part of the returned string.

var groups = GetGroupsDirectorySearcher("benohead", "DC=aw005,DC=amazingweb,DC=de");
foreach (var group in groups)
{
	Console.WriteLine(group);
}

The third way to do it is to use a WindowsIdentity:

private static IEnumerable<string> GetGroupsWindowsIdentity(string userName)
{
	var results = new List<string>();
	var wi = new WindowsIdentity(userName);

	if (wi.Groups != null)
	{
		foreach (var group in wi.Groups)
		{
			try
			{
				results.Add(@group.Translate(typeof (NTAccount)).ToString());
			}
			catch (Exception ex)
			{
				throw new ApplicationException("Unable to query Active Directory.", ex);
			}
		}
	}
	return results;
}

You can then print the roles using:

var groups = GetGroupsWindowsIdentity("benohead");
foreach (var group in groups)
{
	Console.WriteLine(group);
}

You might notice that this last option seems to return more groups than the other two options. I’m not yet sure why. I’ve tested it with multiple users and saw that it does return different groups but for some reason, it also returns groups not returned by any other method. So for now I’ll rather stick to the first or second method.

The post C#: Query active directory to get a user’s roles appeared first on Benohead.

Active Directory Authentication and Authorization in Orchard CMS

$
0
0

Since Orchard CMS doesn’t (yet) support authentication and authorization of domain users against an Active Directory, you have to install a module to achieve this. There are handful of modules which could help. I decided to use ActiveDirectoryAuthorization by Moov2 because it was the only one which had a decent number of downloads, reviews and a project site.

If you decide to use this module, you’ll first notice that there isn’t any complete documentation how to adapt your system so that the authentication and authorization works over an Active Directory. But there is a blog article which gives some instructions. Unfortunately, the instructions seem not to be complete.

Basically when it comes to the changes to be made in your web.config, the blog post says you should “simply replace the current Forms authentication settings with the authentication settings shown below”:

    <authentication mode="Windows" />
    <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/>

Unfortunately, only with this change, whenever I entered my credentials, I used to get the same dialog over and over. What’s missing here, is that you also need to add an authorization tag, thus replacing:

    <authentication mode="Forms">
      <forms loginUrl="~/Users/Account/AccessDenied" timeout="2880" />
    </authentication>

by:

    <authentication mode="Windows"/> 
    <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/> 
    <authorization>
	    <allow roles="aw001\Domain Users"/>
	    <deny users="?"/>
    </authorization>

Of course, you have to replace aw001 by your domain name.

The question mark in the deny tag basically means that anonymous users will be denied access and the allow tag that all Domain Users of this particular domain will be granted access.

After that, Orchard just gave me a white page. So at least something was activated… In the logs, I found the following exception:

2014-09-25 11:36:01,653 [6] Orchard.Environment.DefaultBuildManager – Error when compiling assembly under ~/Modules/ActiveDirectoryAuthorization/ActiveDirectoryAuthorization.csproj.
System.Web.HttpCompileException (0x80004005): c:\inetpub\wwwroot\orchard\Modules\ActiveDirectoryAuthorization\Core\Authorizer.cs(144): error CS1061: ‘Orchard.ContentManagement.IContentManager’ does not contain a definition for ‘Flush’ and no extension method ‘Flush’ accepting a first argument of type ‘Orchard.ContentManagement.IContentManager’ could be found (are you missing a using directive or an assembly reference?)
at System.Web.Compilation.AssemblyBuilder.Compile()
at System.Web.Compilation.BuildProvidersCompiler.PerformBuild()
at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetCompiledAssembly(String virtualPath)
at Orchard.Environment.DefaultBuildManager.GetCompiledAssembly(String virtualPath) in Orchard\Environment\IBuildManager.cs:line 53

I could see the line of code where this was done but still wasn’t sure what I had to do. So I googled for it. There was exactly one hit. Somehow, it looks like someone had the same problem with a completely unrelated module. This problem was solved in this module and I checked what was the code change. It turns out they only removed the call to ContentManager.Flush(). So I gave it a try, editing ActiveDirectoryAuthorization\Core\Authorizer.cs and commenting out the following line in the CreateUser method:

_contentManager.Flush();

After that I could log in.

The other problem I had was that my domain user didn’t have the permissions I thought I had assigned. The problem is that I created a role with the same name as a group of this user in Active Directory but didn’t add the domain name to it i.e. I called my role myusergroup instead of aw001\myusergroup. After correcting it, it worked fine.

When logging in with a domain user, an Orchard User is created. You do not see in the Orchard administration that this user has the role you’ve created (which is called the same as an Active Directory group) but when considering the roles of the user for checking the permissions, now Orchard will use both the roles assigned in Orchard and the groups assigned to the user in the Active Directory. Great !

 

The post Active Directory Authentication and Authorization in Orchard CMS appeared first on Benohead.

Orchard CMS: NullReferenceException when adding roles

$
0
0

When clicking on “Add a role” in the Users administration, I got the following exception:

System.NullReferenceException: Object reference not set to an instance of an object.
at Orchard.Roles.Services.RoleService.GetInstalledPermissions()
at Orchard.Roles.Controllers.AdminController.Create()
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass13.<InvokeActionMethodWithFilters>b__10()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass13.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass13.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)

I found a reported issue which did look similar. It was reported against Orchard CMS 1.7 and was marked as resolved. I am using Orchard CMS 1.7.2. Unfortunately, the issue details neither show in which version it was solved nor what the actual root cause was. Since it was closed by Sébastian who’s an Orchard Core developer and was actually born in the same city as I was, I could have contacted him but in-between I found out what the problem was.

Actually my problem was caused by a module I am working on. When disabling the module, it worked fine and when reactivating it, it is broken again.

The problem was in the Permissions.cs file. There were basically two problems. Basically what Orchard does when you click on “Add a role” is to get all features and their permissions. The two problem I had were:

  1. The GetPermissions() method did not returned all permissions I had defined and was returning in GetDefaultStereotypes()
  2. ReSharper had suggested me to make the setter for the Feature property private since it was not accessed anywhere.

But fixing the first one alone didn’t solve anything. I guess it was necessary to fix it but the root cause of the problem was the private setter for the Feature property. Once I made it public again it worked fine:

public Feature Feature { get; set; }

So the lesson here is that especially when working with such a system as Orchard CMS you should not blindly implement changes in the visibility of properties or methods suggested by ReSharper/Visual Studio. Since properties and methods are rarely directly referenced, your tools will very often miss some dependencies.

 

 

 

The post Orchard CMS: NullReferenceException when adding roles appeared first on Benohead.

ASP.NET: Slow first loading time

$
0
0

You might have experienced the problem that when you first load a large ASP.NET application (e.g. a CMS), it takes quite some time to load. If you then reload the page or even restart the browser and load the page again, it’s quite fast. There seems to be a few possible cause for this. So this post will not give you an extensive answer as to what all could go wrong but focus on application pool recycling.

What is an Application Pool?

Application Pools are used by IIS to isolate web applications. It allows you to use different settings in different applications. This is especially important when your different applications use different security settings. Applications in different application pools run in different windows processes (w3wp.exe) and thus also provide some kind of segregation by preventing an application from interfering with other applications. So an error in one application won’t cause other applications to crash or behave unexpectedly.

What is Application Pool Recycling?

Application pool recycling basically means that when a given event occurs, the resources related to an application pool will be recovered. It is mainly useful to prevent long running application from crashing or hanging e.g. because of memory leaks. When the recycling happens, a new worker process is started which will receive new web requests and the old one is shut down (once it’s done processing current requests), so there is no downtime while recycling.

Why does recycling cause the first load to last longer ?

Many applications need to first compile scripts or DLLs on the fly. Others need to load a large amount of data and pre-process it. This is basically what’s causing the delay on the first load. Afterwards once everything is compiled and data pre-processed, everything is fast.

Whenever an application pool is recycled and the worker processes are shutdown, next time the application is called, a new worker process needs to be started and these compilation and pre-processing activities need to be performed again.

When does recycling happen?

There are basically two different ways to recycle application pools:

  1. Recycling based on configuration
  2. On-demand recycling

On-demand recycling can be done:

  • in the IIS manager
  • from the command line using appcmd
  • using Windows Management Instrumentation (WMI) i.e. the ApplicationPool.Recycle method

Automatic application pool recycling can be configured to recycle:

  • when reaching a memory threshold (virtual memory or used memory)
  • when reaching a certain number of requests
  • at a scheduled time
  • after a scheduled time

Additionally, recycling will happen, when the configuration of an application is changed or when an unhealthy ISAPI condition is reported.

How to configure when automatic application pool recycling is done?

This can be configured in the Application Pools configuration panel of the IIS manager (Go to Start -> Administrative Tools -> Internet Information Services (IIS) Manager):

Application pool configuration

Select an application pool on the left-hand side and click on Recycling on the right.

The default configuration is to recycle an application pool after 29 hours (1740 minutes):

Application Pool Recycling Settings

If there are long periods of time during which your site/application has few hits, it might be a good idea to increase this default value. Actually, except if you know that you have a memory leak somewhere and do not manage to fix it, there is no big benefit in recycling your application pools at fixed intervals. If your application is running on a server where other applications are running, you may want to used the memory based maximums. Otherwise just removing the time interval based configuration may be a good solution. If nothing else it configured, you application pool will be recycled anyway once all available memory is used.

Idle Time-out

Also note that even though strictly speaking, it’s not an automatic application pool recycling, you can configure the application pool so that worker processes are shutdown after a specified amount on time being idle i.e. not receiving new requests or processing existing requests. The default value is 20 minutes. Actually I guess in most cases it makes no sense. It’s only useful if you have so limited resources that you need to get rid of unused application pools as fast as possible. So in most cases, I’d recommend setting the idle time-out to zero:

Application pool idle time-out

How do I know when recycling has occurred?

There are two places where you can configure under which conditions an event log entry is generated when an application pool is recycled.

The first one is when you press “Next” in the dialog shown above. You will then see the following:

Recycling application pool recycling events to log

The checkbox under “Configurable recycling events” are disable in this screenshot because I haven’t configured any  trigger for an automatic application pool recycling. But if you defined e.g. a number of requests, some checkboxes will be enabled.

Another place where you can set it is the Advanced Settings dialog. Just select your application pool and press “Advanced Settings”. The following dialog will be displayed:

Application pool advanced settings

The recycling settings are the bottom and contain a section called “Generate Recycle Event Log Entry”. You can then set the appropriate entries to true to get the required event log entries.

Also remember that starting from Windows 2008, you can have an email sent when an event is triggered.

The post ASP.NET: Slow first loading time appeared first on Benohead.

Windows 7: empty pages displayed in CHM file

$
0
0

When opening a CHM file downloaded from Internet on a Windows Vista or Windows 7 machine, the file may not render properly and just show empty pages. All you’ll see no matter which page you select is an error message saying that “Navigation to the webpage was canceled” e.g.:

Navigation to the webpage was canceled

The problem is that the file comes from another computer and is blocked. It’s strange because you actually get a security warning when opening the file and one would expect that if you open it anyway, everything should be fine. Here an example of such a security warning:

Open File - Security Warning

The solution is to unblock the file. In order to do it, do not open the file directly from the browser but save it to disk, then right click on the file, choose Properties and unblock the file:

CHM file properties - Unblock

Now, when you open the file, no security warning will be displayed and the contents will be displayed properly.

Note that you should only unblock files that you trust.

If you do not see an Unblock button, you have either already unblocked it and it doesn’t work anymore (not exactly sure when this happens) or you might have stored the file on a file system which doesn’t support the Unblock feature (not sure but it looks like it only works on NTFS).

You can also implicitly unblock the file by unchecking “Always ask before opening this file” in the security warning shown above.

So this whole behavior seems not to be very consistent but fixing it was pretty straight forward.

Update: It looks like on Windows 8, you can unblock files from a PowerShell using the following commandlet:

Unblock-File .\SshNet.Help.chm

 

The post Windows 7: empty pages displayed in CHM file appeared first on Benohead.

Viewing all 24 articles
Browse latest View live