Facebook как отслеживание уведомлений (Дизайн DB)

Я использую этого, я получаю его от сети

public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter)) return this;
        return null;
    }

    private const string fileSizeFormat = "fs";
    private const Decimal OneKiloByte = 1024M;
    private const Decimal OneMegaByte = OneKiloByte * 1024M;
    private const Decimal OneGigaByte = OneMegaByte * 1024M;

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {    
        if (format == null || !format.StartsWith(fileSizeFormat))    
        {    
            return defaultFormat(format, arg, formatProvider);    
        }

        if (arg is string)    
        {    
            return defaultFormat(format, arg, formatProvider);    
        }

        Decimal size;

        try    
        {    
            size = Convert.ToDecimal(arg);    
        }    
        catch (InvalidCastException)    
        {    
            return defaultFormat(format, arg, formatProvider);    
        }

        string suffix;
        if (size > OneGigaByte)
        {
            size /= OneGigaByte;
            suffix = "GB";
        }
        else if (size > OneMegaByte)
        {
            size /= OneMegaByte;
            suffix = "MB";
        }
        else if (size > OneKiloByte)
        {
            size /= OneKiloByte;
            suffix = "kB";
        }
        else
        {
            suffix = " B";
        }

        string precision = format.Substring(2);
        if (String.IsNullOrEmpty(precision)) precision = "2";
        return String.Format("{0:N" + precision + "}{1}", size, suffix);

    }

    private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)
    {
        IFormattable formattableArg = arg as IFormattable;
        if (formattableArg != null)
        {
            return formattableArg.ToString(format, formatProvider);
        }
        return arg.ToString();
    }

}

, пример использования был бы:

Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 100));
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 10000));

Кредиты на http://flimflan.com/blog/FileSizeFormatProvider.aspx

существует проблема с ToString (), он ожидает тип NumberFormatInfo, который реализует IFormatProvider, но класс NumberFormatInfo изолируется: (

при использовании C# 3.0 можно использовать дополнительный метод для получения результата, который Вы хотите:

public static class ExtensionMethods
{
    public static string ToFileSize(this long l)
    {
        return String.Format(new FileSizeFormatProvider(), "{0:fs}", l);
    }
}

можно использовать его как это.

long l = 100000000;
Console.WriteLine(l.ToFileSize());

Hope это помогает.

39
задан reformed 10 February 2017 в 23:49
поделиться

3 ответа

Я не знаю, лучший ли это способ сделать это, но поскольку У меня нет идей ни от кого, это то, чем я буду заниматься. Я надеюсь, что этот ответ может помочь и другим.

У нас есть 2 таблицы

notification
-----------------
id (pk)
userid
notification_type (for complexity like notifications for pictures, videos, apps etc.)
notification
time


notificationsRead
--------------------
id (pk) (i dont think this field is required, anyways)
lasttime_read
userid

Идея состоит в том, чтобы выбрать уведомления из таблицы уведомлений и присоединиться к таблице notificationsRead и проверить последнее уведомление о прочтении и строки с ID> notificationid. И каждый раз, когда открывается страница уведомлений, обновляйте строку из таблицы notificationsRead.

Я думаю, запрос непрочитанных уведомлений будет таким ..

SELECT `userid`, `notification`, `time` from `notifications` `notificationsRead`
WHERE 
`notifications`.`userid` IN ( ... query to get a list of friends ...) 
AND 
(`notifications`.`time` > (
    SELECT `notificationsRead`.`lasttime_read` FROM `notificationsRead` 
    WHERE `notificationsRead`.`userid` = ...$userid...
))

Вышеупомянутый запрос не проверяется. Thanks to the idea of db design from @espais

40
ответ дан 27 November 2019 в 02:43
поделиться

Вы можете добавить еще одну таблицу ...

tblUserNotificationStatus
-------------------------
- id (pk)
- notification_id
- user_id
- read_status (boolean)

Если вы хотите сохранить историю, вы можете сохранить X последних уведомлений и удалить остальные, которые старше вашего последнего уведомления в списке ....

9
ответ дан 27 November 2019 в 02:43
поделиться

If, when you give notifications, you give all relevant notifications available at that time, you can make this simpler by attaching timestamps to notifiable events, and keeping track of when each user last received notifications. If you are in a multi-server environment, though, you do have to be careful about synchronization. Note that this approach doesn't require true date-time stamps, just something that increases monotonically.

7
ответ дан 27 November 2019 в 02:43
поделиться
Другие вопросы по тегам:

Похожие вопросы: