WordPress XML RPC Upload Image C# - c#

Hey all, I am developing a site for work that will push info from a database into Wordpress using Wordpress XML RPC. I can grab info and post it just fine, however when I get to the point of uploading images it seems to work(no runtime errors/image in WP Media Tab) however it uploads a broken image link. It appears it is somehow no getting the data from my image and I am not certain why here is some of my code.
MemoryStream ms = new MemoryStream();
System.Drawing.Image img = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("_Images/DownloadButton-PSD.png"));
img.Save(ms, ImageFormat.Png);
byte[] imagebytes = new byte[ms.Length];
ms.Position = 0;
ms.Read(imagebytes, 0, Convert.ToInt32(ms.Length));
after that code loads the image info I pass it to the function in the format of a Data variable
var data = new Data
{
Base64 = Convert.ToBase64String(imagebytes),
Name = "DownloadButton-PSD.png",
Type = "image/png",
Overwrite = false,
};
_wpWrapper.UploadFile(data);
FYI: I am also using the dll's from
http://joeblogs.codeplex.com/
for my project
The Data Class looks like this:
public class Data
{
public string Name { get; set; }
public string Type { get; set; }
public string Base64 { get; set; }
public bool Overwrite { get; set; }
}
The Upload File Function looks like this:
public void UploadFile(Data data)
{
var xmlRpcData = Map.From.Data(data);
var result = _wrapper.UploadFile(this.BlogID, Username, Password, xmlRpcData);
}

In JoeBlogs library try using the class MetaWeblogWrapper and method: MediaObjectInfo NewMediaObject(MediaObject mediaObject) - for upload image.

Related

assigning Youtube api Thumbnail to datatype c#

trying to assign youtube thumbnail I receive from youtube api to a datatype or something of some sort so it can be passed through my system and appear in a image box on my website
have tried using system.drawing.bitmap and system.drawing.image and get error:
'cannot implicitly convert type'
foreach (var playlistItem in playlistItemsListResponse.Items)
{
// Print information about each video.
//Console.WriteLine("{0} ({1})",playlistItem.Snippet.Thumbnails, playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
playlistItem.Snippet.ResourceId.VideoId = vidDetails.vidId;
playlistItem.Snippet.Title= vidDetails.vidTitle;
playlistItem.Snippet.Thumbnails = vidDetails.vidThumb;
}
video details:
public string vidId { get; set; }
public string vidTitle { get; set; }
public string vidDesc { get; set; }
public string vidTags { get; set; }
public System.Drawing.Bitmap vidThumb { get; set; }
display:
protected void Page_Load(object sender, EventArgs e) {
Video_details vidDetails = new Video_details();
uploaded_videos uploadedVids = new uploaded_videos();
new uploaded_videos().Run(vidDetails).Wait();
vidDetails.vidThumb = imgVid1....
}
}
Try using PictureBox.Load("https://i.ytimg.com/vi/abcdefghijk/default.jpg") from the PictureBox.Load method in C#.
You can also use the method provided in this SO thread:
var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
pictureBox1.Image = Bitmap.FromStream(stream);
}
snippet.thumbnails property is an object that identifies the thumbnail images available for that resource.A thumbnail resource contains a series of objects. The name of each object (default, medium, high, etc.) refers to the thumbnail image size.
item.Snippet.Thumbnails.Default__.Url
will give you the address of default thumbnail image by accessing which you can use Image and assign it to the local variables and vice versa.

Asp.net - adding function to class

I have a code-first Entity Framework class that looks like this:
public class Image
{
public int ImageID { get; set; }
public string DataType { get; set; }
public int Size { get; set; }
public byte[] Content { get; set; }
}
I have written several lines of code in a controller that receives a IFormFile and then extracts the file data and reads it into an Image:
var content = formFile.OpenReadStream();
byte[] buf = new byte[content.Length];
content.Read(buf, 0, buf.Length);
var newImg = new Image();
newImg.Content = buf;
newImg.DataType = formFile.ContentType;
Since this code is re-used wherever an image is being uploaded, I would like to somehow encapsulate it as a 'SaveUpload' function. It will be used in various controllers across the solution.
Is the best way to add this as a {set;} only non-mapped property to the Image class/table?
Or do I somehow encapsulate or inherit this property (sorry, I am still learning OOP terms)?
You may want to consider creating an UploadService class to encapsulate this logic. Neither the controller(s), nor the Image class should really be aware of these details and by abstracting it into a service you will likely find that the code is more readable and easier to maintain.
UploadService:
public class UploadService
{
public void SaveUpload(IFormFile formFile)
{
var content = formFile.OpenReadStream();
byte[] buf = new byte[content.Length];
content.Read(buf, 0, buf.Length);
var newImg = new Image();
newImg.Content = buf;
newImg.DataType = formFile.ContentType;
//insert newImg...
}
}
I would even consider taking it one step further by injecting this service into your controllers using a dependency injection framework like Unity or Ninject, which will allow you to isolate the service for unit testing.
You could do something like
public class Image
{
public int ImageID { get; set; }
public string DataType { get; set; }
public int Size { get; set; }
public byte[] Content { get; set;
public static Image SaveUpload(IFormFile formFile) {
var newImage = new Image();
var content = formFile.OpenReadStream();
byte[] buf = new byte[content.Length];
content.Read(buf, 0, buf.Length);
var newImg = new Image();
newImg.Content = buf;
newImg.DataType = formFile.ContentType;
return newImage;
}
}
Save with
var image = Image.SaveUpload(formFile);
Inside your class do next step:
public static void YourMethod(/*parameters, if you need them*/){
var content = formFile.OpenReadStream();
byte[] buf = new byte[content.Length];
content.Read(buf, 0, buf.Length);
var newImg = new Image();
newImg.Content = buf;
newImg.DataType = formFile.ContentType;
}
It's possible to add normal static function, but for good practic: POCO class should't have any logic expect fields. Better way is to create other class, f.e: UploadService which method: Save(Image image). Your choice.

How to pass image to a default image to database as byte array in C# WCF

I'm developing a system that use Entity Framework Code First technology for data base creation and, I need to store an image file to the database using this. I have done this but have a problem when there is no image file selected.
So I need to know, how to pass a default image file to the db if no image selected, (let's think i have no default image in my hard drive, so by default code need to generate the image file any how).
I'm using layered architecture,
1.Entity Layer - for code first db creation
2.Data Access Layer - for accessing db and all the db related methods are here
3.Business Logic layer - for connecting interface with data access layer
4.Presentation Layer - for interface designing
codes on 1,2,3 has completed as follows,
-------Entity-------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BisCare.BMS.Entity
{
public class RentingGood
{
public RentingGood() { }
public Guid RentingGoodId { get; set; }
public string RentingGoodName { get; set; }
public bool RentingGoodStatus { get; set; }
public byte[] RentingGoodImage { get; set; }
public virtual Category Category { get; set; }
public virtual Company Company { get; set; }
public virtual ICollection<RentingGoodsStock> RentingGoodsStocks { get; set; }
}
}
------- Data access-------
public bool AddRentingGoodData(string name, string catName, byte[] image)
{
try
{
Guid catGuid = new Guid();
using (EntityModel model = new EntityModel())
{
var CatId = from b in model.Categories
where b.CategoryName == catName
select b;
foreach (var x in CatId)
{
catGuid = x.CategoryId;
}
Category category = model.Categories.Find(catGuid);
RentingGood newGood = new RentingGood() { RentingGoodId = Guid.NewGuid(), RentingGoodName = name, Category = category, RentingGoodStatus = true,RentingGoodImage = image };
model.RentingGoods.Add(newGood);
model.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
You could simply generate a standard image at runtime:
Bitmap standardImage = new Bitmap(200, 200);
Graphics standardGraphics = Graphics.FromImage(standardImage);
int red = 0;
int white = 10;
while (white <= 200)
{
standardGraphics.FillRectangle(Brushes.Red, 0, red, 200, 10);
standardGraphics.FillRectangle(Brushes.White, 0, white, 200, 10);
red += 20;
white += 20;
}
//This will be your byte array
byte[] result = ConvertImageToByteArray(standardImage);
This example above draws a red white flag. More examples and tutorials about drawing in C# can be foun here.
I made the method ConvertImageToByteArray to convert the image to a byte array which can be saved in the database which looks like this:
public byte[] ConvertImageToByteArray(System.Drawing.Image image)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
return ms.ToArray();
}
}
It would be better if you could save the generated byte array somewhere. Then you don't need to regenerate the image everytime someone don't upload an image.

Get file information from System.Web.HttpInputStream

I have code:
public Upload.UploadResponse Post(Upload.UploadRequest request)
{
Stream str = request.RequestStream; // RequestStream is System.Web.HttpInputStream
byte[] result;
using (var streamReader = new MemoryStream())
{
str.CopyTo(streamReader);
result = streamReader.ToArray();
}
return new Upload.UploadResponse() { Successed = 1 };
}
Is there any way to get file name ( with extension) from MemoryStream or stream or System.Web.HttpInputStream (part of Upload.UploadRequest request) without saving the file? I need to recognize the file without knowing what is sent to me. I've tried to cast it to FileStream but it was null. Service framework that I am using is service stack ServiceStack
edit: Maybe I need to send file info with request?
p.s sorry for my poor English any corrections are welcome
EDIT:
this is UploadClass that I am using for code above
public class Upload
{
[Route("/upload")]
public class UploadRequest : IRequiresRequestStream
{
public System.IO.Stream RequestStream { set; get; }
}
public class UploadResponse
{
public int Successed { set; get; }
}
}
You cannot extract file name from stream.
You need to add FileName property to your request.

Serialize and Store an Image in an XML File

Got a little bit of a problem. I have a program that builds an observable collection of Users. The User has a Firstname, Lastname, and Image. I can add the user to the observable collection, but I also want to save the collection and load it everytime I reopen the program.
My problem is that while its fairly easy to save a firstname and lastname, the writer can't write the image to the xml file. Is there any way around this?
Here's what I have so far:
the observable collection:
ObservableCollection<VendorClass> ProfileList = new ObservableCollection<VendorClass>();
the problematic writer:
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<VendorClass>));
using (StreamWriter wr = new StreamWriter("vendors.xml")) //Data/customers.xml
{
xs.Serialize(wr, ProfileList);
}
Any ideas? And if there does exist a solution to write in an image, is there a viable way to read it out again?
XmlSerializer can't serialize or deserialize the WPF image types like BitmapImage etc. It is however able to (de)serialize byte arrays. So you may add a byte[] ImageBuffer property to your Person class, which contains the binary image data. You would then also set the XmlIgnore attribute on the Image property to suppress its (de)serialization, and set XmlElement("Image") on the ImageBuffer properties to (de)serialize it as <Image>...</Image>.
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
[XmlIgnore]
public BitmapSource Image { get; set; }
[XmlElement("Image")]
public byte[] ImageBuffer
{
get
{
byte[] imageBuffer = null;
if (Image != null)
{
using (var stream = new MemoryStream())
{
var encoder = new PngBitmapEncoder(); // or some other encoder
encoder.Frames.Add(BitmapFrame.Create(Image));
encoder.Save(stream);
imageBuffer = stream.ToArray();
}
}
return imageBuffer;
}
set
{
if (value == null)
{
Image = null;
}
else
{
using (var stream = new MemoryStream(value))
{
var decoder = BitmapDecoder.Create(stream,
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
Image = decoder.Frames[0];
}
}
}
}
}
This approach has also been suggested for properties of type Bitmap in this answer.
You would base64 encode the image to convert it to a string and then write that into a CDATA section. See How do you serialize a string as CDATA using XmlSerializer?

Categories