Ejemplo n.º 1
0
 public static ReportResult createReportResult( ContentTypes type)
 {
     ReportResult rr = new ReportResult();
     rr.Meta.ContentType = type;
     switch (type)
     {
         case ContentTypes.TEXT:
             rr.Data = new string[1][];
             rr.Data[0] = new string[1];
             rr.Data[0][0]=string.Empty;
             return rr;
             
         case ContentTypes.IMAGE:
             rr.Data = new string[1][];
             rr.Data[0] = new string[1];
             rr.Data[0][0] = string.Empty;           
             return rr;
             
         case ContentTypes.TABLE:
             rr.Data = new string[1][];
             rr.Data[0] = new string[1];
             rr.Data[0][0] = string.Empty;
             return rr;                    
         default:
             return null;
     }            
 }
Ejemplo n.º 2
0
        public async Task LoadMD5()
        {
            var c = new ContentTypes();
            var root = Environment.CurrentDirectory;
            var path = string.Format("{0}\\{1}.bin", root, Guid.NewGuid());

            var random = new Random();
            var bytes = new byte[64];
            random.NextBytes(bytes);

            string md5;
            using (var createHash = System.Security.Cryptography.MD5.Create())
            {
                var hash = createHash.ComputeHash(bytes);
                md5 = System.Convert.ToBase64String(hash);
            }

            File.WriteAllBytes(path, bytes);

            var item = new FileItem(root, path);
            await item.LoadMD5();

            Assert.AreEqual(bytes, item.Data);
            Assert.AreEqual(c.ContentType(path), item.ContentType);
            Assert.AreEqual(md5, item.MD5);
        }
Ejemplo n.º 3
0
        //
        // GET: /Media/

        public ActionResult Index(ContentTypes? mediaType = null)
        {
            this.SaveReferrer();

            var list = db.Contents
                .Select(m => new ContentWithSize
                { 
                    ContentId = m.ContentId,
                    Name = m.Name,
                    Type = (ContentTypes)m.Type,
                    Size = System.Data.Entity.SqlServer.SqlFunctions.DataLength(m.Data) / 1024
                })
                .OrderBy(m => m.Name)
                .AsQueryable()
                ;

            if (mediaType != null)
            {
                list = list.Where(c => c.Type == mediaType);
            }

            FillMediaTypesSelectList();
            
            return View(list);
        }
Ejemplo n.º 4
0
 public static string GetContentType(ContentTypes contentType)
 {
     string sResult = "";
     switch (contentType)
     {
         case ContentTypes.csv:
             sResult = "text/csv";
             break;
         case ContentTypes.docx:
             sResult = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
             break;
         case ContentTypes.jpg:
             sResult = "image/jpg";
             break;
         case ContentTypes.pdf:
             sResult = "application/pdf";
             break;
         case ContentTypes.text:
             sResult = "text/plain";
             break;
         case ContentTypes.xml:
             sResult = "text/xml";
             break;
         case ContentTypes.zip:
             sResult = "application/zip";
             break;
         default:
             sResult = "application/octet-stream";
             break;
     }
     return sResult;
 }
Ejemplo n.º 5
0
 public static FileStreamResult CreateFileStreamResult(Stream document, string outputName, ContentTypes contentType)
 {
     string sMimeType = GetContentType(contentType);
     FileStreamResult oResult = new FileStreamResult(document, sMimeType);
     oResult.FileDownloadName = outputName;
     return oResult;
 }
Ejemplo n.º 6
0
 public static FileStreamResult CreateFileStreamResult(byte[] documentBytes, string outputName, ContentTypes contentType)
 {
     MemoryStream oStream = new MemoryStream();
     oStream.Write(documentBytes, 0, (int)documentBytes.Length);
     oStream.Position = 0;
     return CreateFileStreamResult(oStream, outputName, contentType);
 }
Ejemplo n.º 7
0
 public MetaData(Roles role, Actions action, ContentTypes contentType, string message)
 {
     this.role = role;
     this.action = action;
     this.contentType = contentType;
     messageSize = encoding.GetByteCount(message);
 }
Ejemplo n.º 8
0
 public void ContentConstructorTest()
 {
     ContentTypes types = new ContentTypes(); // TODO: Initialize to an appropriate value
     string[] commandParams = null; // TODO: Initialize to an appropriate value
     Content target = new Content(types, commandParams);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Initializes a new instance of the DefaultThumbnailViewModel class.
 /// </summary>
 /// <param name="thumbnailID">Thumbnail Guid</param>
 /// <param name="entity">Type of the entity</param>
 /// <param name="altText">Alt text for IMG tag</param>
 /// <param name="contentType">Content Type of the content. In case of community, it will be generic which will not be used.</param>
 public DefaultThumbnailViewModel(Guid? thumbnailID, EntityType entity, string altText, ContentTypes contentType)
 {
     this.ThumbnailID = thumbnailID;
     this.Entity = entity;
     this.AltText = HttpContext.Current.Server.HtmlEncode(altText);
     this.ContentType = contentType;
 }
Ejemplo n.º 10
0
 public CatalogContent(ContentTypes type, string[] commandParams)
 {
     this.Type = type;
     this.Title = commandParams[(int)ItemData.Title];
     this.Author = commandParams[(int)ItemData.Author];
     this.Size = long.Parse(commandParams[(int)ItemData.Size]);
     this.URL = commandParams[(int)ItemData.Url];
 }
Ejemplo n.º 11
0
 public Content(ContentTypes types, string[] commandParams)
 {
     this.Types = types;
     this.Title = commandParams[(int)ContentItemTypes.Title];
     this.Author = commandParams[(int)ContentItemTypes.Author];
     this.Size = Int64.Parse(commandParams[(int)ContentItemTypes.Size]);
     this.Url = commandParams[(int)ContentItemTypes.Url];
 }
Ejemplo n.º 12
0
 public IEnumerable<string> AvailableRoutes(ContentTypes? type)
 {
     EnsureFolder(_baseDir);
     var routes = from d in Directory.EnumerateDirectories(_baseDir, "*", SearchOption.AllDirectories)
                  let route = d.Replace(_baseDir, "").Replace("\\", "/").Substring(1)
                  where Directory.EnumerateFiles(d, "contents.html").Any()
                  let properties = GetProperties(route)
                  where !type.HasValue || (type == ContentTypes.Partial).ToString() == properties["Partial"]
                  select route;
     return routes;
 }
Ejemplo n.º 13
0
 public void AuthorTest()
 {
     ContentTypes types = new ContentTypes(); // TODO: Initialize to an appropriate value
     string[] commandParams = null; // TODO: Initialize to an appropriate value
     Content target = new Content(types, commandParams); // TODO: Initialize to an appropriate value
     string expected = string.Empty; // TODO: Initialize to an appropriate value
     string actual;
     target.Author = expected;
     actual = target.Author;
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Ejemplo n.º 14
0
 public void CompareToTest()
 {
     ContentTypes types = new ContentTypes(); // TODO: Initialize to an appropriate value
     string[] commandParams = null; // TODO: Initialize to an appropriate value
     Content target = new Content(types, commandParams); // TODO: Initialize to an appropriate value
     object obj = null; // TODO: Initialize to an appropriate value
     int expected = 0; // TODO: Initialize to an appropriate value
     int actual;
     actual = target.CompareTo(obj);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;

            response.StatusCode = (int)statusCode;

            //Alternate response type passed in the url by the client
            string alt = context.RouteData.Values["alt"] as string;
            if (!string.IsNullOrEmpty(alt))
            {
                if (alt.ToLower().Contains("xml"))
                {
                    contentType = ContentTypes.Xml;
                }
                else if (alt.ToLower().Contains("json"))
                {
                    contentType = ContentTypes.Json;
                }
            }

            if (contentType != ContentTypes.Null)
            {
                response.ContentType = string.Format(
                    RestfulContent.ContentTypeApplication,
                    contentType.ToString().ToLower());
            }

            if (data != null)
            {
                if (contentType == ContentTypes.Json ||
                    contentType == ContentTypes.Xml)
                {
                    //Add model response type so clients know how to deserialize the response
                    response.AddHeader(RestfulContent.Expect, data
                        .GetType()
                        .AssemblyQualifiedName);
                }

                try
                {
                    var stream = Serializer.Serialize(data);
                    response.BinaryWrite(stream.ToArray());
                }
                catch (Exception e)
                {
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    response.StatusDescription = RestfulContent.ResponseSerializationFailed;
                    response.ContentType = string.Empty;
                }
            }
        }
Ejemplo n.º 16
0
 public override bool UpdateItem(ContentTypes.IEditableObject item, System.Web.UI.Control editor)
 {
     TextBox tb = editor as TextBox;
     string value = (tb.Text == DefaultValue) ? null : tb.Text;
     if (string.IsNullOrEmpty(value))
         return false;
     value = Context.Current.Resolve<ICredentialService>().EncryptPassword(value);
     if (!AreEqual(value, item[Name]))
     {
         item[Name] = value;
         return true;
     }
     return false;
 }
Ejemplo n.º 17
0
        public IEnumerable<string> AvailableRoutes(ContentTypes? type)
        {
            IMongoQuery query = Query.Null;

            if (type.HasValue)
            {
                if (type.Value == ContentTypes.Partial)
                    query = Query.EQ("Partial", true);
                else
                    query = Query.EQ("Partial", false);
            }

            return Content.Find(query).Select(x => x["_id"].AsString);
        }
Ejemplo n.º 18
0
        public IEnumerable<string> AvailableRoutes(ContentTypes? type)
        {
            var query = DataFile.Element("Meek").Elements("content");

            if (type.HasValue)
            {
                if (type.Value == ContentTypes.Partial)
                    query = query.Where(x => x.Attribute("partial").Value == bool.TrueString);
                else
                    query = query.Where(x => x.Attribute("partial").Value == bool.FalseString);
            }

            return query.Select(x => x.Attribute("route").Value);
        }
Ejemplo n.º 19
0
        public IEnumerable<string> AvailableRoutes(ContentTypes? type)
        {
            var query = Content.AsQueryable();

            if (type.HasValue)
            {
                if (type.Value == ContentTypes.Partial)
                    query = query.Where(x => x.Value.Partial);
                else
                    query = query.Where(x => x.Value.Partial == false);
            }

            return query.Select(x => x.Key);
        }
Ejemplo n.º 20
0
        public static void ResponseFile(byte[] documentBytes, string filename, ContentTypes contentType)
        {
            string sMimeType = GetContentType(contentType);

            HttpContext oContext = HttpContext.Current;
            oContext.Response.Clear();
            oContext.Response.ContentType = sMimeType;
            oContext.Response.Cache.SetCacheability(HttpCacheability.Private);
            oContext.Response.Expires = -1;
            oContext.Response.Buffer = false;
            oContext.Response.AddHeader("Content-Disposition", string.Format("{0};FileName=\"{1}\"", "attachment", filename));
            oContext.Response.OutputStream.Write(documentBytes, 0, documentBytes.Length);
            oContext.Response.End();
        }
Ejemplo n.º 21
0
        public void LoadSurface()
        {
            if (contentType == ContentTypes.Avalon)
            {
                contentType = ContentTypes.SurfacePlot;

                if (abScene != null)
                    abScene.Dispose();

                abScene = cachedSurfaceScene;
                SetupView();
                ResetDevice();
                Invalidate();
            }
        }
Ejemplo n.º 22
0
 public PocketRetrieveItem(string ConsumerKey, string AccessToken, States State = States.Unread, Favorites Favorite = Favorites.Both, string Tag = null, ContentTypes ContentType = ContentTypes.All, Sorts Sort = Sorts.NoSort, DetailTypes DetailType = DetailTypes.NoType, string Search = null, string Domain = null, string Since = null, int Count = -1, int Offset = -1)
 {
     _consumerKey = ConsumerKey;
     _accessToken = AccessToken;
     _state = State;
     _favorite = Favorite;
     _tag = Tag;
     _contentType = ContentType;
     _sort = Sort;
     _detailType = DetailType;
     _search = Search;
     _domain = Domain;
     _since = Since;
     _count = Count;
     _offset = Offset;
 }
Ejemplo n.º 23
0
 public static ProcessedContent LoadContent(string file, ContentBuildLogger logger, ContentTypes desiredType, bool process = true, TargetPlatform plat = TargetPlatform.Windows)
 {
     Content content = new SGDEImport().Import(file, new FakeContentImporterContext(Path.GetFullPath(file), logger));
     if (content.Type != desiredType)
     {
         logger.LogImportantMessage(Resources.DATA_UTIL_LOAD_BADTYPE, content.Type, desiredType);
         return null;
     }
     if (process)
     {
         FakeContentProcessorContext context = new FakeContentProcessorContext(logger);
         context.TPalt = plat;
         return new SGDEProcessor().Process(content, context);
     }
     return new TempProcessedContent(); //Just to prevent a null outptu
 }
Ejemplo n.º 24
0
        public async Task Delete()
        {
            var c = new ContentTypes();
            var root = Environment.CurrentDirectory;
            var path = string.Format("{0}\\{1}.bin", root, Guid.NewGuid());

            var random = new Random();
            var bytes = new byte[64];
            random.NextBytes(bytes);

            File.WriteAllBytes(path, bytes);

            var item = new FileItem(root, path);
            await item.Delete();

            Assert.IsFalse(File.Exists(path));
        }
Ejemplo n.º 25
0
 public string Get(ContentTypes section)
 {
     try
     {
         var content = MarkupService.Get(section);
         if (content != null)
         {
             _localCache.WriteToCache(section, content, DateTime.Now);
             return content;
         }
         return _localCache.ReadFromCache(section);
     }
     catch (Exception)
     {
         return _localCache.ReadFromCache(section);
     }
 }
Ejemplo n.º 26
0
 public Content Get(ContentTypes section)
 {
     try
     {
         var content = ContentService.Get(section);
         if (content != null)
         {
             _localCache.WriteToCache(section, content, content.RefreshDate);
             return content;
         }
         return _localCache.ReadFromCache(section);
     }
     catch (Exception)
     {
         return _localCache.ReadFromCache(section);
     }
 }
 public static System.Web.Mvc.ActionResult Result(object data, ContentTypes contentType, HttpStatusCode statusCode)
 {
     switch (contentType)
     {
         case ContentTypes.Html:
         case ContentTypes.Text:
         case ContentTypes.FormEncoded:
             return new StringActionResult(data, contentType, statusCode);
         case ContentTypes.Binary:
             return new BinaryActionResult(data, contentType, statusCode);
         case ContentTypes.Xml:
             return new XmlActionResult(data, contentType, statusCode);
         case ContentTypes.Json:
             return new JsonActionResult(data, contentType, statusCode);
         default:
             throw Errors.ContentTypeNotSupported(contentType);
     }
 }
Ejemplo n.º 28
0
        public static BlogMLContent Create(string unencodedText, ContentTypes contentType)
        {
            var content = new BlogMLContent {ContentType = contentType};
            if (content.Base64Encoded)
            {
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(unencodedText);
                content.Text = Convert.ToBase64String(byteArray);
            }
            else if(content.HtmlEncoded)
            {
                content.Text = HttpUtility.HtmlEncode(unencodedText);
            }
            else
            {
                content.Text = unencodedText;
            }

            return content;
        }
Ejemplo n.º 29
0
        public Content(int contentId)
        {
			string sql = string.Format(
				"SELECT TOP 1 * FROM Content WHERE ContentId={0}; ",
                contentId
				);

			using (DataSet ds = DataAccess.RunSql(sql))
			{
				if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
				{
					DataRow dr = ds.Tables[0].Rows[0];
                    ContentId = dr.IntOrZero("ContentId");
					Name = dr.StringOrBlank("Name");
                    Type = (ContentTypes)dr.IntOrZero("Type");
                    if (dr["Data"] != DBNull.Value)
                        Data = (byte[])dr["Data"];
                }
			}
        }
Ejemplo n.º 30
0
 public bool LoadModel(string file)
 {
     if (contentType == ContentTypes.SurfacePlot)
     {
         cachedSurfaceScene = abScene;
         abScene = null;
     }
     bool result = LoadABSupportedScene(file);
     if (result)
     {
         contentType = ContentTypes.Avalon;
         SetupView();
         Invalidate();
     }
     else
     {
         abScene = cachedSurfaceScene;
     }
     return result;
 }
Ejemplo n.º 31
0
            /// <summary>
            /// Генерация экземпляра запроса на основе параметров
            /// </summary>
            /// <param name="channel">Канал, используемый для отправки запроса</param>
            /// <param name="uri">Целевой путь для отправки запроса</param>
            /// <param name="UsedChannels">Список использованных каналов для отправки данного запроса</param>
            /// <param name="PostBody">Тело Post-запроса (если есть)</param>
            /// <param name="tpe">Запрашиваемый заголовок запроса</param>
            public WebHostCacheRequest(WebHostCacheChannel channel, string uri, List <WebHostCacheChannel> UsedChannels, XElement PostBody = null, ContentTypes tpe = ContentTypes.xml) : base()
            {
                if (uri[0] != '/')
                {
                    uri = '/' + uri;
                }
                this.RequestUri   = new Uri(channel.Uri.OriginalString + uri);
                this.UsedChannels = UsedChannels;
                switch (tpe)
                {
                case ContentTypes.xml:
                    this.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
                    break;

                case ContentTypes.json:
                    this.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    break;

                default: break;
                }
                if (PostBody == null)
                {
                    this.Method = HttpMethod.Get;
                }
                else
                {
                    this.Method  = HttpMethod.Post;
                    this.Content = new ObjectContent <XElement>(PostBody, new XmlMediaTypeFormatter());
                }
            }
Ejemplo n.º 32
0
        public string GetData(string _URL, string _Verb, string _WebRequestPostData, ref object cc, ContentTypes ContentType = ContentTypes.UrlEncoded)
        {
            string page;

            this.Exception = "";
            HttpWebRequest request = null;

            try
            {
                HttpWebResponse response = GetResponse(_URL, _Verb, _WebRequestPostData, ref cc, ref request, ContentType);
                ResponseStatusCode = response.StatusCode;
                Stream       responseStream = response.GetResponseStream();
                StreamReader readStream     = new StreamReader(responseStream, Encoding.UTF8);

                page = readStream.ReadToEnd();
            }
            catch (Exception ee)
            {
                ResponseStatusCode = HttpStatusCode.InternalServerError;
                this.Exception     = ee.Message;
                page = "Failure " + ee.ToString();
            }

            return(page);
        }
Ejemplo n.º 33
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Insert the body of a paragraph. This is normally (with fApplyProps true) the body
        /// of case kfrPara and kfrFootnotePara in the Display method, but some subclasses
        /// need to separate this from applying the properties.
        /// </summary>
        /// <param name="vwenv"></param>
        /// <param name="hvo"></param>
        /// <param name="frag"></param>
        /// <param name="fApplyProps"></param>
        /// <param name="contentType"></param>
        /// <param name="vc">The view constructor used to create the paragraphs</param>
        /// ------------------------------------------------------------------------------------
        protected void InsertParagraphBody(IVwEnv vwenv, int hvo, int frag, bool fApplyProps,
                                           ContentTypes contentType, StVc vc)
        {
            vc.SetupWsAndDirectionForPara(vwenv, hvo);

            if (fApplyProps)
            {
                ApplyParagraphStyleProps(vwenv, hvo, vc);
            }

            // This was causing assertions in the layoutmgr
            // TODO (TE-5777): Should be able to do this with an in-memory stylesheet.
            //			if (DisplayTranslation)
            //			{
            //				// display the back translation text as double spaced
            //				vwenv.set_IntProperty((int)FwTextPropType.ktptLineHeight,
            //					(int)FwTextPropVar.ktpvRelative, 20000);
            //			}
            // The body of the paragraph is either editable or not.
            vwenv.set_IntProperty((int)FwTextPropType.ktptEditable,
                                  (int)FwTextPropVar.ktpvEnum,
                                  vc.Editable ? (int)TptEditable.ktptIsEditable
                                : (int)TptEditable.ktptNotEditable);
            // Make the paragraph containing the paragraph contents.
            OpenPara(vwenv, hvo);
            // Cause a regenerate when the style changes...this is mainly used for Undo.
            vwenv.NoteDependency(new int[] { hvo },
                                 new int[] { (int)StPara.StParaTags.kflidStyleRules }, 1);
            // Insert the label if it is the first paragraph.
            if (vc.Label != null)
            {
                int lev = vwenv.EmbeddingLevel;
                int hvoOuter;
                int ihvoItem;
                int tagOuter;
                vwenv.GetOuterObject(lev - 1, out hvoOuter, out tagOuter, out ihvoItem);
                if (ihvoItem == 0)
                {
                    vwenv.AddObj(hvo, vc, (int)StTextFrags.kfrLabel);
                }
            }
            if (frag == (int)StTextFrags.kfrFootnotePara)
            {
                int lev = vwenv.EmbeddingLevel;
                int hvoOuter;
                int ihvoItem;
                int tagOuter;
                vwenv.GetOuterObject(lev - 1, out hvoOuter, out tagOuter, out ihvoItem);
                // Note a dependency on the footnote options so that the footnote will
                // be refreshed when these are changed.
                int[] depHvos = { hvoOuter };
                int[] depTags = { StFootnote.ktagFootnoteOptions };
                vwenv.NoteDependency(depHvos, depTags, 1);
                // If this is the 0th paragraph in the footnote...
                if (ihvoItem == 0)
                {
                    vwenv.AddObj(hvoOuter, vc, (int)StTextFrags.kfrFootnoteMarker);
                    vwenv.AddObj(hvoOuter, /*vc.Parent != null ? vc.Parent :*/ vc,
                                 (int)StTextFrags.kfrFootnoteReference);
                }
            }

            if (contentType == ContentTypes.kctSimpleBT)
            {
                // If a translation is being shown instead of the paragraph, then show it instead
                // of the text of the paragraph.
                int transHvo = GetTranslationForPara(hvo);
                vwenv.AddObj(transHvo, vc, (int)StTextFrags.kfrTranslation);
                vwenv.NoteDependency(new int[] { hvo },
                                     new int[] { (int)StTxtPara.StTxtParaTags.kflidContents }, 1);
            }
            else if (contentType == ContentTypes.kctSegmentBT)
            {
                InsertBtSegments(vc, vwenv, hvo);
            }
            else if (!InsertParaContentsUserPrompt(vwenv, hvo))
            {
                // Display the text paragraph contents, or its user prompt.
                vwenv.AddStringProp((int)StTxtPara.StTxtParaTags.kflidContents, null);
            }

            // Display an "end-of-paragraph" marker if needed
            InsertEndOfParaMarks(vwenv, hvo);

            vwenv.CloseParagraph();
        }
Ejemplo n.º 34
0
        private static RestRequest GetBaseRequest(string endpoint, HttpMethod method = null, ContentTypes contentType = ContentTypes.Json)
        {
            method = method ?? HttpMethod.Get;
            var request = new RestRequest(endpoint, method, contentType);

            // looks like portable rest controls the default user agent, this forces it for the request
            request.AddHeader("user-agent", "com.vine.iphone/1.0.3 (unknown, iPhone OS 7.0.0, iPhone, Scale/2.000000)");

            return(request);
        }
        private static void PrepareRequestContentStream(IEnumerable <string> files, IEnumerable <KeyValuePair <string, string> > formFields, string boundary, MemoryStream requestContentStream)
        {
            var boundarybytes    = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            var endBoundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");

            var formdataTemplate = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";

            if (formFields != null)
            {
                var formFieldData = Encoding.UTF8.GetBytes(string.Join(string.Empty, formFields.Select(kvp => string.Format(CultureInfo.InvariantCulture, formdataTemplate, kvp.Key, kvp.Value))));
                requestContentStream.Write(formFieldData, 0, formFieldData.Length);
            }

            foreach (var file in files)
            {
                requestContentStream.Write(boundarybytes, 0, boundarybytes.Length);

                var headerTemplate = "Content-Disposition: form-data; name=\"fname\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";

                var header      = string.Format(CultureInfo.InvariantCulture, headerTemplate, file, ContentTypes.GetContentTypeFromFileExtension(Path.GetExtension(file)));
                var headerbytes = Encoding.UTF8.GetBytes(header);
                requestContentStream.Write(headerbytes, 0, headerbytes.Length);

                var fileBytes = File.ReadAllBytes(file);
                requestContentStream.Write(fileBytes, 0, fileBytes.Length);
            }

            requestContentStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Creates a new RestRequest instance for a given Resource and Method, specifying whether or not to ignore the root object in the response.
 /// </summary>
 /// <param name="resource">The URL format string of the resource to request.</param>
 /// <param name="contentType">The <see cref="ContentTypes">Content Type</see> for the request.</param>
 public RestRequest(string resource, ContentTypes contentType)
     : this(resource)
 {
     ContentType = contentType;
 }
Ejemplo n.º 37
0
        } // end function Download

        public HttpResponse Request(
            string url,
            object data                         = null,
            HttpMethods method                  = HttpMethods.GET,
            ContentTypes contentType            = ContentTypes.UrlEncoded,
            Dictionary <string, string> headers = null
            )
        {
            try
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string requestData = "";

                if (data == null && this.parameters != null && contentType == ContentTypes.UrlEncoded)
                {
                    requestData = this.GetQueryString(this.parameters);
                }

                if (data != null && contentType == ContentTypes.UrlEncoded)
                {
                    this.parameters = (Dictionary <string, object>)data;
                    requestData     = this.GetQueryString(this.parameters);
                }

                if (data == null && !string.IsNullOrEmpty(this.jsonData) && contentType == ContentTypes.Json)
                {
                    requestData = this.jsonData;
                }

                if (data != null && contentType == ContentTypes.Json && IsJson(data.ToString()))
                {
                    requestData = data.ToString();
                }

                //  here we got and object and we serialize it to json
                if (data != null && contentType == ContentTypes.Json && !IsJson(data.ToString()))
                {
                    requestData = serializer.Serialize(data);
                    string pattern = "Date\\(\\d*\\)";
                    pattern = "\\\\\\/Date\\(\\d*\\)\\\\\\/";
                    Regex regex = new Regex(pattern);
                    foreach (Match m in regex.Matches(requestData))
                    {
                        string dateStr = m.Value;
                        dateStr = dateStr.Replace("\\/Date(", "").Replace(")\\/", "");
                        dateStr = JsonDateFromMS(Convert.ToInt64(dateStr));
                        requestData
                            = requestData.Replace(m.Value, dateStr);
                    }
                }

                if (headers == null)
                {
                    headers = this.headers;
                }

                WebRequest request;
                Stream     dataStream;
                if (method == HttpMethods.GET)
                {
                    if (!string.IsNullOrEmpty(requestData))
                    {
                        url += "?" + requestData;
                    }

                    request        = WebRequest.Create(url);
                    request.Method = method.ToString();
                    foreach (string key in headers.Keys)
                    {
                        request.Headers.Add(key, headers[key]);
                    }
                }
                else
                {
                    request        = WebRequest.Create(url);
                    request.Method = method.ToString();
                    foreach (string key in headers.Keys)
                    {
                        request.Headers.Add(key, headers[key]);
                    }

                    byte[] byteArray = Encoding.UTF8.GetBytes(requestData);
                    if (contentType == ContentTypes.Json)
                    {
                        request.ContentType = "application/json; charset=UTF-8";
                    }
                    else if (contentType == ContentTypes.UrlEncoded)
                    {
                        request.ContentType = "application/x-www-form-urlencoded";
                    }

                    request.ContentLength = byteArray.Length;
                    dataStream            = request.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();
                }

                HttpWebResponse response     = (HttpWebResponse)request.GetResponse();
                HttpResponse    httpResponse = new HttpResponse();
                httpResponse.StatusCode  = response.StatusCode;
                httpResponse.ContentType = response.ContentType;

                foreach (var header in response.Headers)
                {
                    httpResponse.Headers.Add(
                        (string)header,
                        response.Headers.Get((string)header).ToString()
                        );
                }

                dataStream = response.GetResponseStream();
                StreamReader reader             = new StreamReader(dataStream);
                string       responseFromServer = reader.ReadToEnd();
                httpResponse.Data = responseFromServer;

                reader.Close();
                dataStream.Close();
                response.Close();

                this.ClearHeaders();
                this.ClearParameters();
                return(httpResponse);
            }
            catch (WebException webEx)
            {
                Console.Write(webEx);
                HttpResponse    httpResponse = new HttpResponse();
                HttpWebResponse response     = (HttpWebResponse)webEx.Response;
                if (response != null)
                {
                    httpResponse.StatusCode = response.StatusCode;
                    Stream       dataStream         = response.GetResponseStream();
                    StreamReader reader             = new StreamReader(dataStream);
                    string       responseFromServer = reader.ReadToEnd();
                    httpResponse.ErrorDescription = responseFromServer;
                    return(httpResponse);
                }
                throw webEx;
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                throw ex;
            }
        } // end post
Ejemplo n.º 38
0
        protected ServiceStackHost(string serviceName, params Assembly[] assembliesWithServices)
        {
            this.StartedAt = DateTime.UtcNow;

            ServiceName = serviceName;
            AppSettings = new AppSettings();
            Container   = new Container {
                DefaultOwner = Owner.External
            };
            ServiceAssemblies = assembliesWithServices.ToList();

            ContentTypes                      = new ContentTypes();
            RestPaths                         = new List <RestPath>();
            Routes                            = new ServiceRoutes(this);
            Metadata                          = new ServiceMetadata(RestPaths);
            PreRequestFilters                 = new List <Action <IRequest, IResponse> >();
            RequestConverters                 = new List <Func <IRequest, object, Task <object> > >();
            ResponseConverters                = new List <Func <IRequest, object, Task <object> > >();
            GlobalRequestFilters              = new List <Action <IRequest, IResponse, object> >();
            GlobalRequestFiltersAsync         = new List <Func <IRequest, IResponse, object, Task> >();
            GlobalTypedRequestFilters         = new Dictionary <Type, ITypedFilter>();
            GlobalResponseFilters             = new List <Action <IRequest, IResponse, object> >();
            GlobalResponseFiltersAsync        = new List <Func <IRequest, IResponse, object, Task> >();
            GlobalTypedResponseFilters        = new Dictionary <Type, ITypedFilter>();
            GlobalMessageRequestFilters       = new List <Action <IRequest, IResponse, object> >();
            GlobalMessageRequestFiltersAsync  = new List <Func <IRequest, IResponse, object, Task> >();
            GlobalTypedMessageRequestFilters  = new Dictionary <Type, ITypedFilter>();
            GlobalMessageResponseFilters      = new List <Action <IRequest, IResponse, object> >();
            GlobalTypedMessageResponseFilters = new Dictionary <Type, ITypedFilter>();
            GatewayRequestFilters             = new List <Action <IRequest, object> >();
            GatewayRequestFiltersAsync        = new List <Func <IRequest, object, Task> >();
            GatewayResponseFilters            = new List <Action <IRequest, object> >();
            GatewayResponseFiltersAsync       = new List <Func <IRequest, object, Task> >();
            ViewEngines                       = new List <IViewEngine>();
            ServiceExceptionHandlers          = new List <HandleServiceExceptionDelegate>();
            UncaughtExceptionHandlers         = new List <HandleUncaughtExceptionDelegate>();
            BeforeConfigure                   = new List <Action <ServiceStackHost> >();
            AfterConfigure                    = new List <Action <ServiceStackHost> >();
            AfterInitCallbacks                = new List <Action <IAppHost> >();
            OnDisposeCallbacks                = new List <Action <IAppHost> >();
            OnEndRequestCallbacks             = new List <Action <IRequest> >();
            AddVirtualFileSources             = new List <IVirtualPathProvider>();
            RawHttpHandlers                   = new List <Func <IHttpRequest, IHttpHandler> > {
                ReturnRedirectHandler,
                ReturnRequestInfoHandler,
            };
            CatchAllHandlers        = new List <HttpHandlerResolverDelegate>();
            CustomErrorHttpHandlers = new Dictionary <HttpStatusCode, IServiceStackHandler> {
                { HttpStatusCode.Forbidden, new ForbiddenHttpHandler() },
                { HttpStatusCode.NotFound, new NotFoundHttpHandler() },
            };
            StartUpErrors = new List <ResponseStatus>();
            AsyncErrors   = new List <ResponseStatus>();
            PluginsLoaded = new List <string>();
            Plugins       = new List <IPlugin> {
                new HtmlFormat(),
                new CsvFormat(),
                new PredefinedRoutesFeature(),
                new MetadataFeature(),
                new NativeTypesFeature(),
                new HttpCacheFeature(),
                new RequestInfoFeature(),
            };
            ExcludeAutoRegisteringServiceTypes = new HashSet <Type> {
                typeof(AuthenticateService),
                typeof(RegisterService),
                typeof(AssignRolesService),
                typeof(UnAssignRolesService),
                typeof(NativeTypesService),
                typeof(PostmanService),
                typeof(TemplateHotReloadService),
                typeof(TemplateHotReloadFilesService),
                typeof(TemplateApiPagesService),
                typeof(TemplateMetadataDebugService),
            };

            JsConfig.InitStatics();
        }
Ejemplo n.º 39
0
        public static void RegisterServiceAutoMappers()
        {
            // Used by CommentService
            Mapper.CreateMap <CommentDetails, CommunityComments>()
            .ForMember(target => target.CommunityID, options => options.MapFrom(source => source.ParentID))
            .ForMember(target => target.CommunityCommentsID, options => options.MapFrom(source => source.CommentID));

            Mapper.CreateMap <CommentDetails, ContentComments>()
            .ForMember(target => target.ContentID, options => options.MapFrom(source => source.ParentID))
            .ForMember(target => target.ContentCommentsID, options => options.MapFrom(source => source.CommentID));

            Mapper.CreateMap <CommunityComments, CommentDetails>()
            .ForMember(target => target.ParentID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.CommentedBy, options => options.MapFrom(source => source.User.FirstName + " " + source.User.LastName))
            .ForMember(target => target.CommentedByPictureID, options => options.MapFrom(source => source.User.PictureID))
            .ForMember(target => target.CommentID, options => options.MapFrom(source => source.CommunityCommentsID));

            Mapper.CreateMap <ContentComments, CommentDetails>()
            .ForMember(target => target.ParentID, options => options.MapFrom(source => source.ContentID))
            .ForMember(target => target.CommentedDatetime, options => options.MapFrom(source => source.CommentDatetime))
            .ForMember(target => target.CommentedBy, options => options.MapFrom(source => source.User.FirstName + " " + source.User.LastName))
            .ForMember(target => target.CommentedByPictureID, options => options.MapFrom(source => source.User.PictureID))
            .ForMember(target => target.CommentID, options => options.MapFrom(source => source.ContentCommentsID));

            // Used by CommunityService
            Mapper.CreateMap <CommunityDetails, Community>()
            .ForMember(target => target.CommunityTypeID, options => options.MapFrom(source => (int)source.CommunityType))
            .ForMember(target => target.CommunityType, options => options.Ignore())
            .ForMember(target => target.ThumbnailID, options => options.Ignore())
            .ForMember(target => target.CommunityID, options => options.Ignore());

            // Used by ContentService
            Mapper.CreateMap <ContentDetails, Content>()
            .ForMember(target => target.Title, options => options.MapFrom(source => source.Name));

            Mapper.CreateMap <Content, DownloadDetails>();

            Mapper.CreateMap <StaticContent, StaticContentDetails>();

            // Used by EntityService
            Mapper.CreateMap <TopCategoryEntities, ContentDetails>()
            .ForMember(target => target.Name, options => options.MapFrom(source => source.Title))
            .ForMember(target => target.ID, options => options.MapFrom(source => source.ID))
            .ForMember(target => target.ParentID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.ParentName, options => options.MapFrom(source => source.CommunityName))
            .ForMember(target => target.Tags, options => options.Condition(source => !source.IsSourceValueNull))
            .ForMember(target => target.ParentType, options => options.MapFrom(source => source.CommunityTypeID.ToEnum <int?, CommunityTypes>(CommunityTypes.None)));

            Mapper.CreateMap <TopCategoryEntities, EntityDetails>()
            .ForMember(target => target.Tags, options => options.Condition(source => !source.IsSourceValueNull))
            .ForMember(target => target.ID, options => options.MapFrom(source => source.ID))
            .ForMember(target => target.Name, options => options.MapFrom(source => source.Title));

            Mapper.CreateMap <Community, CommunityDetails>()
            .ForMember(target => target.ID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.CategoryID, options => options.MapFrom(source => (int)source.Category.CategoryID))
            .ForMember(target => target.AccessTypeID, options => options.MapFrom(source => (int)source.AccessType.AccessTypeID))
            .ForMember(target => target.AccessTypeName, options => options.MapFrom(source => source.AccessType.Name))
            .ForMember(target => target.CommunityType, options => options.MapFrom(source => source.CommunityTypeID))
            .ForMember(target => target.LastUpdatedDatetime, options => options.MapFrom(source => source.ModifiedDatetime));

            // Used by ProfileService
            Mapper.CreateMap <ProfileDetails, User>()
            .ForMember(target => target.LiveID, options => options.MapFrom(source => source.PUID))
            .ForMember(target => target.UserID, options => options.MapFrom(source => source.ID))
            .ForMember(target => target.Email, options => options.MapFrom(source => source.Email.FixEmailAddress()))
            .ForMember(target => target.UserTypeID, options => options.MapFrom(source => (int?)source.UserType))
            .ForMember(target => target.UserType, options => options.Ignore());

            Mapper.CreateMap <User, ProfileDetails>()
            .ForMember(target => target.PUID, options => options.MapFrom(source => source.LiveID))
            .ForMember(target => target.ID, options => options.MapFrom(source => source.UserID))
            .ForMember(target => target.Email, options => options.MapFrom(source => source.Email.FixEmailAddress()))
            .ForMember(target => target.UserType, options => options.MapFrom(source => source.UserTypeID.HasValue ? source.UserTypeID.Value.ToEnum <int, UserTypes>(UserTypes.Regular) : UserTypes.Regular))
            .ForMember(target => target.TotalSize, options => options.MapFrom(source => source.UserType.MaxAllowedSize));

            Mapper.CreateMap <User, AdminReportProfileDetails>()
            .ForMember(target => target.PUID, options => options.MapFrom(source => source.LiveID))
            .ForMember(target => target.LastLoggedOn, options => options.MapFrom(source => source.LastLoginDatetime))
            .ForMember(target => target.UserName, options => options.MapFrom(source => source.GetFullName()))
            .ForMember(target => target.Email, options => options.MapFrom(source => source.Email.FixEmailAddress()));

            Mapper.CreateMap <UserCommunities, PermissionItem>()
            .ForMember(target => target.Name, options => options.MapFrom(source => source.User.FirstName + " " + source.User.LastName))
            .ForMember(target => target.Role, options => options.MapFrom(source => (UserRole)source.RoleID))
            .ForMember(target => target.Date, options => options.MapFrom(source => source.CreatedDatetime));

            Mapper.CreateMap <PermissionRequest, PermissionItem>()
            .ForMember(target => target.Name, options => options.MapFrom(source => source.User.FirstName + " " + source.User.LastName))
            .ForMember(target => target.CommunityName, options => options.MapFrom(source => source.Community.Name))
            .ForMember(target => target.Role, options => options.MapFrom(source => (UserRole)source.RoleID))
            .ForMember(target => target.Date, options => options.MapFrom(source => source.RequestedDate));

            Mapper.CreateMap <PermissionItem, PermissionRequest>()
            .ForMember(target => target.RoleID, options => options.MapFrom(source => (UserRole)source.Role))
            .ForMember(target => target.Role, options => options.Ignore());

            // Used by RatingService
            Mapper.CreateMap <RatingDetails, CommunityRatings>()
            .ForMember(target => target.CommunityID, options => options.MapFrom(source => source.ParentID));

            Mapper.CreateMap <RatingDetails, ContentRatings>()
            .ForMember(target => target.RatingByID, options => options.MapFrom(source => source.RatedByID))
            .ForMember(target => target.ContentID, options => options.MapFrom(source => source.ParentID));

            // Used by ReportEntityService
            Mapper.CreateMap <ReportEntityDetails, OffensiveCommunities>()
            .ForMember(target => target.CommunityID, options => options.MapFrom(source => source.ParentID))
            .ForMember(target => target.OffensiveTypeID, options => options.MapFrom(source => (int)source.ReportEntityType))
            .ForMember(target => target.OffensiveStatusID, options => options.MapFrom(source => (int)source.Status))
            .ForMember(target => target.Comments, options => options.MapFrom(source => source.Comment));

            Mapper.CreateMap <ReportEntityDetails, OffensiveContent>()
            .ForMember(target => target.ContentID, options => options.MapFrom(source => source.ParentID))
            .ForMember(target => target.OffensiveTypeID, options => options.MapFrom(source => (int)source.ReportEntityType))
            .ForMember(target => target.OffensiveStatusID, options => options.MapFrom(source => (int)source.Status))
            .ForMember(target => target.Comments, options => options.MapFrom(source => source.Comment));

            Mapper.CreateMap <ContentsView, ContentDetails>()
            .ForMember(target => target.ID, options => options.MapFrom(source => source.ContentID))
            .ForMember(target => target.Name, options => options.MapFrom(source => source.Title))
            .ForMember(target => target.ParentType, options => options.MapFrom(source => source.CommunityTypeID))
            .ForMember(target => target.ParentID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.ParentName, options => options.MapFrom(source => source.CommunityName))
            .ForMember(target => target.Tags, options => options.MapFrom(source => (source.Tags ?? string.Empty)))
            .ForMember(target => target.SortOrder, options => options.Ignore())
            .ForMember(target => target.TourLength, options => options.MapFrom(source => source.TourRunLength))
            .ForMember(
                target => target.Thumbnail,
                options => options.MapFrom(source => new FileDetail()
            {
                AzureID = source.ThumbnailID ?? Guid.Empty
            }))
            .ForMember(
                target => target.ContentData,
                options => options.ResolveUsing(source =>
            {
                ContentTypes type = source.TypeID.ToEnum <int, ContentTypes>(ContentTypes.Generic);
                DataDetail dataDetail;

                if (type == ContentTypes.Link)
                {
                    dataDetail = new LinkDetail(source.ContentUrl, source.ContentID);
                }
                else
                {
                    var fileDetail       = new FileDetail();
                    fileDetail.ContentID = source.ContentID;
                    fileDetail.AzureID   = source.ContentAzureID;
                    dataDetail           = fileDetail;
                }

                dataDetail.Name        = source.Filename;
                dataDetail.ContentType = type;
                return(dataDetail);
            }));

            Mapper.CreateMap <AllContentsView, ContentDetails>()
            .ForMember(target => target.ID, options => options.MapFrom(source => source.ContentID))
            .ForMember(target => target.Name, options => options.MapFrom(source => source.Title))
            .ForMember(target => target.AccessTypeName, options => options.MapFrom(source => source.AccessType))
            .ForMember(target => target.ParentType, options => options.MapFrom(source => source.CommunityTypeID))
            .ForMember(target => target.ParentID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.ParentName, options => options.MapFrom(source => source.CommunityName))
            .ForMember(target => target.Tags, options => options.MapFrom(source => (source.Tags ?? string.Empty)))
            .ForMember(target => target.SortOrder, options => options.Ignore())
            .ForMember(
                target => target.Thumbnail,
                options => options.ResolveUsing(source =>
            {
                var thumbnailDetail     = new FileDetail();
                thumbnailDetail.AzureID = source.ThumbnailID.HasValue ? source.ThumbnailID.Value : Guid.Empty;
                return(thumbnailDetail);
            }))
            .ForMember(
                target => target.ContentData,
                options => options.ResolveUsing(source =>
            {
                ContentTypes type = source.TypeID.ToEnum <int, ContentTypes>(ContentTypes.Generic);
                DataDetail dataDetail;

                if (type == ContentTypes.Link)
                {
                    dataDetail = new LinkDetail(source.ContentUrl, source.ContentID);
                }
                else
                {
                    var fileDetail       = new FileDetail();
                    fileDetail.ContentID = source.ContentID;
                    fileDetail.AzureID   = source.ContentAzureID;
                    dataDetail           = fileDetail;
                }

                dataDetail.Name        = source.Filename;
                dataDetail.ContentType = type;
                return(dataDetail);
            }));

            Mapper.CreateMap <FeaturedContentsView, ContentDetails>()
            .ForMember(target => target.ID, options => options.MapFrom(source => source.ContentID))
            .ForMember(target => target.Name, options => options.MapFrom(source => source.Title))
            .ForMember(target => target.ParentType, options => options.MapFrom(source => source.CommunityTypeID))
            .ForMember(target => target.ParentID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.ParentName, options => options.MapFrom(source => source.CommunityName))
            .ForMember(target => target.Tags, options => options.MapFrom(source => (source.Tags == null ? string.Empty : source.Tags)))
            .ForMember(
                target => target.Thumbnail,
                options => options.ResolveUsing(source =>
            {
                var thumbnailDetail     = new FileDetail();
                thumbnailDetail.AzureID = source.ThumbnailID.HasValue ? source.ThumbnailID.Value : Guid.Empty;
                return(thumbnailDetail);
            }))
            .ForMember(
                target => target.ContentData,
                options => options.ResolveUsing(source =>
            {
                ContentTypes type = source.TypeID.ToEnum <int, ContentTypes>(ContentTypes.Generic);
                DataDetail dataDetail;

                if (type == ContentTypes.Link)
                {
                    dataDetail = new LinkDetail(source.ContentUrl, source.ContentID);
                }
                else
                {
                    var fileDetail       = new FileDetail();
                    fileDetail.ContentID = source.ContentID;
                    fileDetail.AzureID   = source.ContentAzureID;
                    dataDetail           = fileDetail;
                }

                dataDetail.Name        = source.Filename;
                dataDetail.ContentType = type;
                return(dataDetail);
            }));

            Mapper.CreateMap <CommunitiesView, CommunityDetails>()
            .ForMember(target => target.ID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.Name, options => options.MapFrom(source => source.CommunityName))
            .ForMember(target => target.AccessTypeName, options => options.MapFrom(source => source.AccessType))
            .ForMember(target => target.AccessTypeID, options => options.MapFrom(source => (int)source.AccessType.ToEnum <string, AccessType>(AccessType.Private)))
            .ForMember(target => target.CommunityType, options => options.MapFrom(source => source.CommunityTypeID.ToEnum <int, CommunityTypes>(CommunityTypes.None)))
            .ForMember(target => target.SortOrder, options => options.Ignore())
            .ForMember(
                target => target.Thumbnail,
                options => options.ResolveUsing(source =>
            {
                var thumbnailDetail     = new FileDetail();
                thumbnailDetail.AzureID = source.ThumbnailID.HasValue ? source.ThumbnailID.Value : Guid.Empty;
                return(thumbnailDetail);
            }));

            Mapper.CreateMap <AllCommunitiesView, CommunityDetails>()
            .ForMember(target => target.ID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.Name, options => options.MapFrom(source => source.CommunityName))
            .ForMember(target => target.AccessTypeName, options => options.MapFrom(source => source.AccessType))
            .ForMember(target => target.AccessTypeID, options => options.MapFrom(source => (int)source.AccessType.ToEnum <string, AccessType>(AccessType.Private)))
            .ForMember(target => target.CommunityType, options => options.MapFrom(source => source.CommunityTypeID.ToEnum <int, CommunityTypes>(CommunityTypes.None)))
            .ForMember(target => target.SortOrder, options => options.Ignore())
            .ForMember(
                target => target.Thumbnail,
                options => options.ResolveUsing(source =>
            {
                var thumbnailDetail     = new FileDetail();
                thumbnailDetail.AzureID = source.ThumbnailID.HasValue ? source.ThumbnailID.Value : Guid.Empty;
                return(thumbnailDetail);
            }));

            Mapper.CreateMap <FeaturedCommunitiesView, CommunityDetails>()
            .ForMember(target => target.ID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.Name, options => options.MapFrom(source => source.CommunityName))
            .ForMember(target => target.AccessTypeName, options => options.MapFrom(source => source.AccessType))
            .ForMember(target => target.AccessTypeID, options => options.MapFrom(source => (int)source.AccessType.ToEnum <string, AccessType>(AccessType.Private)))
            .ForMember(target => target.CommunityType, options => options.MapFrom(source => source.CommunityTypeID.ToEnum <int, CommunityTypes>(CommunityTypes.None)))
            .ForMember(
                target => target.Thumbnail,
                options => options.ResolveUsing(source =>
            {
                var thumbnailDetail     = new FileDetail();
                thumbnailDetail.AzureID = source.ThumbnailID.HasValue ? source.ThumbnailID.Value : Guid.Empty;
                return(thumbnailDetail);
            }));

            // Used by AdministrationService
            Mapper.CreateMap <OffensiveCommunities, OffensiveEntityDetails>()
            .ForMember(target => target.EntityID, options => options.MapFrom(source => source.CommunityID))
            .ForMember(target => target.EntityName, options => options.MapFrom(source => source.Community.Name))
            .ForMember(target => target.EntryID, options => options.MapFrom(source => source.OffensiveCommunitiesID))
            .ForMember(target => target.ReportedByID, options => options.MapFrom(source => source.ReportedByID))
            .ForMember(target => target.ReportedBy, options => options.MapFrom(source => source.User.FirstName + " " + source.User.LastName))
            .ForMember(target => target.ReportedDatetime, options => options.MapFrom(source => source.ReportedDatetime))
            .ForMember(target => target.Reason, options => options.MapFrom(source => Resources.ResourceManager.GetString(source.OffensiveTypeID.ToEnum <int, ReportEntityType>(ReportEntityType.None).ToString())))
            .ForMember(target => target.Comment, options => options.MapFrom(source => source.Comments));

            Mapper.CreateMap <OffensiveContent, OffensiveEntityDetails>()
            .ForMember(target => target.EntityID, options => options.MapFrom(source => source.ContentID))
            .ForMember(target => target.EntityName, options => options.MapFrom(source => source.Content.Title))
            .ForMember(target => target.EntryID, options => options.MapFrom(source => source.OffensiveContentID))
            .ForMember(target => target.ReportedByID, options => options.MapFrom(source => source.ReportedByID))
            .ForMember(target => target.ReportedBy, options => options.MapFrom(source => source.User.FirstName + " " + source.User.LastName))
            .ForMember(target => target.ReportedDatetime, options => options.MapFrom(source => source.ReportedDatetime))
            .ForMember(target => target.Reason, options => options.MapFrom(source => Resources.ResourceManager.GetString(source.OffensiveTypeID.ToEnum <int, ReportEntityType>(ReportEntityType.None).ToString())))
            .ForMember(target => target.Comment, options => options.MapFrom(source => source.Comments));

            Mapper.CreateMap <InviteRequestItem, InviteRequestContent>();
            Mapper.CreateMap <InviteRequestItem, InviteRequestItem>()
            .ForMember(target => target.EmailIdList, options => options.Ignore());
            Mapper.CreateMap <InviteRequestsView, InviteRequestItem>()
            .ForMember(target => target.EmailIdList, options => options.MapFrom(source => new Collection <string>()
            {
                source.EmailID
            }));

            Mapper.CreateMap <CommunityDetails, AdminEntityDetails>()
            .ForMember(target => target.EntityID, options => options.MapFrom(source => source.ID))
            .ForMember(target => target.EntityName, options => options.MapFrom(source => source.Name))
            .ForMember(target => target.Visibility, options => options.MapFrom(source => source.AccessTypeName))
            .ForMember(target => target.ModifiedDatetime, options => options.MapFrom(source => source.LastUpdatedDatetime))
            .ForMember(target => target.EntityType, options => options.UseValue(EntityType.Community))
            .ForMember(target => target.Category, options => options.MapFrom(source => source.CategoryID.ToEnum <int, CategoryType>(CategoryType.All)))
            .ForMember(target => target.CreatedBy, options => options.MapFrom(source => source.ProducedBy))
            .ForMember(target => target.CreatedByID, options => options.MapFrom(source => source.CreatedByID))
            .ForMember(target => target.DistributedBy, options => options.MapFrom(source => HttpContext.Current.Server.HtmlDecode(source.DistributedBy).GetTextFromHtmlString()));

            Mapper.CreateMap <ContentDetails, AdminEntityDetails>()
            .ForMember(target => target.EntityID, options => options.MapFrom(source => source.ID))
            .ForMember(target => target.EntityName, options => options.MapFrom(source => source.Name))
            .ForMember(target => target.Visibility, options => options.MapFrom(source => source.AccessTypeName))
            .ForMember(target => target.ModifiedDatetime, options => options.MapFrom(source => source.LastUpdatedDatetime))
            .ForMember(target => target.EntityType, options => options.UseValue(EntityType.Content))
            .ForMember(target => target.Category, options => options.MapFrom(source => source.CategoryID.ToEnum <int, CategoryType>(CategoryType.All)))
            .ForMember(target => target.CreatedBy, options => options.MapFrom(source => source.ProducedBy))
            .ForMember(target => target.CreatedByID, options => options.MapFrom(source => source.CreatedByID))
            .ForMember(target => target.DistributedBy, options => options.MapFrom(source => HttpContext.Current.Server.HtmlDecode(source.DistributedBy).GetTextFromHtmlString()));

            Mapper.CreateMap <ProfileDetails, AdminUserDetails>()
            .ForMember(target => target.UserID, options => options.MapFrom(source => source.ID))
            .ForMember(target => target.UserName, options => options.MapFrom(source => source.FirstName + " " + source.LastName))
            .ForMember(target => target.UserImageID, options => options.MapFrom(source => source.PictureID))
            .ForMember(target => target.Email, options => options.MapFrom(source => source.Email));

            Mapper.CreateMap <SearchView, EntityViewModel>()
            .ForMember(target => target.Tags, options => options.MapFrom(source => string.IsNullOrWhiteSpace(source.Tags) ? string.Empty : source.Tags))
            .ForMember(target => target.ParentType, options => options.Condition(source => !source.IsSourceValueNull));
        }
Ejemplo n.º 40
0
        private void ClientHandler()
        {
            while (alive)
            {
                byte[] data = GetMessage();
                if (data == null)
                {
                    return;
                }

                if (data[0] == 230) //authication
                {
                    log.msg("User '" + id + "' start auth");

                    try
                    {
                        int nick_size = Array.IndexOf(data, (byte)0x00) - 1;
                        int pass_size = 64;

                        string nick      = Encoding.UTF8.GetString(data, 1, nick_size);
                        string pass_hash = Encoding.UTF8.GetString(data, nick_size + 2, pass_size);

                        byte[] message;
                        authenticated = db.AuthentificateUser(nick, pass_hash);
                        if (authenticated)
                        {
                            id = nick;
                            DBUser userInfo = db.LoadUserData(id);
                            message   = GenerateMessage(200, userInfo.user_code.ToString());
                            user_code = userInfo.user_code.ToString();
                            db.SetUserActive(id, true);
                            log.msg("User '" + id + "' auth success");
                        }
                        else
                        {
                            message = GenerateMessage(255, "Wrong login or password");
                            log.msg("User '" + id + "' auth failed");
                        }

                        if (!SendMessage(message))
                        {
                            throw new Exception("Error send message");
                        }

                        continue;
                    }
                    catch (Exception exp)
                    {
                        log.msg("Error at user '" + id + "' " + exp.Message);
                        alive = false;
                        SetInactive();
                        return;
                    }
                }

                if (data[0] == 240) // registration
                {
                    try
                    {
                        int nick_size = Array.IndexOf(data, (byte)0x00) - 1;
                        int pass_size = Array.IndexOf(data, (byte)0x00, nick_size + 2) - nick_size - 2;

                        string nick   = Encoding.UTF8.GetString(data, 1, nick_size);
                        string passwd = Encoding.UTF8.GetString(data, nick_size + 2, pass_size);

                        //string pas_hash = passwd.GetHashCode().ToString();

                        //if (!db.RegisterNewUser(user))
                        //    throw new Exception("DataBase Error");

                        continue;
                    }
                    catch (Exception exp)
                    {
                        log.msg("Error at user '" + id + "' " + exp.Message);
                        alive = false;
                        return;
                    }
                }

                if (data[0] == 250) // recieved PC config
                {
                    if (!authenticated)
                    {
                        continue;
                    }

                    log.msg("User '" + id + "' sended PC config");

                    try
                    {
                        int mb_size  = Array.IndexOf(data, (byte)0x00) - 1;
                        int cpu_size = Array.IndexOf(data, (byte)0x00, mb_size + 2) -
                                       mb_size - 2;
                        int gpu_size = Array.IndexOf(data, (byte)0x00,
                                                     mb_size + cpu_size + 3) - mb_size - cpu_size - 3;

                        string mb  = Encoding.UTF8.GetString(data, 1, mb_size);
                        string cpu = Encoding.UTF8.GetString(data, mb_size + 2, cpu_size);
                        string gpu = Encoding.UTF8.GetString(data, mb_size + cpu_size + 3, gpu_size);

                        log.msg("User '" + id + "' sended mb info: " + mb);
                        log.msg("User '" + id + "' sended cpu info: " + cpu);
                        log.msg("User '" + id + "' sended gpu info: " + gpu);

                        device = db.LoadDevice(mb, cpu, gpu);
                        if (device == -1)
                        {
                            DBDevice dev_config = new DBDevice();
                            dev_config.active      = true;
                            dev_config.cpu         = cpu;
                            dev_config.motherboard = mb;
                            dev_config.gpu         = gpu;

                            if (!db.AddNewDevice(dev_config))
                            {
                                throw new Exception("Failed to add the device to the database");
                            }

                            device = db.LoadDevice(mb, cpu, gpu);
                            if (device == -1)
                            {
                                throw new Exception("Failed to load device from database");
                            }
                        }

                        if (!db.CheckDeviceUser(device, id))
                        {
                            if (!db.CorrelateUserDevice(device, id))
                            {
                                throw new Exception("Failed to correlate device and user");
                            }
                        }

                        if (!db.SetDeviceActive(device, true))
                        {
                            throw new Exception("Failed to activate device");
                        }

                        user_pc = cpu + " " + mb + " " + gpu;

                        continue;
                    }
                    catch (Exception exp)
                    {
                        log.msg("Error at user '" + id + "' " + exp.Message);
                        alive = false;
                        SetInactive();
                        return;
                    }
                }

                if (data[0] == 100) //Get library
                {
                    if (!authenticated)
                    {
                        try
                        {
                            byte[] err_mes = GenerateMessage(255,
                                                             "User don't authenticated");
                            if (!SendMessage(err_mes))
                            {
                                throw new Exception("Error send message");
                            }

                            continue;
                        }
                        catch (Exception exp)
                        {
                            log.msg("Error at user '" + id + "' " + exp.Message);
                            alive = false;
                            SetInactive();
                            return;
                        }
                    }

                    try
                    {
                        List <DBUnit> result = db.LoadUserLibrary(id);

                        int answ_size = 5;
                        int offset    = 5;
                        foreach (DBUnit unit in result)
                        {
                            answ_size += (17 + Encoding.UTF8.GetBytes(unit.name).Length);
                        }

                        byte[] answer = new byte[answ_size];

                        answer[0] = 200;
                        byte[] lib_size = BitConverter.GetBytes(result.Count);
                        Array.Copy(lib_size, 0, answer, 1, 4);

                        foreach (DBUnit unit in result)
                        {
                            byte[] unit_id = BitConverter.GetBytes(unit.id_software);
                            Array.Copy(unit_id, 0, answer, offset, 8);
                            offset += 8;
                            byte[] unit_code = BitConverter.GetBytes(unit.product_code);
                            Array.Copy(unit_code, 0, answer, offset, 8);
                            offset += 8;
                            byte[] unit_name = Encoding.UTF8.GetBytes(unit.name);
                            Array.Copy(unit_name, 0, answer, offset, unit_name.Length);
                            offset        += unit_name.Length;
                            answer[offset] = 0;
                            offset        += 1;
                        }

                        if (!SendMessage(answer))
                        {
                            throw new Exception("Error when send library");
                        }
                    }
                    catch (Exception exp)
                    {
                        log.msg("Error at user '" + id + "' " + exp.Message);
                        alive = false;
                        SetInactive();
                        return;
                    }
                }

                if (data[0] == 110) //Install soft
                {
                    if (!authenticated)
                    {
                        try
                        {
                            byte[] err_mes = GenerateMessage(255,
                                                             "User don't authenticated");
                            if (!SendMessage(err_mes))
                            {
                                throw new Exception("Error send message");
                            }

                            continue;
                        }
                        catch (Exception exp)
                        {
                            log.msg("Error at user '" + id + "' " + exp.Message);
                            alive = false;
                            SetInactive();
                            return;
                        }
                    }

                    try
                    {
                        byte[] id_soft     = GetMessage();
                        string id_software = Encoding.UTF8.GetString(id_soft);

                        DBUnit soft = db.LoadUnitInfo(Convert.ToUInt64(id_software));
                        log.msg("User '" + id + "' want software " + soft.name);

                        string key_info = user_pc + " " +
                                          user_code + " " + soft.product_code.ToString();
                        byte[] row_key_info = Encoding.UTF8.GetBytes(key_info);
                        SHA256 sha          = SHA256.Create();
                        byte[] key          = sha.ComputeHash(row_key_info);

                        string config = "D:\\DataWall\\" +
                                        id_software + " " + soft.name + "\\files.info";
                        StreamReader  conf_reader = new StreamReader(config);
                        List <byte[]> config_list = new List <byte[]>();
                        byte[]        b200        = { 200 };
                        config_list.Add(b200);
                        List <DWFileInfo> files = new List <DWFileInfo>();
                        while (!conf_reader.EndOfStream)
                        {
                            byte[] btype    = { 0 };
                            byte[] bnull    = { 0 };
                            byte[] bcontent = { 0, 0, 0, 0 };

                            string       fname        = conf_reader.ReadLine();
                            string       type         = conf_reader.ReadLine();
                            string       content_code = "";
                            ContentTypes DW_type      = ContentTypes.NON;
                            if (type == "1")
                            {
                                btype[0]     = 1;
                                content_code = conf_reader.ReadLine();
                                switch (content_code)
                                {
                                case "DLL":
                                    DW_type  = ContentTypes.DLL;
                                    bcontent = BitConverter.GetBytes((Int32)ContentTypes.DLL);
                                    break;

                                case "IMG":
                                    DW_type  = ContentTypes.IMG;
                                    bcontent = BitConverter.GetBytes((Int32)ContentTypes.IMG);
                                    break;

                                case "TXT":
                                    DW_type  = ContentTypes.TXT;
                                    bcontent = BitConverter.GetBytes((Int32)ContentTypes.TXT);
                                    break;

                                case "SND":
                                    DW_type  = ContentTypes.SND;
                                    bcontent = BitConverter.GetBytes((Int32)ContentTypes.SND);
                                    break;

                                case "BIN":
                                    DW_type  = ContentTypes.BIN;
                                    bcontent = BitConverter.GetBytes((Int32)ContentTypes.BIN);
                                    break;
                                }
                            }

                            config_list.Add(btype);
                            config_list.Add(bcontent);
                            config_list.Add(Encoding.UTF8.GetBytes(fname));
                            config_list.Add(bnull);

                            files.Add(new DWFileInfo("D:\\DataWall\\" +
                                                     id_software + " " + soft.name + "\\" + fname, DW_type));
                        }

                        byte[] eof = { 255 };
                        config_list.Add(eof);

                        byte[][] tmp = config_list.ToArray();

                        byte[] answer = tmp.SelectMany(x => x).ToArray();
                        SendMessage(answer);

                        foreach (DWFileInfo file in files)
                        {
                            BinaryReader file_reader = new BinaryReader(File.OpenRead(file.name));
                            FileInfo     info        = new FileInfo(file.name);
                            byte[]       file_data   = file_reader.ReadBytes((int)info.Length);
                            file_reader.Close();
                            if (file.type == ContentTypes.NON)
                            {
                                SendMessage(file_data);
                            }
                            else
                            {
                                string tmp_name = "D:\\DataWall\\temp\\" +
                                                  user_code + "_" + file.name.GetHashCode() + ".pak";
                                DataWallEngine.PackInContainer(
                                    file_data,
                                    (int)info.Length,
                                    (int)file.type,
                                    key,
                                    Encoding.UTF8.GetBytes(tmp_name));
                                BinaryReader encr_reader = new BinaryReader(File.OpenRead(tmp_name));
                                FileInfo     encr_info   = new FileInfo(tmp_name);
                                byte[]       encr_data   = encr_reader.ReadBytes((int)encr_info.Length);
                                encr_reader.Close();
                                SendMessage(encr_data);
                                File.Delete(tmp_name);
                            }
                        }

                        byte[] row_hash  = GetMessage();
                        string soft_hash = Encoding.UTF8.GetString(row_hash);
                        log.msg("User '" + id + "' Soft '" + soft.name + "' hash: " + soft_hash);

                        if (!db.WriteNewSoftHash(id, id_software, soft_hash))
                        {
                            throw new Exception("Coudn't write soft hash in db");
                        }
                    }
                    catch (Exception exp)
                    {
                        log.msg("Error at user '" + id + "' " + exp.Message);
                        byte[] err_mes = GenerateMessage(255,
                                                         "Unexpected error");
                        SendMessage(err_mes);
                        alive = false;
                        SetInactive();
                        return;
                    }
                }

                if (data[0] == 130) //check hash
                {
                    if (!authenticated)
                    {
                        try
                        {
                            byte[] err_mes = GenerateMessage(255,
                                                             "User don't authenticated");
                            if (!SendMessage(err_mes))
                            {
                                throw new Exception("Error send message");
                            }

                            continue;
                        }
                        catch (Exception exp)
                        {
                            log.msg("Error at user '" + id + "' " + exp.Message);
                            alive = false;
                            SetInactive();
                            return;
                        }
                    }

                    try
                    {
                        byte[] id_soft     = GetMessage();
                        string id_software = Encoding.UTF8.GetString(id_soft);

                        byte[] row_hash = GetMessage();
                        string hash     = Encoding.UTF8.GetString(row_hash);

                        byte[] message;
                        if (db.CheckSoftHash(id, id_software, hash))
                        {
                            message = GenerateMessage(200, "OK");
                            log.msg("User '" + id + "' check hash passed");
                        }
                        else
                        {
                            message = GenerateMessage(255, "Wrong hash");
                            log.msg("User '" + id + "' check hash failed");
                        }

                        if (!SendMessage(message))
                        {
                            throw new Exception("Error send message");
                        }
                    }
                    catch (Exception exp)
                    {
                        log.msg("Error at user '" + id + "' " + exp.Message);
                        byte[] err_mes = GenerateMessage(255,
                                                         "Unexpected error");
                        SendMessage(err_mes);
                        alive = false;
                        SetInactive();
                        return;
                    }
                }
            }
        }
Ejemplo n.º 41
0
 public static bool IsVisualizerVisible(ApiResponseModel response)
 {
     return(ContentTypes.IsText(response.ContentType));
 }
Ejemplo n.º 42
0
 public static string LoadContent(ContentTypes contentType, string contentID, bool isTestContent) =>
 ContentManager.LoadContent(contentType, isTestContent ? Path.Combine(TestContentStore.TEST_PREFIX, contentID) : contentID);
Ejemplo n.º 43
0
        public override void Add()
        {
            var folderId = ContentTypes.CreateFolder("Aub.Blog");

            ContentTypes.CreateFromFolder("~/App_Data/Aubergine/Blog/DocumentType/", folderId);
        }
        private void CreateOrUnhideDockableContent(ContentTypes contentType, string title, string viewPropertyName, object parent)
        {
            if (!this.dockableContents.Keys.Contains(contentType))
            {
                DockableContent dockableContent = new DockableContent();

                ContentControl contentControl = new ContentControl();

                dockableContent.IsCloseable = true;
                dockableContent.HideOnClose = false;

                dockableContent.Title = title;

                dockableContent.Content = contentControl;

                if (parent is ResizingPanel)
                {
                    DockablePane dockablePane = new DockablePane();
                    dockablePane.Items.Add(dockableContent);
                    ResizingPanel resizingPanel = parent as ResizingPanel;

                    switch (contentType)
                    {
                    case ContentTypes.PropertyInspector:
                        resizingPanel.Children.Add(dockablePane);
                        ResizingPanel.SetResizeWidth(dockablePane, new GridLength(300));
                        break;

                    case ContentTypes.Outline:
                        resizingPanel.Children.Insert(1, dockablePane);
                        ResizingPanel.SetResizeWidth(dockablePane, new GridLength(250));
                        break;

                    case ContentTypes.Toolbox:
                        resizingPanel.Children.Insert(0, dockablePane);
                        ResizingPanel.SetResizeWidth(dockablePane, new GridLength(250));
                        break;
                    }
                }
                else if (parent is DockablePane)
                {
                    DockablePane dockablePane = parent as DockablePane;
                    dockablePane.Items.Add(dockableContent);
                    if (dockablePane.Parent == null)
                    {
                        this.verticalResizingPanel.Children.Add(dockablePane);
                    }
                }

                Binding dataContextBinding = new Binding(viewPropertyName);
                dockableContent.SetBinding(DockableContent.DataContextProperty, dataContextBinding);

                Binding contentBinding = new Binding(".");
                contentControl.SetBinding(ContentControl.ContentProperty, contentBinding);

                this.dockableContents[contentType] = dockableContent;

                dockableContent.Closed += delegate(object sender, EventArgs args)
                {
                    contentControl.Content = null;
                    this.dockableContents[contentType].DataContext = null;
                    this.dockableContents.Remove(contentType);
                };
            }
            else
            {
                if (this.dockableContents[contentType].State == DockableContentState.Hidden)
                {
                    this.dockableContents[contentType].Show();
                }
            }
        }
Ejemplo n.º 45
0
 public ContentTypeAttribute(string mediaType)
 {
     ContentTypes.Add(MediaTypeHeaderValue.Parse(mediaType));
 }
Ejemplo n.º 46
0
        public async Task <JsonResult> GetBrowseContent(HighlightType highlightType, EntityType entityType, int page, int pageSize, CategoryType categoryType, ContentTypes contentType, long?entityId)
        {
            var pageDetails = new PageDetails(page);

            pageDetails.ItemsPerPage = pageSize;
            var entityHighlightFilter = new EntityHighlightFilter(highlightType, categoryType, entityId, contentType);
            var highlightEntities     = await GetHighlightEntities(entityType, entityHighlightFilter, pageDetails);



            // It creates the prefix for id of links
            SetSiteAnalyticsPrefix(highlightType);
            var result = new JsonResult
            {
                Data = new
                {
                    entities = highlightEntities,
                    pageInfo = pageDetails
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            return(result);
        }
Ejemplo n.º 47
0
        public StfsFile(Stream stream) : this()
        {
            EndianReader reader = new EndianReader(stream, Endianness.BigEndian);

            Header = PackageHeader.Create(reader);

            if (Header == null)
            {
                throw new FormatException();
            }

            reader.ReadBytes(ContentID);
            EntryID         = reader.ReadUInt32();
            ContentType     = (ContentTypes)reader.ReadUInt32();
            MetadataVersion = reader.ReadUInt32();
            ContentSize     = reader.ReadUInt64();
            MediaID         = reader.ReadUInt32();
            Version         = reader.ReadUInt32();
            BaseVersion     = reader.ReadUInt32();
            TitleID         = reader.ReadUInt32();
            Platform        = reader.ReadByte();
            ExecutableType  = reader.ReadByte();
            DiscNumber      = reader.ReadByte();
            DiscInSet       = reader.ReadByte();
            SaveGameID      = reader.ReadUInt32();
            reader.ReadBytes(ConsoleID);
            ProfileID    = reader.ReadUInt64();
            Descriptor   = PackageDescriptor.Create(reader);
            DataFiles    = reader.ReadUInt32();
            DataFileSize = reader.ReadUInt64();
            Reserved     = reader.ReadUInt64();
            reader.ReadBytes(Padding);
            reader.ReadBytes(DeviceID);
            for (int i = 0; i < DisplayName.Length; i++)
            {
                DisplayName[i] = ReadString(reader);
            }
            for (int i = 0; i < DisplayDescription.Length; i++)
            {
                DisplayDescription[i] = ReadString(reader);
            }
            Publisher          = ReadString(reader);
            TitleName          = ReadString(reader);
            TransferFlags      = reader.ReadByte();
            ThumbnailSize      = reader.ReadUInt32();
            TitleThumbnailSize = reader.ReadUInt32();

            Thumbnail      = new Bitmap(new Substream(stream, 0x171A, ThumbnailSize));
            TitleThumbnail = new Bitmap(new Substream(stream, 0x571A, TitleThumbnailSize));

            // None of this seems right, I'm hardcoding 0x0C
            // BaseBlock = ((EntryID + 0xFFF) & 0xF000) / BlockSize;
            // BaseBlock = (uint)(Util.RoundUp(EntryID, BlockSize) / BlockSize) + 1;

            Stream = new BlockStream(this, stream);
            Stream.SeekBlock(Descriptor.FileTableBlock);
            EndianReader blockreader = new EndianReader(Stream, Endianness.BigEndian);

            while (true)
            {
                FileDescriptor file = FileDescriptor.Create(blockreader, Stream);
                if (file.IsNull())
                {
                    break;
                }
                Files.Add(file);
            }
        }
Ejemplo n.º 48
0
        public BitmapCollection <BitmapSource> GetIconForContentType(string contentType)
        {
            if (string.Equals(contentType, "application/vnd.openxmlformats-package.relationships+xml", StringComparison.Ordinal))
            {
                return(RelsIcon);
            }

            if (ContentTypes.IsSupportedAudioType(contentType))
            {
                return(AudioIcon);
            }

            if (ContentTypes.IsSupportedImageType(contentType))
            {
                return(ImageIcon);
            }

            if (ContentTypes.IsSupportedVideoType(contentType))
            {
                return(VideoIcon);
            }

            if (ContentTypes.IsXmlType(contentType))
            {
                return(XmlIcon);
            }

            if (ContentTypes.IsXmlType(contentType))
            {
                return(CodeIcon);
            }

            switch (contentType)
            {
            case "application/rtf":
            case "message/rfc822":
                return(DocumentIcon);

            case "application/vnd.openxmlformats-officedocument.vmlDrawing":
                return(CodeIcon);

            case "application/msword":
            case "application/vnd.ms-word.document.macroEnabled.12":
            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                return(WordIcon);

            case "application/vnd.ms-powerpoint":
            case "application/vnd.ms-powerpoint.presentation.macroEnabled.12":
            case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
            case "application/vnd.openxmlformats-package.relationships+xml":
            case "application/vnd.ms-powerpoint.slide.macroEnabled.12":
            case "application/vnd.openxmlformats-officedocument.presentationml.slide":
                return(PptIcon);

            case "application/vnd.visio":
            case "application/vnd.ms-visio.drawing.macroEnabled":
            case "application/vnd.ms-visio.drawing":
                return(VisioIcon);

            case "application/vnd.ms-excel":
            case "application/vnd.ms-excel.sheet.binary.macroEnabled.12":
            case "application/vnd.ms-excel.sheet.macroEnabled.12":
            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                return(ExcelIcon);

            default:
                return(UnknownIcon);
            }
        }
Ejemplo n.º 49
0
        public void UpdateParentElementProcessStatus(ContentTypes contentType)
        {
            ElementProcessStatus parentElementProcessStatus = this.elementProcessStatusStack.Peek();

            parentElementProcessStatus.ContentType |= contentType;
        }
Ejemplo n.º 50
0
        public async Task GetCarInsuranceAdvice_UpdatesRuleAndAddsNewOneAndEvaluates_ReturnsPay()
        {
            // Arrange
            const ContentTypes expectedContent   = ContentTypes.CarInsuranceAdvice;
            DateTime           expectedMatchDate = new DateTime(2018, 06, 01);

            Condition <ConditionTypes>[] expectedConditions = new Condition <ConditionTypes>[]
            {
                new Condition <ConditionTypes>
                {
                    Type  = ConditionTypes.RepairCosts,
                    Value = 800.00000m
                },
                new Condition <ConditionTypes>
                {
                    Type  = ConditionTypes.RepairCostsCommercialValueRate,
                    Value = 23.45602m
                }
            };

            IServiceCollection serviceDescriptors = new ServiceCollection();

            serviceDescriptors.AddSingleton(this.inMemoryRulesStorage);
            IServiceProvider serviceProvider = serviceDescriptors.BuildServiceProvider();

            RulesEngine <ContentTypes, ConditionTypes> rulesEngine = RulesEngineBuilder.CreateRulesEngine()
                                                                     .WithContentType <ContentTypes>()
                                                                     .WithConditionType <ConditionTypes>()
                                                                     .SetInMemoryDataSource(serviceProvider)
                                                                     .Configure(reo =>
            {
                reo.PriotityCriteria = PriorityCriterias.BottommostRuleWins;
            })
                                                                     .Build();

            IRulesDataSource <ContentTypes, ConditionTypes> rulesDataSource = CreateRulesDataSourceTest <ContentTypes, ConditionTypes>(this.inMemoryRulesStorage);

            RuleBuilderResult <ContentTypes, ConditionTypes> ruleBuilderResult = RuleBuilder.NewRule <ContentTypes, ConditionTypes>()
                                                                                 .WithName("Car Insurance Advise on self damage coverage")
                                                                                 .WithDateBegin(DateTime.Parse("2018-01-01"))
                                                                                 .WithPriority(1)
                                                                                 .WithContentContainer(new ContentContainer <ContentTypes>(ContentTypes.CarInsuranceAdvice, (t) => CarInsuranceAdvices.Pay))
                                                                                 .Build();
            IEnumerable <Rule <ContentTypes, ConditionTypes> > existentRules1 = await rulesDataSource.GetRulesByAsync(new RulesFilterArgs <ContentTypes>
            {
                Name = "Car Insurance Advise on repair costs lower than franchise boundary"
            });

            Rule <ContentTypes, ConditionTypes> ruleToAdd     = ruleBuilderResult.Rule;
            Rule <ContentTypes, ConditionTypes> ruleToUpdate1 = existentRules1.FirstOrDefault();

            ruleToUpdate1.Priority = 2;

            // Act 1
            RuleOperationResult updateOperationResult1 = await rulesEngine.UpdateRuleAsync(ruleToUpdate1);

            Rule <ContentTypes, ConditionTypes> eval1 = await rulesEngine.MatchOneAsync(expectedContent, expectedMatchDate, expectedConditions);

            IEnumerable <Rule <ContentTypes, ConditionTypes> > rules1 = await rulesDataSource.GetRulesByAsync(new RulesFilterArgs <ContentTypes>());

            // Assert 1
            updateOperationResult1.Should().NotBeNull();
            updateOperationResult1.IsSuccess.Should().BeTrue();

            eval1.Priority.Should().Be(2);
            CarInsuranceAdvices content1 = eval1.ContentContainer.GetContentAs <CarInsuranceAdvices>();

            content1.Should().Be(CarInsuranceAdvices.RefusePaymentPerFranchise);

            Rule <ContentTypes, ConditionTypes> rule11 = rules1.FirstOrDefault(r => r.Name == "Car Insurance Advise on repair costs lesser than 80% of commercial value");

            rule11.Should().NotBeNull();
            rule11.Priority.Should().Be(1);
            Rule <ContentTypes, ConditionTypes> rule12 = rules1.FirstOrDefault(r => r.Name == "Car Insurance Advise on repair costs lower than franchise boundary");

            rule12.Should().NotBeNull();
            rule12.Priority.Should().Be(2);
            Rule <ContentTypes, ConditionTypes> rule13 = rules1.FirstOrDefault(r => r.Name == "Car Insurance Advise on repair costs greater than 80% of commercial value");

            rule13.Should().NotBeNull();
            rule13.Priority.Should().Be(3);

            // Act 2
            RuleOperationResult addOperationResult = await rulesEngine.AddRuleAsync(ruleToAdd, new RuleAddPriorityOption
            {
                PriorityOption        = PriorityOptions.AtRuleName,
                AtRuleNameOptionValue = "Car Insurance Advise on repair costs lower than franchise boundary"
            });

            Rule <ContentTypes, ConditionTypes> eval2 = await rulesEngine.MatchOneAsync(expectedContent, expectedMatchDate, expectedConditions);

            IEnumerable <Rule <ContentTypes, ConditionTypes> > rules2 = await rulesDataSource.GetRulesByAsync(new RulesFilterArgs <ContentTypes>());

            // Assert 2
            addOperationResult.Should().NotBeNull();
            addOperationResult.IsSuccess.Should().BeTrue();

            eval2.Priority.Should().Be(3);
            CarInsuranceAdvices content2 = eval2.ContentContainer.GetContentAs <CarInsuranceAdvices>();

            content2.Should().Be(CarInsuranceAdvices.RefusePaymentPerFranchise);

            Rule <ContentTypes, ConditionTypes> rule21 = rules2.FirstOrDefault(r => r.Name == "Car Insurance Advise on repair costs lesser than 80% of commercial value");

            rule21.Should().NotBeNull();
            rule21.Priority.Should().Be(1);
            Rule <ContentTypes, ConditionTypes> rule22 = rules2.FirstOrDefault(r => r.Name == "Car Insurance Advise on self damage coverage");

            rule22.Should().NotBeNull();
            rule22.Priority.Should().Be(2);
            Rule <ContentTypes, ConditionTypes> rule23 = rules2.FirstOrDefault(r => r.Name == "Car Insurance Advise on repair costs lower than franchise boundary");

            rule23.Should().NotBeNull();
            rule23.Priority.Should().Be(3);
            Rule <ContentTypes, ConditionTypes> rule24 = rules2.FirstOrDefault(r => r.Name == "Car Insurance Advise on repair costs greater than 80% of commercial value");

            rule24.Should().NotBeNull();
            rule24.Priority.Should().Be(4);

            // Act 3
            IEnumerable <Rule <ContentTypes, ConditionTypes> > existentRules2 = await rulesDataSource.GetRulesByAsync(new RulesFilterArgs <ContentTypes>
            {
                Name = "Car Insurance Advise on repair costs lower than franchise boundary"
            });

            Rule <ContentTypes, ConditionTypes> ruleToUpdate2 = existentRules2.FirstOrDefault();

            ruleToUpdate2.Priority = 4;

            RuleOperationResult updateOperationResult2 = await rulesEngine.UpdateRuleAsync(ruleToUpdate2);

            Rule <ContentTypes, ConditionTypes> eval3 = await rulesEngine.MatchOneAsync(expectedContent, expectedMatchDate, expectedConditions);

            IEnumerable <Rule <ContentTypes, ConditionTypes> > rules3 = await rulesDataSource.GetRulesByAsync(new RulesFilterArgs <ContentTypes>());

            // Assert 3
            updateOperationResult2.Should().NotBeNull();
            updateOperationResult2.IsSuccess.Should().BeTrue();

            eval3.Priority.Should().Be(4);
            CarInsuranceAdvices content3 = eval3.ContentContainer.GetContentAs <CarInsuranceAdvices>();

            content3.Should().Be(CarInsuranceAdvices.RefusePaymentPerFranchise);

            Rule <ContentTypes, ConditionTypes> rule31 = rules3.FirstOrDefault(r => r.Name == "Car Insurance Advise on repair costs lesser than 80% of commercial value");

            rule31.Should().NotBeNull();
            rule31.Priority.Should().Be(1);
            Rule <ContentTypes, ConditionTypes> rule32 = rules3.FirstOrDefault(r => r.Name == "Car Insurance Advise on self damage coverage");

            rule32.Should().NotBeNull();
            rule32.Priority.Should().Be(2);
            Rule <ContentTypes, ConditionTypes> rule33 = rules3.FirstOrDefault(r => r.Name == "Car Insurance Advise on repair costs greater than 80% of commercial value");

            rule33.Should().NotBeNull();
            rule33.Priority.Should().Be(3);
            Rule <ContentTypes, ConditionTypes> rule34 = rules3.FirstOrDefault(r => r.Name == "Car Insurance Advise on repair costs lower than franchise boundary");

            rule34.Should().NotBeNull();
            rule34.Priority.Should().Be(4);
        }
 /// <summary>
 /// Initializes a new instance of the DefaultThumbnailViewModel class.
 /// </summary>
 /// <param name="thumbnailID">Thumbnail Guid</param>
 /// <param name="entity">Type of the entity</param>
 /// <param name="altText">Alt text for IMG tag</param>
 /// <param name="contentType">Content Type of the content. In case of community, it will be generic which will not be used.</param>
 public DefaultThumbnailViewModel(Guid?thumbnailID, EntityType entity, string altText, ContentTypes contentType)
 {
     this.ThumbnailID = thumbnailID;
     this.Entity      = entity;
     this.AltText     = HttpContext.Current.Server.HtmlEncode(altText);
     this.ContentType = contentType;
 }
Ejemplo n.º 52
0
        protected override void OnPreRender(EventArgs e)
        {
            UITools.AddStyleSheetToHeader(UITools.GetHeader(), "$skin/styles/SN.Tagging.css");
            using (var traceOperation = Logger.TraceOperation("TagCloudPortlet.OnPreRender: ", this.Name))
            {
                base.OnPreRender(e);
                //if cached return
                if (Cacheable && CanCache && IsInCache)
                {
                    //System.Diagnostics.Trace.WriteLine(this.ID + " OnPreRender END - Portlet cached.");
                    return;
                }

                char[] splitchars       = { ',' };
                var    contentTypeArray = ContentTypes.Split(splitchars, StringSplitOptions.RemoveEmptyEntries);
                var    searchPathArray  = !string.IsNullOrEmpty(SearchPaths)
                                          ? SearchPaths.ToLower().Split(splitchars, StringSplitOptions.RemoveEmptyEntries)
                                          : (ContextNode == null ? new string[0] : new[] { ContextNode.Path.ToLower() });
                var allTypes = new List <string>();

                foreach (var type in contentTypeArray)
                {
                    allTypes.Add(type.ToLower());

                    if (IncludeChildren) //if all descendant types are needed
                    {
                        var baseType = ContentType.GetByName(type);
                        if (baseType != null)
                        {
                            foreach (var childType in ContentType.GetContentTypes())
                            {
                                if (childType.IsDescendantOf(baseType))
                                {
                                    allTypes.Add(childType.Name.ToLower());
                                }
                            }
                        }
                    }
                }

                var ctrl = Page.LoadControl(contentViewPath) as TagCloudControl;
                if (ctrl != null)
                {
                    var repeater = ctrl.FindControl("TagCloudRepeater") as System.Web.UI.WebControls.Repeater;
                    if (repeater != null)
                    {
                        if (allTypes.Count == 0 && searchPathArray.Count() == 0)
                        {
                            repeater.DataSource = TagManager.GetTagClasses(MaxCount);
                        }
                        else
                        {
                            repeater.DataSource = TagManager.GetTagClasses(searchPathArray, allTypes.ToArray(), MaxCount);
                        }
                        ctrl.SearchPortletPath = SearchPortletPath;
                        repeater.DataBind();
                    }

                    Controls.Add(ctrl);
                }
                else
                {
                    Controls.Add(new LiteralControl("ContentView error."));
                }
                traceOperation.IsSuccessful = true;
            }
        }
Ejemplo n.º 53
0
        private HttpWebResponse GetResponse(string _URL, string _Verb, string _WebRequestPostData, ref object cc, ref HttpWebRequest request, ContentTypes ContentType = ContentTypes.UrlEncoded, int TimeOutMinutes = 60)
        {
            if (_WebRequestPostData == null)
            {
                _WebRequestPostData = "";
            }


            Uri uri = new Uri(_URL);

            request = (HttpWebRequest)WebRequest.Create(uri);

            if (_URL.ToLower().Contains("https"))
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = (SecurityProtocolType)3072; // TLS 1.2
            }

            string postsourcedata = _WebRequestPostData;

            // start added codes
            request.KeepAlive       = true;
            request.ProtocolVersion = HttpVersion.Version10;

            request.Method        = _Verb;
            request.ContentType   = ContentType.ToDescription();
            request.ContentLength = postsourcedata.Length;

            request.Proxy = GetProxy();
            request.UseDefaultCredentials = true;

            if (cc != null)
            {
                setCookies(ref request, cc);
            }
            else
            {
                request.CookieContainer = new CookieContainer();
            }
            request.AllowAutoRedirect            = true;
            request.MaximumAutomaticRedirections = 50;

            request.Timeout   = (int)new TimeSpan(60, TimeOutMinutes, 60).TotalMilliseconds;
            request.UserAgent = GetRandomUserAgents();

            if (!string.IsNullOrEmpty(postsourcedata) && _Verb == "POST")
            {
                Stream writeStream = request.GetRequestStream();
                byte[] bytes       = System.Text.Encoding.ASCII.GetBytes(postsourcedata);
                writeStream.Write(bytes, 0, bytes.Length);
                writeStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            return(response);
        }
Ejemplo n.º 54
0
 /// <summary>
 /// Add all the details for a content type to this
 /// </summary>
 /// <param name="t">The content type</param>
 public void AddContentType(Type t)
 {
     ContentTypes.Add(t.FullName);
     AddTypeInner(t);
 }
Ejemplo n.º 55
0
        public virtual IOutputFormatter SelectFormatter(
            OutputFormatterContext formatterContext,
            IEnumerable <IOutputFormatter> formatters)
        {
            // Check if any content-type was explicitly set (for example, via ProducesAttribute
            // or Url path extension mapping). If yes, then ignore content-negotiation and use this content-type.
            if (ContentTypes.Count == 1)
            {
                return(SelectFormatterUsingAnyAcceptableContentType(formatterContext,
                                                                    formatters,
                                                                    ContentTypes));
            }

            var sortedAcceptHeaderMediaTypes = GetSortedAcceptHeaderMediaTypes(formatterContext);

            IOutputFormatter selectedFormatter = null;

            if (ContentTypes == null || ContentTypes.Count == 0)
            {
                // Check if we have enough information to do content-negotiation, otherwise get the first formatter
                // which can write the type.
                MediaTypeHeaderValue requestContentType = null;
                MediaTypeHeaderValue.TryParse(
                    formatterContext.ActionContext.HttpContext.Request.ContentType,
                    out requestContentType);
                if (!sortedAcceptHeaderMediaTypes.Any() && requestContentType == null)
                {
                    return(SelectFormatterBasedOnTypeMatch(formatterContext, formatters));
                }

                //
                // Content-Negotiation starts from this point on.
                //

                // 1. Select based on sorted accept headers.
                if (sortedAcceptHeaderMediaTypes.Any())
                {
                    selectedFormatter = SelectFormatterUsingSortedAcceptHeaders(
                        formatterContext,
                        formatters,
                        sortedAcceptHeaderMediaTypes);
                }

                // 2. No formatter was found based on accept headers, fall back on request Content-Type header.
                if (selectedFormatter == null && requestContentType != null)
                {
                    selectedFormatter = SelectFormatterUsingAnyAcceptableContentType(
                        formatterContext,
                        formatters,
                        new[] { requestContentType });
                }

                // 3. No formatter was found based on Accept and request Content-Type headers, so
                // fallback on type based match.
                if (selectedFormatter == null)
                {
                    // Set this flag to indicate that content-negotiation has failed to let formatters decide
                    // if they want to write the response or not.
                    formatterContext.FailedContentNegotiation = true;

                    return(SelectFormatterBasedOnTypeMatch(formatterContext, formatters));
                }
            }
            else
            {
                if (sortedAcceptHeaderMediaTypes.Any())
                {
                    // Filter and remove accept headers which cannot support any of the user specified content types.
                    var filteredAndSortedAcceptHeaders = sortedAcceptHeaderMediaTypes
                                                         .Where(acceptHeader =>
                                                                ContentTypes.Any(contentType =>
                                                                                 contentType.IsSubsetOf(acceptHeader)));

                    selectedFormatter = SelectFormatterUsingSortedAcceptHeaders(
                        formatterContext,
                        formatters,
                        filteredAndSortedAcceptHeaders);
                }

                if (selectedFormatter == null)
                {
                    // Either there were no acceptHeaders that were present OR
                    // There were no accept headers which matched OR
                    // There were acceptHeaders which matched but there was no formatter
                    // which supported any of them.
                    // In any of these cases, if the user has specified content types,
                    // do a last effort to find a formatter which can write any of the user specified content type.
                    selectedFormatter = SelectFormatterUsingAnyAcceptableContentType(
                        formatterContext,
                        formatters,
                        ContentTypes);
                }
            }

            return(selectedFormatter);
        }
        private static TResponse SendFileUploadRequest <TResponse>(string path, string query, FileInfo[] files)
        {
            var blogApplicationController = CreateController();
            var request = blogApplicationController.ControllerContext.HttpContext.Request;

            request.Path        = new PathString($"/{nameof(BlogApplicationController).Replace("Controller", string.Empty)}{path}");
            request.QueryString = new QueryString($"{query}");

            var boundary = $"{Guid.NewGuid()}";

            request.ContentType = $"multipart/form-data; boundary={boundary}";

            var requestBodyStream = new MemoryStream();

            for (int fileIndex = 0; fileIndex < files.Length; fileIndex++)
            {
                var seperatorBytes = Encoding.ASCII.GetBytes($"{(fileIndex == 0 ? string.Empty : Environment.NewLine)}--{boundary}{Environment.NewLine}Content-Disposition: form-data; name=\"filename\"; filename=\"{Path.GetFileName(files[fileIndex].FullName)}\"{Environment.NewLine}Content-Type: {ContentTypes.GetContentTypeFromFileExtension(files[fileIndex].Extension)}{Environment.NewLine}{Environment.NewLine}");
                requestBodyStream.Write(seperatorBytes);
                requestBodyStream.Write(File.ReadAllBytes(files[fileIndex].FullName));
            }

            requestBodyStream.Write(Encoding.ASCII.GetBytes($"{Environment.NewLine}--{boundary}--"));

            requestBodyStream.Position = 0;
            request.ContentLength      = requestBodyStream.Length;
            request.Body = requestBodyStream;

            return((TResponse)blogApplicationController.ReceiveRequest());
        }
Ejemplo n.º 57
0
 /// <summary>
 /// Отправка запроса на канал. Если канал "упал", выбирается следующий доступный
 /// </summary>
 /// <param name="currentChannel">Канал, по которому надо отправить запрос</param>
 /// <param name="request">Экземпляр заполненного запроса</param>
 /// <param name="tpe">Запрашиваемый заголовок запроса (нужен, если канал упал)</param>
 /// <returns>Экземпляр HttpResponseMessage</returns>
 private HttpResponseMessage GetResult(WebHostCacheChannel currentChannel, WebHostCacheRequest request, ContentTypes tpe = ContentTypes.xml)
 {
     try
     {
         // Добавляем в список запрос и обновляем значение коэффициента нагрузки
         currentChannel.RequestsList.Add(request);
         Task <HttpResponseMessage> response = currentChannel.Client.SendAsync(request);
         HttpResponseMessage        result   = response.Result;
         result.EnsureSuccessStatusCode();
         currentChannel.ReqSended++;
         return(result);
     }
     catch (Exception ee)
     {
         // Канал не доступен, выбираем другой менее нагруженный, но не этот
         WebHostCacheChannel nextCannel = GetLessLoadedEndPoint(request.UsedChannels);
         request.UsedChannels.Add(nextCannel);
         WebHostCacheRequest newRequest = new WebHostCacheRequest(nextCannel, request.RequestUri.AbsolutePath,
                                                                  request.UsedChannels, request.Content == null ? null : request.Content.ReadAsAsync <XElement>().Result, tpe);
         return(GetResult(nextCannel, newRequest));
     }
     finally
     {
         // Пришёл ответ или была ошибка, удаляем запрос из списка и обновляем значение коэффициента нагрузки
         currentChannel.RequestsList.Remove(request);
     }
 }
Ejemplo n.º 58
0
 /// <summary>
 /// Creates a new RestRequest instance for a given Resource and Method, specifying whether or not to ignore the root object in the response.
 /// </summary>
 /// <param name="resource">The URL format string of the resource to request.</param>
 /// <param name="method">The <see cref="HttpMethod"/> for the request.</param>
 /// <param name="contentType">The <see cref="ContentTypes">Content Type</see> for the request.</param>
 public RestRequest(string resource, HttpMethod method, ContentTypes contentType)
     : this(resource, method)
 {
     ContentType = contentType;
 }
Ejemplo n.º 59
0
        static void Main(string[] args)
        {
            CommandLine cmdline = new CommandLine(args);
            IDictionary <string, string> parameters = cmdline.Named;

            serverAE    = parameters["serverAE"];
            serverHost  = parameters["host"];
            serverPort  = int.Parse(parameters["port"]);
            studyFolder = parameters["folder"];

            if (parameters.ContainsKey("type"))
            {
                if (parameters["type"] == "dicom")
                {
                    type = ContentTypes.Dicom;
                }
                else if (parameters["type"] == "pixel")
                {
                    type = ContentTypes.RawPixel;
                }
                else
                {
                    throw new Exception("Invalid 'type' value");
                }
            }

            repeat = cmdline.Switches.ContainsKey("repeat");

            Console.WriteLine("Retrieve image in {0}", studyFolder);

            DirectoryInfo dirInfo = new DirectoryInfo(studyFolder);

            DirectoryInfo[] partitions = dirInfo.GetDirectories();

            try
            {
                do
                {
                    Random        r         = new Random();
                    DirectoryInfo partition = partitions[r.Next(partitions.Length)];

                    DirectoryInfo[] studydates = partition.GetDirectories();
                    if (studydates.Length > 0)
                    {
                        // pick one
                        DirectoryInfo studyate = studydates[r.Next(studydates.Length)];

                        DirectoryInfo[] studies = studyate.GetDirectories();

                        if (studies.Length > 0)
                        {
                            // pick one
                            DirectoryInfo study = studies[r.Next(studies.Length)];

                            string path = study.FullName;
                            RetrieveImages(partition.Name, path);
                        }
                    }


                    //if (repeat)
                    //    Thread.Sleep(r.Next(10000));
                } while (repeat);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 60
0
 public DWFileInfo(string _name, ContentTypes _type)
 {
     name = _name;
     type = _type;
 }