Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

2011/02/25

Names of custom content types cannot contain slashes

This is a definition of a custom content type generated in Visual Studio. The only thing I changed is the Name attribute.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!-- Parent ContentType: Task (0x0108) -->
  <ContentType ID="0x010800096b8767b29a4191929d5cc2d50e094e"
               Name="Yes/No Task"
               Group="Custom Content Types"
               Description="My Content Type"
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
    </FieldRefs>
  </ContentType>
</Elements>
It seems to be perfectly valid. The package can be built and deployed to SharePoint without any errors or warnings. However, the new content type does not show up on the Site content types page (/_layouts/mngctype.aspx).

The problem is caused by the '/' character in content type's name - remove the slash, re-deploy the package and now the new content type will be visible on the Site content types page.

2009/10/21

Error "The remote debugger is not an acceptable version"

If you try to debug an ASP.NET application remotely using Remote Debugging Monitor (msvsmon.exe) and you get the following error:
The remote debugger is not an acceptable version
it means that the versions of Visual Studio and Msvsmon are different (e.g. Visual Studio 2005 + Msvsmon 2008).

2009/05/15

Missing auto-generated Resources.Designer.cs file

If the Resources.Designer.cs file is missing and there is no Run Custom Tool option in the context menu for the Resources.cs file (or, of course, any other resources file), it probably means that the Custom Tool property of the Resources.cs file is empty:


This is what MSDN says about the Custom Tool property:
Custom tools are components that can be used to transform files from one type to another at design time. For example, a custom tool might be a dataset code generator that reads in an XML Schema (.xsd) file and generates classes in a code file that programmatically exposes its tables and columns. There is a predefined list of custom tools available in the product; this property enables you to see which custom tool is applied to a file. In rare circumstances, you might have to change the value of this property. The value of this property must be either blank or one of the built-in custom tools.
In case of Visual Studio 2008 the default tool generating the *.Designer.cs files is ResXFileCodeGenerator - type it in the property and the problem should be solved:


UPDATE:

I found an easier way to do it:

2009/01/25

furl2delicious - a tool to import bookmarks from Furl to Delicious (with tags!)

I decided to switch from Furl to Delicious. Furl is a good bookmarking service, it has a unique feature that I think is very useful - it saves a copy of every bookmarked page. But recently it's been very slow, sometimes I couldn't even log in. Moreover, I like new Delicious design and Firefox integration so much better!

So I decided to switch. But I didn't want to lose more than 500 bookmarks. I tried to use the Delicious import feature - everything went smoothly but all my tags were lost. I looked for a solution on the Internet but I didn't find a working one, so I wrote my own tool.


It imports the following data:
  • the URL,
  • the title,
  • the comments (if there were any),
  • the tags (!),
  • the date when the bookmark was created (!).
I imported my bookmarks - it took about 20 minutes; out of 515 bookmarks that left Furl 501 arrived at Delicious, I didn't investigate why 14 bookmarks were lost.

I used the Delicious.Net library and Visual C# 2005 Express Edition.

Downloads:
furl2delicious - executables
furl2delicious - source code (.NET, C#)

2008/05/01

Calling a .NET library from a VB6 application

Calling a .NET library from a VB6 application is pretty easy. There are many resources explaining how to do it (e.g. 1, 2, 3, 4). However, all of the (or at least the ones that I have read) forget to mention that, if you are using C#, there is a catch - the assemblies created in C# have a ComVisible attribute set to false by default. This simply means that they cannot be called from a VB6 application.

To change it open the AssemblyInfo.cs file, find the following line:
[assembly: ComVisible(false)]
and change it to:
[assembly: ComVisible(true)]

2008/03/27

Shrinking an outsized KeePassX/KeePass database

There is an error in KeePassX (and there was a similar bug in KeePass, too) that can cause the database file to grow at a very rapid pace (I don't know what triggers this growth). To be precise, the database size doubles every time it is saved even if a very small change is made.

My database reached 256 MB. KeePass running on Windows XP could not open it (because of an Out of memory error) while KeePassX on Ubuntu could open it but it was taking a few minutes. But the main problem anyway was the fact that I couldn't add new entries or make any changes because the file would grow again.

I tried to shrink the file by saving it as a new database or exporting and then importing it, but it didn't work. I also tried to find a solution on the Internet, but I only found an information that there was such a bug and it was fixed in Windows version. So after a few days I downloaded the KeePass sources, spent half a day (it's been a long time since I last saw a C++ code :) first trying to make them compile (I didn't have a libboost_regex-vc80-mt-sgd-1_34_1.lib library file; I installed it with BoostPro Binary Installer for Visual C++ - take a look here and here) and then trying to find a place in the code where the individual entries get loaded. :)

Finally, it turned out that the problem was caused by an attachment which was taking almost all space in the database file (it had a few KB when I attached it some time ago).

So I placed a line responsible for loading the attachment inside a try... catch... block and added a message box.
try
{
pEntry->pszBinaryDesc = _UTF8ToString((UTF8_BYTE *)pData);
}
catch (...)
{
AfxMessageBox((CString)"There was a problem with reading pszBinaryDesc " 
+ (CString)"field of " + pEntry->pszTitle + (CString)" entry.\n"
+ (CString)"This data has been LOST. However, you can now save the "
+ (CString)"database as a new file and its size should be normal again.", 
MB_ICONEXCLAMATION);
}
Thanks to this if there is a broken (outsized) attachment in some entry, an exception is thrown (important: if you try to run KeePass on Linux using WINE, this exception will not be thrown) and KeePass skips loading it and informs the user that such a problem occurred. Be aware that I didn't find a way to restore a broken attachment so some data is lost, but the database can be opened and saved as a new database. The new database has a normal size.

If anyone has a similar problem, let me know - I can e-mail modified sources or a compiled EXE file.

UPDATE:

A tip from an anonymous reader:
I was able to get around the same issue and shrink my keepass database via "File" -> "Export To" -> "KeePass Database" in v1.14. Using "Save As" wouldn't do it, but exporting did the trick!

2008/01/10

Error when attempting to change a revision description (Subversion)

If you cannot modify a revision description in Subversion (SVN) because of the following error:

Repository has not been enabled to accept revision propchanges;
ask the administrator to create a pre-revprop-change hook

(or 'almost in Polish' ;)

Repozytorium nie ma włączone możliwości zmieniania atrybutów;
poproś administratora o utworzenie skryptu hook pre-revprop-change

it can be solved by creating an pre-revprop-change.bat file (in case you are using Windows) in the hooks directory of the repository. Of course the file does not have to be empty, it can do something like logging information about changes being made (because Subversion's revision properties are not versioned).

UPDATE:

On Windows 2003 BAT files cannot be empty - see here.

2007/07/27

Preventing code from being generated in InitializeComponent() method for a property

When you place controls on a form, Visual Studio generates code in the InitializeComponent() method that sets values of their properties.

If you are developing a custom control and you don't want Visual Studio to generate such code for some of its properties, you should apply the DesignerSerializationVisiblityAttribute to such properties and place DesignerSerializationVisiblity.Hidden value on them.
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DateTime Value
{
    get { /* ... */ }
    set { /* ... */ }
}
More information about customizing the code generated by Visual Studio can be found here.

2007/05/16

A SQL CLR user-defined aggregate - notes on creating and debugging

At the end of this post you will find my very first attempt to use one of the new features of SQL Server 2005 - CLR integration. It is a CLR user-defined aggregate that produces a comma-separated (comma plus space to be precise) list of values.
Column1
--------
aaa
bbb       -->   aaa, bbb, ccc
ccc
My code is a modified version of an example that I found here.

Global variables

You may expect (at least I did) that if you have a global variable (e.g. intermediateResult in my example) and you assign it a value in the Init method then you will be able to use this value in the Terminate method. Well, that's not true.

If you need to use a value of some variable in the Terminate method, you have to serialize it in the Write method (to save the needed value) and then deserialize it in the Read method and assign to some variable (to restore the needed value).

You can of course save and restore more than one variable - use some kind of serializable object to store the values.

Debugging

There is an MSDN article that explains exactly how to debug a CLR user-defined aggregate - Walkthrough: Debugging a SQL CLR User-Defined Aggregate - nonetheless, I encountered one problem.

I started with a solution that contained two projects - one project contained the aggregate code and the other was for a SQL test script. It is possible to perform debugging in such configuration (I managed to do it, although I am not sure how), but it is a better idea to have a single SQL Server project with both the aggregate code and SQL test scripts. This is what the IDE expects, so following this advice can spare you lots of hassle.

For example, MSDN says that to debug a CLR user-defined aggregate you need to enable CLR Debugging, but it doesn't say that Application Debugging must also be enabled.

Application Debugging option

When I worked with a single project, Visual Studio enabled this option automatically when needed, while with the two-project solution I had to do it myself.
using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;
using System.Text;

[Serializable()]
[SqlUserDefinedAggregate(
    Format.UserDefined,
    IsInvariantToNulls=true,
    IsInvariantToDuplicates=false,
    IsInvariantToOrder=false,
    MaxByteSize=8000)]
public class Concat : IBinarySerialize
{
    #region Private fields
    private string separator;
    private StringBuilder intermediateResult;
    #endregion

    #region IBinarySerialize members
    public void Read(BinaryReader r)
    {
        this.intermediateResult = new StringBuilder(r.ReadString());
    }

    public void Write(BinaryWriter w)
    {
        w.Write(this.intermediateResult.ToString());
    }
    #endregion

    #region Aggregation contract methods
    public void Init()
    {
        this.separator = ", ";
        this.intermediateResult = new StringBuilder();
    }

    public void Accumulate(SqlString pValue)
    {
        if (pValue.IsNull)
        {
            return;
        }

        if (this.intermediateResult.Length > 0)
        {
            this.intermediateResult.Append(this.separator);
        }
        this.intermediateResult.Append(pValue.Value);
    }

    public void Merge(Concat pOtherAggregate)
    {
        this.intermediateResult.Append(pOtherAggregate.intermediateResult);
    }

    public SqlString Terminate()
    {
        return this.intermediateResult.ToString();
    }
    #endregion
}

2007/05/12

Regular expressions are easy! You only need Regulazy

I think that this tool is really, really great. Regulazy is an absolute (if you know me, you know that I don't get overexcited like this very often ;) must-have for anybody who needs to create regular expressions, but is not a regex guru.
Regulazy is a visual Regex Creation tool for beginners.
It contains an easy "point and click" user interface, and allows creating regular expressions for simple searches almost instantly without requiring Regex syntax knowledge from the end user!
And if you need a more advanced and powerful tool, check out The Regulator. I have used it a few years ago and found it great, too.

2007/04/25

Sending mail using System.Net.Mail.SmtpClient and Gmail

This code snippet:
MailMessage message = new MailMessage();
message.From = new MailAddress("somebody@gmail.com");
message.To.Add(new MailAddress("somebody-else@some.server.com"));
message.Subject = "testing...";
message.Body = "This is a test.";

SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Send(message);
along with this app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.net>
    <mailSettings>
      <smtp>
        <network
          host="smtp.gmail.com"
          port="587"
          userName="somebody@gmail.com"
          password="some-password"
          defaultCredentials="false"
        />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>
allows to send e-mail from .NET code using Gmail as an SMTP server.

It is crucial to remember to:
  1. set EnableSsl to true;
  2. use port 587 (not 465, clicky).

2007/03/28

HOWTO Getting 16x16 icons for file types

1. Download this sample.

2. Put a button and a textbox on the form.

3. Use a snippet similar to:
Dim types As String() = txtFileTypes.Text.Split(",")
For i As Integer = 0 To types.GetLength(0) - 1
  Dim im As Image = _
  Me.FileSystemImages.SmallImageList.Images( _
  FileSystemImages.GetTheFileIconIndex("*." & types(i)))
  im.Save(Application.StartupPath & "\" & types(i) & ".bmp", _
  Imaging.ImageFormat.Bmp)
Next
and you have a tool that allows you to retrieve 16x16 icons for different file types.

2007/01/25

HOWTO: Edit properties of DataGrid columns (.NET 1.1)

Editing DataGrid properties
It's probably obvious for everyone working with Visual Studio 2003, but it doesn't work this way in VS 2005 (which I usually use) and as a result it recently took me a while to find this option.

2007/01/12

Reading data from a sorted view (Microsoft SQL Server)

If you read data from a sorted view (a view that contains an ORDER BY clause in its SELECT statement) into a DataTable (ADO.NET) or a ADODB.Recordset ('old' Visual Basic 6 ADO), it will not sorted in the DataTable/Recordset.

2006/12/21

A property of a custom control is not shown in the Properties pane

If you are creating a custom control and it has a property that is not shown in the Properties pane in Visual Studio IDE, ensure the property is not write-only.

Write-only properties are not shown in the Properties pane.
Read-and-write as well as read-only properties are shown in the Properties pane.

2006/07/19

Visual Studio 2003 sets a breakpoint in another file

There is a bug in Visual Studio 2003 that sometimes makes setting a breakpoint in certain files impossible. When you try to set it, the breakpoint is set, but not in the file that you opened - the moment you hit F9, VS jumps to another file and sets the breakpoint there.

I struggled with this problem for quite a long time. I tried using the mouse instead hitting F9, setting the breakpoint on different lines, reopening the file, reloading the project, restarting VS, using another machine. Nothing helped.

Finally, I discovered that I could open a Breakpoints window (Crtl+Alt+B), press New button and create a new Function Breakpoint - a breakpoint of this type was created successfully.



Note that you can copy the full name of a function from the Class View window.

2006/06/21

Debugging a Windows service

OnPause, OnContinue and OnStop methods can be debugged by simply attaching to the [WindowsServiceName].exe process and setting breakpoints in the appropriate places.

The problem gets a little bit harder when it comes to debugging OnStart method, since there is no process that can be attached to, because the service is not running. There are many ways to solve this problem, but, in my opinion, the easiest one is to
call a System.Diagnostics.Debugger.Launch() method within the OnStart method in order to start a debugger programmatically.

A detailed description of this problem can be found here.

2006/04/12

Visual Studio - Command Window vs. Immediate Window

While debugging in Visual Studio, I often use Command Window to check values of variables (?mySqlStr), assign values to variables (mySqlStr = "SELECT FOO_ID FROM dbo.FOO") or execute short code snippets (myDS.Fill()).

Today I closed Command Window and re-opened it after a while. And I could no longer evaluate any expressions. I also noticed a > prompt that I've never seen before.

It turns out that Command Window has two different modes (clicky):
  • Command mode - used for executing Visual Studio Commands directly in the IDE, bypassing the menu system, or for executing commands that do not appear in any menu,
  • Immediate mode - used for debugging purposes, evaluating expressions, executing statements, printing variable values, and so forth.
Command mode (notice the prompt)


Switching from Command mode to Immediate mode (type immed and press Enter)

Command Window - Immediate mode (no prompt)

2006/03/12

devenv - building a .NET solution from the command line

The easiest way to build a .NET solution (or a project) from the command line is to use devenv command.

However, there are two devenv files - devenv.com and devenv.exe. Today, I have noticed one really essential difference between them. The former one is a console tool, while the latter one is not. If you type devenv.exe to build a solution, it will start a background process and immediately return control to the console. It means that, if devenv.exe is used in a batch file, the commands succeeding it may be executed before the build process completes.

UPDATE:

The above happens only when you type something like devenv.exe SomeSolution.sln /Rebuild Release in the command line and hit Enter. It does not happen when such a command is used in a batch file.

2005/12/09

Beware of Replace functions!

If you are using VB.NET and want to replace all occurrences of one string in a variable with another string, you can use either Replace function from Microsoft.VisualBasic namespace (which is, unfortunately, imported by default in every new VB project and you cannot even see this in the code!) or Replace function from String class (and this is a preferred method).

I was absolutely sure that the following snippets of code would give the same results:
Dim s1 As String = ""
s1 = Replace(s1, "foo", "fee")

Dim s2 As String = ""
s2 = s2.Replace("foo", "fee")
Well, they don't. While the variable s2 remains to be an empty string, s1 is set to Nothing. That's something worth remembering.