Datas from database to custom List - asp.net

I would like to store some datas from a database to a list of a class.
Unfortunatly, my webpage is totally blank and totally emply...
This my code :
CODE BEHIND :
protected void Page_Load(object sender, EventArgs e)
{
// Requête en chaînes de caractères qui sera utilisée pour récupérer les données dans la table Template
string request = "SELECT Id, Name, Content From Template";
// Process principal
try
{
// Connexion à la base de données et à la table et utilisation de la requêtes SQL
SqlCommand cmd = new SqlCommand(request, connect);
connect.Open();
// Exécution de la requête SQL
SqlDataReader sdr = cmd.ExecuteReader();
// Si la commande comporte des lignes
if (sdr.HasRows)
{
sdr.Read();
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
List<TemplateObject> Liste_template = new List<TemplateObject>()
{
new TemplateObject(temp_id,temp_name)
};
}
GridView1.DataSource = Liste_template;
GridView1.DataBind();
}
finally
{
connect.Close();
}
}
Code from the Class i created :
public class TemplateObject
{
string Id_template { get; set; }
string Name_template { get; set; }
public TemplateObject(string id, string name)
{
this.Id_template = id;
this.Name_template = name;
}
}
I would like to store and display an object which is composed of one TemplateObject and one FormObject, composed with two parameters (as TemplateObject) : id and name. I d'ont create the FormObject, because i'm starting with one at first.
I have to store my datas like this, beacause the datasource is a bit weird and i only work with strings.

You need a loop
create the list before that loop
fill the list in the loop
List<TemplateObject> Liste_template = new List<TemplateObject>()
while(sdr.Read())
{
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
TemplateObject newObject = new TemplateObject(temp_id,temp_name);
Liste_template.Add(TemplateObject)
}
Now you can assign it as DataSource of the GridView:
GridView1.DataSource = Liste_template;
GridView1.DataBind();

Related

mail merge with dynamic file path

I had a problem generating a word template because I wanted it to be selected dynamically with ddlTemplate when selected to write in it with the merge field in the word template.
this is my code:
public partial class unTemplate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)// call the method for ONLY first time for visitor
{
{
populateDdlInstitution();
}
}
}
protected void populateDdlInstitution()
{
CRUD myCrud = new CRUD();
string mySql = #"select institutionid, institution from institution";
SqlDataReader dr = myCrud.getDrPassSql(mySql);
ddlInstitution.DataTextField = "institution";
ddlInstitution.DataValueField = "institutionid";
ddlInstitution.DataSource = dr;
ddlInstitution.DataBind();
}
protected void ddlInstitution_SelectedIndexChanged(object sender, EventArgs e)
{
// call a method to populate the template ddl
populateDdlTemplate();
}
protected void populateDdlTemplate()
{
CRUD myCrud = new CRUD();
string mySql = #"select internDocId, DocName
from internDoc
where institutionId = #institutionId";
Dictionary<string, object> myPara = new Dictionary<string, object>();
myPara.Add("#institutionId", ddlInstitution.SelectedItem.Value);
SqlDataReader dr = myCrud.getDrPassSql(mySql, myPara);
ddlTemplate.DataTextField = "DocName";
ddlTemplate.DataValueField = "internDocId";
ddlTemplate.DataSource = dr;
ddlTemplate.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
CRUD myCrud = new CRUD();
string mySql = #"select* from intern
where institutionId = #institutionId"/*+#"select internDocId,DocName from internDoc where internDocId=internDocId"*/;
Dictionary<string, object> myPara = new Dictionary<string, object>();
myPara.Add("#institutionId", ddlInstitution.SelectedItem.Value);
//myPara.AsEnumerable(#"internDocId");
SqlDataReader dr = myCrud.getDrPassSql(mySql, myPara);
gvData.DataSource = dr;
gvData.DataBind();
}
protected void btnGenerateTemplate_Click(object sender, EventArgs e)
{
wordT();
}
private static DataTable GetRecipients()
{
//Creates new DataTable instance.
DataTable table = new DataTable();
//Loads the database.
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + #"../../CustomerDetails.mdb");
//Opens the database connection.
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from intern", conn);
//Gets the data from the database.
adapter.Fill(table);
//Releases the memory occupied by database connection.
adapter.Dispose();
conn.Close();
return table;
}
public void wordT()
{
for (int i = 0; i <= gvData.Rows.Count - 1; i++)
{
String internId = gvData.Rows[i].Cells[0].Text;
String fullName = gvData.Rows[i].Cells[7].Text;
String cell = gvData.Rows[i].Cells[8].Text;
String email = gvData.Rows[i].Cells[9].Text;
Syncfusion.DocIO.DLS.WordDocument document = new Syncfusion.DocIO.DLS.WordDocument(Server.MapPath(getPath()));
//Deleting null fields
document.MailMerge.RemoveEmptyParagraphs = true;
string[] fieldNames = new string[] { "fullName", "internId", "email", "cell" };
string[] fieldValues = new string[] { fullName, internId, email, cell };
// mail merge
document.MailMerge.Execute(fieldNames, fieldValues);
//Saves
document.Save(Server.MapPath("~/myDoc/" + email + ".docx"));
document.Close();
}
// pass message to user notifying of successfull operation
lblOutput.Text = "Word Doc output generated successfully!";
}
public string getPath()
{
DirectoryInfo di = new DirectoryInfo(#"C:\projects\unSupervisorApp\Uploads\");
foreach (var d in di.EnumerateDirectories())
{
foreach (var fi in d.EnumerateFileSystemInfos())
{
if (fi.Name == (ddlTemplate.DataTextField))
{
return fi.FullName.Replace(fi.Name, "");
}
}
}
return di.FullName;
}
}//cls
the problem:
‎1-'C:/projects/unSupervisorApp/Uploads/' is a physical path but was expected to be a virtual path.‎
2- and sometime it gives me that it i can not find the file in EnumerateDirectories.
but i get the first one the most.
getFile
getPath
path of folder + ddlselectedItem.text

Populate a gridview with Object

I create a class with 3 parameters so as to populate and display a gridview.
this object is composed like this : string, string, list.
I managed to display the first and the second parameter, but not the third one, like this :
enter image description here
This is my main code :
protected void Page_Load(object sender, EventArgs e)
{
// Process principal
try
{
// Requête en chaînes de caractères qui sera utilisée pour récupérer les données dans la table Template
string request = "SELECT Id, Name, Content From Template";
// Connexion à la base de données et à la table et utilisation de la requêtes SQL
SqlCommand cmd = new SqlCommand(request, connect);
connect.Open();
// Exécution de la requête SQL
SqlDataReader sdr = cmd.ExecuteReader();
// Si la commande comporte des lignes
if (sdr.HasRows)
{
Liste_template = new List<TemplateObject>();
// Tant que le DataReader lit des informations.
while(sdr.Read())
{
string temp_name = sdr["Name"].ToString();
string temp_id = sdr["Id"].ToString();
TemplateObject newTemplate = new TemplateObject(temp_id, temp_name, liste_id_form("Content", sdr));
Liste_template.Add(newTemplate);
}
}
gv.DataSource = Liste_template;
gv.DataBind();
}
finally
{
connect.Close();
}
}
// Méthode pour délimiter chaque chaque chaine de caractères à partir des symboles dans le tableau delimiterChars.
public string[] RecupChaines(string chaine)
{
char[] delimiterChars = { ';', '&', '=', '"' };
string[] words = chaine.Split(delimiterChars);
return words;
}
// Méthode de récupération des Id des Form dans le champs Content de la table Template.
public List<String> liste_id_form(string field, SqlDataReader sdr)
{
List<string> listIdForm = new List<string>();
// enregistrement du contenu du champs Content dans une variable
string content = sdr[field].ToString();
// Tentative de séparation des deux parties de la chaine de caracteres
string chaineACouper = "<Property Name=\"Description\" Value=\"\" />";
string[] chaineArrive = content.Split(new string[] { chaineACouper }, StringSplitOptions.None);
chaineArrive[0] += chaineACouper;
// Séparation des deux parties.
string stringPartOne = chaineArrive[0];
string stringPartTwo = chaineArrive[1];
// Récuperation de la liste des valeurs des FormId de la chaine de caractères
string[] words = RecupChaines(stringPartTwo);
for (int i = 0; i < words.Length; i++)
{
if (words[i].Equals("FormId"))
{
listIdForm.Add(words[i + 5]);
}
}
return listIdForm;
}
}
I don't know how to loop on list_id_form, so as to display it on my gridview. For information, my class has an id, a name, and a list of datas.
I have to work with strings, because the datas from the database is not correctly stored. I don't have hand on this and i can't modify this.

Show Image from database on Web Api

I have a Web Api that shows some datas. Now, i have to Show a image, that is stored on a Oracle DB... in Oracle DB is everything ok and the Stored Procedure brings me a "Long Raw".
Actualy the result of FOTO on the controller is empty [{"ISUSPID":0,"FOTO":""}], even when on DB brings me the image...
The question is what i am doind wrong, thats the FOTO is empty on Json ???
This is my class [FotoEnvolvido]:
using System;
using System.ComponentModel.DataAnnotations;
namespace WebApiApp.Models
{
public class FotoEnvolvido
{
[Key]
public Int32 ISUSPID { get; set; }
public byte[] FOTO { get; set; }
}
}
This is my Controller:
[HttpGet]
[Route("Foto")]
public IEnumerable<FotoEnvolvido> GetFoto(Int32 isuspid)
{
DataSet lretorno = new DataSet();
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
OracleDataReader reader = null;
OracleCommand cmd = new OracleCommand();
cmd.Connection = connection;
cmd = new OracleCommand("MOBILE.XAPIMANDADOMOBILE.BUSCAFOTO", connection);
cmd.CommandType = CommandType.StoredProcedure;
//variáveis entrada
cmd.Parameters.Add(new OracleParameter("isuspid", isuspid));
//variáveis de saida
cmd.Parameters.Add(new OracleParameter("oretorno", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;
connection.Open();
cmd.ExecuteNonQuery();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
//CRIO A LISTA
lretorno.Load(reader, LoadOption.OverwriteChanges, "BUSCAFOTO");
connection.Close();
connection.Dispose();
//CARREGO O DATASET E TRANSFORMO PARA IENUMERABLE E RETORNO SEUS VALORES PRO JSON
return lretorno.Tables[0].AsEnumerable().Select(row => new FotoEnvolvido
{
FOTO = (byte[])(row["FOTO"]),
});
}
}

web service page System.IndexOutOfRangeException

public class GetAreaFromCity : System.Web.Services.WebService
{
[WebMethod]
public GetAreaByCityId ClassForGetCIty(int City_Id)
{
string CS =ConfigurationManager.ConnectionStrings["FOODINNConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spGetCityById",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("#ID", City_Id);
//To assiate this parameter object with cmd object
cmd.Parameters.Add(parameter);
GetAreaByCityId GETAreaByCityId =new GetAreaByCityId();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
//as WeakReference read data wewant ToString retrive Column value & then polute this property City_Id values
while (reader.Read()){
GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);
GETAreaByCityId.Area_Id = Convert.ToInt32(reader["Area_Id"]);
}
return GETAreaByCityId;
//ToString return sql
}
}
}
that's my codes for service page
public class GetAreaByCityId
{
public int Ca_Id {get;set; }
public int City_Id { get; set; }
public int Area_Id { get; set; }
}
that's the class for getting the Area by city
Create Proc [dbo].[spGetCityById]
#ID int
as
Begin
Select Area_Id from
CITIES_AREA where City_Id = #ID
End
GO
and above the database procedure which is data can be retrieve
System.IndexOutOfRangeException: City_Id
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at System.Data.SqlClient.SqlDataReader.get_Item(String name)
at WebApplication1.GetAreaFromCity.ClassForGetCIty(Int32 City_Id) in c:\Users\Mudassir\Documents\Visual Studio 2013\Projects\WebApplication1\WebAppli
the above error i dont know whats the problem
Your stored procedure is returning only Area_Id. Your code in the "while loop" while (reader.Read()){ is attempting to read data from two columns:
City_Id
Area_Id
You could add the column City_Id to the result set for your stored procedure query, BUT you already have that value because you are passing it to the stored procedure as a parameter.
Easiest fix is probably to just change this line:
GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);
to this:
GETAreaByCityId.City_Id = City_Id;

Asp.Net: Returning a DataSet from a Class

I've decided to start another thread based on the responses I got in this thread:
Asp.Net: Returning a Reader from a Class
I was returning a reader, but members have suggested I'd be better off returning a Dataset instead and also try to seperate the data access tier from the presentation tier.
This is what I have so far:
//my class methods
public DataSet GetSuppliers()
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("con_spSuppliersList", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#blogid", HttpContext.Current.Request.QueryString["p"]);
return FillDataSet(cmd, "SuppliersList");
}
//my FillDataSet method
private DataSet FillDataSet(SqlCommand cmd, string tableName)
{
SqlConnection conn = new SqlConnection(connectionString);
cmd.Connection = conn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
adapter.Fill(ds, tableName);
}
finally
{
conn.Close();
}
return ds;
}
// on my ascx page I call the method like so:
protected void Page_Load(object sender, EventArgs e)
{
//instantiate our class
MyClass DB = new MyClass();
// grab the table of data
DataTable dt = DB.GetSuppliers().Tables["SuppliersList"];
//loop through the results
foreach (DataRow row in dt.Rows)
{
this.supplierslist.InnerHtml += Server.HtmlEncode(row["Address"].ToString()) + "<br/>";
this.supplierslist.InnerHtml += "<b>Tel: </b>" + Server.HtmlEncode(row["Telephone"].ToString()) + "<p/>";
}
}
}
Would anyone like to suggest improvements?
Is my loop 'data tier' or 'presentation tier', should the loop be inside the class and I just return a formatted string instaed of a dataset?
Thanks for all the great advice
I also would use a Typed DataSet or create your own class that holds the properties so you are not dealing with strings like row["Address"] you would say object.Address and get compile time checking.
DataSets have a lot of built in functionality that is nice but also caries with it a lot of overhead that might not be needed in something simple. Creating a simple class with properties and passing that out of your data access layer is probably the simplest way to implement what you want.
Something like this on the DAL (Data Access Layer) side:
//Also pass in the blogID dont have the DAL get the value from the UI layer..
//make the UI layer pass it in.
public IList<Supplier> GetSuppliers(string connectionString, int blogID)
{
IList<Supplier> suppliers = new List<Supplier>();
//wrap with the using statements
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("con_spSuppliersList", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#blogid", blogID);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
suppliers.Add(new Supplier
{
Address = reader.GetString(0),
Telephone = reader.GetString(1)
});
}
}
}
return suppliers;
}
}
public class Supplier
{
//I would have Address an object....but you have as string
//public Address Address { get; set; }
public string Address { get; set; }
public string Telephone { get; set; }
}
//Example if you went with Address class...
public class Address
{
//Whatever you want in the address
public string StreetName { get; set; }
public string Country { get; set; }
public string Region { get; set; }
public string City { get; set; }
}
One thing you should get in the habit of doing is calling Dispose() on your SqlConnection. The best pattern to do this is to use the using statement, which will automatically dispose of it for you. It looks like this:
private DataSet FillDataSet(SqlCommand cmd, string tableName)
{
using(SqlConnection conn = new SqlConnection(connectionString))
{
cmd.Connection = conn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
adapter.Fill(ds, tableName);
}
finally
{
conn.Close();
}
return ds;
}
}
What you have in the foreach loop in Page_Load, is presentation logic (layout), and IMO this should not be in the code-behind of your page, but in the markup.
I'd suggest that instead of using a foreach loop to construct the HTML output, you should use a databound control (such as a asp:Repeater, DataList or GridView). Then you can bind the repeater to your dataset or datatable and have all the markup where it belongs (in the ASCX file). See this page for an example.
As a general note: you can find lots of tutorials on www.asp.net, e.g. about data access: http://www.asp.net/%28S%28pdfrohu0ajmwt445fanvj2r3%29%29/learn/data-access/

Resources