Archive for the Category: '
Programming '

Occasionally you may present an interface which allows the user to select a subset of specific items. You may have a setting which allows the user to configure for example a set of plugins, turning on or off certain plugins or features.

At the same time it may be desirable to present an abbreviated notation for those items. As an example, if you were presenting a selection from alphabetic characters, you may want to present them as a series of ranges; if you had A,B,C,D,E, and Q selected, for example, you may want to show it as “A-E,Q”.

The first step, then, would be to define a range. We can then take appropriate inputs, generate a list of ranges, and then convert that list of ranges into a string expression to provide the output we are looking for.

For flexibility we would like many aspects to be adjustable, in particular, it would be nice to be able to adjust the formatting of each range based on other information, so rather than hard-coding an appropriate ToString() routine, we’ll have it call a custom function.

Pretty straightforward- a starting point, an ending point, and some string formatting. Now, one might wonder about the lack of an IComparable constraint on the type parameter. That would make sense for certain types of data being collated but in some cases the “data” doesn’t have a type-specific succession.

Now, we need to write a routine that will return an enumeration of these ranges given a list of all the items and a list of the selected items. This, too, is relatively straightforward. Instead of a routine this could also be encapsulated as a separate class with member variables to customize the formatted output. As with any programming problem, there are many ways to do things, and the trick is finding the right balance, and in some cases a structured approach to a problem can be suitable.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

/// <summary>

/// Given a list of selected entries, and a full listing of those entries, retrieves a series of selection ranges representing the specified selection within that full listing.

Sometimes you might not have a full list of the items in question, but you might be able to indicate what an item is followed by. For this, I constructed a separate routine with a similar structure which instead uses a function to callback and determine the item that follows another. For integer types we can just add 1, for example.

This is expanded in the github project I linked above, which also features a number of other helper routines for a few primitive types as well as example usage. In particular, the most useful “helper” is the routine that simply joins the results of these functions into a resulting string:

Windows 10 introduced a new software development platform- the Universal Windows Platform, or UWP. In some respects it builds upon the earlier Windows Runtime that was introduced with Windows 8. One interesting aspect of the platform is that- properly used- it can be utilized to have software that can be built once and distributed to a number of platforms running Microsoft Operating Systems, such as the XBox One.

I’ve fiddled a bit with UWP but honestly I found it tricky to determine what it’s for; As it is, it’s API as well as set of third-party portable libraries simply isn’t anywhere near a typical Application targeting the Desktop via WPF or even Windows Forms. But I think that is intentional; these aren’t built towards the same purpose. Instead, the main advantage of UWP appears to be in being able to deploy to multiple Windows Platforms. Unfortunately that is an advantage that I don’t think I can really utilize. However, I expect it will be well used for future applications- and it has already been well used for games like Forza Horizon 3, which utilized it for “Play anywhere” so it can be played not only on the XBox console but on any capable Windows 10 system. Forza 7 will also be using it to much the same effect.

Even if I won’t utilize it, it probably makes a lot of sense to cover it. My recent coding-related posts always seem to involve Windows Forms. Perhaps I should work instead to learn UWP and then cover that learning experience within new posts? If I an encountering these hurdles then I don’t think it is entirely unreasonable to think perhaps others are as well.

I’ve also got to thinking that perhaps I have become stuck in my ways, as I’m not partial to the approach that appears to bring web technologies to the desktop; Even today I find web applications and UI designed around the web to have a “feel” that is behind a traditional desktop application in usability. That said, I’m also not about to quit my job just because it involves “legacy” frameworks; We’re talking about quite an old codebase- bringing it forward based on library and platform upgrades would mean no time for adding new features that customers actually want. That, and the upgrade path is incredibly murky and unclear; with about 50 different approaches for every 50 different problems we might encounter, not to mention things like deciding on the Framework versions and editions and such.

I know I was stuck in my ways previously so it’s hardly something that isn’t worth considering- I stuck with VB6 for far too long and figured it fine and these newfangled .NET things were unnecessary and complicated. But as it happens I was wrong about that. So it’s possible I am wrong about UWP; and if so then a lot of the negative discussion about UWP may be started by the same attitude and thinking. Is it that it is something rather large and imposing that I would need to learn that results in me perceiving it so poorly? I think that is very likely.

Which is not to suggest of course that UWP is perfect and it is I who is wrong for not recognizing it; but perhaps it is the potential of UWP as a platform that I have failed to assess. While there are many shortcomings, future revisions and additions to the Platform are likely to resolve those problems as long as enough developers hop on board. And it does make sense for there to be a reasonable Trust Model where you “Know” what information an application actually uses or requests, rather then it being pretty much either limited user accounts or Administrator accounts and you don’t know exactly what is being used.

It may be time to come up with a project idea and implement it as a UWP application to start that learning experience. I did it for C# and Windows Forms, I did it for WPF, and I don’t see how the same approach couldn’t work for UWP. Unless it’s impossible to learn new stuff after turning 30, which I’m pretty sure is not the case!) If there is a way to execute other programs from UWP, perhaps the Repeater program I’m working on could be adapted. That is a fairly straightforward program.

QuickBASIC is an out of place choice when compared to most other languages that I’ve written in this series. Why would I jump so far backwards to QuickBASIC?

There are actually an umber of reasons. The first is that QuickBASIC actually imposes a number of limitations. Aside from the more limited programming language compared to, say C#, it also means any solution needs to appropriately contend with issues such as Memory usage and Open File Handles on MS-DOS. At the same time, a lot of the development task is actually more simple; one doesn’t need to fiddle with designers, or property pages or configuration tabs, or anything of that sort. You open a text file and start writing the program.

The first task is to determine an algorithm. Of course, we know the Algorithm- it’s been described previously- However, in this instance, we don’t have hashmaps available; furthermore, even if we want to implement that ourself, we cannot even keep all the information in memory. As a result, one compromise is to instead keep an array of index information in memory; that array can contain the sorted word as well as a record index into another random-access file, so, to start, we have these two TYPE structures:

1

2

3

4

5

6

7

8

9

TYPE SORTINDEX

SORTED ASSTRING*28

OFFSET ASLONG

ENDTYPE

TYPE SORTRECORD

WORDCOUNT ASINTEGER

SORTWORDS(1TO20)ASSTRING*28

ENDTYPE

By writing and reading directly from a scratch file when we need to add a new file to the “hash” we can avoid having any of the SORTRECORD structures in memory except the one we are working with. This drastically reduces our memory usage. As did determining that the longest word in SORTINDEX is 28 characters/bytes. The algorithm thus becomes similar- basically, with a word, we sort the words letters, and then we consult the array of SORTINDEX types. If we find one with the sorted word, we take the OFFSET and we read in the SORTRECORD at that offset, increment wordcount, and add the word to the SORTWORDS array, then PUT it back into the scratch file. And if it isn’t found in the SORTINDEX, we create a new entry- saving a new record with the word to the scratch file and recording the offset and sorted text in the index for that record.

Of course this does have several inefficiencies that I won’t address; The first is that the search for the matching sorted word is effectively a sequential search. Ideally, the in-memory index would be kept sorted and searches could use a Binary Search. I guess if somebody is interested I “left it as an exercise for the reader”.

Otherwise all seems well. But not so fast- the dict.txt file has 45402 words. Our type definition is 32 bytes, which means for all words to be stored in the index, we would need 1,452,864 bytes, which is far beyond the conventional memory limits that we are under. So we need to drastically reduce the memory usage of our algorithm. And we had something so promising! Seems like it’s back to the drawing board.

Or is it? instead of trying to reduce how much our algorithm uses, we could reduce how much data it is working with. At a time. We can split the original dictionary file into chunks, and as it happens since words of different lengths cannot be anagrams of each other, we can merely split the file into separate file organized by length. Then we perform the earlier algorithm on each of those files and output the resulting anagram list of each to one file. That would give us one file listing all anagrams without exceeding memory limitations!

Before we get too excited, let’s make sure that the largest “chunk” would be small enough. using another QuickBASIC program (because, what the hell, right?) I checked over the count of files of particular lengths. In this case, the chunk with the most is words of 7 letters in length, of which there are 7371 in the test dictionary file. This would require 235,872 Bytes of storage, which is well within our 640K conventional memory limit.

Of course, there is a minor caveat; we do need to start QuickBASIC with certain command line arguments, as, by default, the dynamic array maximum is actually 64K. We do this by launching it with the /Ah command line parameter. Otherwise, we might find that it encounters Subscript out of range errors once we get beyond around the 2000 mark for our 32-byte index record type.

Another consideration I encountered was open files. I had it opening all the dictionary output files at once, but it maxed out at 16 files, so I had to refactor it to be much slower by reading a line, determining the file to open, writing the line, and them closing the file. Again, there may be a better technique here to increase performance. For reference, I wasn’t able to find how to increase the limit, either (adjusting config.sys didn’t help).

After that, it worked a treat- the primary algorithm runs on each length subset, and writes the results to an output file.

Without further Adieu- The Full source of this “solution”:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

DECLARESUB SPLITDICT()

DECLARESUB ADDWORD(WORDADD ASSTRING)

DECLAREFUNCTIONGETOFFSET%(SORTEDWORD ASSTRING)

DECLAREFUNCTIONGETBYTEOFFSET%(SORTEDWORD ASSTRING)

DECLAREFUNCTIONSORTCHARS$(ST ASSTRING)

TYPE SORTINDEX

SORTED ASSTRING*28

OFFSET ASLONG

ENDTYPE

TYPE SORTRECORD

WORDCOUNT ASINTEGER

SORTWORDS(1TO20)ASSTRING*28

ENDTYPE

DIMxASINTEGER

COMMON SHARED INDEXDATA()ASSORTINDEX

COMMON SHARED INDEXFILE ASSTRING

COMMON SHARED INDEXCOUNT ASINTEGER

COMMON SHARED INDEXHANDLE ASINTEGER

DIM USEFILE ASINTEGER

DIM READWORD ASSTRING

DIM READINDEX ASLONG

DIM ANAGRAMOUT ASINTEGER

SPLITDICT

ANAGRAMOUT=FREEFILE

OPEN"C:\ANAGRAMS.TXT"FOROUTPUT ASANAGRAMOUT

DIM LETTERCOUNT ASINTEGER

FORLETTERCOUNT=2TO32

INDEXFILE="C:\DICT.IDX"

INDEXHANDLE=FREEFILE

INDEXCOUNT=0

KILL INDEXFILE

OPEN INDEXFILE FORRANDOM ASINDEXHANDLE LEN=562

ERASE INDEXDATA

DIM DICTFILE ASSTRING

DICTFILE="C:\DICT\DICT"+RTRIM$(LTRIM$(STR$(LETTERCOUNT)))+".TXT"

USEFILE=FREEFILE

IFDIR$(DICTFILE)<>""THEN

OPEN DICTFILE FORINPUT ASUSEFILE

PRINT USEFILE

PRINT INDEXHANDLE

'each line is a word. However, as we have limited memory

'compared to,C# and other languages we need to come up with a clever workaround.

'that workaround? we use the file system. Instead of using a hashmap, we instead create a

'C:\DICT\DICT7.TXT would contain the words that have7letters,forexample.

DIM FILENAMES(2TO28)ASSTRING

DIM TOTALCOUNT(2TO28)ASLONG

DIM LCOUNT ASINTEGER

DIM USEOUTFILE ASSTRING

DIM DICTREADER ASINTEGER

DIM LINEREAD ASSTRING

DIM CHECKLEN ASINTEGER

DIM FSORT ASINTEGER

FORLCOUNT=2TO28

USEOUTFILE="C:\DICT\DICT"+RTRIM$(LTRIM$(STR$(LCOUNT)))+".TXT"

FILENAMES(LCOUNT)=USEOUTFILE

FSORT=FREEFILE

OPEN USEOUTFILE FOROUTPUT AS#FSORT

CLOSE#FSORT

NEXT LCOUNT

DICTREADER=FREEFILE

OPEN"C:\DICT\DICT.TXT"FORINPUT AS#DICTREADER

PRINT"Reading Dictionary File Data..."

DOWHILENOTEOF(DICTREADER)

LINE INPUT#DICTREADER, LINEREAD

CHECKLEN=LEN(LINEREAD)

TOTALCOUNT(CHECKLEN)=TOTALCOUNT(CHECKLEN)+1

PRINT LINEREAD

FSORT=FREEFILE

OPEN FILENAMES(CHECKLEN)FORAPPEND ASFSORT

PRINT#FSORT, LINEREAD

CLOSE#FSORT

LOOP

ENDSUB

And there you have it. an Anagram search program written in QuickBASIC. Of course, it is arather basic and is a bit picky about preconditions (hard-coded for a specific file, for example) but it was largely written against my test VM.

One of the fun parts of personal projects is, well, you can do whatever you want. Come up with a silly or even dumb idea and you can implement it if you want. That is effectively how I’ve approached BASeBlock. Iit’s sort of depressing to play- held back by older technologies like WindowsForms and GDI+, and higher resolution screens make it look quite awful too. Even so, when I fire it up I can’t help but be happy with what I did. Anyway, I had a lot of pretty crazy ideas for things to add into BASeBlock, some fit and were even rather fun to play- like adding a “Snake” boss that was effectively made out of bricks- others were sort of- well, strange, like my Pac man boss which attempts to eat the ball. At some point, I decided that the paddle being able to shoot lightning Palpatine-style wasn’t totally ridiculous.

Which naturally led to the question- how can we implement lightning in a way that sort of kind of looks believable in a mostly low-resolution way such that if you squint at the right angle you go “yeah I can sort of see that possible being lightning?” For that, I basically considered the recursive “tree drawing” concept. One of the common examples of recursionm is drawing a tree; f irst you draw the trunk, then you draw some branches coming out of the trunk, and then branches from those branches, and so on. For lightning, I adopted the same idea. The eesential algorithm I came up with was thus:

From the starting point, Draw a line in the specified direction in that direction at the specified “velocity”

From that end point, choose a random number of forks. For each fork, pick an angle up to 45 degrees of difference from the angle between the starting point and the second point, and take the specified velocity and randomly add or subtract up to a maximum of 25% of it.

If any of the generated forks now have a velocity of 0 or less, ignore them

otherwise, recursively call this same routine and start another “lightning” from this position at the specified velocity from the fork position.

Proceed until there are no forks to draw or a specified maximum number of recursions has been reached

of course as I mentioned this is a very crude approximation; lightning doesn’t just randomly strike and stop short of the ground and this doesn’t really seek out a path to ground or anything along those lines. Again, crude approximation to at least mimic lightning. The result in BASeBlock looked something like this:

Now, there are a number of other details in the actual implementation- first it is written against the game engine so it “draws” using the game’s particle system, and also uses other engine features to for example stop short on blocks and do “damage” to blocks that are impacted, and there are short delays between each fork (which again is totally not how lightning works but I’m taking creative license). The result does look far more like a tree when you look at it but the animation and how quickly it disappears (paired with the sound effect) is enough, I think, to at least make it “passably” lightning.

But All this talk, and no code, huh? Well, since this starts from the somewhat typical “Draw a shrub” concept applied recursively and with some randomization, let’s just build that- the rest, as they say, will come on their own. And by that, I suppose they mean you can adjust and tweak it as needed until it gets the desired effect. Or maybe you want to draw a shrubbery, I’m not judging. With that in mind here’s a quick little method that does this against a GDI+ Graphics object. Why a GDI+ Graphics Object? Well, there isn’t really any other way of doing standard Bitmap drawing on a Canvas type object as far as I know. Also as usual I just sort of threw this together so I didn’t have time to paint it and it might not be to scale or whatever.

What amazing beautiful output do we get from this? Whatever this is supposed to be:

It does sort of look like a shrubbery I suppose. I mean, aside from it being blue, that is. It looks nothing like lightning, mind you. Though in my defense if electricity tunnels through certain things it often leaves tree-like patterns like this. Yeah, so it’s totally electricity related.

This is all rather unfulfilling, so as a bonus- how about making lightning in Photoshop:

Step 1: Start with a Gradient like so

Next, Apply the “Difference Clouds” filter with White and Black selected as Main and Secondary Colours.

Invert the image colours, then Adjust the levels to get a more pronounced “Beam” as shown.

Finally, add a layer on top and use the Overlay filter to add a vibrant hue- Yellow, Red, Orange, Pink, whatever. I’m not your mom. I made it cyan for some reason here.

Storing, calculating, and working with Currency data types seems like one of the few things that still provides a mixed bag of emotion. in C#, on the one hand you have the decimal data type, but on the other, you have pretty much no functions which actually accept a decimal data type or return one.

As it is the most suitable, the decimal data type is largely recommended for financial calculations.This makes the most sense. And while, as mentioned, there are many functions and calls you might need to make which will result in casts back and forth from other data types like double or even float, if you design your software and data from the ground up to deal with it you can usually accommodate these issues.

The problems arise, as usual, when we start looking at existing systems. For example, your old product might be working reasonably well with only a few problems for a customer, and they have loads of data. They aren’t going to be as likely to hop aboard your new system if it means that they will have to re-enter a load of data, and they aren’t going to like seeing errors from their current data appear in the new system. It was working before, after all. These old systems might be using ISAM databases and may have used floating point internally for calculations; even if it doesn’t use it’s own math routines you’ve got to consider that whatever programming environment was used for the old software might not follow the same mathematical rules as the new system, and so you have to decide how to proceed. Something as simple as a rounding function dealing with a corner case differently could result in massive amounts of manual data entry for either the customer or even yourself. On the other hand, using floating point types and writing wrappers to mimic the fiobles of the old functions is effectively building technical debt into the product. The compromise solution- have some sort of configuration which will either set it to use floating point compatibility mode or for the product to use decimal native mode would involve a lot of ground-up architecture to implement. Database schemas will differ, and you can’t just willy-nilly swap the option either

It’s the sort of problem that doesn’t seem to get covered in Academia on the subject, but it comes up often and each decision must be made carefully, in order to avoid alienating customer bases while attempting to avoid unnecessary technical debt. particularly since technical debt is why new systems might be implemented to begin with- bringing forward technical debt from the replaced system sort of defeats the purpose.

Upgrading library components across an entire suite of applications is not without it risks, as one may shortly learn when upgrading from Npgsql 2 to Npgsql 3. Though it applies between any version- who knows what bugs might be added or maybe even bugs were fixed that you relied upon previously, either intentionally or without even being aware that the behaviour on which you relied was in fact unintended.

As it happens, Npgsql 3 has such particulars when it comes to upgrading from Npgsql 2. On some sites, and with some workstations, we were receiving reports of Exceptions and errors after the upgrade was deployed. These were in the form of IOExceptions from within the Npgsql library when we ran a query, which failed because “a connection was forcibly closed by the remote host” form. Even adding some retry loops/attempts didn’t resolve the issue, as it would hit it’s retry limit, as if at some point it just refuses to work across the NpgsqlConnection.

After some investigation, it turned out to be a change in Npgsql 3 and how pooling is managed. In this case, a connection in the pool was being “closed” by the postgres server. This was apparently masked with previous versions because with Npgsql 2, the Pooled connections would be re-opened if they were found to be closed. Npgsql 3 changed this both for performance reasons as well as to be consistent with other Data Providers; This change meant that our code was Creating a connection and opening it- but that connection was actually a remotely closed connection from the pool, as a result attempts to query against that connection would throw exceptions.

Furthermore, because of the nature of the problem there was no clear workaround that could be used. We could trap the exception but at that point, how do we actually handle it? If we try to re-open the connection we’d just get the same closed connection back. It would be possible to disable pooling to get the connection open in that case but there isn’t much reason to have that only take place when that specific exception occurs, and it means having added handling such that we handle the error everywhere we perform an SQL query- and that exception might not specifically be caused by the pooling consideration either.The fix we used was to add new global configuration options to our software which would add parameters to the connection string to disable pooling and/or enable Npgsql’s keepalive feature. The former of which would sidestep the issue by not using pooled connections and the latter which would prevent the connections from being closed remotely (except when there was a serious problem of course, in which case we want to exception to take place). So far it has been successful in resolving the problem on affected systems.

Now, this is obviously Audio related, but where does the Volume Slapper program fit in here? Well to Record, I must turn down the volume of all programs I do not want to record (for example, System sounds, Skype notifications, sound in Web browsers) and switch the sound card to Headphone mode. I also need to disable the Aux Input, as it causes feedback (the tape deck outputs a low level signal of it’s own as well when recording). Now, for the most part these are pretty simple to do but adjusting audio levels is slightly annoying to do- especially if their current levels were carefully crafted over a period of time to suit what I was doing. My thinking towards Volume Slapper was to make it easy to restore the Audio levels I was using before I had a “recording session”. Disabling sound devices and flipping hardware relays (the headphone setting of the card) are outside the scope of the program IMO.

it also seems more widely applicable. It could be useful to save the volume settings of active programs so you can restore them later for a number of reasons. Maybe you achieved a perfect balance between your browser being used for video playback on one monitor and the audio of your game being played on your other screen, for example.

Now that that is out of the way, the actual implementation is actually quite simple. We just need to handle the new save and load features, obviously. In order to simplify my own usage I had it default to a “quick.xml” file saved to appdata if a file isn’t specified. The file itself- as indicated by the filename, is an XML file. it is built using the standard XElement capabilities of the .NET Framework. Since the usage is so simple here I didn’t reference Elementizer. it just saves the session names and the volume to the XML file, or loads them from an XML file. Of course since the sessions can be different between saving and loading, it currently ignores new sessions or sessions that didn’t exist when the data was saved. Saving the volume, starting word, and loading the volume file that was created won’t affect Word’s audio volume, for example.

VolumeSlapper, including these recent modifications, can be found on github.

As an interesting aside I’ve started working on a sort of silly “task” project which basically acts as a strict task scheduler that runs precisely and shows the time before each task is going to be run next.

BASeCamp Network Menu, which I wrote about previously, was a handy little tool for connecting to my VPN networks. It, however, had one disadvantage- It was clearly out of place- the style was “outdated” for the OS themes:

BCNetMenu displaying available VPN connections.

As we can see above, the style it uses is more like Office 2003, Windows XP, etc. Since the program is intended for Windows 10, that was a bit of a style issue, I think. Since none of the other Renderers really fit the bill, I set about writing my own “Win10” style menu foldout ToolStrip Renderer; Since the intent was merely to provide for drawing this menu, I’ve skipped certain features as a result to make it a bit easier.

Windows 10 uses an overwhelmingly “flat” style. This worked in my favour since that makes it fairly easy to draw using that style. Windows Forms- and thus the ContextMenuStrip one attaches to the NotifyIcon, allows overriding the standard drawing logic with a ToolStripRenderer implementation; so the first step was to create a class which I derived from the ToolStripSystemRenderer. This attempts to mimic the appearance of many Windows 10 foldouts by first drawing a dark background, then drawing a color over top. However- the color over top is where things were less clear. We want to use the Accent Color that is defined in the Windows Display Properties. How do we find that?

As it happens, dwmapi.dll has us covered. However, it bears warning that this is currently an undocumented function- we need to reference it by ordinal, and since it’s undocumented, it could be problematic when it comes to future compatibility. It’s very much a “use at your own risk” function:

This function uses DWMCOLORIZATIONPARAMS, which we of course, need to define:

1

2

3

4

5

6

7

8

9

10

publicstructDWMCOLORIZATIONPARAMS

{

publicuint ColorizationColor,

ColorizationAfterglow,

ColorizationColorBalance,

ColorizationAfterglowBalance,

ColorizationBlurBalance,

ColorizationGlassReflectionIntensity,

ColorizationOpaqueBlend;

}

Once defined, we can now create a helper method that will give us a straight-up color value:

1

2

3

4

5

6

7

8

9

10

11

privatestaticColor GetWindowColorizationColor(boolopaque)

{

DWMCOLORIZATIONPARAMS parms=newDWMCOLORIZATIONPARAMS();

DWMNativeMethods.DwmGetColorizationParameters(ref parms);

returnColor.FromArgb(

(byte)(opaque?255:(parms.ColorizationColor>>24)/2),

(byte)(parms.ColorizationColor>>16),

(byte)(parms.ColorizationColor>>8),

(byte)parms.ColorizationColor

);

}

We allow for an “Opaque” parameter to specify whether the caller wants the Alpha value or not; of course, t he caller could always do this itself but the entire point of functions is to reduce code so may as well put it in this way. it takes the 32-bit integer representing the color and splits it into it’s appropriate byte-sized components through shift operators, and uses those to construct an appropriate Color to return.

Using this color to paint over an opaque dark background (the color used with the Taskbar Right-click menu, for example) gives the following Menu, using the new WIndows 10 Renderer I created:

Not a bad representation, if I say so myself! Not perfect, mind you, but certainly fits better than the Professional ToolStrip Renderer, so I don’t think calling it a success would be entirely out of band. A more interesting problem presents itself, however- When configured in the display properties to have transparency effects,The default Windows 10 Network foldout has a “Blur” effect. How can we do the same thing?

After unsuccessful experiments with DwmExtendGlassIntoFrame and related functions, I eventually stumbled on the SetWindowCompositionAttribute(). This could be used to set an accent on a window directly- including, setting Blur Behind. Of course, as with any P/Invoke, one needs to prepare yourself for the magical journey with some declarations:

If the Blur setting is enabled, then the EnableBlur function is called to enable blur; otherwise, to disable blur. In both cases, it tosses in the Handle of the ToolStrip that is opening, which, apparently, is the Window handle to the actual menu’s “Window”, so it actually works as intended:

I also found that darker colours being drawn seemed to be “more” transparent. Best I could determine was that there is some kind of transclucency key; the closer to black, the more “clear” the glass appears. References I found suggest that SetLayeredWindowAttributes() could be used to adjust the colour key, but I wasn’t able to get it to work as I intended; Since the main effect is that the “Disabled” text, which is gray, appears like more “clear” glass within the coloured blurred menu, I found it to be fine.

It will still be ideal to write additional custom draw routines in order to allow checked/selected items in the listing to be more apparent. As it stands the default “Check” draw routine appears more like an overlay on the top left of the icon, but it’s easy to miss; it would be better to custom draw the items entirely, and instead of a checkmark perhaps highlight the Icon in some fashion to indicate selection.

implemented a new “Windows 10 Style” Menu Renderer. This is the default when installed on Windows 10, and will by default use the Windows 10 Accent Color as well. (No blur behind). It’s not precise and is more a stylistic imitation but it fits better with Win10 than the other Renderers (IMO)

As usual the latest source can always be found On github. And The Installer for 1.1 can be found Here.

I wrote previously about manners in which the SimpleWifi library can be utilized to enumerate available wireless connections and disconnect or connect to them. As my entire reason for writing BCNetMenu, however, was for VPN connections- not for wireless connections- it was necessary to figure out that piece of the puzzle as well.

The approach I discovered may not be entirely forward compatible, however it appears to be functional going back through many versions of Windows, so it ought to keep working. I wasn’t able to find a more official, “sanctioned” method. Thje basic idea is to effectively read the configuration information directly. The Configuration information for VPN connections can be found in the file “%APPDATA%\Microsoft\Network\Connections\Pbk\rasphone.pbk”. I suspect it may also be in the corresponding Common Application Data folder, found set in the %PROGRAMDATA% environment variable.

Retrieving the VPN names is fairly straight forward; effectively, we just want to find the section names. We can use a straight String parse of each line, but we can also use a Regular Expression with a group to define the actual name. Matches to:

1

\[(.*?)\]

is sufficient to find all the appropriate sections, and retrieve the names via the matches. However, the name is not quite enough; we need to cross-reference this information with information available via the NetworkInterface class; then we can use appropriate properties to return a particular data object representing the VPN connection:

But enumerating connections is one thing- connecting or disconnecting is another. After some searching I ended up finding only one method that was suitable for my use case, as other methods either required manual password input or to have BCNetMenu manage passwords, which I felt was outside the scope of what I wanted to do. Instead, the program will basically just run rasphone.exe with the appropriate VPN name; while this will show a dialog, the saved login information is pre-populated, so, at least for my intended use, I’ve found it sufficient to improve upon the default Windows 10 VPN Foldout.

For the same of comparison, here is the “before” image:

This is an entirely usable foldout- or, it appears that way. However, clicking a connection takes one to the Control Panel. For example, here is the WIndow that appears when I click the connected “Mainframe” option:

From a UI design perspective this boggles my mind. There is zero indication that I clicked “Mainframe” at all. Why are these options listed separately and clickable individually if they all lead to the same place? Clicking a connected VPN connection should disconnect it; clicking a disconnected VPN connection should connect it. The way it has been altered in Windows 10 defies good UI design as far as I’m concerned.

Not that I’m any expert on good UI design; I just know what is easy to use for myself and when a “feature” or alteration causes one to occasionally mumble to themselves angrily or laugh about how silly the feature is even months after it’s introduction it probably wasn’t for the best. As far as getting the desired behaviour, I had two alternatives; the one that I originally used was a registry adjustment which would set the foldout to use the Windows 8 implementation. This worked for some time, however I found that, since the dialog hadn’t had adjustments for Windows 10, some features didn’t work properly; I found in some cases it wouldn’t respond to clicks or refused to connect to a wireless network, but the network control panel functioned as intended. In order to bring back my own desired behaviour, I created BCNetMenu, which appears like this:

BCNetMenu displaying available VPN connections.

It’s not the fanciest thing in the world; it’s not intended to blow anybody’s mind with an amazing glass-like appearance or transparent Window blur or anything like that. It’s a relatively basic pop-up menu that just lists available connections. Clicking a connected one disconnects. Clicking a disconnected one connects.