I have code like this:
public class Paket
{
public int PaketID { get { return _PaketID; } set { _PaketID = value; } }
public int ProizvodID { get { return _ProizvodID; } set { _ProizvodID = value; } }
public double Kolicina { get { return _Kolicina; } set { _Kolicina = value; } }
public double CenaBezPdv { get { return _CenaBezPdv; } set { _CenaBezPdv = value; } }
private int _PaketID;
private int _ProizvodID;
private double _Kolicina;
private double _CenaBezPdv;
public string _errorMessage { get; set; }
private Paket()
{
}
public Paket(int proizvodID)
{
if (proizvodID == null) { throw new Exception("ProizvodID ne moze biti NULL!"); }
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string url = "https://www.new.termodom.rs/Php/Proizvodi/Paketi/GetOne.php?proizvodid=" + proizvodID;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
_errorMessage = "Paket nije pronadjen u web bazi!";
break;
default:
Paket p = JsonConvert.DeserializeObject<Paket>(resp);
this._PaketID = p.PaketID;
this._ProizvodID = p.ProizvodID;
this._Kolicina = p.Kolicina;
this._CenaBezPdv = p.CenaBezPdv;
break;
}
}
public static List<Paket> SviPaketi(int ProizvodID)
{
List<Paket> list = new List<Paket>();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string url = "https://www.new.termodom.rs/Php/Proizvodi/Paketi/GetAll.php?proizvodid=" + ProizvodID;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
break;
default:
list = JsonConvert.DeserializeObject<List<Paket>>(resp);
break;
}
return list;
}
}
When i run function like this List<Proizvod> myList = Proizvod.SviPaketi(139) i am getting some error (i do not know now which one it was but it is not important for my question).
When i started debugging i saw that JsonConvert.DeserializeObject<List<Paket>>(resp); doesn't enter only private Paket() which is empty but public Paket(int proizvodID) which has some code inside it.
So my question is why did JsonConvert.DeserializeObject<List<Paket>>(resp); triggered public Paket(int proizvodID) when i haven't passed any parameter to it?
JSON de-serializer will prefer a public constructor. You can however make it use the private constructor using a ConstructorHandling. Check this example
Related
As the title says, my empty itself in middle of code.
I do not do any background/thread work so it couldn't empty itself in middle of executing code. It empty itself on one particular point every time.
ObservableCollection is proizvod.GrupeIPodgrupe in my case
Here is where it happens:
private void NamestiGrupeIPodgrupe()
{
foreach (TreeNode n in treeView1.Nodes)
{
if (proizvod.GrupeIPodGrupe.Grupe.Any(g => g.Id == (int)n.Tag))
{
n.Checked = true;
foreach (TreeNode n1 in n.Nodes) //Here it empty
{
if (proizvod.GrupeIPodGrupe.Podgrupe.Any(pg => pg.PodGrupaId == (int)n1.Tag))
{
n1.Checked = true;
}
}
}
else
n.Checked = false;
}
}
Here are images when I debug it step by step:
Here is full code of my Form class where this problem is happening:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Magacin.Sajt;
namespace Magacin
{
public partial class Sajt_Proizvod : Form
{
private Proizvod proizvod;
private Komercijalno.Roba roba;
public Sajt_Proizvod(int proizvodID)
{
InitializeComponent();
UcitajGrupeIPodgrupe();
this.roba = new Komercijalno.Roba(proizvodID);
UcitajProizvod(proizvodID);
k_jm_txt.Text = roba.Jm;
k_katBr_txt.Text = roba.KatBr;
k_naziv_txt.Text = roba.Naziv;
k_pdv_txt.Text = String.Format("{0:#.00}%", roba.Pdv);
k_robaid_txt.Text = roba.RobaId.ToString();
NamestiGrupeIPodgrupe();
}
private void PodesiPremaPravima()
{
if (!Korisnik.ImaPravo(200103))
{
w_naziv_txt.Enabled = false;
w_naziv_txt.BackColor = SystemColors.Info;
slika_txt.Enabled = false;
slika_txt.BackColor = SystemColors.Info;
w_opis_rtxt.Enabled = false;
w_opis_rtxt.BackColor = SystemColors.Info;
akcijskiArtikal_cb.Enabled = false;
akcijskiArtikal_cb.BackColor = SystemColors.Info;
aktivan_cb.Enabled = false;
aktivan_cb.BackColor = SystemColors.Info;
button2.BackColor = SystemColors.Info;
}
else
{
w_naziv_txt.Enabled = true;
w_naziv_txt.BackColor = SystemColors.Window;
slika_txt.Enabled = true;
slika_txt.BackColor = SystemColors.Window;
w_opis_rtxt.Enabled = true;
w_opis_rtxt.BackColor = SystemColors.Window;
akcijskiArtikal_cb.Enabled = true;
akcijskiArtikal_cb.BackColor = SystemColors.Window;
aktivan_cb.Enabled = true;
aktivan_cb.BackColor = SystemColors.Window;
}
}
private void NamestiGrupeIPodgrupe()
{
foreach (TreeNode n in treeView1.Nodes)
{
if (proizvod.GrupeIPodGrupe.Grupe.Any(g => g.Id == (int)n.Tag))
{
n.Checked = true;
foreach (TreeNode n1 in n.Nodes)
{
if (proizvod.GrupeIPodGrupe.Podgrupe.Any(pg => pg.PodGrupaId == (int)n1.Tag))
{
n1.Checked = true;
}
}
}
else
n.Checked = false;
}
}
private void UcitajProizvod()
{
proizvod = new Proizvod(proizvod.PROIZVODID);
w_proizvodId_txt.Text = proizvod.PROIZVODID.ToString();
w_naziv_txt.Text = proizvod.NAZIV.ToString();
w_katBr_txt.Text = proizvod.KATBR.ToString();
w_pdv_txt.Text = String.Format("{0}%", proizvod.PDV);
w_jm_txt.Text = proizvod.JM.ToString();
slika_txt.Text = proizvod.SLIKA.ToString();
kratakOpis_txt.Text = proizvod.KratakOpis;
w_opis_rtxt.Text = proizvod.OPIS;
akcijskiArtikal_cb.Checked = (proizvod.AKCIJSKI_ARTIKAL == 1) ? true : false;
aktivan_cb.Checked = (proizvod.AKTIVAN == 1) ? true : false;
}
private void UcitajProizvod(int poizvodId)
{
proizvod = new Proizvod(poizvodId);
w_proizvodId_txt.Text = proizvod.PROIZVODID.ToString();
w_naziv_txt.Text = proizvod.NAZIV.ToString();
w_katBr_txt.Text = proizvod.KATBR.ToString();
w_pdv_txt.Text = String.Format("{0}%", proizvod.PDV);
w_jm_txt.Text = proizvod.JM.ToString();
slika_txt.Text = proizvod.SLIKA.ToString();
kratakOpis_txt.Text = proizvod.KratakOpis;
w_opis_rtxt.Text = proizvod.OPIS;
akcijskiArtikal_cb.Checked = (proizvod.AKCIJSKI_ARTIKAL == 1) ? true : false;
aktivan_cb.Checked = (proizvod.AKTIVAN == 1) ? true : false;
}
private void UcitajGrupeIPodgrupe()
{
List<Grupa> grupe = Grupa.ListaSvihGrupa();
foreach(Grupa gp in grupe)
{
TreeNode tn = new TreeNode(gp.Naziv);
List<PodGrupa> pg = PodGrupa.ListaSvihPodgrupa(gp.Id);
if(pg != null && pg.Count > 0)
{
foreach(PodGrupa pgp in pg)
{
TreeNode tn1 = new TreeNode(pgp.Naziv);
tn1.Tag = pgp.PodGrupaId;
tn1.ToolTipText = "PodGrupa";
tn.Nodes.Add(tn1);
}
}
tn.Tag = gp.Id;
tn.ToolTipText = "Grupa";
treeView1.Nodes.Add(tn);
}
}
private void sacuvaj_btn_Click(object sender, EventArgs e)
{
if (Korisnik.ImaPravo(200103))
{
proizvod.Update();
MessageBox.Show(proizvod.errorMessage);
}
else
{
MessageBox.Show("Nemate pravo pristupa modulu [ 200103 ] ");
}
}
private void odbaci_btn_Click(object sender, EventArgs e)
{
UcitajProizvod();
}
private void novi_btn_Click(object sender, EventArgs e)
{
using (Sajt_NoviProizvod np = new Sajt_NoviProizvod())
{
np.ShowDialog();
}
}
private void w_naziv_txt_TextChanged(object sender, EventArgs e)
{
proizvod.NAZIV = w_naziv_txt.Text;
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void w_jm_txt_TextChanged(object sender, EventArgs e)
{
proizvod.JM = w_jm_txt.Text;
}
private void w_opis_rtxt_TextChanged(object sender, EventArgs e)
{
proizvod.OPIS = w_opis_rtxt.Text;
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void akcijskiArtikal_cb_CheckedChanged(object sender, EventArgs e)
{
proizvod.AKCIJSKI_ARTIKAL = Convert.ToInt32(akcijskiArtikal_cb.Checked);
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void aktivan_cb_CheckedChanged(object sender, EventArgs e)
{
proizvod.AKTIVAN = Convert.ToInt32(aktivan_cb.Checked);
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
using (Sajt_Paketi sp = new Sajt_Paketi(proizvod.PROIZVODID))
{
sp.ShowDialog();
}
}
private void slika_txt_TextChanged(object sender, EventArgs e)
{
proizvod.SLIKA = slika_txt.Text;
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void kratakOpis_txt_TextChanged(object sender, EventArgs e)
{
proizvod.KratakOpis = kratakOpis_txt.Text;
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Node.Parent != null)
{
if (e.Node.Parent.Parent != null)
{
e.Node.Parent.Parent.Checked = true;
}
e.Node.Parent.Checked = true;
}
if (e.Node.Tag.ToString() == "Grupa")
{
foreach (TreeNode tn in e.Node.Nodes)
{
tn.Checked = false;
}
}
ProveriGrupeIPodgrupe();
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void ProveriGrupeIPodgrupe()
{
proizvod.GrupeIPodGrupe.Reset();
foreach (TreeNode tn in treeView1.Nodes)
{
if (tn.Checked)
{
foreach (TreeNode tn1 in tn.Nodes)
{
if (tn1.Checked)
{
proizvod.GrupeIPodGrupe.Podgrupe.Add(new PodGrupa { PodGrupaId = Convert.ToInt32(tn1.Tag), GrupaId = Convert.ToInt32(tn.Tag) });
}
}
}
}
}
private void odbaci_btn_EnabledChanged(object sender, EventArgs e)
{
if (odbaci_btn.Enabled)
odbaci_btn.BackColor = Color.White;
else
odbaci_btn.BackColor = Color.DimGray;
}
private void sacuvaj_btn_EnabledChanged(object sender, EventArgs e)
{
if (sacuvaj_btn.Enabled)
sacuvaj_btn.BackColor = Color.White;
else
sacuvaj_btn.BackColor = Color.DimGray;
}
}
}
Here is my Proizvod class
public class Proizvod
{
#region Variables
public int PROIZVODID { get { return _PROIZVODID; } set { _PROIZVODID = value; } }
public string NAZIV { get { return _NAZIV; } set { _NAZIV = value; } }
public string OPIS { get { return _OPIS; } set { _OPIS = value; } }
public string JM { get { return _JM; } set { _JM = value; } }
public int AKCIJSKI_ARTIKAL { get { return _AKCIJSKI_ARTIKAL; } set { _AKCIJSKI_ARTIKAL = value; } }
public int AKTIVAN { get { return _AKTIVAN; } set { _AKTIVAN = value; } }
public string KATBR { get { return _KATBR; } set { _KATBR = value; } }
public double PDV { get { return _PDV; } set { _PDV = value; } }
public string SLIKA { get { return _SLIKA; } set { _SLIKA = value; } }
public string KratakOpis { get { return _KratakOpis; } set { _KratakOpis = value; } }
public GrupeIPodgrupe GrupeIPodGrupe { get { return _GrupeIPodGrupe; } }
public List<Paket> Paketi { get { return _Paketi; } }
public string errorMessage { get { return _errorMessage; } }
private int _PROIZVODID;
private string _NAZIV;
private string _OPIS;
private string _JM;
private int _AKCIJSKI_ARTIKAL;
private int _AKTIVAN;
private string _KATBR;
private double _PDV;
private string _SLIKA;
private string _KratakOpis;
private GrupeIPodgrupe _GrupeIPodGrupe;
private List<Paket> _Paketi;
private string fileNameSlika;
private string pathSlika;
string _errorMessage = "Sve je ok!";
#endregion
#region classes
public class GrupeIPodgrupe
{
public ReadOnlyCollection<Grupa> Grupe
{
get
{
return _Grupe.AsReadOnly();
}
}
public ObservableCollection<PodGrupa> Podgrupe
{
get
{
return _PodGrupe;
}
set
{
_PodGrupe = value;
}
}
private List<Grupa> _Grupe;
private ObservableCollection<PodGrupa> _PodGrupe;
private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (PodGrupa pg in e.NewItems)
{
if (_Grupe.Count < 1 || !_Grupe.Any(g => g.Id == pg.GrupaId))
{
_Grupe.Add(new Grupa { Id = pg.GrupaId });
}
}
}
}
public GrupeIPodgrupe()
{
_PodGrupe = new ObservableCollection<PodGrupa>();
_PodGrupe.CollectionChanged += HandleChange;
}
public GrupeIPodgrupe(int proizvodId)
{
this._Grupe = Grupa.ListaGrupaProizvoda(proizvodId);
if(this.Grupe.Count > 0)
{
this.Podgrupe = PodGrupa.ListaPodgrupaProizvoda(Grupe[0].Id, proizvodId);
}
}
public GrupeIPodgrupe(TreeView treeView)
{
_Grupe = new List<Grupa>();
_PodGrupe = new ObservableCollection<PodGrupa>();
_PodGrupe.CollectionChanged += HandleChange;
foreach (TreeNode n in treeView.Nodes)
{
if(n.Checked)
{
foreach(TreeNode n1 in n.Nodes)
{
if(n1.Checked)
_PodGrupe.Add(new PodGrupa { GrupaId = (int)n.Tag, PodGrupaId = (int)n1.Tag });
}
}
}
}
public void Reset()
{
_Grupe = new List<Grupa>();
_PodGrupe = new ObservableCollection<PodGrupa>();
}
}
public class Paket
{
public int PaketId;
public int ProizvodId;
public double CenaBezPdv;
public double Kolicina;
}
#endregion
private Proizvod()
{
}
/// <summary>
/// Kreira klasu sa podacima proizvoda sa web-a
/// </summary>
/// <param name="ROBAID">Unikatni ID za stavku/proizvod/robu</param>
public Proizvod(int ROBAID)
{
if(ROBAID == null ) { throw new Exception("ROBAID ne moze biti NULL!"); }
string url = "censoredLink";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
_errorMessage = "Proizvod nije pronadjen u web bazi!";
break;
default:
Proizvod p = JsonConvert.DeserializeObject<Proizvod>(resp);
if(p == null)
{
MessageBox.Show("Unhandled error!");
return;
}
this._PROIZVODID = p.PROIZVODID;
this._NAZIV = p.NAZIV;
this._OPIS = p.OPIS;
this._JM = p.JM;
this._AKCIJSKI_ARTIKAL = p.AKCIJSKI_ARTIKAL;
this._AKTIVAN = p.AKTIVAN;
this._KATBR = p.KATBR;
this._PDV = p.PDV;
this._SLIKA = p.SLIKA;
this._KratakOpis = p.KratakOpis;
this._GrupeIPodGrupe = new GrupeIPodgrupe(p.PROIZVODID);
break;
}
}
public Proizvod(int RobaId, string Naziv, string Opis, string Jm, bool AkcijskiArtikal, bool Aktivan, string KatBr, double PDV, string Slika, string KratakOpis, GrupeIPodgrupe gip, List<Paket> paketi, string fileNameSlika, string filePathSlika)
{
this._PROIZVODID = RobaId;
this._NAZIV = Naziv;
this._OPIS = Opis;
this._JM = Jm;
this._AKCIJSKI_ARTIKAL = (AkcijskiArtikal) ? 1 : 0;
this._AKTIVAN = (Aktivan) ? 1 : 0;
this._KATBR = KatBr;
this._PDV = PDV;
this._SLIKA = Slika;
this._KratakOpis = KratakOpis;
this._GrupeIPodGrupe = gip;
this._Paketi = paketi;
this.fileNameSlika = fileNameSlika;
this.pathSlika = filePathSlika;
}
/// <summary>
/// Updateuje trenutne vrednosti proizvoda na sajt!
/// </summary>
public void Update()
{
#region Proizvod table
string url = String.Format("censoredLink");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
_errorMessage = "Doslo je do greske!";
break;
case "1":
_errorMessage = "Uspesno updateovan prozvod na WEB-u";
break;
case "2":
_errorMessage = "Proizvod sa tim ID-em nije pronadjen u bazi!";
break;
default:
break;
}
#endregion
DeGrupisi();
Grupisi();
}
public void Publish()
{
PublishProizvod();
Grupisi();
PublishPakete();
Thread t = new Thread(PublishSliku);
t.Start();
}
public static List<Proizvod> SviProizvodi()
{
List<Proizvod> list = new List<Proizvod>();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string url = "censoredLink";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
break;
default:
list = JsonConvert.DeserializeObject<List<Proizvod>>(resp);
break;
}
return list;
}
/// <summary>
/// Skida proizvodu bilo kakvu grupu i podgrupu
/// </summary>
private void DeGrupisi()
{
string url = "censoredLink";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0":
_errorMessage = "Doslo je do greske prilikom brisanja proizvoda iz grupa i podgrupa";
break;
case "1":
_errorMessage = "Uspesno degrupisani proizvodi!";
break;
default:
_errorMessage = "Unhandled error";
break;
}
}
private void Grupisi()
{
foreach(PodGrupa pg in GrupeIPodGrupe.Podgrupe)
{
string url = string.Format("censoredLink");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0":
_errorMessage = "Doslo je do greske prilikom grupisanja proizvoda";
break;
case "1":
_errorMessage = "Proizvod je uspesno grupisan!";
break;
case "2":
_errorMessage = "Proizvod je vec u grupi!";
break;
default:
_errorMessage = "Unhandled error";
break;
}
}
}
private void PublishProizvod()
{
string url = string.Format("censoredLink");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0":
_errorMessage = "Doslo je do greske prilikom kreiranja proizvoda";
break;
case "1":
_errorMessage = "Proizvod je uspesno kreiran!";
break;
case "2":
_errorMessage = "Proizvod vec postoji u web bazi!";
break;
default:
_errorMessage = "Unhandled error";
break;
}
}
private void PublishPakete()
{
foreach (Proizvod.Paket p in Paketi)
{
string url = string.Format("censoredLink");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0":
_errorMessage = "Doslo je do greske prilikom dodavanja paketa";
break;
case "1":
_errorMessage = "Paketi uspesno dodati!";
break;
default:
_errorMessage = "Unhandled error";
break;
}
}
}
private void PublishSliku()
{
if (!string.IsNullOrWhiteSpace(_SLIKA))
{
M.preventClosing = true;
MessageBox.Show("Dodavanje slike ce potrajati i zavisi od brzine interneta koju imate i nece vam dozvoliti zatvaranje programa!\nDodavanje slike se vrsi u pozadini te mozete nastaviti sa radom u programu!");
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("username", "password");
client.UploadFile("censoredLink");
}
M.preventClosing = false;
}
}
}
Your code is calling:
proizvod.GrupeIPodGrupe.Reset()
which is emptying the ObservableCollection.
I am using the following code and the code is working for some images is fine but most images EXIF data is not getting.
ImageMetadata imageMetadata = new ImageMetadata();
public ImageMetadata ReadEXIFMetadata(string filepath)
{
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
System.Drawing.Image image__1 = System.Drawing.Image.FromStream(fs);
PropertyItem[] imagePropertyItems = image__1.PropertyItems;
foreach (PropertyItem pi in imagePropertyItems)
{
switch ((EXIFProperty)pi.Id)
{
case EXIFProperty.Title:
imageMetadata.Title = Encoding.Unicode.GetString(pi.Value);
break;
case EXIFProperty.Author:
imageMetadata.Author = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Author = Encoding.UTF8.GetString(pi.Value)
break;
case EXIFProperty.Keywords:
imageMetadata.Keywords = Encoding.Unicode.GetString(pi.Value);
break;
case EXIFProperty.Comments:
imageMetadata.Comments = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Comments = Encoding.UTF8.GetString(pi.Value)
break;
default:
break;
}
}
fs.Close();
return imageMetadata;
}
public enum EXIFProperty
{
Title = 40091,
Author = 40093,
Keywords = 40094,
Comments = 40092
}
public class ImageMetadata
{
private string _title = string.Empty;
private string _author = string.Empty;
private string _keywords = string.Empty;
private string _comments = string.Empty;
public ImageMetadata()
{
this._title = string.Empty;
this._author = string.Empty;
this._keywords = string.Empty;
this._comments = string.Empty;
}
public ImageMetadata(string title, string author, string keywords, string comments)
{
this._title = title;
this._author = author;
this._keywords = keywords;
this._comments = comments;
}
public string Title
{
get
{
return this._title;
}
set
{
this._title = value;
}
}
public string Author
{
get
{
return this._author;
}
set
{
this._author = value;
}
}
public string Keywords
{
get
{
return this._keywords;
}
set
{
this._keywords = value;
}
}
public string Comments
{
get
{
return this._comments;
}
set
{
this._comments = value;
}
}
}
Correct me if I am doing something wrong in the above code.please help stuck with this problem.
I'm not sure why you've created your own ImageMetaData class as .NET already has one. Try:
BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile;
BitmapMetadata importedMetaData = new BitmapMetadata("jpg");
using (Stream sourceStream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
BitmapDecoder sourceDecoder = BitmapDecoder.Create(sourceStream, createOptions, BitmapCacheOption.Default);
// Check source is has valid frames
if (sourceDecoder.Frames[0] != null && sourceDecoder.Frames[0].Metadata != null)
{
sourceDecoder.Frames[0].Metadata.Freeze();
// Get a clone copy of the metadata
BitmapMetadata sourceMetadata = sourceDecoder.Frames[0].Metadata.Clone() as BitmapMetadata;
importedMetaData = sourceMetadata;
}
}
return importedMetaData;
I am facing an issue while making changes to the database using httpclient.putasync. following is the error message i receive : error while copying content to a stream
Any help would be great
namespace ABC
{
public enum SupportedHttpMethods
{
GET,
POST,
PUT,
DELETE
}
public class HttpClass : IHttpClass
{
Uri _uri;
HttpMethod _httpMethod;
StringContent _content;
HttpClient _httpClient = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true, AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip});
Action _action;
HttpResponseMessage _httpResponseMessage;
public HttpClass(
SupportedHttpMethods httpMethod,
string uri,
string content)
: this(httpMethod, uri)
{
if (httpMethod == SupportedHttpMethods.POST || httpMethod == SupportedHttpMethods.PUT)
{
JObject.Parse(content);
_content = new StringContent(content);
_content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
else
{
throw new InvalidHttpMethodContentCombinationException();
}
}
public HttpClass(
SupportedHttpMethods httpMethod,
string uri)
{
_uri = new Uri(uri);
_httpMethod = new HttpMethod(httpMethod.ToString());
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")
);
switch (httpMethod)
{
case SupportedHttpMethods.GET:
_action = get;
break;
case SupportedHttpMethods.POST:
_action = post;
break;
case SupportedHttpMethods.PUT:
_action = put;
break;
case SupportedHttpMethods.DELETE:
_action = delete;
break;
default:
throw new InvalidHttpMethodException();
}
}
public HttpResponseMessage GetHttpResponseMessage()
{
return _httpResponseMessage;
}
public string GetResponseContent()
{
if (_httpMethod.Method == SupportedHttpMethods.GET.ToString())
return _httpResponseMessage.Content.ReadAsStringAsync().Result;
return null;
}
public void Invoke()
{
_action.Invoke();
}
void delete()
{
_httpResponseMessage = _httpClient.DeleteAsync(_uri).Result;
}
void get()
{
_httpResponseMessage = _httpClient.GetAsync(_uri).Result;
}
void post()
{
_httpResponseMessage = _httpClient.PostAsync(_uri, _content).Result;
}
void put()
{
_httpResponseMessage = _httpClient.PutAsync(_uri, _content).Result;
}
}
public class InvalidHttpMethodContentCombinationException : Exception
{
public InvalidHttpMethodContentCombinationException()
: base("When speciying content, either a POST or PUT must be used") { }
}
public class InvalidHttpMethodException : Exception
{
public InvalidHttpMethodException()
: base("Only PUT, POST, GET and DELETE Methods are supported") { }
}
}
I have a huge XML file like this:
<Tests>
<Test>
<Code>a</Code>
<Destination>test a</Destination>
<Coordinate>
<Latitude>0.0</Latitude>
<Longitude>0.0</Longitude>
</Coordinate>
<Images>
<ImageURL>1. url 1</ImageURL>
<ImageURL>1. url 2</ImageURL>
<ImageURL>1. url 3</ImageURL>
</Images>
</Test>
<Test>
<Code>b</Code>
<Destination>test b</Destination>
<Coordinate>
<Latitude>0.0</Latitude>
<Longitude>0.0</Longitude>
</Coordinate>
<Images>
<ImageURL>2. url 1</ImageURL>
<ImageURL>2. url 2</ImageURL>
<ImageURL>2. url 3</ImageURL>
<ImageURL>2. url 4</ImageURL>
<ImageURL>2. url 5</ImageURL>
</Images>
</Test>
...
</Tests>
and I try this
reader = XmlReader.Create("file");
while (reader.Read())
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "Test":
{
.....
Test elem = (Test)DeSerializerDestination.Deserialize(reader);
.....
} break;
default: reader.Skip(); break;
}
}
private static readonly XmlSerializer DeSerializerTest = new XmlSerializer(typeof(Test));
public class Test
{
private string _Code = string.Empty;
public string Code
{
get { return _Code; }
set { _Code = value; }
}
private string _Destination = string.Empty;
public string Destination
{
get { return _Destination; }
set { _Destination = value; }
}
private Coordinate _Coordinates = new Coordinate();
public Coordinate Coordinates
{
get { return _Coordinates; }
set { _Coordinates = value; }
}
private ImageUrl[] _ImageUrl;
public ImageUrl[] Images
{
get { return _ImageUrl; }
set { _ImageUrl = value; }
}
}
public class Coordinate
{
private string _Latitude = string.Empty;
public string Latitude
{
get { return _Latitude; }
set { _Latitude = value; }
}
private string _Longitude = string.Empty;
public string Longitude
{
get { return _Longitude; }
set { _Longitude = value; }
}
}
public class ImageUrl
{
private string _ImageURL = string.Empty;
public string ImageURL
{
get { return _ImageURL; }
set { _ImageURL = value; }
}
}
The object elem contains information but not all; property "Images" is always empty.
I think it's because I don't initialize this private ImageUrl[] _ImageUrl;, but would I initialize it, considering I don't know the number of images? I need to mention, I must use .net 2.0.
Update: If I use this in "Images" always I get the first image url.
public class ImageUrl
....
System.Xml.Serialization.XmlElementAttribute("ImageURL")]
public string ImageURL
...
public class Test
...
System.Xml.Serialization.XmlElementAttribute("Images")]
public ImageUrl[] Images
...
Update: I use this
[System.Xml.Serialization.XmlArray("Images")]
[System.Xml.Serialization.XmlArrayItem("ImageURL")]
public List<ImageUrl> Images
{
get { return _ImageUrl; }
set { _ImageUrl = value; }
}
now I get list but "ImageUrl" is empty, do not contain "1. url 1" ....
This is the resolve
[System.Xml.Serialization.XmlIgnore]
private List<string> images = new List<string>();
[System.Xml.Serialization.XmlArray("Images")]
[System.Xml.Serialization.XmlArrayItem("ImageURL")]
public List<string> Images
{
get { return images; }
set { images = value; }
}
Try the following, which will serialize your Xml into your object, providing you object matches your Xml structure.
YourObject oObject = new YourObject ();
try
{
XmlSerializer oSerializer = new XmlSerializer(typeof(YourObject));
using (StringReader oReader = new StringReader(XmlString))
{
oObject = (YourObject)oSerializer.Deserialize(oReader);
}
}
catch
{
...
}
I'm trying to post a photo to Facebook using Graph API. I have managed to post a message to my timeline, but not a photo. The Facebook-debugger gives no errors and the object properties are correct.
public class oAuthFacebook
{
public enum Method { GET, POST };
public const string AUTHORIZE = "https://graph.facebook.com/oauth/authorize";
public const string ACCESS_TOKEN = "https://graph.facebook.com/oauth/access_token";
public const string CALLBACK_URL ="http://test.com/FbCallback.aspx";
private string _consumerKey = "";
private string _consumerSecret = "";
private string _token = "";
public string ConsumerKey
{
get
{
if (_consumerKey.Length == 0)
{
_consumerKey = "";
}
return _consumerKey;
}
set { _consumerKey = value; }
}
public string ConsumerSecret
{
get
{
if (_consumerSecret.Length == 0)
{
_consumerSecret = "";
}
return _consumerSecret;
}
set { _consumerSecret = value; }
}
public string Token { get { return _token; } set { _token = value; } }
public string AuthorizationLinkGet()
{
return string.Format("{0}?client_id={1}&redirect_uri={2}&,publish_actions",
AUTHORIZE, this.ConsumerKey, CALLBACK_URL);
}
public void AccessTokenGet(string authToken)
{
this.Token = authToken;
string accessTokenUrl = string.Format("{0}?client_id={1}&redirect_uri=
{2}&client_secret={3}&code={4}",
ACCESS_TOKEN, this.ConsumerKey, CALLBACK_URL, this.ConsumerSecret, authToken);
string response = WebRequest(Method.GET, accessTokenUrl, String.Empty);
if (response.Length > 0)
{
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs["access_token"] != null)
{
this.Token = qs["access_token"];
}
}
}
public string WebRequest(Method method, string url, string postData)
{
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = "http://test.com";
webRequest.Timeout = 40000;
if (method == Method.POST)
{
webRequest.ContentType = "application/x-www-form-urlencoded";
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
And this is how I sent a testmessage, it works fine:
var json = oAuth.WebRequest(oAuthFacebook.Method.POST, url, "message=" +
HttpUtility.UrlEncode("Testmessage"));
I've tried for days to get it to work with a photo instead, any ideas of what I'm doing wrong?
I can suggest to look at FB C# SDK (available here or in NuGet) instead of sending raw requests. Here is my function I use to upload images to FB album (you should either know album ID or you can create it as well, or you can enumerate all the albums and get the one you need):
public static string UploadPhoto(string imageName, string albumID, string accesstoken, string photoComment = null, bool doNotPostStory = false)
{
var fbAPI = new FacebookApp(accesstoken);
var p = new FacebookMediaObject {FileName = path};
p.SetValue( <<YOUR IMAGE GOES HERE AS byte[]>>);
p.ContentType = "multipart/form-data";
var param = new Dictionary<string, object> { {"attachment", p} };
if (!string.IsNullOrEmpty(photoComment))
param.Add("message", photoComment);
// http://stackoverflow.com/questions/7340949/is-it-possible-to-upload-a-photo-to-fanpage-album-without-publishing-it
// http://developers.facebook.com/blog/post/482/
if (doNotPostStory == true)
{
param.Add("no_story", "1");
}
var result = fbAPI.Post(string.Format("http://graph.facebook.com/{0}/photos", albumID), param);
return result.ToString();
}