Prevent duplicate user from being added to database - c#

I want to prevent the same user from being added to the database automatically. I want to check this against the FacebookID field/column set in my database. How would I do this? Below is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCFacebookTestApp.Models;
using Facebook;
using Facebook.Web;
namespace MVCFacebookTestApp.Controllers
{
public class HomeController : Controller
{
public FacebookSession FacebookSession
{
get { return (FacebookWebContext.Current.Session); }
}
public ActionResult Index()
{
string request = Request.Form["signed_request"];
string accessToken = "";
if (Request.Form["access_token"] != null)
{
accessToken = Request.Form["access_token"];
}
FacebookApplication app = new FacebookApplication();
FacebookSignedRequest result = FacebookSignedRequest.Parse(app.InnerCurrent, request);
if (String.IsNullOrWhiteSpace(accessToken))
{
accessToken = result.AccessToken;
}
dynamic data = result.Data;
bool liked = data.page.liked;
//bool liked = true;
if (!liked)
{
Home h = Home.NotLiked();
return View(h);
}
else
{
Home h = Home.Liked();
FacebookWebClient fb = null;
if (String.IsNullOrWhiteSpace(accessToken))
{
var fbRequest = FacebookWebContext.Current;
if (fbRequest.IsAuthorized())
fb = new FacebookWebClient(fbRequest);
accessToken = fbRequest.AccessToken;
}
else
{
fb = new FacebookWebClient(accessToken);
}
if (fb != null)
{
dynamic r = fb.Get("/me");
//h.TestString2 += " Ha! We captured this data about you!";
//h.TestString2 += " Name: " + r.name;
//h.TestString2 += " Location: " + r.location;
//h.TestString2 += " Birthday: " + r.birthday;
//h.TestString2 += " About Me: " + r.aboutme;
//h.ImgUrl = "http://graph.facebook.com/" + r.id + "/picture?type=large";
//string fqlResult = "";
//var fbApp = new FacebookClient(accessToken);
//basic fql query execution
//dynamic friends = fbApp.Query("SELECT uid FROM page_admin WHERE page_id='160828267335555'");
//SELECT uid FROM page_fan WHERE page_id = 160828267335555
//"SELECT uid FROM page_fan WHERE uid=me() AND page_id=<your page id>";
//loop through all friends and get their name and create response containing friends' name and profile picture
//foreach (dynamic friend in friends)
//{
// fqlResult += friend.uid + ".... ";
// //fqlResult += friend.name + "<img src='" + friend.pic_square + "' alt='" + friend.name + "' /><br />";
//}
h.AddUser(r.id, accessToken, r.first_name, r.last_name, DateTime.ParseExact(r.birthday, "MM/dd/yyyy", new System.Globalization.CultureInfo("en-GB")), r.email, DateTime.Now, r.gender, "http://graph.facebook.com/" + r.id + "/picture?type=large");
//ViewBag.Likes = fqlResult;
}
else
{
//Display a message saying not authed....
}
// if statement to stop same user from being added to the database...
if ()
{
//condition here
}
else
{
//condition here
}
return View(h);
}
}
}
}
I'm trying it this way at the moment using the if else if and else statement.
var User = SELECT from User WHERE FBID = FBID();
if (User.Count==0)
{
User.AddUser(facebookID as string, accessToken as string, fName as string, lName as string, dob as DateTime, email as string, dateLiked as DateTime, gender as string, imageURL as string); //Create newUser
}
else if (User.Count ==1)
{
//set properties to User[0]
}
else
{
// THROW EXCEPTION
}
and these are my properties to the database that i have created;
//public string UserID { get; set; }
public string FBID { get; set; }
public string AccessToken { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string Gender { get; set; }
public DateTime DOB { get; set; }
public string Email { get; set; }
public DateTime DateLiked { get; set; }
public string ImageURL { get; set; }
//public string TestString { get; set; }
//public string TestString2 { get; set; }
public bool IsLiked { get; set; }
//public string ImgUrl { get; set; }
public void AddUser (string facebookID, string accessToken, string fName, string lName, DateTime dob, string email, DateTime dateLiked, string gender, string imageURL)
{
//UserID = userID;
FBID = facebookID;
AccessToken = accessToken;
FName = fName;
LName = lName;
DOB = dob;
Email = email;
DateLiked = dateLiked;
Gender = gender;
ImageURL = imageURL;
User newUser = new User();
Entities newContext = new Entities();
//newUser.UserID = 1;
newUser.FacebookID = facebookID;
newUser.AccessToken = accessToken;
newUser.FName = fName;
newUser.LName = lName;
newUser.Gender = gender;
newUser.DOB = DOB;
newUser.Email = email;
newUser.DateLiked = dateLiked;
newUser.ImageURL = imageURL;
newContext.Users.AddObject(newUser);
newContext.SaveChanges();
}
}
}
I hope it makes sense, newbie here so go easy on me. =)

To preserve the integrity of your database you should add a unique constraint to this column in your database and then catch the exception of the violation of this constraint when performing the UPDATE/INSERT query.

Related

How to fix: The UPDATE statement conflicted with the FOREIGN KEY SAME TABLE constraint

Im makeing a update statement from my C# code. Now I had it working but I needed to add a constructor to my class. now that I added the constructor it doesn't work anymore.
If i dont make a constructur it does work
class
namespace FontysHotel
{
public class Medewerker
{
//instantie variabelen
private int id;
private string naam;
private string functie;
private DateTime datum_in_dienst;
private string telefoonnummer;
private string email;
private string wachtwoord;
private int hotelid;
private int managementid;
//proporties
public int Id
{
get { return id; } set { id = value; }
}
public string Naam
{
get { return naam; } set { naam = value; }
}
public string Functie
{
get { return functie; } set { functie = value; }
}
public DateTime Datum_in_dienst
{
get { return datum_in_dienst; } set { datum_in_dienst = value; }
}
public string Telefoonnummer
{
get { return telefoonnummer; } set { telefoonnummer = value; }
}
public string Email
{
get { return email; } set { email = value; }
}
public string Wachtwoord
{
get { return wachtwoord; } set { wachtwoord = value; }
}
public int Hotelid
{
get { return hotelid; } set { hotelid = value; }
}
public int Managementid
{
get { return managementid; } set { managementid = value; }
}
//constructor
public Medewerker(int id, string naam, string functie, DateTime datum_in_dienst, string telefoonnummer, string email, string wachtwoord, int hotelid, int mangementid)
{
Id = id;
Naam = naam;
Functie = functie;
Datum_in_dienst = datum_in_dienst;
Telefoonnummer = telefoonnummer;
Email = email;
Wachtwoord = wachtwoord;
Hotelid = hotelid;
Managementid = managementid;
}
}
}
method
public static void UpdateSchoonmaker(int id, string naam, string functie, DateTime datum_in_dienst, string telefoonnummer, string email,string wachtwoord, string hotelid, string managementid )
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("update medewerker set medewerkerid = " + id + ", naam ='" + naam + "',functie ='" + functie + "',datum_in_dienst = '" + datum_in_dienst + "',telefoonnummer =" + telefoonnummer + ",email ='" + email + "', wachtwoord ='" +wachtwoord+ "',hotelid = "+hotelid+", managementid ="+managementid+" where medewerkerid =" + id, conn);
SqlDataReader reader;
reader = cmd.ExecuteReader();
}
}
constructor involved at getallstaf
public static List<Medewerker> Getmedewerker()
{
var result = new List<Medewerker>();
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
const string query = "Select * from medewerker where functie = 'schoonmaak'";
SqlCommand selectMedewerker = new SqlCommand(query, conn);
SqlDataReader reader = selectMedewerker.ExecuteReader();
while (reader.Read())
{
Medewerker mdw = new Medewerker((int)reader["medewerkerid"], (string)reader["naam"], (string)reader["functie"], (DateTime)reader["datum_in_dienst"], (string)reader["telefoonnummer"], (string)reader["email"], (string)reader["wachtwoord"], (int)reader["hotelid"], (int)reader["managementid"]);
//mdw.Id = (int)reader["medewerkerid"];
//mdw.Naam = (string)reader["naam"];
//mdw.Functie = (string)reader["functie"];
//mdw.Datum_in_dienst = (DateTime)reader["datum_in_dienst"];
//mdw.Telefoonnummer = (string)reader["telefoonnummer"];
//mdw.Email = (string)reader["email"];
//mdw.Wachtwoord = (string)reader["wachtwoord"];
//mdw.Hotelid = (int)reader["hotelid"];
//mdw.Managementid = (int)reader["managementid"];
result.Add(mdw);
}
reader.Close();
}
return result;
}
code that gets info from datagrid
private void DgSchoonmedewerker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dg = (DataGrid)sender;
var row_selected = dg.SelectedItem as Medewerker;
if (row_selected != null)
{
medewerkerid = row_selected.Id;
tbNaamSchoon.Text = row_selected.Naam;
tbTelefoonSchoon.Text = row_selected.Telefoonnummer;
tbEmailSchoon.Text = row_selected.Email;
tbWachtSchoon.Text = row_selected.Wachtwoord;
cbHotelSchoonmaak.Text = row_selected.Hotelid.ToString();
cbManagerSchoonmaak.Text = row_selected.Managementid.ToString();
dpDatumindienst.SelectedDate = row_selected.Datum_in_dienst;
}
}
now this way if I click anything in the datagrid it fills the information to the textboxes. The next code is how i send the code to the Update method
Database.UpdateSchoonmaker(medewerkerid, tbNaamSchoon.Text, "Schoonmaak",Convert.ToDateTime(dpDatumindienst.SelectedDate), tbTelefoonSchoon.Text, tbEmailSchoon.Text, tbWachtSchoon.Text, cbHotelSchoonmaak.Text, cbManagerSchoonmaak.Text);
So First I use the public static list getmedewerker to load the information. Here is probaly something wrong loading in the managersids. because as you can see in the first screenshot they are all set to 0 while in sql server express they do have a value.
Now if I click something in the datagrid the combox for managersid's also doesnt automaticly fill and if I manaul select a managersid it then adds 0 to the managersid.
if I dont put anything in the new medewerker and uncomment the mdw.XXX = and comment the constructor the update does work
I expect it to update a row in the table. But how do I add constructor to the class and make the update statement so that I dont get this error message
edit
I suggest doing some research into object orientated programming. I haven't tested this, but it should be pretty close to what I'm guessing you want.
public class Medewerker
{
//instantie variabelen
public int id {get;}
public string naam {get; set;}
public string functie {get; set;}
public DateTime datum_in_dienst {get; set;}
public string telefoonnummer {get; set;}
public string email {get; set;}
public string wachtwoord {get; set;}
public int hotelid {get; set;}
public int managementid {get; set;}
//constructor
public Medewerker(int id, string naam, string functie, DateTime datum_in_dienst, string telefoonnummer, string email, string wachtwoord, int hotelid, int mangementid)
{
Id = id;
Naam = naam;
Functie = functie;
Datum_in_dienst = datum_in_dienst;
Telefoonnummer = telefoonnummer;
Email = email;
Wachtwoord = wachtwoord;
Hotelid = hotelid;
Managementid = managementid;
}
public static void UpdateSchoonmaker()
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("update medewerker set naam ='" + this.naam + "',functie ='" + this.functie + "',datum_in_dienst = '" + this.datum_in_dienst + "',telefoonnummer =" + this.telefoonnummer + ",email ='" + this.email + "', wachtwoord ='" +this.wachtwoord+ "',hotelid = "+this.hotelid+", managementid ="+this.managementid+" where medewerkerid =" + id, conn);
cmd.ExecuteNonQuery();
}
}
}
Then in whatever area you want to call the method
var myMedewerker = new Medewerker(0, "Matt", ...);
myMedewerker.naam = "James";
myMedewerker.UpdateSchoonmaker();

How to send email confirmation mail to user using asp.net mvc c#

I have build an application and want to send user a confirmation email after registration.I have taken ActivationCode value by guid=new.guid(); but it don't get store in the database and after debugging I evaluate the value it says :The name 'ActivationCode' does not exist in the current context.
public ActionResult Activation()
{
ViewBag.Message = "Invalid Activation code.";//This get outputted always
if (RouteData.Values["id"] != null)
{
Guid activationcode = new Guid(RouteData.Values["id"].ToString());
IPHISEntities usersEntities = new IPHISEntities();
User userActivation = usersEntities.Users.Where(p => p.ActivationCode == activationcode).FirstOrDefault();
if (userActivation != null)//this condition gets true
{
usersEntities.Users.Remove(userActivation);
try {
usersEntities.SaveChanges();
}
catch (DbEntityValidationException e)
{
Console.WriteLine(e);
}
ViewBag.Message = "Activation successful.";
}
}
return View();
}
private void SendActivationEmail(User user)
{
Guid activationcode = Guid.NewGuid();
IPHISEntities usersEntities = new IPHISEntities();
usersEntities.Users.Add(new User
{
UserId = user.UserId,
ActivationCode = activationcode
});
try
{
usersEntities.SaveChanges();
}
catch (DbEntityValidationException e)
{
Console.WriteLine(e);
}
using (MailMessage mm = new MailMessage("xyzz#gmail.com", user.EmailAddress))
{
mm.Subject = "Account Activation";
string body = "Hello " + user.FirstName + ",";
body += "<br /><br />Please click the following link to activate your account";
body += "<br /><a href = '" + string.Format("{0}://{1}/User/Activation/{2}", Request.Url.Scheme, Request.Url.Authority, activationcode) + "'>Click here to activate your account.</a>";
body += "<br /><br />Thanks";
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("xyzz#gmail.com", "********");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
//**User.cs**:
namespace ConnectionSQL_webAPI_.Models
{
using System;
using System.Collections.Generic;
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Answers = new HashSet<Answer>();
this.Appointments = new HashSet<Appointment>();
this.DoctorInfoes = new HashSet<DoctorInfo>();
this.Payments = new HashSet<Payment>();
this.UserLoginDetails = new HashSet<UserLoginDetail>();
}
public int UserId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public System.Guid ActivationCode { get; set; }
public string Password { get; set; }
public string PhoneNumber { get; set; }
public string UserUniqueId { get; set; }
public Nullable<int> UserTypeId { get; set; }
public Nullable<int> AddressId { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
}
Expected Output
Activation Successful
Actual Output
Invalid Activation code
Take ActivationCode in different table and make it uniqueidentifier in database.Now update your database in the model and check for the ActivationCode Property if it is Guid and Execute the above code.
Result Output: Activation successfull
Add
using System.Runtime.Remoting;

JSON String to DataTable Object in C#

So basically I SEARCHED everywhere, and I'm not finding anything that works in my situation.
I'm working with an API for Overwatch (a game) and I want to turn a String I download from the web, and check if it has a JSON string.
Let me show you the code:
< !--language: c# -->
HttpClient dc = new HttpClient();
string tag = e.Message.Text.ToString().Substring(7).Replace("#", "-");
string apiurl = (#"http://api.lootbox.eu/" + "pc/" + "global/" + tag + "/profile");
HttpResponseMessage datares = await dc.GetAsync(apiurl);
string finaldata = await datares.Content.ReadAsStringAsync();
#region PC
if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "us/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "kr/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "eu/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "cn/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
#endregion
#region XBOX LIVE
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "us/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "eu/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "kr/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "cn/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "global/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
#endregion
#region PSN
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "us/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "global/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "cn/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "eu/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "kr/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
#endregion
DataTable obj = JsonConvert.DeserializeObject(finaldata);
So an example output, in this case, wouldv'e been:
{"data":{"username":"Rezoh","level":305,"games":{"quick":{"wins":"378"},"competitive":{"wins":"82","lost":85,"played":"167"}},"playtime":{"quick":"88 hours","competitive":"36 hours"},"avatar":"https://blzgdapipro-a.akamaihd.net/game/unlocks/0x0250000000000D70.png","competitive":{"rank":"3392","rank_img":"https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-5.png"},"levelFrame":"https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Border.png","star":"https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Rank.png"}}
Now I need to convert that to a table of some sort or something.
I got the JSON.Net but most people said to setup a class BEFORE you convert,
Problem was that: I had 2 "wins": and 3 "competitive": as you can see in the JSON string.
So making a class wasn't possible to my belief in this case. I tried making a new DataTable as shown in the last line of code but it tells me "Cannot implicitly convert type object to System.Data.DataTable" when using JsonConvert.DeserializeObject(finaldata); I even tried doing .ToString(); and also the dates variable, and .ToString() in that too.
I need a proper way to show these stats so, for example, I can show:
"Stats for user " + obj.Name + ":"
"Wins: " + obj.Wins
"Losses: " + obj.Losses
"Rank: " + obj.Rank
And no solutions online help me in my situation.
EDIT:
This solution doesn't work either for me:
convert json String to datatable?
or this
Nested Json String to DataTable
Nor does this:
var token = JToken.Parse(finaldata);
if (token.Type == JTokenType.Object)
token = new JArray(token);
var a = token.ToObject<DataTable>();
You can use a class as they said. I used http://json2csharp.com/ but VS can do it too.
You can try it here: https://dotnetfiddle.net/iaIvOn
using System;
using Newtonsoft.Json;
public class Program
{
public void Main()
{
var json = #"{""data"":{""username"":""Rezoh"",""level"":305,""games"":{""quick"":{""wins"":""378""},""competitive"":{""wins"":""82"",""lost"":85,""played"":""167""}},""playtime"":{""quick"":""88 hours"",""competitive"":""36 hours""},""avatar"":""https://blzgdapipro-a.akamaihd.net/game/unlocks/0x0250000000000D70.png"",""competitive"":{""rank"":""3392"",""rank_img"":""https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-5.png""},""levelFrame"":""https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Border.png"",""star"":""https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Rank.png""}}";
// read the doc: http://www.newtonsoft.com/json
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine("Stats for user " + rootObject.Data.Username + ":");
Console.WriteLine("Wins: " + rootObject.Data.Games.Competitive.Wins);
Console.WriteLine("Losses: " + rootObject.Data.Games.Competitive.Lost);
Console.WriteLine("Rank: " + rootObject.Data.Competitive.Rank);
}
public class Quick
{
// Free case support!
public string Wins { get; set; }
}
public class Competitive
{
public string Wins { get; set; } // you may want to check this string here ;)
public int Lost { get; set; }
public string Played { get; set; }
}
public class Games
{
public Quick Quick { get; set; }
public Competitive Competitive { get; set; }
}
public class Playtime
{
public string Quick { get; set; }
public string Competitive { get; set; }
}
public class Competitive2
{
public string Rank { get; set; }
// attribute ftw! http://www.newtonsoft.com/json/help/html/SerializationAttributes.htm
[JsonProperty(PropertyName = "rank_img")]
public string RankImg { get; set; }
}
public class Data
{
public string Username { get; set; }
public int Level { get; set; }
public Games Games { get; set; }
public Playtime Playtime { get; set; }
public string Avatar { get; set; }
public Competitive2 Competitive { get; set; }
public string LevelFrame { get; set; }
public string Star { get; set; }
}
public class RootObject
{
public Data Data { get; set; }
}
}
output
Stats for user Rezoh:
Wins: 82
Losses: 85
Rank: 3392
If Quick and Competitive are Game, maybe:
public abstract class Game
{
public string Wins { get; set; } // you may want to check this string here ;)
public int Lost { get; set; }
public string Played { get; set; }
}
public class Quick : Game // note that Quick game has Lost and PLayed now!
{
}
public class Competitive : Game
{
}
Or even (as #EpicSam proposed in comment):
public class Game
{
public string Wins { get; set; } // you may want to check this string here ;)
public int Lost { get; set; }
public string Played { get; set; }
}
public class Games
{
public Game Quick { get; set; }
public Game Competitive { get; set; }
}

Remove/Replace comma from CSV file when using entity framework?

I have come across this issue and I can't solve it and it's driving me insane. I've created an C# app that reads a csv file, then inserts the information into MSSQL. When I do this though, I'm getting some skewed inserts. Everything inserts fine until there is a comma within double quotes.. for example, if the Bank Name is "Capital One,Inc" it will insert 'Inc' into the next column. I have tried removing the comma's, but I'm getting the same results. I am using the entity framework to do this.. this is how my dataclass is set up.
namespace CIT
{
class RawData
{
public string Branch { get; set; }
public string Pfx { get; set; }
public string AcctNo { get; set; }
public string CustName { get; set; }
public string CtrlNo { get; set; }
public string RefNo { get; set; }
public string Days { get; set; }
public string DealNoCat { get; set; }
public string BankNameFiCat { get; set; }
public string FinMgrName { get; set; }
public string Desc { get; set; }
public string DealDateCat { get; set; }
public string SchedNo { get; set; }
public string SchedTypeDv { get; set; }
public string SchedRemarks { get; set; }
public string Amt { get; set; }
public string Src { get; set; }
public string SysDateCat { get; set; }
public string JrnlDateDv { get; set; }
public string DateY4 { get; set; }
public string DaysOut { get; set; }
public RawData(string csvString)
{
string[] citData = csvString.Replace(", ", " ").Replace(".", " ").Split(',');
try
{
Branch = citData[0].Replace("\"", "");
Pfx = citData[1].Replace("\"", "");
AcctNo = citData[2].Replace("\"", "");
CustName = citData[3].Replace("\"", "");
CtrlNo = citData[4].Replace("\"", "");
RefNo = citData[5].Replace("\"", "");
Days = citData[6].Replace("\"", "");
DealNoCat = citData[7].Replace("\"", "");
BankNameFiCat = citData[8].Replace("\"", "");
FinMgrName = citData[9].Replace("\"", "");
Desc = citData[10].Replace("\"", "");
DealDateCat = citData[11].Replace("\"", "");
SchedNo = citData[12].Replace("\"", "");
SchedTypeDv = citData[13].Replace("\"", "");
SchedRemarks = citData[14].Replace("\"", "");
Amt = citData[15].Replace("\"", "");
Src = citData[16].Replace("\"", "");
SysDateCat = citData[17].Replace("\"", "");
JrnlDateDv = citData[18].Replace("\"", "");
DateY4 = citData[19].Replace("\"", "");
DaysOut = null;
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong. " + ex.ToString());
}
}
}
}
I have also tried
BankNameFiCat = citData[8].Replace(",", " ").Replace("\"", "");
but I have no had any luck with that. I think the problem is that the comma has no spaces before or after it. It is like "Capital One,Inc" and it's like that with other bank names as well.
This is how I'm uploading the file to the list then writing it to the db..
string text = File.ReadAllText(lblFileName.Text);
string[] lines = text.Split('\n');
int total = 0, reduced = 0;
foreach (string line in lines)
{
RawData temp = new RawData(line);
total++;
if (!(temp.Branch.Length == 0 || temp.Branch == "Branch"))
{
reduced++;
data.Add(temp);
}
}
Linq/Entity
foreach (RawData rData in data)
{
tFIManager fimanag;
tBank bank;
tCustomer cust;
fimanag = (context.tFIManagers.Any(fimanager => fimanager.FIName == rData.FinMgrName) ? context.tFIManagers.Where(fimanager => fimanager.FIName == rData.FinMgrName).FirstOrDefault() : context.tFIManagers.Add(new tFIManager { FIName = rData.FinMgrName }));
bank = (context.tBanks.Any(banks => banks.BankName == rData.BankNameFiCat) ? context.tBanks.Where(banks => banks.BankName == rData.BankNameFiCat).FirstOrDefault() : context.tBanks.Add(new tBank { BankName = rData.BankNameFiCat }));
cust = (context.tCustomers.Any(custs => custs.CustomerName == rData.CustName) ? context.tCustomers.Where(custs => custs.CustomerName == rData.CustName).FirstOrDefault() : context.tCustomers.Add(new tCustomer { CustomerName = rData.CustName }));
DateTime DateY4, DealDate, SysDate, JrnlDate;
bool hasDate = DateTime.TryParse(rData.DateY4, out DateY4);
bool hasDeal = DateTime.TryParse(rData.DealDateCat, out DealDate);
bool hasSys = DateTime.TryParse(rData.SysDateCat, out SysDate);
bool hasJrnl = DateTime.TryParse(rData.JrnlDateDv, out JrnlDate);
decimal amt;
bool hasAmt = Decimal.TryParse(rData.Amt, out amt);
tContractsInTransit cit = new tContractsInTransit
{
Branch = rData.Branch,
Pfx = rData.Pfx,
AcctNo = rData.AcctNo,
CustomerID = cust.CustomerID,
CtrlNo = rData.CtrlNo,
RefNo = rData.RefNo,
Days = rData.Days,
DealNoCat = rData.DealNoCat,
BankID = bank.BankID,
FIManagerID = fimanag.FIManagerID,
Desc = rData.Desc,
DealDateCat = null,
SchedNo = rData.SchedNo,
SchedTypeDv = rData.SchedTypeDv,
SchedRemarks = rData.SchedRemarks,
Amt = hasAmt ? amt : 0,
Src = rData.Src,
SysDateCat = null,
JrnlDateDv = null,
DateY4 = null
};
if (hasDeal)
{
cit.DealDateCat = DealDate;
}
if (hasSys)
{
cit.SysDateCat = SysDate;
}
if (hasJrnl)
{
cit.JrnlDateDv = JrnlDate;
}
if (hasDate)
{
cit.DateY4 = DateY4;
}
context.tContractsInTransits.Add(cit);
context.SaveChanges();
}
context.Dispose();
I'm not sure what else to try.. I probably am just tired of looking at it at this point. Thanks in advance!
Just find commas in quotes and replace them prior to doing anything else. You could probably use the code from one of the answers in this question.
Use Microsoft.ACE.OLEDB.12.0 to read Excel file. This should solve your problem.
public static DataSet ReadFile(string file)
{
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Extended Properties='text;HDR=YES;FMT=Delimited';";
string sql = "select * from " + name;
DataSet ds = null;
Using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strSql, connstring))
{
ds = new DataSet();
myCommand.Fill(ds, "table1");
}
}
return ds;
}

How to use "like" feature in facebook c# sdk 5.4.1?

in facebook developers site it seems pretty easy.just make a HTTP POST to POST_ID/likes(i got the post i.d).
in c# sdk v.5.4.1 there is a POST method but i can't figure out how to use it and make the right call.
Look at the face book API documentation..here http://developers.facebook.com/
var fb = new FacebookClient("my token");
dynamic parameters = new ExpandoObject();
parameters.message = "the publish msg";
dynamic result = fb.Post("/me/feed", parameters);
var id = result.id;
var res = fb.Post("/" + id + "/likes");
I was having the same issue so I tried few things & this worked for me
var token = "[your access token]";
var fb = new Facebook.FacebookClient(token);
var postId = "173213306032925_745288855492031"; //replace this with your big id which comprises of [userid]_[postid]
Console.WriteLine(fb.Post(id+"/likes", null).ToString()); // should print 'True'
Console.WriteLine(fb.Get("173213306032925_745288855492031/likes").ToString()); //should give you details
public void FacebookLike(AppConnect appconnect )
{
try
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string fb_exchange = appconnect.UserToken;
string url =
string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&grant_type=fb_exchange_token&fb_exchange_token={3}&redirect_uri=https://www.facebook.com/connect/login_success.html&scope={1}&client_secret={2}",
appconnect.AppID, appconnect.ExtendedPermissions, appconnect.AppSecret, fb_exchange);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic parameters = new ExpandoObject(); parameters.idobject = "";
client.Post("/" + appconnect.AppID.ToString() + "_" + appconnect.PostID.ToString() + "/Likes", parameters);
// MessageBox.Show("....... Done ..........");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message +"\n"+ex.InnerException);
}
}
class AppConnect
{
//tring appId, string Appsecret, string userToken, string userID, string PostID
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string AppID { get; set; } = "991341734653453831";
public string AppSecret { get; set; } = "99dfbf29234ergec4a";
public string UserID { get; set; } = null;
public string UserToken { get; set; } = null;
public string PostID { get; set; } = null;
public string ExtendedPermissions { get; set; } = "user_posts, publish_actions, publish_pages,manage_pages,user_likes";
}

Categories

Resources