Navigation

Friday, June 25, 2010

Access WCF Service by WEBGet from Browser

If you want to expose a simple web service (WCF) so that it can be accessed by a web get or browser you need to first insure that the input and output are simple data types like strings or integers.

1.Create the web site project

2.  Add a reference to System.ServiceModel.Web (so we can access the WebGet decleration.

3.  Add your function and decerate it with the following;

<OperationContract()> _
    <WebGet()> _
    Function Dosmothing(ByVal pValue As String) As String




4.  Add the following to your web.config file;



 <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>


 



5.  Update your service model to reflect the one below. 



<system.serviceModel>
<behaviors>
   <endpointBehaviors>
    <behavior name="NewBehavior">
     <webHttp />
    </behavior>
   </endpointBehaviors>
   <serviceBehaviors>
    <behavior name="my.Application.Behavior1">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
   </serviceBehaviors>
  </behaviors>
<services>
   <service behaviorConfiguration="Behavior1"
    name="myInterface">
    <endpoint behaviorConfiguration="NewBehavior" binding="webHttpBinding"
     bindingConfiguration="" contract="myInterface" />
   </service>
  </services>
</system.serviceModel>


6.Now you can access the function like this;


http://localhost:54433/myInterface.svc/DoSmothing?pValue=Smothing

Calling web service from browser

If you want to access a simple web service via the browser address line you have to add the following to the web.config to enable httpget.

 

 <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>


</system.web>



Then you can do this;



    <WebMethod()> _
    Public Function GetTime(ByVal pText As String) As String
        Return pText & " " & Now.ToString
    End Function


http://localhost:6722/WebService1.asmx/GetTime?pText=hi

Wednesday, June 23, 2010

Converting Image to String and Back in Base64

When you need to store an image as string for say xml transmission you will need to transfer it back and forth from base64 encoding.

 

 

Public Function ImageToBase64(image As Image, format As System.Drawing.Imaging.ImageFormat) As String
    Using ms As New MemoryStream()
        ' Convert Image to byte[]
        image.Save(ms, format)
        Dim imageBytes As Byte() = ms.ToArray()

        ' Convert byte[] to Base64 String
        Dim base64String As String = Convert.ToBase64String(imageBytes)
        Return base64String
    End Using
End Function

 

Public Function Base64ToImage(base64String As String) As Image
    ' Convert Base64 String to byte[]
    Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
    Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)

    ' Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length)
    Dim image__1 As Image = Image.FromStream(ms, True)
    Return image__1
End Function

Convert MemoryStream to String and String to MemoryStream

These functions allow you to swap strings and memory streams back and forth.

 

Public Shared Function GetMemoryStreamFromString(ByVal s As String) As IO.MemoryStream
        If s Is Nothing OrElse s.Length = 0 Then
            Return Nothing
        End If

        Dim m As New IO.MemoryStream()
        Dim sw As New IO.StreamWriter(m)
        sw.Write(s)
        sw.Flush()

        Return m
    End Function


 



    Public Shared Function GetStringFromMemoryStream(ByVal m As IO.MemoryStream) As String
        If m Is Nothing OrElse m.Length = 0 Then
            Return Nothing
        End If

        m.Flush()
        m.Position = 0
        Dim sr As New IO.StreamReader(m)
        Dim s As String = sr.ReadToEnd()
        Return s
    End Function

Tuesday, June 22, 2010

Clipx, Great clipboard history tool!

http://bluemars.org/clipx/

Visual Studio 2010 Pro Power Tools Released!

Microsoft released this package that is a set of extensions to Visual Studio Professional (and above) which improves developer productivity.


http://bit.ly/alyr2C

Revision Notes

10.0.10608.1630

Fixed issue where Visual Studio may crash on startup on computers where proxies required user entered credentials.

Visual Studio 2010 Productivity Power Tools



A set of extensions to Visual Studio Professional (and above) which improves developer productivity.



Document Well 2010 Plus (More Info)

One of the key pieces of feedback that we have received over several versions of Visual Studio is that users want to be able to customize the behaviour of their document tabs. From the ordering of tabs to the position of the close buttons, user can now configure dozens of different options for their tabs. Go to Tools -> Options -> Environment -> Document Tab Well to configure these options as you prefer:

Tab Well UI

Scrollable tabs

Maintain spatial consistency of the documents that are included in the document well.

Vertical tabs

Document tabs are shown vertically, allowing you to fit more tabs than are normally visible when shown horizontally.

Pinned tabs

Allows you to pin tabs to keep them always visible and available.

Show close button in tab well

Similar to Visual Studio 2008, will show a close button in the document well that will close the active tab.

Tab Behavior

Remove tabs by usage order (LRU)

When a new tab is inserted and existing tabs don't fit in the document well, instead of removing the tab at the end of the well it will remove the least recently used tab. This ensures that frequently used tabs are readily available.

Show pinned tabs in a separate row/column

Pinning tabs can quickly cause you to run out of space for regular tabs. The option allows you to always show pinned tabs in a separate row (or column, if displayed vertically) from regular tabs.

Sorting

Sort tabs by project

Tabs will be sorted by the project they belong to, thus keeping them always together in the document tab well.

Sort tabs alphabetically

Tabs will be sorted alphabetically. When Sort By Project is turned on, tabs will be sorted first by project and then alphabetically.

Sort tab well dropdown alphabetically

The drop down menu at the right end of the document well is sorted alphabetically. This option allows ordering as the tabs are laid out in the document well.

Tab UI

Color tabs according to their project or according to regular expressions

This option permits tabs to be colored according to the project they belong to. This is particularly useful when sorting tabs by project, as it allows you to immediately identify different groups of project documents.

You can also configure regular expressions and assign a color to each one. If the name of a tab matches the configured regular expression, it will be colored with the assigned color.

Miscellaneous options that modify tab UI

Show document/toolwindow icon in tab

Show close button in tab

Modify dirty indicator style

This option allows you to select from a set of different dirty indicators that you might prefer over the asterisk.

Modify minimum and maximum tab size

Allows you to modify minimum and maximum tab size. Try setting minimum and maximum sizes to the same value, and you will have evenly spaced tabs.

Searchable Add Reference Dialog

The new Add Reference dialog makes it faster and easier for you to find the reference that you are looking for and add it to your VB, C# or F# project. From the Solution Explorer, simply right click on the References node, select the Add Reference command to see the updated Add Reference Dialog.

Highlight Current Line

As the resolution of monitors increases, it’s becoming more difficult to find the caret in the code editor. The highlight current line extension makes it easy to find the caret by highlighting the line that the caret is on in the editor. You can even configure the default colour by changing the setting for “Current Line (Extension)” and “Current Line Inactive (Extension)” in Tools Options Fonts & Colors.

HTML Copy (More Info)

This extension provides support for the HTML Clipboard format when copying code from the editor. This means that you’ll no longer have to go fix up the formatting of your code when you paste it into a TFS bug form or any other HTML based control.

Triple Click

It’s never been easier to select a line of code from the mouse by simple triple-clicking anywhere on the line.

Fix Mixed Tabs

Some developers prefer tabs, others prefer spaces, and nobody likes mixing tabs & spaces. This extension promotes developer harmony by warning as they are open or save a file that has a mixture of tabs & spaces. The information bar also provides an easy way to fix the file to suit your preference.

Ctrl + Click Go To Definition

This extension gives the editor a web browser by adding clickable hyperlinks to symbols in your code as you hold down the Ctrl key.

Align Assignments

This extension is useful for making your code a little more readable by aligning the assignments when you type Ctrl+Alt+]

Please note: This may conflict with your formatting settings. E.g. in C# you will need to disable: Tools->Options->Text Editor->C#->Formatting->Spacing->"Ignore spaces in declaration statements"

Colorized Parameter Help

This extension improves consistency with the editor by applying syntax highlighting to the contents of the Parameter Help window for C# &VB.

Move Line Up/Down Commands

This extension maps the Alt+Up Arrow & Alt+Down Arrow keys such that they will move the current line of code or the selected lines up and down through the editor.

Column Guides

Since Visual Studio 2002, there has been a not so secret registry key which allowed user to draw a vertical line in the code editor. This is very useful to remind developers that their full line of code or comments may not fit one a single screen. Thanks to this extension this feature has returned with UI configure it. Simply place the cursor at the appropriate column and select Add Guideline from the context menu 

PowerCommands for Visual Studio 2010

This is a must have for the VB.net 2010 developer!

http://bit.ly/9SOxFl

PowerCommands 10.0


PowerCommands 10.0 is a set of useful extensions for the Visual Studio 2010 adding additional functionality to various areas of the IDE. Visit the VSX Developer Center at http://msdn.com/vsx for more information about extending Visual Studio.

Below is a list of the commands included in PowerCommands for Visual Studio 2010 version 10.0.

Enable/Disable PowerCommands in Options dialog

This feature allows you to select which commands to enable in the Visual Studio IDE. Point to the Tools menu, then click Options. Expand the PowerCommands options, then click Commands. Check the commands you would like to enable.

Note: All power commands are initially defaulted Enabled.

Format document on save / Remove and Sort Usings on save

The Format document on save option formats the tabs, spaces, and so on of the document being saved. It is equivalent to pointing to the Edit menu, clicking Advanced, and then clicking Format Document. The Remove and sort usings option removes unused using statements and sorts the remaining using statements in the document being saved.

Note: The Remove and sort usings option is only available for C# documents.

Note: Format document on save and Remove and sort usings both are initially defaulted OFF.

Clear All Panes

This command clears all output panes. It can be executed from the button on the toolbar of the Output window.


Copy Path

This command copies the full path of the currently selected item to the clipboard. It can be executed by right-clicking one of these nodes in the Solution Explorer:

The solution node; A project node; Any project item node; Any folder.


Email CodeSnippet

To email the lines of text you select in the code editor, right-click anywhere in the editor and then click Email CodeSnippet.


Insert Guid Attribute

This command adds a Guid attribute to a selected class. From the code editor, right-click anywhere within the class definition, then click Insert Guid Attribute.


Show All Files

This command shows the hidden files in all projects displayed in the Solution Explorer when the solution node is selected. It enhances the Show All Files button, which normally shows only the hidden files in the selected project node.


Undo Close

This command reopens a closed document , returning the cursor to its last position. To reopen the most recently closed document, point to the Edit menu, then click Undo Close. Alternately, you can use the CtrlShiftZ shortcut.

To reopen any other recently closed document, point to the View menu, click Other Windows, and then click Undo Close Window. The Undo Close window appears, typically next to the Output window. Double-click any document in the list to reopen it.


Collapse Projects

This command collapses a project or projects in the Solution Explorer starting from the root selected node. Collapsing a project can increase the readability of the solution. This command can be executed from three different places: solution, solution folders and project nodes respectively.


Copy Class

This command copies a selected class entire content to the clipboard, renaming the class. This command is normally followed by a Paste Class command, which renames the class to avoid a compilation error. It can be executed from a single project item or a project item with dependent sub items.


Paste Class

This command pastes a class entire content from the clipboard, renaming the class to avoid a compilation error. This command is normally preceded by a Copy Class command. It can be executed from a project or folder node.


Copy References

This command copies a reference or set of references to the clipboard. It can be executed from the references node, a single reference node or set of reference nodes.


Paste References

This command pastes a reference or set of references from the clipboard. It can be executed from different places depending on the type of project. For CSharp projects it can be executed from the references node. For Visual Basic and Website projects it can be executed from the project node.


Copy As Project Reference

This command copies a project as a project reference to the clipboard. It can be executed from a project node.


Edit Project File

This command opens the MSBuild project file for a selected project inside Visual Studio. It combines the existing Unload Project and Edit Project commands.


Open Containing Folder

This command opens a Windows Explorer window pointing to the physical path of a selected item. It can be executed from a project item node


Open Command Prompt

This command opens a Visual Studio command prompt pointing to the physical path of a selected item. It can be executed from four different places: solution, project, folder and project item nodes respectively.


Unload Projects

This command unloads all projects in a solution. This can be useful in MSBuild scenarios when multiple projects are being edited. This command can be executed from the solution node.


Reload Projects

This command reloads all unloaded projects in a solution. It can be executed from the solution node.


Remove and Sort Usings

This command removes and sort using statements for all classes given a project. It is useful, for example, in removing or organizing the using statements generated by a wizard. This command can be executed from a solution node or a single project node.


Extract Constant

This command creates a constant definition statement for a selected text. Extracting a constant effectively names a literal value, which can improve readability. This command can be executed from the code editor by right-clicking selected text.


Clear Recent File List

This command clears the Visual Studio recent file list. The Clear Recent File List command brings up a Clear File dialog which allows any or all recent files to be selected.


Clear Recent Project List

This command clears the Visual Studio recent project list. The Clear Recent Project List command brings up a Clear File dialog which allows any or all recent projects to be selected.


Transform Templates

This command executes a custom tool with associated text templates items. It can be executed from a DSL project node or a DSL folder node.


Close All

This command closes all documents. It can be executed from a document tab.

Monday, June 21, 2010

How to get index fragmentation of all indexes

SELECT ps.database_id, ps.OBJECT_ID,


ps.index_id, b.name,

ps.avg_fragmentation_in_percent

FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS ps

INNER JOIN sys.indexes AS b ON ps.OBJECT_ID = b.OBJECT_ID

AND ps.index_id = b.index_id

WHERE ps.database_id = DB_ID()

ORDER BY ps.OBJECT_ID

GO

Monday, June 14, 2010

Small Basic V0.9 is here!

This is a great starting point for kids that not only teaches programming but math and logic!  The new release is full of features and bug fixes.

Learn the programming concepts starting with the fundamentals and move your way up. Small Basic is based on .NET and what you learn here could be easily applied to other .NET programming languages like Visual Basic. And when you do graduate to Visual Basic, you can bring your existing programs with you using a built-in conversion utility.


http://bit.ly/afcpeR

The Morning Brew

The Morning Brew is a great blog that covers daily news on Microsoft .Net!

http://bit.ly/cDAAT6

Thursday, June 10, 2010

Source Control Questions

Having used a few source control systems (visual studio, Source Gears Vault & Fortress, TFS and others) there is often some fundamental questions regarding source control in general.
Below is a short article from Source Gear’s Eric Sink on the topic;
Most people use only a small portion of the features of the version control system. If you use little more than checkout and checkin, you might actually be in the majority.
The "more advanced" features exist for teams and projects which are, er, more advanced. The bigger your team, the bigger your company, the more stuff you have going on, then the more powerful you want your Source Control Management (SCM) tool to be.
Even still, I've run across teams of significant size who prefer to use only the basics. The truth is that concurrent development is hard. Good SCM tools make it easier, but some people prefer to adopt processes which prevent complexity instead of using tools which help manage complexity.
But for those who dare, good version control systems offer several ways to maintain your sanity even while lots of things are going on at one time.
The most painless feature on the list is Label. Labels are conceptually very simple and are used by most teams. A label is used to mark a specific version of a file or a group of files. It is typical to apply a label when a project milestone is reached. A label is often applied when an important build is made, thus making it easier to retrieve the exact source code which corresponds to that build. In other SCM tools, labels are sometimes called "tags".
Suppose you've been working for months to deliver a beta to your customers. When you finally reach completion, you build your beta release. You want to remember exactly what the state of your repository was at the moment you reached beta, so you create a Label. You can later fetch the files from that Label and you will get the same versions you used to build your beta release.
Some processes call for the very frequent use of labels. For example, Sapient's BuildIt tool applies a label for every build it does.
Another rather painless feature on your list is Cloak. This one is actually even simpler. Cloak allows you to hide folders you don't care about. The folder is still there, but you no longer have to deal with it. For example, assume you have a big folder hierarchy. Three levels down, your marketing people placed a folder containing a whole bunch of enormous TIFF images. Developers don't want to be retrieving this stuff every time they do a get-latest operation. Luckily they can just cloak that folder and Vault will pretend it's not there. Cloak is a personal feature. When you cloak a folder, you hide it from yourself, but others can still see it.
Taking a step up the stairway of complexity we come to Share. This feature allows a folder or file to appear in multiple places in the repository. For you Unix-heads out there, Share is somewhat like a file system link.
For example, suppose your team's projects are in $/blue and another team in your company stores their work in $/red. They have a library in $/red/turboLib that you want to use, but you don't want to constantly be fetching everything else in $/red. So, you Share $/red and make it appear as $/blue/red/shares/turboLib. Now, the following two repository paths actually point to the same folder:
$/red/turboLib
$/blue/red/shares/turboLib
Any change to one of these folders will automatically appear in the other. They are not copies of each other. Rather, there is only one instance of the folder, and it simply shows up in two different places.
Note that Vault's Share command works considerably better than SourceSafe because folders can be shared, not just files. When you share a folder in SourceSafe, it just recursively shares every folder inside. If this example were done in SourceSafe, then $/blue/red/shares/turboLib would simply be a set of new folders which contain a bunch of files which are individually shared with their counterparts back in $/red/... However, the folders themselves are distinct. After the Share is created, if you add a file to $/red/turboLib, that new file will not automatically appear in $/blue/red/shares/turboLib. With Vault, the added file does appear, because the folders themselves are shared, not just the files.
Pin is handy when you have shared something but you want to freeze it. Let's say that you've been happily benefiting from the excellent efforts of the red team and you're very happy with how turboLib is working out for your project. Every time they checkin a change to turboLib, it magically becomes part of your tree as well. Suddenly one Friday, the manager of the red team decides that the fridge in their building will from now on be stocked with free beer for all the programmers. Shortly thereafter, the quality of turboLib starts going down. You are no longer quite as happy with the Share you established.
So, you bring up the Show History window and Pin $/blue/red/shares/turboLib to the version which existed on that fateful Friday. The red team can continue their "work" in $/red/turboLib, but your side of the share link will no longer automatically get their changes. It has been frozen at a Friday in the past. If you later Unpin that folder, the Share will become alive again. As long as your folder is pinned, you can't make any changes in it.
This brings us to the topic of Branching. This is the most advanced of the features mentioned here. Suppose you have a folder in which development is going on, but you want to start a second development effort using that same folder. You want the two efforts to be separate, even if you eventually want them to be one again. What you want is a branch.
Returning once again to my Share example, let's assume that after several weeks of the party life, the red team doesn't seem to be returning to normal. Pin has shielded you from their rather questionable checkins to turboLib, but now you need more. You need bugfixes in turboLib. It's time to take matters into your own hands and start maintaining your own version of turboLib. It's time to Branch.
You can branch at any version you like. In this case, you want to branch back on that freaky Friday when the red team began its decline. Those versions, the same ones you've held pinned for the last several weeks, will be the initial contents of your branch, which you create at $/blue/red/forks/turboLib.
There continues to be a relationship between $/blue/red/forks/turboLib and $/red/turboLib. They share all their history prior to that Friday. But after that Friday they diverge. Changes to one folder do not appear in the other.
Now let's say that the manager of the red team leaves and the new manager is horrified to find beer in the fridge. The beer is removed and the red team gradually regains its capacity for consecutive thought. Suddenly the red and blue versions of turboLib might seem a little too detached. The blue team has made changes which the newly coherent red team finds desirable. Similarly the red team is now beginning to improve turboLib again, leading the blue team to become interested in their new changes as well.
What these two teams need is the ability to migrate changes back and forth. This feature can go by different names. Vault and SourceSafe call it Merge Branches. The basic idea is that the user can review changes to either folder and choose to apply those changes to the other folder. The SCM tool tries to make this process as painless as possible.
Different SCM tools handle branch merging in different ways. Suffice it to say that the topic is extremely complex. A truly powerful implementation can require years of development.

Monday, June 07, 2010

Bing Maps Announcements, Updated SDK!

Today Microsoft Bing maps made several updates and released an updated SDK.

Channel9 video: http://bit.ly/abuhB7
Bing developer site:  http://www.bing.com/developers
Bing maps API: http://bit.ly/dhZqzU

Microsoft Releases Expression Studio 4

Today Microsoft released Expression Studio 4.

MSDN subscribers can download from MSDN now!

Link to press release: http://bit.ly/a831TZ
Link to express website with links to trial versions: http://bit.ly/a3EYGV

Missing Assemblies in Data Source Configuration Wizard?

If your trying to bind to custom object stored in external dll with the visual studio data sources data source configuration wizard and your assembly is missing from the selection list it might be due to a missing dependency of your external dll.


This behavior occurs when the assembly your trying to bind to has a dependency that is not included in the current project. To correct simply ensure that all the dependencies for the external dll are present in your project.

Thursday, June 03, 2010

Apple & Att iPad 3G unlimited data plan marketing criminal?

Last month I purchased the best iPad I could (64GB with 3G) for my wife as a mothers day present specifically because of the unlimited $29.95 a month data plan which was advertized by both Apple and Att.


Now less then a month later Att’s announcement that they will no longer offer the plan is no less then criminal on both Att’s and Apple’s part.

Had I known that the plan would not be available I would never have waited and spent the extra money for a version with 3G when clearly the cost of using the plan is unpredictably expensive.

Over the last several years I have heard (but not participated) in the Att bashing, however, clearly I should have seen the unethical behavior.

I am a capitalist and understand that nothing in life is free. I don’s expect anything from anyone that I don’t deserve (pay for). However, what Att is doing is selling a service (unlimited data) and then complaining that people are using it. They should never have offered the plan to begin with.

The fact that they did and Apple and Att marketed a device based on service and a plan then revoked it within 2 months is just bad customer service and business.

After being a loyal customer with many active accounts with Att I will do everything in my power to take my business both personnel and otherwise to another provider who are has some ethics.

Wednesday, June 02, 2010

Testing Ping.fm

This is a feed test trying out ping.fm!

Deploying wireless jail tracking system using .net CF, WCF an bar coding

Just deployed wireless handheld jail inmate tracking system developed with net CF, Wcf, bar coding and nLog.

This allows correction officers to perform cell checks on high risk inmates.










Windows Mobile Client Development (OS 5) Logging with Nlog

I just completed a windows mobile client application targeting a 5.1 mobile OS.  This project provided the ability to scan a barcode with the embedded barcode scanner, return the selected item from a web service (along with a photo stored on a network share) and allow the user to post movement and status changed on the scanned item.

This was the first time I used NLog on a Compact Framework device and after getting use to some of the minor issues related to the OS was able to use NLog just like a VB.net application.

In this project I configured Nlog via code rather then a configuration file.  The first issue was getting the application path to pass to Nlog.

First, I created a global variable to save the path and the Nlog logger;

Public gApplicationPath As String = String.Empty

Public gLogger As NLog.Logger = Nothing

 

Next I set the path with the following statement;

gApplicationPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)

The configuration was simple with the following code;

NLog.Internal.InternalLogger.LogFile = gApplicationPath & "\nlog.txt"
NLog.LogManager.ThrowExceptions = False

Dim config As New NLog.Config.LoggingConfiguration
Dim filetarget As New NLog.Targets.FileTarget
With filetarget
    .Name = "filetarget"
    .FileName = gApplicationPath & "\ErrorLog.txt"
    .Layout = "${longdate}||${level}||${logger}|||${message}|${exception:format=message:separator=*}^"
End With
config.AddTarget("file", filetarget)
Dim rule1 As New NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, filetarget)
config.LoggingRules.Add(rule1)
NLog.LogManager.Configuration = config
gLogger = LogManager.GetLogger("myLogerName")

Pretty straightforward!

I am a big fan of targeting a database to store the logging data to and will address updating the application to use that target next time.