Error SQL data reader - asp.net

I created Intranet project which connect with AD to retrieve User's
data as Image , Department . I did my code and it works well but I had
the below error a lot of times .
string User = ConfigurationManager.AppSettings["User"];
string Password = ConfigurationManager.AppSettings["Password"];
var entry = new DirectoryEntry("LDAP://" + "xxxxx", User, Password);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.SearchScope = SearchScope.Subtree;
string UserName = Page.User.Identity.Name;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", UserName.Split('\\')[1]);
SearchResult findUser = searcher.FindOne();
if (findUser != null)
{
DirectoryEntry user = findUser.GetDirectoryEntry();
//string loginuser = user.Properties["UserName"].Value.ToString();
LoggedUser = user.Properties["displayName"].Value.ToString();
Session.Add("LoggedUser", LoggedUser);
LoggedEmail = user.Properties["mail"].Value.ToString();
Session.Add("LoggedEmail", LoggedEmail);
string Mobile = user.Properties["Mobile"] != null && user.Properties["Mobile"].Value != null ? user.Properties["Mobile"].Value.ToString() : null;
string Login = user.Properties["sAMAccountName"].Value.ToString();
if (user.Properties["Department"].Value != null)
LoggedDepartement = user.Properties["Department"].Value.ToString();
_userDept = user.Properties["Department"].Value != null ? user.Properties["Department"].Value.ToString() : "";
ftier.AddLoggedUser(LoggedUser, LoggedDepartement, title, LoggedEmail, data, DateTime.Now, DateTime.Now, " nnnnn", true);

When I've done this in the past one of the problems was unusual characters in the properties of the user object caused this sort of error.
One approach would be to put error checking on each of the variables you're setting so the code can keep working, or export to a text file all the data and go through it using excel and look for unusual or strange control characters.
If the error always occurs at a certain person you could just look at the properties of that user and hope to find the issue that way.
Our issue was the use of Chinese simplified characters in some fields.
Hope this helps you track down your issue.
Dorje

Related

System.Net.WebClient.DownloadStringTaskAsync method when webpage contains ™ or other special characters

I am using the System.Net.WebClient.DownloadStringTaskAsync async method to upload a web page content and process it or just save it on my local folder. Everything is fine but when the web page contains some special characters like ™ or ®, they are not getting downloaded. Am I missing something here?
String contentToScrapeURL = "https://www.naylornetwork.com/aaho-advertorial/newsletter.asp?issueID=89542";
Boolean success = true;
using (System.Net.WebClient wc = new System.Net.WebClient())
{
String pageSourceCode = await wc.DownloadStringTaskAsync(contentToScrapeURL);
String path = #"C:\MyProjects\TestingThings\App_Data\" + "test.html";
File.WriteAllText(path, pageSourceCode);
}
Found it, or remembered it.
I did set the System.Net.WebClient.Encoding to Encoding.UTF8
So this below is the updated code
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Encoding = Encoding.UTF8;
String pageSourceCode = await wc.DownloadStringTaskAsync(contentToScrapeURL);
String path = #"C:\MyProjects\TestingThings\App_Data\" + "test.html";
File.WriteAllText(path, pageSourceCode);
}

Uploading Image/File via CSOM from ASP web app to SharePoint Online

Novice developer here with an issue I would appreciate some assistance with :-)
I am developing an ASP web application (a simple bulletin board, which allows users to create buy and sale adverts). All of my data is being stored/retrieved from an MSSQL database. However, I wish to store/retrieve images for the adverts using a SharePoint Online library.
I am struggling at the first hurdle, which is uploading the image to the library. I've debugged and debugged some more but I am still hitting a brick wall. After many hours of trying, I now have the code below, which is no longer returning any errors although the image never appears in the destination library.
Given all the above, I would sincerely appreciate any assistance from any experts out there!
The following code fires when the "create advert" button is pressed.
string currentUserName =
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
SqlConnection conn2;
SqlCommand comm2;
SqlDataReader reader;
string connectionString2 =
ConfigurationManager.ConnectionStrings["CCString"].ConnectionString;
conn2 = new SqlConnection(connectionString2);
comm2 = new SqlCommand("SELECT TOP 1 * FROM Threads WHERE ([AdvertiserName] = '" + currentUserName + "') ORDER BY PostCreationDateTime DESC", conn2);
conn2.Open();
reader = comm2.ExecuteReader();
reader.Read();
Guid imageID;
string imageIDConfirmed = "";
string fileExtension = "";
if (reader["UniqueImageID"].GetType().Name != "DBNull")
{
imageID = (Guid)reader["UniqueImageID"];
imageIDConfirmed = imageID.ToString().Replace(":", "-");
string myFile = jpgFileUpload.FileName;
fileExtension = myFile.Substring(myFile.Length - 4, 4);
}
reader.Close();
conn2.Close();
string username = "username#emailaddress.com";
string password = "password";
System.Security.SecureString securePass = new
System.Security.SecureString();
foreach (char ch in password.ToCharArray()) securePass.AppendChar(ch);
SharePointOnlineCredentials credentials = new
SharePointOnlineCredentials(username, securePass);
using (ClientContext client = new
ClientContext("https://company.sharepoint.com/sites/SiteName/"))
{
var formLib = client.Web.Lists.GetByTitle("Documents");
client.Credentials = credentials;
client.Load(formLib.RootFolder);
client.ExecuteQuery();
string fileName = #"C:\Temp\" + jpgFileUpload.FileName;
jpgFileUpload.SaveAs(fileName);
var fileUrl = "";
int fileLen;
fileLen = jpgFileUpload.PostedFile.ContentLength;
byte[] input = new byte[fileLen - 1];
input = jpgFileUpload.FileBytes;
UploadDocument(#"https://company.sharepoint.com/sites/SiteName/", "Documents", "https://company.sharepoint.com/sites/SiteName/Shared%20Documents/", "testDocument", input);
using (var fs = new FileStream(fileName, FileMode.Open))
{
var fi = new FileInfo(imageIDConfirmed + fileExtension);
fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
client.ExecuteQuery();
}
var libFields = formLib.Fields;
client.Load(libFields);
client.ExecuteQuery();
Microsoft.SharePoint.Client.File newFile =
client.Web.GetFileByServerRelativeUrl(fileUrl);
Microsoft.SharePoint.Client.ListItem item = newFile.ListItemAllFields;
item["Title"] = "Any Title";
item["File Name"] = "Any File Name";
item.Update();
client.Credentials = credentials;
client.ExecuteQuery();
which is no longer returning any errors although the image never appears in the destination library
Is it possible that the files are there but are in some unchecked-in state?
As a site collection admin, go to Documents -> Settings -> "Permissions and Management" section -> Manage files which have no checked in version.
If there are files with no checked in version, this could indicate the need to provide check-in logic in your code, or there might be an issue with required fields.

Preserve text line breaks to when collecting from database in ASP.NET MVC

I'm very new to programming and are trying hard to learn. I've been struggling with an issue for a few hours without understanding what I'm doing wrong.
My goal is to save text (article with a lot of line breaks) to a database, and then retrieve the text and view the output as it was written, with all line breaks preserved.
The text is part of an object named KaseriInfo.
I've read some topics regarding this and tried the following:
Before saving to the Db I use the inputText.Replace("\r\n", "<br />");
After retrieving from Db I user the inputText.Replace("<br />", "\r\n");
I've been mixing with the .Replace-methods in different ways but I won't get the result I wish for.
This is my code for adding to the database using a local web service:
public bool AddKaseri(KaserierInfo kaseri)
{
bool successOrNot = false;
Kaserier kaseriToBeAdded = new Kaserier();
kaseriToBeAdded.Title = kaseri.Title;
kaseriToBeAdded.Content = kaseri.Content.Replace("\r\n", "<br />");
kaseriToBeAdded.About = kaseri.About;
kaseriToBeAdded.Uploaded = DateTime.Now;
db.Kaseriers.Add(kaseriToBeAdded);
try
{
db.SaveChanges();
successOrNot = true;
}
catch (Exception e)
{
Console.WriteLine(e);
}
return successOrNot;
}
And this is the code for retrieving the data from the Db:
public KaserierInfo GetOneKaseri(int id)
{
var result = from row in db.Kaseriers
where row.Id == id
select row;
KaserierInfo kaseri = new KaserierInfo();
var kas = result.FirstOrDefault();
if (kas != null)
{
kaseri.Id = kas.Id;
kaseri.Title = kas.Title;
kaseri.About = kas.About;
kaseri.Content = kas.Content.Replace("<br />", "\r\n");
kaseri.UploadedDateOnly = kas.Uploaded.ToString();
kaseri.Uploaded = kas.Uploaded;
kaseri.UploadedDateOnly = kaseri.Uploaded.ToLongDateString();
}
return kaseri;
}
What is stored in the Db
The HTML-output won't come with line breaks for some reason. This is what is displayed:
Output on website
Here is the C# code inside the controller responsible:
public ActionResult ViewKaseri(int id)
{
//Getting the object from WS
var kas = kasref.GetOneKaseri(id);
//Moving to local object
KaseriModel kaseri = new KaseriModel();
kaseri.Id = kas.Id;
kaseri.About = kas.About;
kaseri.Title = kas.Title;
kaseri.Content = kas.Content;
kaseri.UploadedDateOnly = kas.UploadedDateOnly;
return View(kaseri);
}
I would be glad to solve this so that the line breaks will be rendered correctly. Please keep in mind that my skills are low.
Best
/J
you need to use #Html.Raw(). This will allow you to display the contents

Insert into bridge table entity framework

Hi guys,
I'm learning to climb with EF ,I do have basic understanding of CRUD with EF ,but now I have a table which have a navigation property (Which I suspect is the bridge table) ,so I need to add value into the bridge table ,I think I can do it with navigational property.
Problem Explained:
Original partial DB Diagram
Partial EF Model Diagram
Code I Wrote:
protected void BtnAddUser_Click(object sender, EventArgs e)
{
DBEntities entities = new DBEntities();
var usr = new User();
//I thought I would add an Roles object into usr.UserRoles.Add(usrRoles);
//but UserRoles have only two fields ,RoleTypeId and UserId
//var usrRoles = new Roles()
//{Id=0,RoleDescription="dfdfdf",RoleType="WebSite Admin"};
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
//What to Add in the .Add method
usr.UserRoles.Add(
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 1 ? "User created successfully." : "An error occured ,please try later.";
entities.Dispose();
}
Update (What I have tried so far):
I fetch "Website Admin" role from roles table and put it into ObjectContext.UserRoles.Add(UserRoleWebsiteAdmin);
So that what I did in the code,
//Fetch WebsiteAdmin from Roles
var userRole = from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole;
usr.UserName = TxtbxUserName.Text;
//same old code of usr.Property = someTextBox
//I have tried to type cast it LinqtoEntities result into Roles
usr.UserRoles.Add((Roles)userRole);
Exception generated
P.S: Let me know if you need more clarification.
Maybe you can use using http://msdn.microsoft.com/en-us/library/yh598w02.aspx and object initializer http://msdn.microsoft.com/en-us/library/bb384062.aspx for better readability so:
using(DBEntities entities = new DBEntities())
{
//Make user object
var user = new User{
UserName = TxtbxUserName.Text,
Password = TxtBxPassword.Text,
Email = TxtbxEmail.Text,
CreateDate = DateTime.Now,
LastActivityDate = DateTime.Now,
IsEnabled = true
};
//Fetch type of Role from Roles table
var userRole = entities.Roles.Where(x=>x.usrRole.Id ==1).Single();
user.UserRoles.Add(userRole);
entities.User.AddObject(user);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
}
Regards
Well thanks guys...
Here what I have done and it works,
DBEntities entities = new DBEntities();
//Make user object
var usr = new User();
//Fetch type of Role from Roles table
var userRole = (from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole).Single();
//copy user related info from textboxes
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
usr.UserRoles.Add(userRole as Roles);
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
entities.Dispose();

Facebook Credits callback in a mobile web application

I'm trying to create a Facebook Mobile Application using asp.net and MVC3 and integrate Facebook Credits as a payment method. First of all, taking the recent annoucements into consideration, is it now possible to have a mobile web application that accepts Facebook Credits?
If so, I've taken the example provided in the following post
http://www.m-webs.com/blog_facebookcredits.html
And implemented the following Controller action:
public JsonResult CallBack()
{
string fborder_info = Request.Form["order_info"];
string fborder_id = Request.Form["order_id"];
string fbmethod = Request.Form["method"];
if (fbmethod == "payments_get_items")
{
fborder_info = fborder_info.Substring(1, (fborder_info.Length - 2)); // remove the quotes
ulong credscost = 2; // Price of purchase in facebook credits
var theItem = new FacebookBuyItem()
{
item_id = 123456789,
description = "Own yours today!",
price = credscost,
title = "Digital Unicorn",
product_url = "http://www.facebook.com/images/gifts/21.png",
image_url = "http://www.facebook.com/images/gifts/21.png"
};
var res = new Dictionary<string, object>();
res["method"] = fbmethod;
res["order_id"] = fborder_id;
res["content"] = new object[] { theItem };
var jss = new JavaScriptSerializer();
var ob = jss.Serialize(res);
ob = ob.Replace("#$", #"\/".Replace("//", #"\/"));
return Json(ob, JsonRequestBehavior.AllowGet);
}
return null;
}
I've verified that the callback is being requested by facebook, and I've also captured the response being sent back, which appears to contain all of the required information to display the purchase dialog, but I'm still getting the following error message:
API Error Code: 1151
API Error Description: Sorry, but this app may not be eligible to accept Facebook Credits. If this app has accepted credits before, please try again.
Error Message: Invalid Application
and when tested from a mobile browser:
Sorry, but we're having trouble processing your payment. You have not been charged for this transaction. Please try again.
I've also noticed that my callback is being requested twice which doesn't seem right either.
Any insight into how to get my integration up and running would be greatly appreciated. My Facebook AppId is 177876855621874
Thanks.
Update: So I played around with the examples given and reverted back to webforms in order to test the example given at http://www.m-webs.com/blog_facebookcredits.html. In order to get this solution working in an asp.net MVC3 application I had to change the action type to HttpResponse instead of JsonResult which makes sense as the JsonResult leaves elements out that would normally be included in a HttpResponse.
So the Controller Action ended up looking like this:
[HttpPost]
public HttpResponse CallBack()
{
if (Request.Form["signed_request"] != null)
{
var decodeFbSignedRequest = FacebookSignedRequest.Parse(FacebookApplication.Current.AppSecret,
Request.Form["signed_request"]);
LogHelper.MicroLogMsg("SIGNED REQUEST DECODE:: " + decodeFbSignedRequest.Data);
}
string fborder_id = Request.Form["order_id"];
string fbmethod = Request.Form["method"];
string fborder_info = Request.Form["order_info"]; // Use this to look up a product on the database..
if (fbmethod == "payments_get_items")
{
int credscost = 2; // Price of purchase in facebook credits
var theItem = new FacebookBuyItem()
{
item_id = "123456AA",
description = "[Test Mode] Own yours today!",
price = credscost,
title = "[Test Mode] Digital Unicorn",
product_url = #"http:\/\/www.facebook.com\/images\/gifts\/21.png",
image_url = #"http:\/\/www.facebook.com\/images\/gifts\/21.png"
};
// Return the initial response to FB
//------------------------------------------
var res = new Dictionary<string, object>();
res["method"] = fbmethod;
res["content"] = new object[] { theItem };
var jss = new JavaScriptSerializer();
string ob = jss.Serialize(res);
LogHelper.MicroLogMsg(ob);
Response.ContentType = "application/json";
Response.Write(ob);
Response.End();
}
return null;
}
I hope this helps out anyone doing an MVC3 implementation for Facebook Credits.

Resources