/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPgpSignature"/> /// class with a Content-Type of application/pgp-signature. /// </summary> /// <remarks> /// Creates a new MIME part with a Content-Type of application/pgp-signature /// and the <paramref name="stream"/> as its content. /// </remarks> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPgpSignature (Stream stream) : base ("application", "pgp-signature") { ContentDisposition = new ContentDisposition (ContentDisposition.Attachment); ContentTransferEncoding = ContentEncoding.SevenBit; ContentObject = new ContentObject (stream); FileName = "signature.pgp"; }
public void TestWritePerformance() { int count = 100000; Stopwatch classStopwatch = new Stopwatch(); classStopwatch.Start(); for (int i = 0; i < count; i++) { dynamic content = new ContentObject(); content.UUID = Guid.NewGuid().ToString(); content.UserKey = "userkey"; } classStopwatch.Stop(); Stopwatch dynamicStopwatch = new Stopwatch(); dynamicStopwatch.Start(); for (int i = 0; i < count; i++) { dynamic content = new TextContent(); content.UUID = Guid.NewGuid().ToString(); content.UserKey = "userkey"; } dynamicStopwatch.Stop(); Console.WriteLine("class write:{0}ms", classStopwatch.ElapsedMilliseconds); Console.WriteLine("dynamic object write:{0}ms", dynamicStopwatch.ElapsedMilliseconds); }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPgpSignature"/> /// class with a Content-Type of application/pgp-signature. /// </summary> /// <remarks> /// Creates a new MIME part with a Content-Type of application/pgp-signature /// and the <paramref name="stream"/> as its content. /// </remarks> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPgpSignature(Stream stream) : base("application", "pgp-signature") { ContentObject = new ContentObject (stream, ContentEncoding.Default); ContentDisposition = new ContentDisposition ("attachment"); ContentTransferEncoding = ContentEncoding.SevenBit; }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPkcs7Signature"/> /// class with a Content-Type of application/pkcs7-signature. /// </summary> /// <remarks> /// Creates a new MIME part with a Content-Type of application/pkcs7-signature /// and the <paramref name="stream"/> as its content. /// </remarks> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPkcs7Signature (Stream stream) : base ("application", "pkcs7-signature") { ContentDisposition = new ContentDisposition (ContentDisposition.Attachment); ContentTransferEncoding = ContentEncoding.Base64; ContentObject = new ContentObject (stream); FileName = "smime.p7s"; }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> class. /// </summary> /// <remarks> /// <para>Creates a new MIME part with a Content-Type of application/pkcs7-mime /// and the <paramref name="stream"/> as its content.</para> /// <para>Unless you are writing your own pkcs7 implementation, you'll probably /// want to use the <see cref="Compress(MimeEntity)"/>, /// <see cref="Encrypt(CmsRecipientCollection, MimeEntity)"/>, and/or /// <see cref="Sign(CmsSigner, MimeEntity)"/> method to create new instances /// of this class.</para> /// </remarks> /// <param name="type">The S/MIME type.</param> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="type"/> is not a valid value. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPkcs7Mime (SecureMimeType type, Stream stream) : base ("application", "pkcs7-mime") { ContentDisposition = new ContentDisposition ("attachment"); ContentTransferEncoding = ContentEncoding.Base64; ContentObject = new ContentObject (stream); switch (type) { case SecureMimeType.CompressedData: ContentType.Parameters["smime-type"] = "compressed-data"; ContentDisposition.FileName = "smime.p7z"; ContentType.Name = "smime.p7z"; break; case SecureMimeType.EnvelopedData: ContentType.Parameters["smime-type"] = "enveloped-data"; ContentDisposition.FileName = "smime.p7m"; ContentType.Name = "smime.p7m"; break; case SecureMimeType.SignedData: ContentType.Parameters["smime-type"] = "signed-data"; ContentDisposition.FileName = "smime.p7m"; ContentType.Name = "smime.p7m"; break; case SecureMimeType.CertsOnly: ContentType.Parameters["smime-type"] = "certs-only"; ContentDisposition.FileName = "smime.p7c"; ContentType.Name = "smime.p7c"; break; default: throw new ArgumentOutOfRangeException ("type"); } }
public void TestReadPerformance() { int count = 100000; var contentObject = new ContentObject(); contentObject.UUID = Guid.NewGuid().ToString(); contentObject.UserKey = "userkey"; Stopwatch classStopwatch = new Stopwatch(); classStopwatch.Start(); for (int i = 0; i < count; i++) { var uuid = contentObject.UUID; var userKey = contentObject.UserKey; } classStopwatch.Stop(); var dynamicContent = new TextContent(); dynamicContent.UUID = Guid.NewGuid().ToString(); dynamicContent.UserKey = "userkey"; Stopwatch dynamicStopwatch = new Stopwatch(); dynamicStopwatch.Start(); for (int i = 0; i < count; i++) { var uuid = dynamicContent.UUID; var userKey = dynamicContent.UserKey; } dynamicStopwatch.Stop(); Console.WriteLine("class read:{0}ms", classStopwatch.ElapsedMilliseconds); Console.WriteLine("dynamic object read:{0}ms", dynamicStopwatch.ElapsedMilliseconds); }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPgpEncrypted"/> class. /// </summary> /// <remarks> /// Creates a new MIME part with a Content-Type of application/pgp-encrypted /// and content matching <c>"Version: 1\n"</c>. /// </remarks> public ApplicationPgpEncrypted () : base ("application", "pgp-encrypted") { ContentDisposition = new ContentDisposition ("attachment"); ContentTransferEncoding = ContentEncoding.SevenBit; var content = new MemoryStream (Encoding.UTF8.GetBytes ("Version: 1\n"), false); ContentObject = new ContentObject (content); }
public void testParseBlockWithEmptyAttrList() { string adl = System.IO.File.ReadAllText(@"..\..\..\..\java-libs\dadl-parser\src\test\resources\state_item_list.dadl"); DADLParser parser = new DADLParser(adl); ContentObject obj = parser.parse(); AttributeValue av = (AttributeValue)obj.getAttributeValues().get(0); Assert.AreEqual("state", av.getId()); Assert.IsInstanceOfType(av.getValue(), typeof(SingleAttributeObjectBlock)); SingleAttributeObjectBlock saob = (SingleAttributeObjectBlock)av.getValue(); Assert.AreEqual(3, saob.getAttributeValues().size()); av = (AttributeValue)saob.getAttributeValues().get(2); Assert.AreEqual("items", av.getId()); ObjectBlock ob = av.getValue(); Assert.IsInstanceOfType(ob, typeof(SingleAttributeObjectBlock)); saob = (SingleAttributeObjectBlock)ob; Assert.IsTrue(saob.getAttributeValues().isEmpty()); }
public void TestSearch() { ContentObject co = FedoraControl.AddRandomObject(); try { List <string> terms = new List <string> { co.Title, co.Description }; foreach (string keyword in co.Keywords.Split(',')) { terms.Add(keyword); } foreach (string term in terms) { Assert.True(httpSearch(term, co)); } //Alter the search terms to partials Random r = new Random(); for (int i = 0; i < terms.Count; i++) { terms[i] = terms[i].Substring(0, r.Next(terms[i].Length)); } //Test single term search, partial match foreach (string term in terms) { Assert.True(httpSearch(term, co)); } //Test multiple term search Assert.True(httpSearch(String.Join(",", terms), co)); } finally { //delete the content object out of the system to maintain test atomicity new DataAccessFactory().CreateDataRepositorProxy().DeleteContentObject(co); } }
public static ContentObject AddDefaultObject() { IDataRepository dal = new DataAccessFactory().CreateDataRepositorProxy(); ContentObject dco = Default3drContentObject; dal.InsertContentObject(dco); using (FileStream fs = new FileStream(contentPath + "screenshot.png", FileMode.Open)) { dco.ScreenShotId = dal.SetContentFile(fs, dco.PID, dco.ScreenShot); } using (FileStream fs = new FileStream(contentPath + "devlogo.jpg", FileMode.Open)) { dco.DeveloperLogoImageFileNameId = dal.SetContentFile(fs, dco.PID, dco.DeveloperLogoImageFileName); } using (FileStream fs = new FileStream(contentPath + "sponsorlogo.jpg", FileMode.Open)) { dco.SponsorLogoImageFileNameId = dal.SetContentFile(fs, dco.PID, dco.SponsorLogoImageFileName); } using (FileStream fs = new FileStream(contentPath + "original_test.zip", FileMode.Open)) { dco.OriginalFileId = dal.SetContentFile(fs, dco.PID, dco.OriginalFileName); } using (FileStream fs = new FileStream(contentPath + "test.o3d", FileMode.Open)) { dco.DisplayFileId = dal.SetContentFile(fs, dco.PID, dco.DisplayFile); } using (FileStream fs = new FileStream(contentPath + "test.zip", FileMode.Open)) { dal.SetContentFile(fs, dco.PID, dco.Location); } dal.UpdateContentObject(dco); return(dco); }
public List <ContentObject> ParseContentObjects( ) { List <ContentObject> contentObjects = new List <ContentObject>(); while (MoveNext()) { ContentObject contentObject = ParseContentObject(); // Multiple-operation graphics object end? if (contentObject is EndText || // Text. contentObject is RestoreGraphicsState || // Local graphics state. contentObject is EndMarkedContent || // End marked-content sequence. contentObject is EndInlineImage) // Inline image. { return(contentObjects); } contentObjects.Add(contentObject); } return(contentObjects); }
/// <summary> /// Converts the TNEF content into a <see cref="MimeKit.MimeMessage"/>. /// </summary> /// <remarks> /// TNEF data often contains properties that map to <see cref="MimeKit.MimeMessage"/> /// headers. TNEF data also often contains file attachments which will be /// mapped to MIME parts. /// </remarks> /// <returns>A message representing the TNEF data in MIME format.</returns> /// <exception cref="System.InvalidOperationException"> /// The <see cref="MimeKit.MimePart.ContentObject"/> property is <c>null</c>. /// </exception> public MimeMessage ConvertToMessage() { if (ContentObject == null) { throw new InvalidOperationException("Cannot parse TNEF data without a ContentObject."); } int codepage = 0; if (!string.IsNullOrEmpty(ContentType.Charset)) { if ((codepage = CharsetUtils.GetCodePage(ContentType.Charset)) == -1) { codepage = 0; } } using (var reader = new TnefReader(ContentObject.Open(), codepage, TnefComplianceMode.Loose)) { return(ExtractTnefMessage(reader)); } }
private void btnRunSearch_Click(object sender, EventArgs e) { UInt32 id = 0; try { id = UInt32.Parse(txtSearchID.Text); } catch (Exception) { MessageBox.Show(this, "Error parsing search id.", "Invalid ID"); lvResults.Clear(); return; } lvResults.Clear(); ContentObject o = null; //ContentManager.Instance.FindEntry(id); if (o != null) { ListViewItem item = new ListViewItem(o.Name); item.Tag = o.Object; lvResults.Items.Add(item); } if (m_CRCList != null) { string val; if (m_CRCList.TryGetValue(id, out val)) { ListViewItem item = new ListViewItem("CRC Match: \"" + val + "\""); lvResults.Items.Add(item); } } }
protected void Rating_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(ratingText.Text)) { vwarDAL.IDataRepository vd = (new vwarDAL.DataAccessFactory()).CreateDataRepositorProxy();; var ratingValue = rating.CurrentRating; vd.InsertReview(ratingValue, ratingText.Text.Length > 255 ? ratingText.Text.Substring(0, 255) : ratingText.Text, Context.User.Identity.Name, ContentObjectID); ViewState[RATINGKEY] = null; Response.Redirect(Request.RawUrl); ContentObject co = vd.GetContentObjectById(ContentObjectID, false); if (LR_3DR_Bridge.LR_Integration_Enabled()) { LR_3DR_Bridge.ModelRated(co); } vd.Dispose(); vd = null; } }
private bool testGetData(string url, string path) { ContentObject co = FedoraControl.AddDefaultObject(); try { string clientMD5 = MD5(File.ReadAllBytes(path)), serverMD5 = ""; using (WebClient client = new WebClient()) { byte[] data = client.DownloadData(String.Format(url, co.PID)); serverMD5 = MD5(data); } return(clientMD5.Equals(serverMD5)); } finally { new DataAccessFactory().CreateDataRepositorProxy().DeleteContentObject(co); } }
public IActionResult Save([FromBody] ContentObjectViewModel model) { if (string.IsNullOrEmpty(model.Title)) { return(CreateWebResult(ResultState.Error)); } if (model.IsNew) { var content = new ContentObject { Active = true, ContentObjectType = ContentObjectType.Page, Title = model.Title, Description = model.Description, Url = model.Title.GenerateSlug(), CreatedDate = DateTime.Now, ObjectState = ObjectState.Added }; UnitOfWork.Repository <ContentObject>().SaveAllChanges(content); return(CreateWebResult(ResultState.Success, redirectUrl: "/home/list")); } else { var content = UnitOfWork.Repository <ContentObject>().Single(x => x.Id == model.Id); if (content == null) { throw new ArgumentNullException($"Not Found. Id: {content.Id}"); } content.Title = model.Title; content.Description = model.Description; content.Url = model.Title.GenerateSlug(); UnitOfWork.Repository <ContentObject>().SaveAllChanges(content); return(CreateWebResult(ResultState.Success, redirectUrl: "/home/list")); } }
private void DoSubmitAll() { vwarDAL.DataAccessFactory df = new DataAccessFactory(); vwarDAL.IDataRepository dal = df.CreateDataRepositorProxy(); IEnumerable <ContentObject> objects = dal.GetAllContentObjects(); int total = 0; int current = 0; foreach (ContentObject co in objects) { total++; } progressBar1.Maximum = total; progressBar2.Maximum = 4; foreach (ContentObject co in objects) { current++; progressBar1.Value = current; progressBar2.Value = 0; AllowUIToUpdate(); textBlock1.Text = LR_3DR_Bridge.ModelDownloadedInternal(co); progressBar2.Value = 1; AllowUIToUpdate(); ContentObject co2 = dal.GetContentObjectById(co.PID, false, true); textBlock1.Text = LR_3DR_Bridge.ModelRatedInternal(co2); progressBar2.Value = 2; AllowUIToUpdate(); textBlock1.Text = LR_3DR_Bridge.ModelUploadedInternal(co); progressBar2.Value = 3; AllowUIToUpdate(); textBlock1.Text = LR_3DR_Bridge.ModelViewedInternal(co); progressBar2.Value = 4; AllowUIToUpdate(); } }
/** * <summary>Scans a content level looking for text.</summary> */ private void Extract( ContentScanner level, IList <ContentScanner.TextStringWrapper> extractedTextStrings ) { if (level == null) { return; } while (level.MoveNext()) { ContentObject content = level.Current; if (content is Text) { // Collect the text strings! foreach (ContentScanner.TextStringWrapper textString in ((ContentScanner.TextWrapper)level.CurrentWrapper).TextStrings) { extractedTextStrings.Add(textString); } } else if (content is XObject) { // Scan the external level! Extract( ((XObject)content).GetScanner(level), extractedTextStrings ); } else if (content is ContainerObject) { // Scan the inner level! Extract( level.ChildLevel, extractedTextStrings ); } } }
private void Extract( ContentScanner level ) { if (level == null) { return; } while (level.MoveNext()) { ContentObject content = level.Current; if (content is ShowText) { textStrings.Add((TextStringWrapper)level.CurrentWrapper); } else if (content is ContainerObject) { Extract(level.ChildLevel); } } }
protected void ValidationViewSubmitButton_Click(object sender, EventArgs e) { /* if (this.FedoraContentObject == null || String.IsNullOrEmpty(this.FedoraContentObject.PID)) * { * FedoraContentObject = DAL.GetContentObjectById(ContentObjectID, false, false); ; * }*/ vwarDAL.IDataRepository dal = (new vwarDAL.DataAccessFactory()).CreateDataRepositorProxy();; FedoraContentObject = dal.GetContentObjectById(ContentObjectID, false, false); if (!string.IsNullOrEmpty(this.UnitScaleTextBox.Text)) { this.FedoraContentObject.UnitScale = this.UnitScaleTextBox.Text.Trim(); } this.FedoraContentObject.UpAxis = this.UpAxisRadioButtonList.SelectedValue.Trim(); //polygons int numPolys = 0; if (int.TryParse(NumPolygonsTextBox.Text, out numPolys)) { FedoraContentObject.NumPolygons = numPolys; } int numTextures = 0; if (int.TryParse(NumTexturesTextBox.Text, out numTextures)) { FedoraContentObject.NumTextures = numTextures; } FedoraContentObject.Enabled = true; dal.UpdateContentObject(this.FedoraContentObject); //redirect Response.Redirect(Website.Pages.Types.FormatModel(this.ContentObjectID)); dal.Dispose(); }
/// <summary> /// /// </summary> /// <returns></returns> public async Task <List <Notification> > GetNotificationsAsync() { if (!LoggedIn) { throw new NotLoggedInException(); } var response = await client.GetAsync($"/api/users/me/notif-feed?app={Constants.AppVersion}&user_id={token.UserID}&token_id={token.ID}&token_key={token.Key}"); var responseText = await response.Content.ReadAsStringAsync(); JObject obj = JObject.Parse(responseText); if (owner.CheckSuccess(obj)) { var notifs = obj["data"]["items"].AsJEnumerable(); Dictionary <long, string> users = GetUsernameMap(obj["data"]["username_map"]); List <Notification> list = new List <Notification>(); foreach (JObject n in notifs) { var notif = ContentObject.Parse <Notification>(n); if (notif.ActionUser != null) { notif.ActionUsername = users[notif.ActionUser.Value]; } list.Add(notif); } return(list); } else { return(null); } }
public static FileMediaDescriptor FromContentObject(ContentObject content) { var customFields = content.CustomFields.Aggregate(new Dictionary <string, List <string> >(), (dictionary, field) => { if (!dictionary.ContainsKey(field.FieldKey)) { dictionary.Add(field.FieldKey, new List <string>()); } dictionary[field.FieldKey].Add(field.FieldValue); return(dictionary); }); return(new FileMediaDescriptor { ContentLength = long.Parse(customFields[MediaMetadataKeys.LengthKey].First()), ContentType = customFields[MediaMetadataKeys.ContentTypeKey].First(), FileName = customFields[MediaMetadataKeys.FileNameKey].First(), StorageLocation = customFields[FileMediaMetadataKeys.StorageLocation].First(), Url = customFields[MediaMetadataKeys.UrlKey].First() }); }
/// <summary> /// Adds a content object with the same model data as default, but with randomized searchable parameters /// </summary> /// <returns>Newly inserted ContentObject</returns> public static ContentObject AddRandomObject() { IDataRepository dal = new DataAccessFactory().CreateDataRepositorProxy(); ContentObject rco = AddDefaultObject(); Random r = new Random(); rco.Title = r.Next().ToString(); rco.Description = r.Next().ToString(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { sb.Append(r.Next().ToString()); } rco.Keywords = sb.ToString().Trim(','); dal.UpdateContentObject(rco); return(rco); }
/** * <summary>Scans a content level looking for text.</summary> */ /* * NOTE: Page contents are represented by a sequence of content objects, * possibly nested into multiple levels. */ private void Extract(ContentScanner level) { if (level == null) { return; } while (level.MoveNext()) { ContentObject content = level.Current; if (content is ShowText) { Font font = level.State.Font; // Extract the current text chunk, decoding it! Console.WriteLine(font.Decode(((ShowText)content).Text)); } else if (content is Text || content is ContainerObject) { // Scan the inner level! Extract(level.ChildLevel); } } }
public void TestSupportingFile() { ContentObject co = FedoraControl.AddDefaultObject(); string filepath = ConfigurationManager.AppSettings["ContentPath"] + "\\Preconverted\\test.o3d"; using (FileStream fs = new FileStream(filepath, FileMode.Open)) { new DataAccessFactory().CreateDataRepositorProxy().AddSupportingFile(fs, co, "test.o3d", "this is a test description"); } string clientMD5 = MD5(File.ReadAllBytes(filepath)), serverMD5; string url = String.Format("{0}/{1}/SupportingFiles/test.o3d?ID={2}", _baseUrl, co.PID, _apiKey); using (WebClient client = new WebClient()) { byte[] data = client.DownloadData(url); serverMD5 = MD5(data); } Assert.AreEqual(clientMD5, serverMD5); }
/** * <summary>Gets whether the specified content stream part is blank.</summary> * <param name="level">Content stream part to evaluate.</param> * <param name="contentBox">Area to evaluate within the page.</param> */ private static bool IsBlank( ContentScanner level, RectangleF contentBox ) { if (level == null) { return(true); } while (level.MoveNext()) { ContentObject content = level.Current; if (content is ContainerObject) { // Scan the inner level! if (!IsBlank(level.ChildLevel, contentBox)) { return(false); } } else { ContentScanner.GraphicsObjectWrapper contentWrapper = level.CurrentWrapper; if (contentWrapper == null) { continue; } if (contentWrapper.Box.Value.IntersectsWith(contentBox)) { return(false); } } } return(true); }
protected void Page_Load(object sender, EventArgs e) { //maintain scroll position if (this.Page.Master.FindControl("SearchPanel") != null) { //hide the search panel this.Page.Master.FindControl("SearchPanel").Visible = false; } try { FedoraContentObject = CachedFedoraContentObject; } catch { if (!String.IsNullOrEmpty(ContentObjectID)) { vwarDAL.IDataRepository vd = (new vwarDAL.DataAccessFactory()).CreateDataRepositorProxy(); FedoraContentObject = vd.GetContentObjectById(ContentObjectID, false); vd.Dispose(); } } //redirect if user is not authenticated if (!Context.User.Identity.IsAuthenticated) { Response.Redirect(Website.Pages.Types.Default); } if (!Page.IsPostBack) { IsNew = true; var id = ContentObjectID; this.MultiView1.ActiveViewIndex = 0; this.BindCCLHyperLink(); this.BindContentObject(); ContentFileUploadRequiredFieldValidator.Enabled = IsNew; } }
protected void MissingTextureViewNextButton_Click(object sender, EventArgs e) { //get a reference to the model Utility_3D.ConvertedModel model = null;// GetModel(); foreach (Control c in MissingTextureArea.Controls) { if (c is Controls_MissingTextures) { //loop over each dialog and find out if the user uploaded a file Utility_3D.Model_Packager pack = new Utility_3D.Model_Packager(); var uploadfile = (Controls_MissingTextures)c; //if they uploaded a file, push the file and model into the dll which will add the file if (uploadfile.FileName != "") { pack.AddTextureToModel(ref model, uploadfile.FileContent, uploadfile.FileName); } } } //save the changes to the model //SetModel(model); //Get the DAL vwarDAL.IDataRepository dal = (new vwarDAL.DataAccessFactory()).CreateDataRepositorProxy();; //Get the content object for this model ContentObject contentObj = dal.GetContentObjectById(ContentObjectID, false); using (MemoryStream stream = new MemoryStream()) { //upload the modified datastream to the dal stream.Write(model.data, 0, model.data.Length); stream.Seek(0, SeekOrigin.Begin); dal.SetContentFile(stream, contentObj, contentObj.Location); } this.MultiView1.SetActiveView(this.ValidationView); dal.Dispose(); }
public void TestMetadata() { ContentObject co = FedoraControl.AddDefaultObject(); try { string url = String.Format(_baseUrl + "/{0}/Metadata/json?id={1}", co.PID, _apiKey); Metadata metadata = _serializer.Deserialize <Metadata>(getRawJSON(url)); Assert.AreEqual(co.ArtistName, metadata.ArtistName); Assert.AreEqual(co.AssetType, metadata.AssetType); Assert.AreEqual(co.Description, metadata.Description); Assert.AreEqual(co.DeveloperName, metadata.DeveloperName); Assert.AreEqual(co.Downloads.ToString(), metadata.Downloads); Assert.AreEqual(co.Format, metadata.Format); Assert.AreEqual(co.Keywords, metadata.Keywords); Assert.AreEqual(co.MissingTextures, metadata.MissingTextures); Assert.AreEqual(co.NumPolygons.ToString(), metadata.NumPolygons); Assert.AreEqual(co.NumTextures.ToString(), metadata.NumTextures); Assert.AreEqual(co.PID, metadata.PID); Assert.AreEqual(co.Revision.ToString(), metadata.Revision); Assert.AreEqual(co.SponsorName, metadata.SponsorName); Assert.AreEqual(co.SupportingFiles, metadata.SupportingFiles); Assert.AreEqual(co.TextureReferences, metadata.TextureReferences); Assert.AreEqual(co.Title, metadata.Title); Assert.AreEqual(co.NumberOfRevisions.ToString(), metadata.TotalRevisions); Assert.AreEqual(co.UnitScale, metadata.UnitScale); Assert.AreEqual(co.UpAxis, metadata.UpAxis); Assert.AreEqual(co.UploadedDate.ToString(), metadata.UploadedDate); Assert.AreEqual(co.Views.ToString(), metadata.Views); } finally { new DataAccessFactory().CreateDataRepositorProxy().DeleteContentObject(co); } }
protected override void ShowSelectedEntry() { ContentManager mgr = ContentManager.Instance; ContentObject obj = mgr.FindEntry( LinkDestination.GameBINEntryName, Selected.Name); if (obj != null) { // Open the model. DefinitionType defType = mgr.Definitions.GetDefinition( Selected.Definition); if (defType != null) { defType.ReadIn(Selected); FableMod.ContentManagement.Control c = defType.FindControl(0xC8636B2E); if (c != null && c.Members.Count == 5) { Member m = (Member)c.Members[1]; mgr.ShowEntry( LinkDestination.ModelID, m.Value, true); } c = null; defType = null; } } }
/// <summary> /// /// </summary> /// <param name="rantId"></param> /// <returns></returns> public async Task <Rant> GetRant(long rantId) { string url = MakeUrl(Constants.PathRants + rantId); var response = await client.GetAsync(url); var responseText = await response.Content.ReadAsStringAsync(); JObject tmp = JObject.Parse(responseText); if (CheckSuccess(tmp)) { Rant r = ContentObject.Parse <Rant>(tmp["rant"] as JObject); JArray comments = tmp["comments"] as JArray; List <Comment> list = new List <Comment>(); if (comments != null) { foreach (JObject o in comments) { Comment c = ContentObject.Parse <Comment>(o); list.Add(c); } r.Comments = list; } return(r); } else { return(null); } }
public void Update() { if (ContentObject.GetType().GetProperty(PropertyName) != null) { Text = PrependText + ContentObject.GetType().GetProperty(PropertyName).GetValue(ContentObject, null).ToString() + AppendText; } Vector2 size = Font.MeasureString(Text); switch (Alignment) { case (Justification.Left): Origin = new Vector2(0); break; case (Justification.Right): Origin = new Vector2(size.X, 0); break; case (Justification.Center): Origin = new Vector2(size.X / 2, 0); break; } }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> class. /// </summary> /// <remarks> /// <para>Creates a new MIME part with a Content-Type of application/pkcs7-mime /// and the <paramref name="stream"/> as its content.</para> /// <para>Unless you are writing your own pkcs7 implementation, you'll probably /// want to use the <see cref="Compress(MimeEntity)"/>, /// <see cref="Encrypt(CmsRecipientCollection, MimeEntity)"/>, and/or /// <see cref="Sign(CmsSigner, MimeEntity)"/> method to create new instances /// of this class.</para> /// </remarks> /// <param name="type">The S/MIME type.</param> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="type"/> is not a valid value. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPkcs7Mime(SecureMimeType type, Stream stream) : base("application", "pkcs7-mime") { ContentDisposition = new ContentDisposition("attachment"); ContentTransferEncoding = ContentEncoding.Base64; ContentObject = new ContentObject(stream); switch (type) { case SecureMimeType.CompressedData: ContentType.Parameters["smime-type"] = "compressed-data"; ContentDisposition.FileName = "smime.p7z"; ContentType.Name = "smime.p7z"; break; case SecureMimeType.EnvelopedData: ContentType.Parameters["smime-type"] = "enveloped-data"; ContentDisposition.FileName = "smime.p7m"; ContentType.Name = "smime.p7m"; break; case SecureMimeType.SignedData: ContentType.Parameters["smime-type"] = "signed-data"; ContentDisposition.FileName = "smime.p7m"; ContentType.Name = "smime.p7m"; break; case SecureMimeType.CertsOnly: ContentType.Parameters["smime-type"] = "certs-only"; ContentDisposition.FileName = "smime.p7c"; ContentType.Name = "smime.p7c"; break; default: throw new ArgumentOutOfRangeException("type"); } }
/// <summary> /// Initializes this instance. /// </summary> public bool TryRunFrontMatter(IFrontMatter frontMatter, ContentObject obj) { if (frontMatter == null) { throw new ArgumentNullException(nameof(frontMatter)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } var context = new TemplateContext(Builtins); context.PushGlobal(obj); try { context.EnableOutput = false; context.TemplateLoader = new TemplateLoaderFromIncludes(Site); Site.SetValue(PageVariables.Site, this, true); frontMatter.Evaluate(context); } catch (ScriptRuntimeException exception) { LogException(exception); return(false); } finally { context.PopGlobal(); // We don't keep the site variable after this initialization Site.Remove(PageVariables.Site); } return(true); }
/// <summary> /// Requests a collection of stories sorted and selected by the arguments from the rest-api. /// </summary> /// <inheritdoc /> public async Task <IReadOnlyCollection <Rant> > GetStoriesAsync(RantSort sort = RantSort.Top, RantRange range = RantRange.Day, int limit = 50, int skip = 0) { var sortText = sort.ToString().ToLower(); var rangeText = range.ToString().ToLower(); string url = owner.MakeUrl("/api/devrant/story-rants", new Parameters() { { "range", rangeText }, { "sort", sortText }, { "limit", limit.ToString() }, { "skip", skip.ToString() }, }); var response = await client.GetAsync(url); var responseText = await response.Content.ReadAsStringAsync(); JObject tmp = JObject.Parse(responseText); if (owner.CheckSuccess(tmp)) { List <Rant> rants = new List <Rant>(); foreach (JObject obj in tmp["rants"].Children()) { var r = ContentObject.Parse <Rant>(obj); rants.Add(r); } return(rants); } else { return(null); } }
public override ContentObject ToInlineObject(PrimitiveComposer composer) { ContentObject barcodeObject = composer.BeginLocalState(); { fonts::Font font = fonts::PdfType1Font.Load(composer.Scanner.Contents.Document, fonts::PdfType1Font.FamilyEnum.Helvetica, false, false); double fontSize = (DigitGlyphWidth / font.GetWidth(code.Substring(0, 1), 1)); // 1. Bars. { double elementX = DigitWidth; int[] elementWidths = GetElementWidths(); double guardBarIndentY = DigitHeight / 2; bool isBar = true; for (int elementIndex = 0; elementIndex < elementWidths.Length; elementIndex++) { double elementWidth = elementWidths[elementIndex]; // Dark element? /* * NOTE: EAN symbol elements alternate bars to spaces. */ if (isBar) { composer.DrawRectangle( SKRect.Create( (float)elementX, 0, (float)elementWidth, (float)(BarHeight + ( // Guard bar? Array.BinarySearch <int>(GuardBarIndexes, elementIndex) >= 0 ? guardBarIndentY // Guard bar. : 0 // Symbol character. )) ) ); } elementX += elementWidth; isBar = !isBar; } composer.Fill(); } // 2. Digits. { composer.SetFont(font, fontSize); double digitY = BarHeight + (DigitHeight - (font.GetAscent(fontSize))) / 2; // Showing the digits... for (int digitIndex = 0; digitIndex < 13; digitIndex++) { string digit = code.Substring(digitIndex, 1); double pX = DigitGlyphXs[digitIndex] // Digit position. - font.GetWidth(digit, fontSize) / 2; // Centering. // Show the current digit! composer.ShowText( digit, new SKPoint((float)pX, (float)digitY) ); } } composer.End(); } return(barcodeObject); }
public static string SubmitUpload(string DeveloperName, string ArtistName, string DeveloperUrl, string SponsorName, string LicenseType, bool RequireResubmit) { HttpServerUtility server = HttpContext.Current.Server; ContentObject tempCO = (ContentObject)HttpContext.Current.Session["contentObject"]; try { FileStatus status = (FileStatus)HttpContext.Current.Session["fileStatus"]; var factory = new DataAccessFactory(); IDataRepository dal = factory.CreateDataRepositorProxy(); dal.InsertContentObject(tempCO); tempCO.DeveloperName = server.HtmlEncode(DeveloperName); tempCO.ArtistName = server.HtmlEncode(ArtistName); tempCO.MoreInformationURL = server.HtmlEncode(DeveloperUrl); tempCO.RequireResubmit = RequireResubmit; tempCO.SponsorName = server.HtmlEncode(SponsorName); vwarDAL.PermissionsManager perMgr = new PermissionsManager(); var groupSetReturnCode = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AllUsers, ModelPermissionLevel.Fetchable); groupSetReturnCode = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AnonymousUsers, ModelPermissionLevel.Searchable); string pid = tempCO.PID; //tempCO.SponsorURL = SponsorUrl; !missing SponsorUrl metadata in ContentObject if (LicenseType == "publicdomain") { tempCO.CreativeCommonsLicenseURL = "http://creativecommons.org/publicdomain/mark/1.0/"; } else { tempCO.CreativeCommonsLicenseURL = String.Format(ConfigurationManager.AppSettings["CCBaseUrl"], LicenseType); } //Upload the thumbnail and logos string filename = status.hashname; string basehash = filename.Substring(0, filename.LastIndexOf(".") - 1); foreach (FileInfo f in new DirectoryInfo(HttpContext.Current.Server.MapPath("~/App_Data/imageTemp")).GetFiles("*" + basehash + "*")) { using (FileStream fstream = f.OpenRead()) { string type = f.Name.Substring(0, f.Name.IndexOf('_')); switch (type) { case ImagePrefix.DEVELOPER_LOGO: tempCO.DeveloperLogoImageFileName = "developer_logo" + f.Extension; tempCO.DeveloperLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.DeveloperLogoImageFileName); break; case ImagePrefix.SPONSOR_LOGO: tempCO.SponsorLogoImageFileName = "sponsor_logo" + f.Extension; tempCO.SponsorLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.SponsorLogoImageFileName); break; case ImagePrefix.SCREENSHOT: tempCO.ScreenShot = "screenshot" + f.Extension; tempCO.ScreenShotId = dal.SetContentFile(fstream, tempCO.PID, tempCO.ScreenShot); System.Drawing.Imaging.ImageFormat fmt = System.Drawing.Imaging.ImageFormat.Png; if (f.Extension == ".png") { fmt = System.Drawing.Imaging.ImageFormat.Png; } else if (f.Extension == ".jpg") { fmt = System.Drawing.Imaging.ImageFormat.Jpeg; } else if (f.Extension == ".gif") { fmt = System.Drawing.Imaging.ImageFormat.Gif; } else { throw new Exception("Invalid screenshot format"); } tempCO.ThumbnailId = Website.Common.GetFileSHA1AndSalt(fstream) + f.Extension; using (FileStream outFile = new FileStream(HttpContext.Current.Server.MapPath("~/thumbnails/" + tempCO.ThumbnailId), FileMode.Create)) Website.Common.GenerateThumbnail(fstream, outFile, fmt); break; default: break; } } } string dataPath = HttpContext.Current.Server.MapPath("~/App_Data/"); if (status.type == FormatType.VIEWABLE) { //Upload the original file using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open)) { tempCO.OriginalFileId = dal.SetContentFile(s, pid, "original_" + status.filename); tempCO.OriginalFileName = "original_" + status.filename; } using (FileStream s = new FileStream(Path.Combine(dataPath, "converterTemp/" + status.hashname.ToLower().Replace("skp", "zip")), FileMode.Open, FileAccess.Read)) { tempCO.DisplayFileId = dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "zip")); } using (FileStream s = new FileStream(Path.Combine(dataPath, "viewerTemp/" + status.hashname.ToLower().Replace("skp", "o3d").Replace("zip", "o3d")), FileMode.Open)) { dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "o3d").Replace("zip", "o3d")); } } else if (status.type == FormatType.RECOGNIZED) { using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open)) { tempCO.OriginalFileName = "original_" + status.filename; tempCO.OriginalFileId = dal.SetContentFile(s, pid, tempCO.OriginalFileName); } } tempCO.Enabled = true; tempCO.UploadedDate = DateTime.Now; dal.UpdateContentObject(tempCO); UploadReset(status.hashname); List <string> textureReferences = HttpContext.Current.Session["contentTextures"] as List <string>; List <string> textureReferenceMissing = HttpContext.Current.Session["contentMissingTextures"] as List <string>; if (textureReferences != null) { foreach (string tex in textureReferences) { tempCO.SetParentRepo(dal); tempCO.AddTextureReference(tex, "unknown", 0); } } if (textureReferenceMissing != null) { foreach (string tex in textureReferenceMissing) { tempCO.SetParentRepo(dal); tempCO.AddMissingTexture(tex, "unknown", 0); } } if (LR_3DR_Bridge.LR_Integration_Enabled()) { LR_3DR_Bridge.ModelUploaded(tempCO); } Website.Mail.SendModelUploaded(tempCO); dal.Dispose(); perMgr.Dispose(); return(tempCO.PID); } catch (Exception e) { #if DEBUG return(String.Format("fedoraError|" + e.Message + "<br /><br />" + e.StackTrace)); #else return("fedoraError|" + ConfigurationManager.AppSettings["UploadPage_FedoraError"]); #endif } }
public static ContentObject CreateContentObject(int id, string title, string description, global::System.DateTime uploadedDate, global::System.DateTime lastModified, string location, int views, global::System.DateTime lastViewed, int downloads) { ContentObject contentObject = new ContentObject(); contentObject.Id = id; contentObject.Title = title; contentObject.Description = description; contentObject.UploadedDate = uploadedDate; contentObject.LastModified = lastModified; contentObject.Location = location; contentObject.Views = views; contentObject.LastViewed = lastViewed; contentObject.Downloads = downloads; return contentObject; }
public void AddToContentObject(ContentObject contentObject) { base.AddObject("ContentObject", contentObject); }