Exemplo n.º 1
0
        public ActionResult ByPVBase(PVService service, string pvId, string callback,
            DataFormat format = DataFormat.Auto)
        {
            var song = Service.GetSongWithPV(s => new EntryBaseContract(s), service, pvId);

            return Object(song, format, callback);
        }
Exemplo n.º 2
0
        public ActionResult ByPV(PVService service, string pvId, ContentLanguagePreference? lang, string callback, 
            DataFormat format = DataFormat.Auto)
        {
            var song = Service.GetSongWithPV(s => new SongForApiContract(s, lang ?? ContentLanguagePreference.Default), service, pvId);

            return Object(song, format, callback);
        }
Exemplo n.º 3
0
        public ActionResult OEmbed(string url, int maxwidth = 570, int maxheight = 400, DataFormat format = DataFormat.Json)
        {
            if (string.IsNullOrEmpty(url))
                return HttpStatusCodeResult(HttpStatusCode.BadRequest, "URL not specified");

            var route = new RouteInfo(new Uri(url), AppConfig.HostAddress).RouteData;
            var controller = route.Values["controller"].ToString().ToLowerInvariant();

            if (controller != "song" && controller != "s") {
                return HttpStatusCodeResult(HttpStatusCode.BadRequest, "Only song embeds are supported");
            }

            int id;

            if (controller == "s") {
                var match = Regex.Match(route.Values["action"].ToString(), @"(\d+)");
                id = int.Parse(match.Groups[1].Value);
            }
            else {
                id = int.Parse(route.Values["id"].ToString());
            }

            var song = Services.Songs.GetSong(id);
            var html = string.Format("<iframe src=\"{0}\" width=\"{1}\" height=\"{2}\"></iframe>",
                VocaUriBuilder.CreateAbsolute(Url.Action("EmbedSong", new {songId = id})), maxwidth, maxheight);

            return Object(new SongOEmbedResponse(song, maxwidth, maxheight, html), format);
        }
        private WireType GetWireType(TypeCode code, DataFormat format, ref Type type, out int modelKey)
        {
            modelKey = -1;
            if (type.IsEnum) return WireType.None;
            switch (code)
            {
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                case TypeCode.Boolean:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.Char:
                    return WireType.Variant;
                case TypeCode.Double:
                    return WireType.Fixed64;
                case TypeCode.Single:
                    return WireType.Fixed32;
                case TypeCode.String:
                case TypeCode.DateTime:
                case TypeCode.Decimal:
                    return WireType.String;
            }
            if (type == typeof(byte[]) || type == typeof(TimeSpan)
                || type == typeof(Guid) || type == typeof(Uri)) return WireType.String;

            if ((modelKey = GetKey(ref type)) >= 0)
            {
                return WireType.String;
            }
            return WireType.None;
        }
Exemplo n.º 5
0
 public RawTexture()
 {
     Width = 0;
     Height = 0;
     Data = new byte[0];
     Format = DataFormat.Invalid;
 }
Exemplo n.º 6
0
 public RawTexture(int width, int height, DataFormat format, byte[] data)
     : this(width, height, format)
 {
     if (data.Length != Data.Length)
         throw new ArgumentException("Provided Data is of invalid Size", nameof(data));
     Buffer.BlockCopy(data, 0, Data, 0, data.Length);
 }
Exemplo n.º 7
0
        Serialization(DataFormat dataFormat, string streamName)
        {
            Dbg.Assert(!string.IsNullOrEmpty(streamName), "stream needs a name");

            format = dataFormat;
            this.streamName = streamName;
        }
Exemplo n.º 8
0
 public RawTexture(int width, int height, DataFormat format)
 {
     Width = width;
     Height = height;
     var tgtSize = (int) format * width * height;
     Format = format;
     Data = new byte[tgtSize];
 }
        public static string Run(string data, DataFormat inputFormat, DataFormat outputFormat, Operation operation)
        {
            if (string.IsNullOrEmpty(data)) return string.Empty;

            var bytes = GetBytes(data, inputFormat);
            var result = Process(bytes, operation);
            return GetString(result, outputFormat);
        }
 /// <summary>
 /// 实例化RESTfulInvocationHandler
 /// </summary>
 /// <param name="attribute"></param>
 /// <param name="token"></param>
 /// <param name="foramt"></param>
 public RESTfulInvocationHandler(string url, PublishKindAttribute attribute, Token token, DataFormat foramt, int timeout)
 {
     this.format = foramt;
     this.attribute = attribute;
     this.token = token;
     this.url = url;
     this.timeout = timeout;
 }
Exemplo n.º 11
0
        /// <summary>
        /// Uploads an activity.
        /// </summary>
        /// <param name="file">The path to the activity file on your local hard disk.</param>
        /// <param name="dataFormat">The format of the file.</param>
        /// <param name="activityType">The type of the activity.</param>
        /// <returns>The status of the upload.</returns>
        public async Task<UploadStatus> UploadActivityAsync(StorageFile file, DataFormat dataFormat, ActivityType activityType = ActivityType.Ride)
        {
            String format = String.Empty;

            switch (dataFormat)
            {
                case DataFormat.Fit:
                    format = "fit";
                    break;
                case DataFormat.FitGZipped:
                    format = "fit.gz";
                    break;
                case DataFormat.Gpx:
                    format = "gpx";
                    break;
                case DataFormat.GpxGZipped:
                    format = "gpx.gz";
                    break;
                case DataFormat.Tcx:
                    format = "tcx";
                    break;
                case DataFormat.TcxGZipped:
                    format = "tcx.gz";
                    break;
            }
           
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", Authentication.AccessToken));

            MultipartFormDataContent content = new MultipartFormDataContent();

            byte[] fileBytes = null;
            using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
            {
                fileBytes = new byte[stream.Size];
                using (DataReader reader = new DataReader(stream))
                {
                    await reader.LoadAsync((uint)stream.Size);
                    reader.ReadBytes(fileBytes);
                }
            }

            var byteArrayContent = new ByteArrayContent(fileBytes);

            content.Add(byteArrayContent, "file", file.Name);

            HttpResponseMessage result = await client.PostAsync(
                String.Format("https://www.strava.com/api/v3/uploads?data_type={0}&activity_type={1}",
                format,
                activityType.ToString().ToLower()),
                content);

            String json = await result.Content.ReadAsStringAsync();

            return Unmarshaller<UploadStatus>.Unmarshal(json);
        }
Exemplo n.º 12
0
        public ActionResult Index(string query, DiscType discType = DiscType.Unknown,
            int start = 0, bool getTotalCount = false, AlbumSortRule sort = AlbumSortRule.Name,
            NameMatchMode nameMatchMode = NameMatchMode.Exact, DataFormat format = DataFormat.Auto)
        {
            var queryParams = new AlbumQueryParams(query, discType, start, maxResults, false, getTotalCount, nameMatchMode, sort);

            var entries = Service.Find(a => new AlbumForApiContract(a, LoginManager.LanguagePreference), queryParams);

            return Object(entries, format);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates a new <see cref="ConfigurationCell"/> from specified parameters.
        /// </summary>
        /// <param name="parent">The reference to parent <see cref="ConfigurationFrame"/> of this <see cref="ConfigurationCell"/>.</param>
        /// <param name="idCode">The numeric ID code for this <see cref="ConfigurationCell"/>.</param>
        /// <param name="isVirtual">Assigns flag that determines if this <see cref="ConfigurationCell"/> is virtual.</param>
        public ConfigurationCell(ConfigurationFrame parent, ushort idCode, bool isVirtual)
            : base(parent, idCode, int.MaxValue, int.MaxValue, int.MaxValue)
		{			
			m_signalReferences = new Dictionary<SignalType, string[]>();
			m_analogDataFormat = DataFormat.FloatingPoint;
			m_frequencyDataFormat = DataFormat.FloatingPoint;
			m_phasorDataFormat = DataFormat.FloatingPoint;
			m_phasorCoordinateFormat = CoordinateFormat.Polar;
            m_isVirtual = isVirtual;
		}
Exemplo n.º 14
0
        public ActionResult ByPVBase(PVService? service, string pvId, string callback,
            DataFormat format = DataFormat.Auto)
        {
            if (service == null)
                return HttpStatusCodeResult(HttpStatusCode.BadRequest, "Service not specified or invalid");

            var song = Service.GetSongWithPV(s => new EntryBaseContract(s), service.Value, pvId);

            return Object(song, format, callback);
        }
Exemplo n.º 15
0
        public ActionResult Tracks(int id = invalidId, DataFormat format = DataFormat.Auto, 
            ContentLanguagePreference lang = ContentLanguagePreference.Default)
        {
            if (id == invalidId)
                return NoId();

            var tracks = Service.GetAlbum(id, a => a.Songs.Select(s => new SongInAlbumContract(s, lang)).ToArray());

            return Object(tracks, format);
        }
Exemplo n.º 16
0
    // constructor for reading an IDX file
    public IDX(Stream in_stream, bool in_writing=false)
    {
        _idx_stream = in_stream;
        // verify we can actually use this stream
        Debug.Assert(_idx_stream.CanRead && _idx_stream.CanSeek);

        _writing = in_writing;
        if (_writing)
        {
            // just verify stream is writeable
            Debug.Assert(_idx_stream.CanWrite == true);
        }

        // get our endianness
        _idx_endianness = (Endianness)(255 * ReadUInt8() + ReadUInt8());
        Debug.Assert(_idx_endianness == Endianness.BigEndian || _idx_endianness == Endianness.LittleEndian);

        // get data format
        _data_format = (DataFormat)ReadUInt8();

        // number of dimensions
        byte dimensions = ReadUInt8();
        Debug.Assert(dimensions > 0);
        // get number of rows
        _rows = ReadUInt32();

        // calculate length of each row
        _row_length = 1;
        for (int k = 1; k < dimensions; k++)
        {
            _row_length *= ReadUInt32();
        }

        _row_length_bytes = _row_length;
        switch (_data_format)
        {
            case DataFormat.UInt8:
            case DataFormat.SInt8:
                _row_length_bytes *= 1;
                break;
            case DataFormat.SInt16:
                _row_length_bytes *= 2;
                break;
            case DataFormat.SInt32:
            case DataFormat.Single:
                _row_length_bytes *= 4;
                break;
            case DataFormat.Double:
                _row_length_bytes *= 8;
                break;
        }

        // get size of the header
        _header_size = (uint)_idx_stream.Position;
    }
Exemplo n.º 17
0
        /// <summary>
        /// Creates a new <see cref="ConfigurationCell"/> from specified parameters.
        /// </summary>
        /// <param name="parent">The reference to parent <see cref="ConfigurationFrame"/> of this <see cref="ConfigurationCell"/>.</param>
        /// <param name="idCode">The numeric ID code for this <see cref="ConfigurationCell"/>.</param>
        public ConfigurationCell(ConfigurationFrame parent, ushort idCode)
            : base(parent, idCode, int.MaxValue, int.MaxValue, int.MaxValue)
        {
            // Create a cached signal reference dictionary for generated signal references
            m_generatedSignalReferenceCache = new string[Enum.GetValues(typeof(SignalKind)).Length][];

            m_analogDataFormat = DataFormat.FloatingPoint;
            m_frequencyDataFormat = DataFormat.FloatingPoint;
            m_phasorDataFormat = DataFormat.FloatingPoint;
            m_phasorCoordinateFormat = CoordinateFormat.Polar;
        }
Exemplo n.º 18
0
        public ActionResult Versions(DataFormat format = DataFormat.Auto)
        {
            var versions = queries
                .HandleQuery(ctx => ctx.Query()
                    .Where(a => !a.Deleted)
                    .Select(a => new { a.Id, a.Version })
                    .ToArray()
                    .Select(v => new EntryIdAndVersionContract(v.Id, v.Version))
                    .ToArray());

            return ObjectLowercase(versions, format);
        }
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.UserControl.Load"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            foreach (var key in controlMapping.Keys)
            {
                var format = key;
                var rb = controlMapping[format];
                rb.Checked = format == DataFormat;
                rb.CheckedChanged += (s, _) => DataFormat = format;
            }
        }
Exemplo n.º 20
0
        public ActionResult ParsePVUrl(string pvUrl, string callback, DataFormat format = DataFormat.Auto)
        {
            var result = VideoServiceHelper.ParseByUrl(pvUrl, true);

            if (!result.IsOk) {
                return Json(new GenericResponse<string>(false, result.Exception.Message));
            }

            var contract = new PVContract(result, PVType.Original);

            return Object(contract, format, callback);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates a new ValueMember instance
        /// </summary>
        internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat)
        {
            if (memberType == null) throw new ArgumentNullException("memberType");
            if (model == null) throw new ArgumentNullException("model");
            this.fieldNumber = fieldNumber;
            this.memberType = memberType;
            this.itemType = itemType;
            this.defaultType = defaultType;

            this.model = model;
            this.dataFormat = dataFormat;
        }
Exemplo n.º 22
0
        public ActionResult Details(int id = invalidId,
            bool includeAlbums = true, bool includeArtists = true, bool includeNames = true, bool includePVs = false, bool includeTags = true, bool includeWebLinks = false,
            string callback = null, DataFormat format = DataFormat.Auto,
            ContentLanguagePreference lang = ContentLanguagePreference.Default)
        {
            if (id == invalidId)
                return NoId();

            var song = Service.GetSongWithMergeRecord(id, (s, m) => new SongForApiContract(s, m, lang, includeAlbums, includeArtists, includeNames, includePVs, includeTags, true, includeWebLinks));

            return Object(song, format, callback);
        }
Exemplo n.º 23
0
        public ActionResult Details(int id = invalidId, 
            bool includeArtists = true, bool includeNames = true, bool includePVs = false, bool includeTags = true, bool includeWebLinks = false,
            DataFormat format = DataFormat.Auto,
            ContentLanguagePreference lang = ContentLanguagePreference.Default)
        {
            if (id == invalidId)
                return NoId();

            var album = Service.GetAlbumWithMergeRecord(id, (a, m) => new AlbumForApiContract(a, m, lang, includeArtists, includeNames, includePVs, includeTags, includeWebLinks));

            return Object(album, format);
        }
Exemplo n.º 24
0
        public ActionResult Index(string query, DiscType discType = DiscType.Unknown,
            int start = 0, bool getTotalCount = false, AlbumSortRule sort = AlbumSortRule.Name,
            NameMatchMode nameMatchMode = NameMatchMode.Exact,
            bool includeArtists = true, bool includeNames = true, bool includePVs = false, bool includeTags = true, bool includeWebLinks = false,
            DataFormat format = DataFormat.Auto,
            ContentLanguagePreference lang = ContentLanguagePreference.Default)
        {
            var queryParams = new AlbumQueryParams(query, discType, start, maxResults, false, getTotalCount, nameMatchMode, sort);

            var entries = Service.Find(a => new AlbumForApiContract(a, null, lang, includeArtists, includeNames, includePVs, includeTags, includeWebLinks), queryParams);

            return Object(entries, format);
        }
Exemplo n.º 25
0
        public ActionResult ByPV(PVService? service, string pvId, ContentLanguagePreference? lang, string callback,
            bool includeAlbums = true, bool includeArtists = true, bool includeNames = true, bool includePVs = false,
            bool includeTags = true, bool includeWebLinks = false,
            DataFormat format = DataFormat.Auto)
        {
            if (service == null)
                return HttpStatusCodeResult(HttpStatusCode.BadRequest, "Service not specified or invalid");

            var song = Service.GetSongWithPV(s => new SongForApiContract(s, null, lang ?? ContentLanguagePreference.Default,
                includeAlbums, includeArtists, includeNames, includePVs, includeTags, true, includeWebLinks), service.Value, pvId);

            return Object(song, format, callback);
        }
Exemplo n.º 26
0
        public static RestRequest CreateRequest(Method method, string resource, DataFormat format = DataFormat.Json)
        {
            var request = new RestRequest
            {
                Resource = resource,
                Method = method,
                RequestFormat = format
            };

            var basicAuthCred = Convert.ToBase64String(Encoding.Default.GetBytes($":{Constants.Keys.Api}"));
            request.AddHeader("Authorization", $"Basic {basicAuthCred}");
            request.AddHeader("Accept-Version", Constants.ApiVersionHeader);

            return request;
        }
Exemplo n.º 27
0
 public string getExtension(DataFormat dataFormat)
 {
     switch (dataFormat)
     {
         case DataFormat.IFC:
             return ".ifc";
         case DataFormat.gbXML:
             return ".xml";
         case DataFormat.RVT:
             return ".rvt";
         case DataFormat.IDF:
             return ".idf";
         default:
             return "";
     }
 }
Exemplo n.º 28
0
        /// <summary>
        /// Used to make search Request to Amazon Cloud Search
        /// </summary>
        /// <param name="SearchUri"></param>
        /// <param name="searchQuery"></param>
        /// <param name="returnFields"></param>
        /// <param name="pageSize"></param>
        /// <param name="start"></param>
        /// <returns>Response Status</returns>
        public string SearchRequest(string apiEndPoint, string apiVersion,
                                    string searchQuery, string searchOption,
                                    string returnFields, string sortByScore, DataFormat format)
        {
            // Buid search url
            string SearchUrl = "http://search-" + apiEndPoint
                + "/" + apiVersion
                + "/search?" + searchQuery
                + "&" + searchOption
                + "&return=" + returnFields
                + "&sort=" + sortByScore
                + "&size=9999";

            // Check type of format
            if (format == DataFormat.Xml)
                SearchUrl = SearchUrl + "&results-type=xml";

            string responseFromServer = string.Empty;

            // Create a request for the URL.
            WebRequest request = WebRequest.Create(SearchUrl);

            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultNetworkCredentials;
            request.ContentType = "application/json";
            request.Timeout = 10000;

            // Get the response.
            WebResponse response = request.GetResponse();

            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);

            // Read the content.
            responseFromServer = reader.ReadToEnd();

            // Clean up the streams and the response.
            reader.Close();
            response.Close();

            // Returns response from the server
            return responseFromServer;
        }
Exemplo n.º 29
0
 public bool convert(DataFormat inFormat, DataFormat outFormat, string inFile, string outFile)
 {
     bool result;
     if (inFormat == DataFormat.IFC && outFormat == DataFormat.gbXML)
     {
         lock (Program.revitLock)
         {
             result = ifc2gbXML.Convert(inFile, outFile);
         }
         return result;
     }
     if (inFormat == DataFormat.gbXML && outFormat == DataFormat.IDF)
     {
         lock (Program.designBuilderLock)
         {
             result = gbXML2idf.Convert(inFile, outFile);
         }
         return result;
     }
     if (inFormat == DataFormat.IFC && outFormat == DataFormat.RVT)
     {
         lock (Program.revitLock)
         {
             result = ifc2rvt.Convert(inFile, outFile);
         }
         return result;
     }
     if(inFormat== DataFormat.RVT && outFormat == DataFormat.IFC)
     {
         lock(Program.revitLock)
         {
             result = rvt2ifc.Convert(inFile, outFile);
         }
         return result;
     }
     if(inFormat == DataFormat.RVT && outFormat == DataFormat.gbXML)
     {
         lock(Program.revitLock)
         {
             result = rvt2gbXML.Convert(inFile, outFile);
         }
         return result;
     }
     return false;
 }
Exemplo n.º 30
0
        /// <summary>
        /// Uploads an activity.
        /// </summary>
        /// <param name="filePath">The path to the activity file on your local hard disk.</param>
        /// <param name="dataFormat">The format of the file.</param>
        /// <param name="activityType">The type of the activity.</param>
        /// <returns>The status of the upload.</returns>
        public async Task<UploadStatus> UploadActivityAsync(String filePath, DataFormat dataFormat, ActivityType activityType = ActivityType.Ride)
        {
            String format = String.Empty;

            switch (dataFormat)
            {
                case DataFormat.Fit:
                    format = "fit";
                    break;
                case DataFormat.FitGZipped:
                    format = "fit.gz";
                    break;
                case DataFormat.Gpx:
                    format = "gpx";
                    break;
                case DataFormat.GpxGZipped:
                    format = "gpx.gz";
                    break;
                case DataFormat.Tcx:
                    format = "tcx";
                    break;
                case DataFormat.TcxGZipped:
                    format = "tcx.gz";
                    break;
            }

            FileInfo info = new FileInfo(filePath);

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", Authentication.AccessToken));

            MultipartFormDataContent content = new MultipartFormDataContent();

            content.Add(new ByteArrayContent(File.ReadAllBytes(info.FullName)), "file", info.Name);

            HttpResponseMessage result = await client.PostAsync(
                String.Format("https://www.strava.com/api/v3/uploads?data_type={0}&activity_type={1}",
                format,
                activityType.ToString().ToLower()),
                content);

            String json = await result.Content.ReadAsStringAsync();

            return Unmarshaller<UploadStatus>.Unmarshal(json);
        }
Exemplo n.º 31
0
 /// <summary>
 /// 构造函数 -- 封装数据
 /// </summary>
 /// <param name="eField">字段标签</param>
 /// <param name="eFormat">格式标签</param>
 /// <param name="pContent">数据</param>
 internal CustomData(DataField eField, DataFormat eFormat, object pContent)
 {
     this._eField   = eField;
     this._eFormat  = eFormat;
     this._pContent = pContent;
 }
Exemplo n.º 32
0
 /// <summary>
 /// Set the DataFormat of the IRestRequest.
 /// </summary>
 /// <param name="dataFormat"></param>
 /// <returns></returns>
 public IRequestBuilder SetFormat(DataFormat dataFormat)
 {
     _dataFormat = dataFormat;
     return(this);
 }
Exemplo n.º 33
0
 public ActionResult OEmbedResponsive(string url, int maxwidth = 570, int maxheight = 400, DataFormat format = DataFormat.Json)
 {
     return(OEmbed(url, maxwidth, maxheight, format, true));
 }
Exemplo n.º 34
0
 public DataConversion(DataFormat source, DataFormat target)
 {
     Source = source;
     Target = target;
 }
 /// <summary>
 /// Sets the data format which will be used for the drag and drop actions.
 /// </summary>
 public static void SetDataFormat(UIElement source, DataFormat value)
 {
     source.SetValue(DataFormatProperty, value);
 }
        public Writer(Uri dependencyServiceUri, AtlasConfiguration atlasConfiguration, DataFormat dataFormat,
                      string group, IOutputTopic topic, bool enableCache = true)
        {
            var httpDependencyClient =
                new HttpDependencyClient(dependencyServiceUri, group,
                                         enableCache); // DependencyClient stores the Data format, Atlas Configuration
            var dataFormatClient         = new DataFormatClient(httpDependencyClient);
            var atlasConfigurationClient = new AtlasConfigurationClient(httpDependencyClient);
            var atlasConfigurationId     =
                atlasConfigurationClient
                .PutAndIdentifyAtlasConfiguration(atlasConfiguration); // Uniq ID created for the AtlasConfiguration
            var dataFormatId =
                dataFormatClient.PutAndIdentifyDataFormat(dataFormat); // Uniq ID created for the Data Format

            TopicName = topic.TopicName;

            //Init Session
            session = new SessionTelemetryDataOutput(topic, dataFormatId, dataFormatClient);
            session.SessionOutput.AddSessionDependency(DependencyTypes.DataFormat, dataFormatId);
            session.SessionOutput.AddSessionDependency(DependencyTypes.AtlasConfiguration, atlasConfigurationId);
            SessionOutput = session.SessionOutput;
        }
Exemplo n.º 37
0
 /// <summary>
 /// 使用指定的数据解析来实例化对象
 /// </summary>
 /// <param name="dataFormat">数据规则</param>
 public ReverseWordTransform(DataFormat dataFormat) : base(dataFormat)
 {
 }
Exemplo n.º 38
0
 /// <summary>
 /// 使用指定的数据解析来实例化对象
 /// </summary>
 /// <param name="dataFormat">数据规则</param>
 public ByteTransformBase(DataFormat dataFormat)
 {
     this.DataFormat = dataFormat;
 }
Exemplo n.º 39
0
        /// <summary>
        /// 将单个数据表保存到Excel
        /// </summary>
        /// <param name="dataTable">数据表</param>
        /// <param name="fileName">文件名</param>
        public static void ExportExcel(DataTable dataTable, string fileName = null)
        {
            HSSFWorkbook workBook = new HSSFWorkbook();
            Sheet        sheet    = workBook.CreateSheet("Sheet1");

            Font font = workBook.CreateFont();

            font.Boldweight = 700;
            CellStyle style = workBook.CreateCellStyle();

            style.Alignment = HorizontalAlignment.CENTER;
            style.SetFont(font);

            int  rownum = 0;
            Row  row    = sheet.CreateRow(rownum++);
            Cell cell;

            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                cell = row.CreateCell(i);
                cell.SetCellValue(dataTable.Columns[i].ColumnName);
                cell.CellStyle = style;
            }

            CellStyle  dateStyle = workBook.CreateCellStyle();
            DataFormat format    = workBook.CreateDataFormat();

            dateStyle.DataFormat = format.GetFormat("yyyy-MM-dd HH:mm:ss");

            foreach (DataRow dataRow in dataTable.Rows)
            {
                row = sheet.CreateRow(rownum++);
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    cell = row.CreateCell(i);
                    string strValue = dataRow[i].ToString();
                    if (string.IsNullOrWhiteSpace(strValue))
                    {
                        cell.SetCellValue("");
                    }
                    else
                    {
                        switch (dataTable.Columns[i].DataType.ToString())
                        {
                        case "System.DateTime":
                            DateTime dateTime;
                            DateTime.TryParse(strValue, out dateTime);
                            cell.SetCellValue(dateTime);
                            cell.CellStyle = dateStyle;
                            break;

                        case "System.Boolean":
                            bool bValue;
                            bool.TryParse(strValue, out bValue);
                            cell.SetCellValue(bValue);
                            break;

                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int iValue = 0;
                            int.TryParse(strValue, out iValue);
                            cell.SetCellValue(iValue);
                            break;

                        case "System.Decimal":
                        case "System.Double":
                            double dValue = 0;
                            double.TryParse(strValue, out dValue);
                            cell.SetCellValue(dValue);
                            break;

                        default:
                            cell.SetCellValue(strValue);
                            break;
                        }
                    }
                }
            }
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                sheet.AutoSizeColumn(i);
            }

            workBook.Write(HttpContext.Current.Response.OutputStream);
            workBook.Dispose();

            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = DateTime.Now.ToString("yyyyMMddHHmmss");
            }

            HttpContext.Current.Response.AppendHeader("Content-Disposition", "Attachment; FileName=" + GetToExcelName(fileName) + ".xls");
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
Exemplo n.º 40
0
        internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType,
                                                              bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes)
        {
#if !NO_GENERICS
            {
                Type tmp = Helpers.GetUnderlyingType(type);
                if (tmp != null)
                {
                    type = tmp;
                }
            }
#endif
            if (Helpers.IsEnum(type))
            {
                if (allowComplexTypes && model != null)
                {
                    // need to do this before checking the typecode; an int enum will report Int32 etc
                    defaultWireType = WireType.Variant;
                    return(new EnumSerializer(type, model.GetEnumMap(type)));
                }
                else
                { // enum is fine for adding as a meta-type
                    defaultWireType = WireType.None;
                    return(null);
                }
            }
            ProtoTypeCode code = Helpers.GetTypeCode(type);
            switch (code)
            {
            case ProtoTypeCode.Int32:
                defaultWireType = GetIntWireType(dataFormat, 32);
                return(new Int32Serializer(model));

            case ProtoTypeCode.UInt32:
                defaultWireType = GetIntWireType(dataFormat, 32);
                return(new UInt32Serializer(model));

            case ProtoTypeCode.Int64:
                defaultWireType = GetIntWireType(dataFormat, 64);
                return(new Int64Serializer(model));

            case ProtoTypeCode.UInt64:
                defaultWireType = GetIntWireType(dataFormat, 64);
                return(new UInt64Serializer(model));

            case ProtoTypeCode.String:
                defaultWireType = WireType.String;
                if (asReference)
                {
                    return(new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference));
                }
                return(new StringSerializer(model));

            case ProtoTypeCode.Single:
                defaultWireType = WireType.Fixed32;
                return(new SingleSerializer(model));

            case ProtoTypeCode.Double:
                defaultWireType = WireType.Fixed64;
                return(new DoubleSerializer(model));

            case ProtoTypeCode.Boolean:
                defaultWireType = WireType.Variant;
                return(new BooleanSerializer(model));

            case ProtoTypeCode.DateTime:
                defaultWireType = GetDateTimeWireType(dataFormat);
                return(new DateTimeSerializer(model));

            case ProtoTypeCode.Decimal:
                defaultWireType = WireType.String;
                return(new DecimalSerializer(model));

            case ProtoTypeCode.Byte:
                defaultWireType = GetIntWireType(dataFormat, 32);
                return(new ByteSerializer(model));

            case ProtoTypeCode.SByte:
                defaultWireType = GetIntWireType(dataFormat, 32);
                return(new SByteSerializer(model));

            case ProtoTypeCode.Char:
                defaultWireType = WireType.Variant;
                return(new CharSerializer(model));

            case ProtoTypeCode.Int16:
                defaultWireType = GetIntWireType(dataFormat, 32);
                return(new Int16Serializer(model));

            case ProtoTypeCode.UInt16:
                defaultWireType = GetIntWireType(dataFormat, 32);
                return(new UInt16Serializer(model));

            case ProtoTypeCode.TimeSpan:
                defaultWireType = GetDateTimeWireType(dataFormat);
                return(new TimeSpanSerializer(model));

            case ProtoTypeCode.Guid:
                defaultWireType = WireType.String;
                return(new GuidSerializer(model));

            case ProtoTypeCode.Uri:
                defaultWireType = WireType.String;
                return(new StringSerializer(model));

            case ProtoTypeCode.ByteArray:
                defaultWireType = WireType.String;
                return(new BlobSerializer(model, overwriteList));

            case ProtoTypeCode.Type:
                defaultWireType = WireType.String;
                return(new SystemTypeSerializer(model));
            }
            IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null;
            if (parseable != null)
            {
                defaultWireType = WireType.String;
                return(parseable);
            }
            if (allowComplexTypes && model != null)
            {
                int key = model.GetKey(type, false, true);
                if (asReference || dynamicType)
                {
                    defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
                    BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None;
                    if (asReference)
                    {
                        options |= BclHelpers.NetObjectOptions.AsReference;
                    }
                    if (dynamicType)
                    {
                        options |= BclHelpers.NetObjectOptions.DynamicType;
                    }
                    if (key >= 0)
                    { // exists
                        if (asReference && Helpers.IsValueType(type))
                        {
                            string message = "AsReference cannot be used with value-types";

                            if (type.Name == "KeyValuePair`2")
                            {
                                message += "; please see http://stackoverflow.com/q/14436606/";
                            }
                            else
                            {
                                message += ": " + type.FullName;
                            }
                            throw new InvalidOperationException(message);
                        }
                        MetaType meta = model[type];
                        if (asReference && meta.IsAutoTuple)
                        {
                            options |= BclHelpers.NetObjectOptions.LateSet;
                        }
                        if (meta.UseConstructor)
                        {
                            options |= BclHelpers.NetObjectOptions.UseConstructor;
                        }
                    }
                    return(new NetObjectSerializer(model, type, key, options));
                }
                if (key >= 0)
                {
                    defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String;
                    return(new SubItemSerializer(type, key, model[type], true));
                }
            }
            defaultWireType = WireType.None;
            return(null);
        }
        /// <summary>
        /// Returns the current state of the registration, including completion
        /// and satisfaction type data.  Amount of detail depends on format parameter.
        /// </summary>
        /// <param name="registrationId">Unique Identifier for the registration</param>
        /// <param name="instanceId">Integer value (as string) of the registration instance to retrieve.</param>
        /// <param name="resultsFormat">Degree of detail to return</param>
        /// <returns>Registration data in XML Format</returns>
        public string GetRegistrationResult(string registrationId, string instanceId, RegistrationResultsFormat resultsFormat, DataFormat dataFormat)
        {
            ServiceRequest request = new ServiceRequest(configuration);

            request.Parameters.Add("regid", registrationId);
            request.Parameters.Add("instanceid", instanceId);
            request.Parameters.Add("resultsformat", Enum.GetName(resultsFormat.GetType(), resultsFormat).ToLower());
            if (dataFormat == DataFormat.JSON)
            {
                request.Parameters.Add("dataformat", "json");
            }
            XmlDocument response = request.CallService("rustici.registration.getRegistrationResult");

            // Return the subset of the xml starting with the top <summary>
            return(response.ChildNodes[1].InnerXml);
        }
 public NewtonsoftJsonRestRequest(Uri resource, Method method = Method.GET, DataFormat dataFormat = DataFormat.Xml) : base(resource, method, dataFormat)
 {
     InitSerializer();
 }
Exemplo n.º 43
0
Arquivo: Program.cs Projeto: mbcse/AES
    private static bool EncryptDecrypt(
        DataType startType, DataType interType, DataType endType,
        DataFormat startFormat, DataFormat interFormat, DataFormat endFormat,
        string password,
        int saltLength, int keyIterations, int keySize,
        int messageLength
        )
    {
        if ((interType == DataType.Console && interFormat == DataFormat.Raw) || (endType == DataType.Console && endFormat == DataFormat.Raw))
        {
            return(false);
        }

        string startInputArg;
        string startOutputArg = string.Empty;

        byte[] originalClearMessage;

        if (startType == DataType.Console)
        {
            do
            {
                originalClearMessage = GenerateRandom(messageLength, true);

                if (startFormat == DataFormat.Base64)
                {
                    startInputArg = Convert.ToBase64String(originalClearMessage);
                }
                else if (startFormat == DataFormat.Hexa)
                {
                    startInputArg = ToHexString(originalClearMessage);
                }
                else
                {
                    startInputArg = Encoding.ASCII.GetString(originalClearMessage);
                }
            } while (startInputArg.StartsWith("-"));
        }
        else
        {
            originalClearMessage = GenerateRandom(messageLength, false);
            string startFilename = Utils.EnsureFilename("tests/clear.bin");
#if IN_MEMORY
            if (InMemoryFile.Exists(startFilename))
            {
                InMemoryFile.Delete(startFilename);
            }

            if (startFormat == DataFormat.Base64)
            {
                InMemoryFile.WriteAllText(startFilename, Convert.ToBase64String(originalClearMessage));
            }
            else if (startFormat == DataFormat.Hexa)
            {
                InMemoryFile.WriteAllText(startFilename, ToHexString(originalClearMessage));
            }
            else
            {
                InMemoryFile.WriteAllBytes(startFilename, originalClearMessage);
            }
#else
            if (File.Exists(startFilename))
            {
                File.Delete(startFilename);
            }
            if (startFormat == DataFormat.Base64)
            {
                File.WriteAllText(startFilename, Convert.ToBase64String(originalClearMessage));
            }
            else if (startFormat == DataFormat.Hexa)
            {
                File.WriteAllText(startFilename, ToHexString(originalClearMessage));
            }
            else
            {
                File.WriteAllBytes(startFilename, originalClearMessage);
            }
#endif
            startInputArg = startFilename;
        }

        StringBuilder interStringBuilder = null;

        if (interType == DataType.Console)
        {
            interStringBuilder = new StringBuilder();
            Console.SetOut(new StringWriter(interStringBuilder));
        }
        else
        {
            string interFilename = Utils.EnsureFilename("tests/encrypted.aes");
#if IN_MEMORY
            if (InMemoryFile.Exists(interFilename))
            {
                InMemoryFile.Delete(interFilename);
            }
#else
            if (File.Exists(interFilename))
            {
                File.Delete(interFilename);
            }
#endif
            startOutputArg = interFilename;
        }

        var startArgs = new string[]
        {
            "-e",
            "--input-type", startType.ToString().ToLowerInvariant(),
            "--input-format", startFormat.ToString().ToUpperInvariant(),
            "--output-type", interType.ToString().ToLowerInvariant(),
            "--output-format", interFormat.ToString().ToLowerInvariant(),
            "--password", password,
            "--key-salt-length", saltLength.ToString(),
            "--key-iterations", keyIterations.ToString(),
            "--key-size", keySize.ToString(),
            "--skip-bytes", "0",
            startInputArg,
            startOutputArg
        };

        new Aes.Program().Run(startArgs);

        // ==================================================

        string endInputArg;
        string endOutputArg = string.Empty;

        if (interType == DataType.Console)
        {
            endInputArg = ConsoleOutStream.TrimConsoleDataMarkers(interStringBuilder.ToString());
        }
        else
        {
            endInputArg = Utils.EnsureFilename("tests/encrypted.aes");
        }

        StringBuilder endStringBuilder = null;

        if (endType == DataType.Console)
        {
            endStringBuilder = new StringBuilder();
            Console.SetOut(new StringWriter(endStringBuilder));
        }
        else
        {
            string endFilename = Utils.EnsureFilename("tests/decrypted.bin");
#if IN_MEMORY
            if (InMemoryFile.Exists(endFilename))
            {
                InMemoryFile.Delete(endFilename);
            }
#else
            if (File.Exists(endFilename))
            {
                File.Delete(endFilename);
            }
#endif
            endOutputArg = endFilename;
        }

        var endArgs = new string[]
        {
            "-d",
            "--input-type", interType.ToString().ToLowerInvariant(),
            "--input-format", interFormat.ToString().ToUpperInvariant(),
            "--output-type", endType.ToString().ToLowerInvariant(),
            "--output-format", endFormat.ToString().ToLowerInvariant(),
            "--password", password,
            "--key-salt-length", saltLength.ToString(),
            "--key-iterations", keyIterations.ToString(),
            "--key-size", keySize.ToString(),
            "--skip-bytes", "0",
            endInputArg,
            endOutputArg
        };

        new Aes.Program().Run(endArgs);

        byte[] resultMessage = null;

        if (endType == DataType.Console)
        {
            resultMessage = Encoding.ASCII.GetBytes(ConsoleOutStream.TrimConsoleDataMarkers(endStringBuilder.ToString()));
        }
        else
        {
#if IN_MEMORY
            resultMessage = InMemoryFile.ReadAllBytes(Utils.EnsureFilename("tests/decrypted.bin"));
#else
            resultMessage = File.ReadAllBytes(Utils.EnsureFilename("tests/decrypted.bin"));
#endif
        }

        if (endFormat == DataFormat.Base64)
        {
            resultMessage = Convert.FromBase64String(Encoding.ASCII.GetString(resultMessage));
        }
        else if (endFormat == DataFormat.Hexa)
        {
            resultMessage = FromHexStringAsBytes(resultMessage);
        }

        string info = $"{startType} {interType} {endType}, {startFormat} {interFormat} {endFormat}, {password}, {saltLength}, {keyIterations}, {keySize}, {messageLength}";

        if (originalClearMessage.Length != resultMessage.Length)
        {
            throw new Exception($"Length mismatch. [{info}]");
        }

        for (int i = 0; i < originalClearMessage.Length; i++)
        {
            if (originalClearMessage[i] != resultMessage[i])
            {
                throw new Exception($"Data mismatch at position '{i}'. [{info}]");
            }
        }

        return(true);
    }
Exemplo n.º 44
0
        /// <summary>
        /// Converts the specified DigitalRune <see cref="DataFormat"/> to the XNA
        /// <see cref="SurfaceFormat"/>.
        /// </summary>
        /// <param name="format">The <see cref="DataFormat"/>.</param>
        /// <returns>The <see cref="SurfaceFormat"/>.</returns>
        /// <exception cref="NotSupportedException">
        /// The format is not supported in XNA or MonoGame.
        /// </exception>
        public static SurfaceFormat ToSurfaceFormat(this DataFormat format)
        {
            // Use same order as in MonoGame/SurfaceFormat.cs and keep in sync.
            // sRGB formats are treaded as non-sRGB formats.
            switch (format)
            {
            case DataFormat.R8G8B8A8_UNORM:
            case DataFormat.R8G8B8A8_UNORM_SRGB:
                return(SurfaceFormat.Color);

            case DataFormat.B5G6R5_UNORM:
                return(SurfaceFormat.Bgr565);

            case DataFormat.B5G5R5A1_UNORM:
                return(SurfaceFormat.Bgra5551);

            case DataFormat.B4G4R4A4_UNORM:
                return(SurfaceFormat.Bgra4444);

            case DataFormat.BC1_UNORM:
            case DataFormat.BC1_UNORM_SRGB:
                return(SurfaceFormat.Dxt1);

            case DataFormat.BC2_UNORM:
            case DataFormat.BC2_UNORM_SRGB:
                return(SurfaceFormat.Dxt3);

            case DataFormat.BC3_UNORM:
            case DataFormat.BC3_UNORM_SRGB:
                return(SurfaceFormat.Dxt5);

            case DataFormat.R8G8_SNORM:
                return(SurfaceFormat.NormalizedByte2);

            case DataFormat.R8G8B8A8_SNORM:
                return(SurfaceFormat.NormalizedByte4);

            case DataFormat.R10G10B10A2_UNORM:
                return(SurfaceFormat.Rgba1010102);

            case DataFormat.R16G16_UNORM:
                return(SurfaceFormat.Rg32);

            case DataFormat.R16G16B16A16_UNORM:
                return(SurfaceFormat.Rgba64);

            case DataFormat.A8_UNORM:
            case DataFormat.R8_UNORM:
                return(SurfaceFormat.Alpha8);

            case DataFormat.R32_FLOAT:
                return(SurfaceFormat.Single);

            case DataFormat.R32G32_FLOAT:
                return(SurfaceFormat.Vector2);

            case DataFormat.R32G32B32A32_FLOAT:
                return(SurfaceFormat.Vector4);

            case DataFormat.R16_FLOAT:
                return(SurfaceFormat.HalfSingle);

            case DataFormat.R16G16_FLOAT:
                return(SurfaceFormat.HalfVector2);

            case DataFormat.R16G16B16A16_FLOAT:
                return(SurfaceFormat.HalfVector4);

            //return SurfaceFormat.HdrBlendable;  // Only needed as render target format.


            case DataFormat.B8G8R8X8_UNORM:
                return(SurfaceFormat.Bgr32);

            case DataFormat.B8G8R8A8_UNORM:
                return(SurfaceFormat.Bgra32);

            case DataFormat.PVRTCI_2bpp_RGB:
                return(SurfaceFormat.RgbPvrtc2Bpp);

            case DataFormat.PVRTCI_4bpp_RGB:
                return(SurfaceFormat.RgbPvrtc4Bpp);

            case DataFormat.PVRTCI_2bpp_RGBA:
                return(SurfaceFormat.RgbaPvrtc2Bpp);

            case DataFormat.PVRTCI_4bpp_RGBA:
                return(SurfaceFormat.RgbaPvrtc4Bpp);

            case DataFormat.ETC1:
                return(SurfaceFormat.RgbEtc1);

            //case DataFormat.ATC_RGB: Not supported in MonoGame.
            case DataFormat.ATC_RGBA_EXPLICIT_ALPHA:
                return(SurfaceFormat.RgbaAtcExplicitAlpha);

            case DataFormat.ATC_RGBA_INTERPOLATED_ALPHA:
                return(SurfaceFormat.RgbaAtcInterpolatedAlpha);


            default:
                string message = string.Format(CultureInfo.InvariantCulture, "The texture format {0} is not supported in MonoGame.", format);
                throw new NotSupportedException(message);

                // Not supported:
                //  SurfaceFormat.Dxt1a = 70
            }
        }
Exemplo n.º 45
0
        /// <summary>
        /// Creates a new ValueMember instance
        /// </summary>
        public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue)
            : this(model, fieldNumber, memberType, itemType, defaultType, dataFormat)
        {
            if (parentType == null)
            {
                throw new ArgumentNullException(nameof(parentType));
            }
            if (fieldNumber < 1 && !parentType.IsEnum)
            {
                throw new ArgumentOutOfRangeException(nameof(fieldNumber));
            }

            Member     = member ?? throw new ArgumentNullException(nameof(member));
            ParentType = parentType;
            if (fieldNumber < 1 && !parentType.IsEnum)
            {
                throw new ArgumentOutOfRangeException(nameof(fieldNumber));
            }

            if (defaultValue != null && (defaultValue.GetType() != memberType))
            {
                defaultValue = ParseDefaultValue(memberType, defaultValue);
            }
            _defaultValue = defaultValue;

            MetaType type = model.FindWithoutAdd(memberType);

#if FEAT_DYNAMIC_REF
            if (type != null)
            {
                AsReference = type.AsReferenceDefault;
            }
            else
            { // we need to scan the hard way; can't risk recursion by fully walking it
                AsReference = MetaType.GetAsReferenceDefault(memberType);
            }
#endif
        }
Exemplo n.º 46
0
        /// <summary>
        /// Creates a new ValueMember instance
        /// </summary>
        internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type overrideType, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat)
        {
            if (memberType == null)
            {
                throw new ArgumentNullException("memberType");
            }
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            this.fieldNumber  = fieldNumber;
            this.overrideType = overrideType;
            this.memberType   = memberType;
            this.itemType     = itemType;
            this.defaultType  = defaultType;

            this.model      = model;
            this.dataFormat = dataFormat;
        }
Exemplo n.º 47
0
        private static async Task <CityData> FormatResult(CityData _CityData, DataFormat _DataFormat)
        {
            var loader      = new ResourceLoader();
            var dateTime    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var _Visibility = Convert.ToDouble(_CityData.Current.visibility) / 1000;

            _CityData.Current.Date = dateTime.AddSeconds(_CityData.Current.dt).ToLocalTime().ToString("ddd, dd MMM");

            if (_DataFormat.TimeFormat == "24h")
            {
                _CityData.Current.SunriseSunset = dateTime.AddSeconds(_CityData.Current.sys.sunrise).ToLocalTime().ToString("H:mm") + "/" + dateTime.AddSeconds(_CityData.Current.sys.sunset).ToLocalTime().ToString("H:mm");
            }
            else
            {
                _CityData.Current.SunriseSunset = dateTime.AddSeconds(_CityData.Current.sys.sunrise).ToLocalTime().ToString("h:mmtt") + "/" + dateTime.AddSeconds(_CityData.Current.sys.sunset).ToLocalTime().ToString("h:mmtt");
            }

            if (_DataFormat.UnitsFormat == "metric")
            {
                _CityData.Current.wind.speed = _CityData.Current.wind.speed + loader.GetString("MeterSec");
                _CityData.Current.visibility = _Visibility + loader.GetString("Kilometer");
            }
            else
            {
                _CityData.Current.wind.speed = _CityData.Current.wind.speed + loader.GetString("MileHour");
                _CityData.Current.visibility = Math.Round(_Visibility * 0.62, 0) + loader.GetString("Mile");
            }

            StorageFolder _assets = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");

            StorageFolder _icons = await _assets.GetFolderAsync("Icons");

            _CityData.Current.main.temp              = Math.Round(_CityData.Current.main.temp, 0);
            _CityData.Current.main.pressure          = _CityData.Current.main.pressure + loader.GetString("PressureUnit");
            _CityData.Current.weather[0].description = char.ToUpper(_CityData.Current.weather[0].description[0]) + _CityData.Current.weather[0].description.Substring(1);
            if (await _icons.TryGetItemAsync(_CityData.Current.weather[0].icon + ".png") != null)
            {
                _CityData.Current.Image = "ms-appx:///Assets/Icons/" + _CityData.Current.weather[0].icon + ".png";
            }
            else
            {
                _CityData.Current.Image = "ms-appx:///Assets/Icons/02n.png";
            }

            foreach (var item in _CityData.Hourly.list)
            {
                item.Date = dateTime.AddSeconds(item.dt).ToLocalTime().ToString("ddd, H:mm");
                if (await _icons.TryGetItemAsync(item.weather[0].icon + ".png") != null)
                {
                    item.Image = "ms-appx:///Assets/Icons/" + item.weather[0].icon + ".png";
                }
                else
                {
                    item.Image = "ms-appx:///Assets/Icons/02n.png";
                }

                item.main.temp = Math.Round(item.main.temp, 1);
                item.weather[0].description = char.ToUpper(item.weather[0].description[0]) + item.weather[0].description.Substring(1);
            }

            foreach (var item in _CityData.DailyForecast.list)
            {
                item.temp.min = Math.Round(item.temp.min, 0);
                item.temp.max = Math.Round(item.temp.max, 0);
                item.Day      = dateTime.AddSeconds(item.dt).ToLocalTime().ToString("ddd");
                if (await _icons.TryGetItemAsync(item.weather[0].icon + ".png") != null)
                {
                    item.Image = "ms-appx:///Assets/Icons/" + item.weather[0].icon + ".png";
                }
                else
                {
                    item.Image = "ms-appx:///Assets/Icons/02n.png";
                }

                item.weather[0].description = char.ToUpper(item.weather[0].description[0]) + item.weather[0].description.Substring(1);
            }

            return(_CityData);
        }
Exemplo n.º 48
0
        /// <summary>
        /// Imports timecard data from the given string; raises ProgressUpdated event as timecards are imported
        /// </summary>
        /// <param name="content">The data to be imported, in given format</param>
        /// <param name="format">Enum value corresponding to CSV, TSV, JSON, or XML format</param>
        /// <returns>String containing error message (if any) encountered during import</returns>
        public string Import(string content, DataFormat format)
        {
            string[] lines;
            Dictionary <string, int> columnMap;

            var allowedColumnNames = new List <string> {
                "date", "code", "description", "time", "isaftermidnight"
            };
            var report = new StringBuilder();
            var repo   = _factory.Resolve <IRepository>();

            switch (format)
            {
            case DataFormat.CSV:
            case DataFormat.TSV:
                var separator = (format == DataFormat.CSV ? ',' : '\t');

                lines = content.Replace("\r", string.Empty).Split('\n');
                if (lines.Length < 1)
                {
                    report.AppendLine("Content contains no lines of text");
                    break;
                }

                columnMap = ParseColumnMap(lines[0], separator, allowedColumnNames);

                var someFieldsAreMissing = false;
                for (var i = 0; i < allowedColumnNames.Count - 1; ++i)
                {
                    if (!columnMap.ContainsKey(allowedColumnNames[i]))
                    {
                        report.AppendLine($"Content missing column name '{allowedColumnNames[i]}' on first line");
                        someFieldsAreMissing = true;
                    }
                }
                if (someFieldsAreMissing)
                {
                    break;
                }

                // parse and store, raising event for progress
                Timecard tc = null;

                var lastDateString = "zzzz";
                for (var i = 1; i < lines.Length; ++i)
                {
                    var eventArgs = new ProgressUpdateEventArgs(i + 1, lines.Length);
                    OnProgressUpdated(eventArgs);
                    if (eventArgs.Cancel)
                    {
                        report.AppendLine("Import was canceled by the user");
                        break;
                    }

                    if (string.IsNullOrWhiteSpace(lines[i]))
                    {
                        continue;
                    }

                    var tokens = Split(lines[i], separator);

                    if (tokens[columnMap["date"]] != lastDateString)
                    {
                        lastDateString = tokens[columnMap["date"]];

                        if (tc != null)
                        {
                            repo.SaveTimecard(tc);
                        }

                        tc = new Timecard();
                        tc.Activities.DataImportMode = true;

                        if (DateTime.TryParse(StripQuotes(lastDateString), out DateTime newDate))
                        {
                            tc.Date = newDate;
                        }
                        else
                        {
                            report.AppendLine($"Could not parse value {lastDateString} as date on line {i + 1}");
                            break;
                        }
                    }

                    var activity = new Activity
                    {
                        Code        = StripQuotes(tokens[columnMap["code"]]),
                        Description = StripQuotes(tokens[columnMap["description"]]),
                        Time        = StripQuotes(tokens[columnMap["time"]])
                    };

                    if (columnMap.ContainsKey("isaftermidnight"))
                    {
                        if (Boolean.TryParse(StripQuotes(tokens[columnMap["isaftermidnight"]]), out bool newIsAfterMidnight))
                        {
                            activity.IsAfterMidnight = newIsAfterMidnight;
                        }
                        else
                        {
                            report.AppendLine(
                                $"Could not parse value {tokens[columnMap["isaftermidnight"]]} as boolean on line {i + 1}");
                            break;
                        }
                    }
                    else
                    {
                        activity.IsAfterMidnight = false;
                    }

                    tc.Activities.Add(activity);
                }

                if (tc != null && tc.IsDirty)
                {
                    repo.SaveTimecard(tc);
                }

                break;

            case DataFormat.JSON:
                List <Timecard> tcList;

                try
                {
                    // all the parsing work is assumed to be done by the JsonConvert class
                    tcList = JsonConvert.DeserializeObject <List <Timecard> >(content);
                }
                catch (Exception ex)
                {
                    report.AppendLine($"Error occurred while parsing JSON data: {ex.Message}");
                    break;
                }

                for (var i = 0; i < tcList.Count; ++i)
                {
                    var eventArgs = new ProgressUpdateEventArgs(i + 1, tcList.Count);
                    OnProgressUpdated(eventArgs);
                    if (eventArgs.Cancel)
                    {
                        report.AppendLine("Import was canceled by the user");
                        break;
                    }

                    repo.SaveTimecard(tcList[i]);
                }
                break;

            case DataFormat.XML:
                var xdoc = new XmlDocument();
                try
                {
                    xdoc.LoadXml(content);
                }
                catch (Exception ex)
                {
                    report.AppendLine($"Error occurred while parsing XML data: {ex.Message}");
                    break;
                }

                var root = xdoc.SelectSingleNode("/Timecards");
                if (root?.Name != "Timecards")
                {
                    report.AppendLine("Root node in XML data not named \"Timecards\"");
                    break;
                }

                if (root.HasChildNodes)
                {
                    for (var i = 0; i < root.ChildNodes.Count; i++)
                    {
                        var eventArgs = new ProgressUpdateEventArgs(i + 1, root.ChildNodes.Count);
                        OnProgressUpdated(eventArgs);
                        if (eventArgs.Cancel)
                        {
                            report.AppendLine("Import was canceled by the user");
                            break;
                        }

                        var tcNode = root.ChildNodes[i];
                        if (tcNode.Name != "Timecard")
                        {
                            report.AppendLine("Expected parent node in XML data not named \"Timecard\"");
                            break;
                        }

                        var tcAttributes = tcNode.Attributes;

                        var tcAttrDate = tcAttributes["Date"];
                        if (tcAttrDate == null)
                        {
                            report.AppendLine($"Timecard node {i} missing Date attribute");
                            break;
                        }

                        tc = new Timecard();
                        tc.Activities.DataImportMode = true;

                        if (DateTime.TryParse(tcAttributes["Date"].Value, out DateTime newDate))
                        {
                            tc.Date = newDate;
                        }
                        else
                        {
                            report.AppendLine(
                                $"Timecard node {i} Date attribute value \"{tcAttributes["Date"].Value}\" could not be parsed");
                            break;
                        }

                        if (tcNode.HasChildNodes)
                        {
                            var acCollNode = tcNode.ChildNodes[0];
                            if (acCollNode.HasChildNodes)
                            {
                                for (var j = 0; j < acCollNode.ChildNodes.Count; ++j)
                                {
                                    var acNode = acCollNode.ChildNodes[j];

                                    var activity = new Activity
                                    {
                                        Code        = $"{acNode.Attributes["Code"]?.Value}",
                                        Description = $"{acNode.Attributes["Description"]?.Value}",
                                        Time        = $"{acNode.Attributes["Time"]?.Value}"
                                    };

                                    if (Boolean.TryParse($"{ acNode.Attributes["IsAfterMidnight"]?.Value}",
                                                         out bool newIsAfterMidnight))
                                    {
                                        activity.IsAfterMidnight = newIsAfterMidnight;
                                    }

                                    tc.Activities.Add(activity);
                                }
                            }
                        }

                        repo.SaveTimecard(tc);
                    }
                }
                break;

            default:
                throw new Exception("Unhandled data format encountered");
            }

            return(report.ToString());
        }
Exemplo n.º 49
0
 public Deserializer(DataFormat format)
 {
     dataFormat = format;
 }
Exemplo n.º 50
0
        /// <summary>
        /// Creates a new ValueMember instance
        /// </summary>
        public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type overrideType, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue)
            : this(model, fieldNumber, overrideType, memberType, itemType, defaultType, dataFormat)
        {
            if (member == null)
            {
                throw new ArgumentNullException("member");
            }
            if (parentType == null)
            {
                throw new ArgumentNullException("parentType");
            }
            if (fieldNumber < 1 && !Helpers.IsEnum(parentType))
            {
                throw new ArgumentOutOfRangeException("fieldNumber");
            }

            this.member     = member;
            this.parentType = parentType;
            if (fieldNumber < 1 && !Helpers.IsEnum(parentType))
            {
                throw new ArgumentOutOfRangeException("fieldNumber");
            }
//#if WINRT
            if (defaultValue != null && model.MapType(defaultValue.GetType()) != memberType)
//#else
//            if (defaultValue != null && !memberType.IsInstanceOfType(defaultValue))
//#endif
            {
                defaultValue = ParseDefaultValue(memberType, defaultValue);
            }
            this.defaultValue = defaultValue;

            MetaType type = model.FindWithoutAdd(memberType);

            if (type != null)
            {
                this.asReference = type.AsReferenceDefault;
            }
            else
            { // we need to scan the hard way; can't risk recursion by fully walking it
                this.asReference = MetaType.GetAsReferenceDefault(model, memberType);
            }
        }
Exemplo n.º 51
0
 private ContentType(string name, DataFormat format)
 {
     Name   = name;
     Format = format;
 }
        private static void CreateHttpContentTestInput(DataFormat inputFormat, DataFormat outputFormat, Random rndGen, out HttpMethod method, out HttpContent content, out JObject expectedResult, out Dictionary <string, string> headers, out Dictionary <string, string> query, out HttpStatusCode expectedStatus)
        {
            method         = CreateHttpMethod(rndGen);
            content        = null;
            expectedResult = new JObject();
            expectedResult.Add("method", method.Method);
            expectedResult.Add("user", new JObject(new JProperty("level", "anonymous")));
            JToken body     = null;
            string textBody = null;

            if (method.Method != "GET" && method.Method != "DELETE")
            {
                body = CreateJson(rndGen);
                if (outputFormat == DataFormat.Xml || inputFormat == DataFormat.Xml)
                {
                    // to prevent non-XML names from interfering with checks
                    body = SanitizeJsonXml(body);
                }

                switch (inputFormat)
                {
                case DataFormat.Json:
                    // JSON
                    content = new StringContent(body.ToString(), Encoding.UTF8, "application/json");
                    break;

                case DataFormat.Xml:
                    textBody = JsonToXml(body);
                    content  = new StringContent(textBody, Encoding.UTF8, "text/xml");
                    break;

                default:
                    textBody = body.ToString().Replace("{", "<").Replace("}", ">").Replace("[", "__[__").Replace("]", "__]__");
                    content  = new StringContent(textBody, Encoding.UTF8, "text/plain");
                    break;
                }
            }

            if (body != null)
            {
                if (inputFormat == DataFormat.Json)
                {
                    expectedResult.Add("body", body);
                }
                else
                {
                    expectedResult.Add("body", textBody);
                }
            }

            headers = new Dictionary <string, string>();
            var choice = rndGen.Next(5);

            for (int j = 0; j < choice; j++)
            {
                string name  = "x-test-zumo-" + j;
                string value = CreateString(rndGen, 1, 10, Letters);
                headers.Add(name, value);
            }

            query = CreateQueryParams(rndGen) ?? new Dictionary <string, string>();
            if (query.Count > 0)
            {
                JObject outputQuery = new JObject();
                expectedResult.Add("query", outputQuery);
                foreach (var kvp in query)
                {
                    outputQuery.Add(kvp.Key, kvp.Value);
                }
            }

            query.Add("format", outputFormat.ToString().ToLowerInvariant());
            expectedStatus = HttpStatusCode.OK;
            if (rndGen.Next(4) == 0)
            {
                // non-200 responses
                int[] options = new[] { 400, 404, 500, 201 };
                int   status  = options[rndGen.Next(options.Length)];
                expectedStatus = (HttpStatusCode)status;
                query.Add("status", status.ToString(CultureInfo.InvariantCulture));
            }
        }
Exemplo n.º 53
0
        /// <summary>
        /// Exports timecard data in given date range to a string in the given format
        /// </summary>
        /// <param name="startDate">Low end of date range</param>
        /// <param name="endDate">High end of date range</param>
        /// <param name="format">Enum value corresponding to CSV, TSV, JSON, or XML format</param>
        /// <returns>String of data encoded in given format</returns>
        public string Export(DateTime?startDate, DateTime?endDate, DataFormat format)
        {
            var repo = _factory.Resolve <IRepository>();

            // retrieve the timecards to be exported
            var tcList = repo.GetTimecards(startDate, endDate);

            using (var sw = new StringWriter())
            {
                // transform the data
                switch (format)
                {
                case DataFormat.CSV:
                    sw.WriteLine("Date,Code,Description,Time,IsAfterMidnight");
                    foreach (var tc in tcList)
                    {
                        foreach (var ac in tc.Activities)
                        {
                            sw.WriteLine($"\"{tc.Date:yyyy-MM-dd}\",\"{ac.Code}\",\"{ac.Description}\",\"{ac.Time}\",{ac.IsAfterMidnight}");
                        }
                    }
                    break;

                case DataFormat.TSV:
                    sw.WriteLine("Date\tCode\tDescription\tTime\tIsAfterMidnight");
                    foreach (var tc in tcList)
                    {
                        foreach (var ac in tc.Activities)
                        {
                            sw.WriteLine($"{tc.Date:yyyy-MM-dd}\t{ac.Code}\t{ac.Description}\t{ac.Time}\t{ac.IsAfterMidnight}");
                        }
                    }
                    break;

                case DataFormat.JSON:
                    var jsonSettings = new JsonSerializerSettings
                    {
                        DateFormatString = "yyyy-MM-dd",
                        Formatting       = Newtonsoft.Json.Formatting.Indented,
                    };
                    sw.WriteLine(JsonConvert.SerializeObject(tcList, jsonSettings));
                    break;

                case DataFormat.XML:
                    XmlAttribute attr;

                    var xdoc = new XmlDocument();

                    var rootNode = xdoc.CreateElement("Timecards");
                    xdoc.AppendChild(rootNode);

                    foreach (var tc in tcList)
                    {
                        var tcNode = xdoc.CreateElement("Timecard");
                        attr       = xdoc.CreateAttribute("Date");
                        attr.Value = tc.Date.ToString("yyyy-MM-dd");
                        tcNode.Attributes.Append(attr);

                        var acsNode = xdoc.CreateElement("Activities");
                        foreach (var ac in tc.Activities)
                        {
                            var acNode = xdoc.CreateElement("Activity");
                            acNode
                            .AddAttribute("Code", ac.Code)
                            .AddAttribute("Description", ac.Description)
                            .AddAttribute("Time", ac.Time)
                            .AddAttribute("IsAfterMidnight", ac.IsAfterMidnight.ToString());
                            acsNode.AppendChild(acNode);
                        }
                        tcNode.AppendChild(acsNode);

                        rootNode.AppendChild(tcNode);
                    }

                    xdoc.Save(sw);
                    break;

                default:
                    throw new Exception("Unhandled data format encountered");
                }

                return(sw.ToString());
            }
        }
Exemplo n.º 54
0
 protected override void OnBeforeInit(int tag, ref DataFormat format)
 {
     innerProperty = PropertyFactory.CreatePassThru <TValue>(tag, ref format);
     base.OnBeforeInit(tag, ref format);
 }
Exemplo n.º 55
0
        /// <summary>
        /// Creates a new ValueMember instance
        /// </summary>
        internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat)
        {
            FieldNumber = fieldNumber;
            MemberType  = memberType ?? throw new ArgumentNullException(nameof(memberType));
            ItemType    = itemType;
            if (defaultType == null && itemType != null)
            {   // reasonable default
                defaultType = memberType;
            }
            DefaultType = defaultType;

            this.model      = model ?? throw new ArgumentNullException(nameof(model));
            this.dataFormat = dataFormat;
        }
Exemplo n.º 56
0
        public List <SalesReturnVoucherModel> GetAllSalesReturn()
        {
            List <SalesReturnVoucherModel> lstSR = new List <SalesReturnVoucherModel>();
            SalesReturnVoucherModel        objsales;

            string Query = "SELECT * FROM Trans_SalesReturn";

            System.Data.IDataReader dr = _dbHelper.ExecuteDataReader(Query, _dbHelper.GetConnObject());

            while (dr.Read())
            {
                objsales = new SalesReturnVoucherModel();

                objsales.SR_Id          = DataFormat.GetInteger(dr["SR_Id"]);
                objsales.Series         = dr["Series"].ToString();
                objsales.SR_Date        = DataFormat.GetDateTime(dr["SR_Date"]);
                objsales.Voucher_Number = DataFormat.GetInteger(dr["VoucherNo"]);
                objsales.SalesType      = dr["SalesType"].ToString();
                objsales.Party          = dr["Party"].ToString();
                objsales.MatCenter      = dr["MatCentre"].ToString();
                objsales.Narration      = dr["Narration"].ToString();
                //objsales. = Convert.ToDecimal(dr["TotalQty"]);
                //objsales.TotalAmount = Convert.ToDecimal(dr["TotalAmount"]);
                //objsales.BSTotalAmount = Convert.ToDecimal(dr["BSTotalAmount"]);


                //SELECT Sales Items
                string itemQuery = "SELECT * FROM Trans_SalesReturn_Item WHERE SR_Id=" + objsales.SR_Id;
                System.Data.IDataReader drItem = _dbHelper.ExecuteDataReader(itemQuery, _dbHelper.GetConnObject());

                objsales.Item_Voucher = new List <Item_VoucherModel>();
                Item_VoucherModel objItemModel;

                while (drItem.Read())
                {
                    objItemModel = new Item_VoucherModel();

                    objItemModel.ParentId = DataFormat.GetInteger(drItem["TransSRId"]);
                    objItemModel.Item_ID  = DataFormat.GetInteger(drItem["ItemId"]);
                    objItemModel.Item     = drItem["Item"].ToString();
                    objItemModel.Price    = Convert.ToDecimal(drItem["Price"]);
                    objItemModel.Qty      = Convert.ToDecimal(drItem["Qty"]);
                    objItemModel.Unit     = drItem["Unit"].ToString();

                    objItemModel.Amount      = Convert.ToDecimal(drItem["Amount"]);
                    objItemModel.TotalQty    = Convert.ToDecimal(drItem["TotalQty"]);
                    objItemModel.TotalAmount = Convert.ToDecimal(drItem["TotalAmount"]);

                    objsales.Item_Voucher.Add(objItemModel);
                }

                //SELECT Bill Sundry Voucher items
                string bsQuery = "SELECT * FROM Trans_SalesReturn_BS WHERE TransSRId=" + objsales.SR_Id;
                System.Data.IDataReader drBS = _dbHelper.ExecuteDataReader(bsQuery, _dbHelper.GetConnObject());

                objsales.BillSundry_Voucher = new List <BillSundry_VoucherModel>();
                BillSundry_VoucherModel objBSModel;

                while (drBS.Read())
                {
                    objBSModel = new BillSundry_VoucherModel();

                    objBSModel.ParentId    = DataFormat.GetInteger(drBS["TransSRId"]);
                    objBSModel.BSId        = DataFormat.GetInteger(drBS["BSId"]);
                    objBSModel.BillSundry  = drBS["BillSundry"].ToString();
                    objBSModel.Percentage  = Convert.ToDecimal(drBS["Percentage"]);
                    objBSModel.Amount      = Convert.ToDecimal(drBS["Amount"]);
                    objBSModel.TotalAmount = Convert.ToDecimal(drBS["TotalAmount"]);

                    objsales.BillSundry_Voucher.Add(objBSModel);
                }

                lstSR.Add(objsales);
            }
            return(lstSR);
        }
        private async Task customApiDataTest(DataFormat inputFormat, DataFormat outputFormat, Random seedGenerator)
        {
            for (int i = 0; i < 10; i++)
            {
                int    seed   = seedGenerator.Next();
                Random rndGen = new Random(seed);

                JToken body = CreateJson(rndGen);

                Dictionary <string, string> headers = new Dictionary <string, string>()
                {
                    { "aa", "" }
                };
                CreateHttpContentTestInput(inputFormat, outputFormat, rndGen, out HttpMethod method, out HttpContent content,
                                           out JObject expectedResult, out headers, out Dictionary <string, string> query, out HttpStatusCode expectedStatus);

                using (HttpResponseMessage response = await InvokeApiAsync(AppApiName, content, method, headers, query))
                {
                    ValidateResponseHeader(expectedStatus, headers, response);
                    string responseContent = null;
                    if (response.Content != null)
                    {
                        responseContent = await response.Content.ReadAsStringAsync();
                    }

                    JToken jsonResponse = null;
                    if (outputFormat == DataFormat.Json)
                    {
                        jsonResponse = JToken.Parse(responseContent);
                    }
                    else if (outputFormat == DataFormat.Other)
                    {
                        string decodedContent = responseContent
                                                .Replace("__{__", "{")
                                                .Replace("__}__", "}")
                                                .Replace("__[__", "[")
                                                .Replace("__]__", "]");
                        jsonResponse = JToken.Parse(decodedContent);
                    }

                    bool          contentIsExpected = false;
                    List <string> errors            = new List <string>();
                    switch (outputFormat)
                    {
                    case DataFormat.Json:
                    case DataFormat.Other:
                        contentIsExpected = CompareJson(expectedResult, jsonResponse, errors);
                        break;

                    case DataFormat.Xml:
                        string expectedResultContent = JsonToXml(expectedResult);

                        // Normalize CRLF
                        expectedResultContent = expectedResultContent.Replace("\r\n", "\n");
                        responseContent       = responseContent.Replace("\r\n", "\n");

                        Assert.Equal(expectedResultContent, responseContent);
                        break;
                    }
                }
            }
        }
Exemplo n.º 58
0
        public ActionResult OEmbed(string url, int maxwidth = 570, int maxheight = 400, DataFormat format = DataFormat.Json, bool responsiveWrapper = false)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(HttpStatusCodeResult(HttpStatusCode.BadRequest, "URL must be specified"));
            }

            var entryId = entryUrlParser.Parse(url);

            if (entryId.IsEmpty)
            {
                return(HttpStatusCodeResult(HttpStatusCode.BadRequest, "Invalid URL"));
            }

            if (entryId.EntryType != EntryType.Song)
            {
                return(HttpStatusCodeResult(HttpStatusCode.BadRequest, "Only song embeds are supported"));
            }

            var id = entryId.Id;

            var    song = songService.GetSongForApi(entryId.Id, SongOptionalFields.ThumbUrl);
            var    src  = VocaUriBuilder.CreateAbsolute(Url.Action("EmbedSong", new { songId = id })).ToString();
            string html;

            if (responsiveWrapper)
            {
                html = RenderPartialViewToString("OEmbedResponsive", new OEmbedParams {
                    Width = maxwidth, Height = maxheight, Src = src
                });
            }
            else
            {
                html = string.Format("<iframe src=\"{0}\" width=\"{1}\" height=\"{2}\"></iframe>", src, maxwidth, maxheight);
            }

            return(Object(new SongOEmbedResponse(song, maxwidth, maxheight, html), format));
        }
Exemplo n.º 59
0
        public virtual string DataPath(DataFormat dataFormat)
        {
            var extension = dataFormat.ToString().ToLower();

            return(ex.GetDataPath(ext: extension, searchext: extension));
        }
Exemplo n.º 60
0
        /// <summary>
        /// Responsible for deciding how to encode/decode a given data-type; maybe
        /// not the most elegant solution, but it is simple and quick.
        /// </summary>
        private static Property <T> CreateProperty <T>(Type type, ref DataFormat format, MemberSerializationOptions options)
        {
            if (type.IsEnum)
            {
                if (format != DataFormat.Default && Attribute.IsDefined(type, typeof(FlagsAttribute)))
                {
                    type = Enum.GetUnderlyingType(type);
                }
                else
                {
                    format = DataFormat.TwosComplement;
                    return(PropertyUtil <T> .CreateTypedProperty("CreatePropertyEnum", type));
                }
            }

            if (type == typeof(int))
            {
                switch (format)
                {
                case DataFormat.Default:
                case DataFormat.TwosComplement:
                    format = DataFormat.TwosComplement;
                    return(new PropertyInt32Variant <T>());

                case DataFormat.ZigZag:
                    return(new PropertyInt32ZigZag <T>());

                case DataFormat.FixedSize:
                    return(new PropertyInt32Fixed <T>());
                }
            }
            if (type == typeof(short))
            {
                switch (format)
                {
                case DataFormat.Default:
                case DataFormat.TwosComplement:
                    format = DataFormat.TwosComplement;
                    return(new PropertyInt16Variant <T>());

                case DataFormat.ZigZag:
                    return(new PropertyInt16ZigZag <T>());
                }
            }
            if (type == typeof(long))
            {
                switch (format)
                {
                case DataFormat.Default:
                case DataFormat.TwosComplement:
                    format = DataFormat.TwosComplement;
                    return(new PropertyInt64Variant <T>());

                case DataFormat.ZigZag:
                    return(new PropertyInt64ZigZag <T>());

                case DataFormat.FixedSize:
                    return(new PropertyInt64Fixed <T>());
                }
            }
            if (type == typeof(uint))
            {
                switch (format)
                {
                case DataFormat.Default:
                case DataFormat.TwosComplement:
                    format = DataFormat.TwosComplement;
                    return(new PropertyUInt32Variant <T>());

                case DataFormat.FixedSize:
                    return(new PropertyUInt32Fixed <T>());
                }
            }
            if (type == typeof(ulong))
            {
                switch (format)
                {
                case DataFormat.Default:
                case DataFormat.TwosComplement:
                    format = DataFormat.TwosComplement;
                    return(new PropertyUInt64Variant <T>());

                case DataFormat.FixedSize:
                    return(new PropertyUInt64Fixed <T>());
                }
            }

            if (type == typeof(ushort))
            {
                switch (format)
                {
                case DataFormat.Default:
                case DataFormat.TwosComplement:
                    format = DataFormat.TwosComplement;
                    return(new PropertyUInt16Variant <T>());
                }
            }

            if (type == typeof(byte[]))
            {
                format = DataFormat.Default; return(new PropertyBlob <T>());
            }
            if (type == typeof(byte))
            {
                format = DataFormat.TwosComplement; return(new PropertyByte <T>());
            }
            if (type == typeof(sbyte))
            {
                format = DataFormat.ZigZag; return(new PropertySByte <T>());
            }
            if (type == typeof(char))
            {
                format = DataFormat.TwosComplement; return(new PropertyChar <T>());
            }
            if (type == typeof(bool))
            {
                format = DataFormat.TwosComplement; return(new PropertyBoolean <T>());
            }
            if (type == typeof(string))
            {
                format = DataFormat.Default; return(new PropertyString <T>());
            }
            if (type == typeof(float))
            {
                format = DataFormat.FixedSize; return(new PropertySingle <T>());
            }
            if (type == typeof(double))
            {
                format = DataFormat.FixedSize; return(new PropertyDouble <T>());
            }
            if (type == typeof(Uri))
            {
                format = DataFormat.Default; return(new PropertyUri <T>());
            }

            if (type == typeof(Guid))
            {
                switch (format)
                {
                case DataFormat.Group: return(new PropertyGuidGroup <T>());

                case DataFormat.Default: return(new PropertyGuidString <T>());
                }
            }
            if (type == typeof(TimeSpan))
            {
                switch (format)
                {
                case DataFormat.Group: return(new PropertyTimeSpanGroup <T>());

                case DataFormat.Default: return(new PropertyTimeSpanString <T>());

                case DataFormat.FixedSize: return(new PropertyTimeSpanFixed <T>());
                }
            }
            if (type == typeof(DateTime))
            {
                switch (format)
                {
                case DataFormat.Group: return(new PropertyDateTimeGroup <T>());

                case DataFormat.Default: return(new PropertyDateTimeString <T>());

                case DataFormat.FixedSize: return(new PropertyDateTimeFixed <T>());
                }
            }
            if (type == typeof(decimal))
            {
                switch (format)
                {
                case DataFormat.Group: return(new PropertyDecimalGroup <T>());

                case DataFormat.Default: return(new PropertyDecimalString <T>());
                }
            }


            if (Serializer.IsEntityType(type))
            {
                Type baseType = type;
                while (Serializer.IsEntityType(baseType.BaseType))
                {
                    baseType = baseType.BaseType;
                }
                switch (format)
                {
                case DataFormat.Default: return(PropertyUtil <T> .CreateTypedProperty("CreatePropertyMessageString", type, baseType, baseType));

                case DataFormat.Group: return(PropertyUtil <T> .CreateTypedProperty("CreatePropertyMessageGroup", type, baseType, baseType));
                }
            }

            if (type.IsValueType && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
            {
                return(PropertyUtil <T> .CreateTypedProperty("CreatePropertyPairString", type.GetGenericArguments()));
            }
            bool isEnumerableOnly;
            Type listItemType = GetListType(type, out isEnumerableOnly);

            if (type.IsArray)
            {
                // verify that we can handle it
                if (type.GetArrayRank() != 1)
                {
                    throw new NotSupportedException("Only 1-dimensional arrays can be used; consider an array/list of a class-type instead");
                }
            }

            if (listItemType != null && listItemType != typeof(byte[]))
            {
                bool dummy;
                if (GetListType(listItemType, out dummy) != null)
                {
                    throw new NotSupportedException("Nested (jagged) arrays/lists are not supported (except for byte[]); consider an array/list of a class-type with an inner array/list instead");
                }
            }


            if (type == typeof(byte[]))
            {   // want to treat byte[] as a special case
                listItemType = null;
            }
            if (type.IsArray && listItemType != null) // second check is for byte[]
            {
                return(PropertyUtil <T> .CreateTypedProperty(
                           (PropertyFactory.HasOption(options, MemberSerializationOptions.Packed)
                        ? "CreatePropertyPackedArray" : "CreatePropertyArray"), listItemType));
            }

            if (listItemType != null)
            {
                if (isEnumerableOnly)
                {
                    if (GetAddMethod(type, listItemType) != null)
                    {
                        return(PropertyUtil <T> .CreateTypedProperty(
                                   (PropertyFactory.HasOption(options, MemberSerializationOptions.Packed)
                            ? "CreatePropertyPackedEnumerable" : "CreatePropertyEnumerable"), type, listItemType));
                    }
                }
                else
                {
                    return(PropertyUtil <T> .CreateTypedProperty(
                               (PropertyFactory.HasOption(options, MemberSerializationOptions.Packed)
                        ? "CreatePropertyPackedList" : "CreatePropertyList"), type, listItemType));
                }
            }

            Type nullType = Nullable.GetUnderlyingType(type);

            if (nullType != null)
            {
                return(PropertyUtil <T> .CreateTypedProperty("CreatePropertyNullable", nullType));
            }

            if (format == DataFormat.Default && GetParseMethod(type) != null)
            {
                return(PropertyUtil <T> .CreateTypedProperty("CreatePropertyParseable", type));
            }

            throw Serializer.ThrowNoEncoder(format, type);
        }