пятница, 27 декабря 2013 г.

calling google Url Shortner API in C#

you can check the code below (made use of System.Net). You should notice that the contenttype must be specfied, and must be "application/json"; and also the string to be send must be in json format.
using System;
using System.Net;

using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"longUrl\":\"http://www.google.com/\"}";
                Console.WriteLine(json);
                streamWriter.Write(json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var responseText = streamReader.ReadToEnd();
                Console.WriteLine(responseText);
            }

        }

    }
}

Generate unique strings and numbers in C#

The System.Guid is used whenever we need to generate a unique key, but it is very long. That’s in many cases not an issue, but in a web scenario where it is part of the URL we need to use its string representation which is 36 characters long. It clutters up the URL and is just basically ugly.
It is not possible to shorten it without loosing some of the uniqueness of the GUID, but we can come a long way if we can accept a 16 character string instead.
We can change the standard GUID string representation:
21726045-e8f7-4b09-abd8-4bcc926e9e28
Into a shorter string:
3c4ebc5f5f2c4edc
The following method creates the shorter string and it is actually very unique. An iteration of 10 million didn’t create a duplicate. It uses the uniqueness of a GUID to create the string.
private string GenerateId()
{
 long i = 1;
 foreach (byte b in Guid.NewGuid().ToByteArray())
 {
  i *= ((int)b + 1);
 }
 return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
If you instead want numbers instead of a string, you can do that to but then you need to go up to 19 characters. The following method converts a GUID to an Int64.
private long GenerateId()
{
 byte[] buffer = Guid.NewGuid().ToByteArray();
 return BitConverter.ToInt64(buffer, 0);
}
The standard GUID is still the best way to ensure the uniqueness even though it isn’t 100% unique.

What's the best way to create a short hash, similiar to what tiny Url does?

.NET string object has a GetHashCode() function. It returns an integer. Convert it into a hex and then to an 8 characters long string.
Like so:
string hashCode = String.Format("{0:X}", sourceString.GetHashCode());
UPDATE: Added the remarks from the link above to this answer:
The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. A reason why this might happen is to improve the performance of GetHashCode.
If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code.
Notes to Callers
The value returned by GetHashCode is platform-dependent. It differs on the 32-bit and 64-bit versions of the .NET Framework.

понедельник, 2 декабря 2013 г.

.Config Transformation for projects which are not Web Projects in Visual Studio

I tried several solutions, and here is the simplest I've found.
Dan pointed out in the comments that the original post belongs to Oleg Sychthanks, Oleg!
Here are the instructions:
1. Add an XML file for each configuration to the project.
Typically you will have Debug and Release configurations so name your files App.Debug.configand App.Release.config. In my project, I created a configuration for each kind of enironment so you might want to experiment with that.
2. Unload project and open .csproj file for editing
Visual Studio allows you to edit .csproj right in the editor—you just need to unload the project first. Then right-click on it and select Edit .csproj.
3. Bind App.*.config files to main App.config
Find the project file section that contains all App.config and App.*.config references. You'll notice their build actions are set to None:
 Include="App.config" />
 Include="App.Debug.config" />
 Include="App.Release.config" />
First, set build action for all of them to Content.
Next, make all configuration-specific files dependant on the main App.config so Visual Studio groups them like it does designer and codebehind files.
Replace XML above with the one below:
 Include="App.config" />
 Include="App.Debug.config" >
  App.config
Include="App.Release.config" > App.config
4. Activate transformations magic
In the end of file after
 Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
and before final
insert the following XML:
   TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
   Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
    
     Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
    
    
       Remove="app.config" />
       Include="$(IntermediateOutputPath)$(TargetFileName).config">
        $(TargetFileName).config
Now you can reload the project, build it and enjoy App.config transformations!
Another solution I've found is NOT to use the transformations but just have a separate config file, e.g. app.Release.config. Then add this line to your csproj file.
   Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    App.Release.config
This will not only generate the right myprogram.exe.config file but if you're using Setup and Deployment Project in Visual Studio to generate MSI, it'll force the deployment project to use the correct config file when packaging.
You can use a separate config file per configuration, e.g. app.Debug.config, app.Release.config and then use the configuration variable in your project file:

    App.$(Configuration).config
This will then create the correct ProjectName.exe.config file depending on the configuration you are building in.

Windows Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string" where "" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)
Note  File I/O functions in the Windows API convert "/" to "\" as part of converting the name to an NT-style name, except when using the "\\?\" prefix as detailed in the following sections.
The Windows API has many functions that also have Unicode versions to permit an extended-length path for a maximum total path length of 32,767 characters. This type of path is composed of components separated by backslashes, each up to the value returned in the lpMaximumComponentLength parameter of the GetVolumeInformation function (this value is commonly 255 characters). To specify an extended-length path, use the "\\?\" prefix. For example, "\\?\D:\very long path".
Note  The maximum path of 32,767 characters is approximate, because the "\\?\" prefix may be expanded to a longer string by the system at run time, and this expansion applies to the total length.
The "\\?\" prefix can also be used with paths constructed according to the universal naming convention (UNC). To specify such a path using UNC, use the "\\?\UNC\" prefix. For example, "\\?\UNC\server\share", where "server" is the name of the computer and "share" is the name of the shared folder. These prefixes are not used as part of the path itself. They indicate that the path should be passed to the system with minimal modification, which means that you cannot use forward slashes to represent path separators, or a period to represent the current directory, or double dots to represent the parent directory. Because you cannot use the "\\?\" prefix with a relative path, relative paths are always limited to a total of MAX_PATH characters.
There is no need to perform any Unicode normalization on path and file name strings for use by the Windows file I/O API functions because the file system treats path and file names as an opaque sequence of WCHARs. Any normalization that your application requires should be performed with this in mind, external of any calls to related Windows file I/O API functions.
When using an API to create a directory, the specified path cannot be so long that you cannot append an 8.3 file name (that is, the directory name cannot exceed MAX_PATH minus 12).
The shell and the file system have different requirements. It is possible to create a path with the Windows API that the shell user interface is not able to interpret properly.