WCF REST Parameters

I am writing a method in wcf rest service. The method is get method and the parameter is date. How i use parameters as the service consume in jquery.

If i use templateUri, it must be string. Example:

[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetProductionDay/{shiftDate}")]

Otherwise i can use DateTime like query string. Example:

[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetProductionDay?shiftDate={shiftDate}")]

Which one is suitable? Like this i have multiple parameters with int, datetime etc. So if i go with first one all things must be string. am i right? If i follow second one any problems in any type?

Answers


In cases like this I usually use UTC date representation (count of seconds/ms from 01.01.1970). On JavaScript side it could be get as

var utc = new Date().getTime() / 1000;

On server side it could be managed by following logic:

public static class DateTimeExtensions
{
    static readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

    static readonly double _maxUnixSeconds = (DateTime.MaxValue - _unixEpoch).TotalSeconds;

    /// <summary>
    /// Converts .NET <c>DateTime</c> to Unix timestamp used in JavaScript
    /// </summary>
    /// <param name="dateTime">DateTime to convert</param>
    /// <returns>Unix timestamp in seconds</returns>
    public static long ToUnixTimestamp(this DateTime dateTime)
    {
        return (long)(dateTime - _unixEpoch).TotalSeconds;
    }


    public static DateTime FromUnixTimestamp(long seconds)
    {
        return _unixEpoch.AddSeconds(seconds);
    }

    public static DateTime? FromUnixTimestamp(string seconds)
    {
        long secondsNo;
        if(String.IsNullOrEmpty(seconds) || !long.TryParse(seconds, out secondsNo))
        {
           retun null;
        }

        return _unixEpoch.AddSeconds(secondsNo);
    }
}

Using this loigc you could convert all dates to simple numbers on client and use DateTime? on server side to correctly work with empty dates

[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetProductionDay/{shiftDate}")]
public int GetProductionDay (string shiftDate) 
{
    DateTime? dt = DateTimeExtensions.FromUnixTimestamp(shiftDate);  
    ....
    return res;
}

Some more info: How to convert a Unix timestamp to DateTime and vice versa?


Need Your Help

Autohotkey remap Apple Mac keyboard on Windows PC

windows keyboard-shortcuts autohotkey

I'm trying to configure an Apple Keyboard with numeric pad to work on a Windows notebook.

Intellij autocreates xml tags, how can it be disabled?

xml intellij-idea

I'm with IntelliJ Idea 14.1.3 on Ubuntu 14.04.1