I'm trying to implement a function within a Class method and I am somewhat new to C#.
Basically, I have a method that iterates through row in a database and sets values to variables. Then, if a document has been created already it updates the document, if not it creates the document. I'm trying to factor out some of the code and I don't know where to put it as it still needs a reference to my variables. I would like to factor out the repeated items in the if else statement.
private void SyncKinases()
{
DataSet ds = new DataSet();
ds = gn.ExecuteQuery("dx.kinasedatasheet.selectstagingkinases", null);
TreeProvider tp = new TreeProvider(ui);
VersionManager vm = new VersionManager(tp);
TreeNode node;
WorkflowManager wm = new WorkflowManager(tp);
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string className = "dx.kinasedatasheet";
string title = dr["Title"].ToString();
string technologyPlatform = dr["TechnologyPlatform"].ToString();
string ambitGeneSymbol = dr["AmbitGeneSymbol"].ToString();
string targetDescription = dr["TargetDescription"].ToString();
string entrezGeneSymbol = dr["EntrezGeneSymbol"].ToString();
int entrezGeneID = int.Parse(dr["EntrezGeneID"].ToString());
string aliases = dr["Aliases"].ToString();
string kinaseGroup = dr["KinaseGroup"].ToString();
string species = dr["Species"].ToString();
string accessionNumber = dr["AccessionNumber"].ToString();
string kinaseConstruct = dr["KinaseConstruct"].ToString();
string kinaseForm = dr["KinaseForm"].ToString();
string expressionSystem = dr["ExpressionSystem"].ToString();
double avgZValue = 0;
if (!(dr["AverageZValue"] is DBNull))
{
avgZValue = double.Parse(dr["AverageZValue"].ToString());
}
string panel = dr["Panel"].ToString();
string compoundsKds = dr["CompoundsKds"].ToString();
string mutationRelevance = dr["MutationRelevance"].ToString();
string mutationReferences = dr["MutationReferences"].ToString();
string kinaseAliasPath = "/Kinase-Data-Sheets";
if (!(dr["NodeID"] is System.DBNull))
{
node = tp.SelectSingleNode(int.Parse(dr["NodeID"].ToString()));
vm.CheckOut(node);
node.DocumentName = ambitGeneSymbol;
node.NodeName = ambitGeneSymbol;
node.SetValue("Title", title);
node.SetValue("TechnologyPlatform", technologyPlatform);
node.SetValue("AmbitGeneSymbol", ambitGeneSymbol);
node.SetValue("TargetDescription", targetDescription);
node.SetValue("EntrezGeneSymbol", entrezGeneSymbol);
node.SetValue("EntrezGeneID", entrezGeneID);
node.SetValue("Aliases", aliases);
node.SetValue("KinaseGroup", kinaseGroup);
node.SetValue("Species", species);
node.SetValue("AccessionNumber", accessionNumber);
node.SetValue("KinaseConstruct", kinaseConstruct);
node.SetValue("KinaseForm", kinaseForm);
node.SetValue("ExpressionSystem", expressionSystem);
if (!(dr["AverageZValue"] is DBNull))
{
node.SetValue("AverageZValue", avgZValue);
}
node.SetValue("Panel", panel);
node.SetValue("CompoundsKds", compoundsKds);
node.SetValue("MutationRelevance", mutationRelevance);
node.SetValue("MutationReferences", mutationReferences);
node.SetValue("DocumentPublishTo", null);
node.Update();
updatedKinaseCount++;
vm.CheckIn(node, null, null);
WorkflowInfo wi = wm.GetNodeWorkflow(node);
if (node.IsPublished)
{
wm.AutomaticallyPublish(node, wi, null);
}
}
else
{
node = TreeNode.New(className, tp);
node.DocumentName = ambitGeneSymbol;
node.NodeName = ambitGeneSymbol;
node.SetValue("Title", title);
node.SetValue("TechnologyPlatform", technologyPlatform);
node.SetValue("AmbitGeneSymbol", ambitGeneSymbol);
node.SetValue("TargetDescription", targetDescription);
node.SetValue("EntrezGeneSymbol", entrezGeneSymbol);
node.SetValue("EntrezGeneID", entrezGeneID);
node.SetValue("Aliases", aliases);
node.SetValue("KinaseGroup", kinaseGroup);
node.SetValue("Species", species);
node.SetValue("AccessionNumber", accessionNumber);
node.SetValue("KinaseConstruct", kinaseConstruct);
node.SetValue("KinaseForm", kinaseForm);
node.SetValue("ExpressionSystem", expressionSystem);
if (!(dr["AverageZValue"] is DBNull))
{
node.SetValue("AverageZValue", avgZValue);
}
node.SetValue("Panel", panel);
node.SetValue("CompoundsKds", compoundsKds);
node.SetValue("MutationRelevance", mutationRelevance);
node.SetValue("MutationReferences", mutationReferences);
node.SetValue("DocumentPublishTo", null);
node.SetValue("DocumentCulture", "en-US");
TreeNode parentNode = tp.SelectSingleNode("DiscoveRx", kinaseAliasPath, "en-US");
node.Insert(parentNode);
//vm.CheckIn(node, null, null);
newKinaseCount++;
}
}
}
ArchiveItems(archivedKinaseCount, "dx.kinasedatasheet.selectarchivekinases");
}
In addition to refactoring your routine I'd recommend creating some extension methods to save you some typing. For example, here's the an extension for parsing your doubles:
public static class Extensions
{
public static double ToDoubleIfNotDBNull(this object item)
{
if (item is DBNULL) return 0;
return double.Parse(item.ToString());
}
}
So then your code becomes:
double avgZValue = dr["AverageZValue"].ToDoubleIfNotDBNull();
You can just refactor your code so you don't need to set the node values in different cases:
private void SyncKinases()
{
DataSet ds = new DataSet();
ds = gn.ExecuteQuery("dx.kinasedatasheet.selectstagingkinases", null);
TreeProvider tp = new TreeProvider(ui);
VersionManager vm = new VersionManager(tp);
TreeNode node;
WorkflowManager wm = new WorkflowManager(tp);
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string className = "dx.kinasedatasheet";
string title = dr["Title"].ToString();
string technologyPlatform = dr["TechnologyPlatform"].ToString();
string ambitGeneSymbol = dr["AmbitGeneSymbol"].ToString();
string targetDescription = dr["TargetDescription"].ToString();
string entrezGeneSymbol = dr["EntrezGeneSymbol"].ToString();
int entrezGeneID = int.Parse(dr["EntrezGeneID"].ToString());
string aliases = dr["Aliases"].ToString();
string kinaseGroup = dr["KinaseGroup"].ToString();
string species = dr["Species"].ToString();
string accessionNumber = dr["AccessionNumber"].ToString();
string kinaseConstruct = dr["KinaseConstruct"].ToString();
string kinaseForm = dr["KinaseForm"].ToString();
string expressionSystem = dr["ExpressionSystem"].ToString();
double avgZValue = 0;
if (!(dr["AverageZValue"] is DBNull))
{
avgZValue = double.Parse(dr["AverageZValue"].ToString());
}
string panel = dr["Panel"].ToString();
string compoundsKds = dr["CompoundsKds"].ToString();
string mutationRelevance = dr["MutationRelevance"].ToString();
string mutationReferences = dr["MutationReferences"].ToString();
string kinaseAliasPath = "/Kinase-Data-Sheets";
bool isNewNode = false;
if (!(dr["NodeID"] is System.DBNull))
{
node = tp.SelectSingleNode(int.Parse(dr["NodeID"].ToString()));
vm.CheckOut(node);
}
else
{
node = TreeNode.New(className, tp);
node.SetValue("DocumentCulture", "en-US");
isNewNewNode = true;
}
node.DocumentName = ambitGeneSymbol;
node.NodeName = ambitGeneSymbol;
node.SetValue("Title", title);
node.SetValue("TechnologyPlatform", technologyPlatform);
node.SetValue("AmbitGeneSymbol", ambitGeneSymbol);
node.SetValue("TargetDescription", targetDescription);
node.SetValue("EntrezGeneSymbol", entrezGeneSymbol);
node.SetValue("EntrezGeneID", entrezGeneID);
node.SetValue("Aliases", aliases);
node.SetValue("KinaseGroup", kinaseGroup);
node.SetValue("Species", species);
node.SetValue("AccessionNumber", accessionNumber);
node.SetValue("KinaseConstruct", kinaseConstruct);
node.SetValue("KinaseForm", kinaseForm);
node.SetValue("ExpressionSystem", expressionSystem);
if (!(dr["AverageZValue"] is DBNull))
{
node.SetValue("AverageZValue", avgZValue);
}
node.SetValue("Panel", panel);
node.SetValue("CompoundsKds", compoundsKds);
node.SetValue("MutationRelevance", mutationRelevance);
node.SetValue("MutationReferences", mutationReferences);
node.SetValue("DocumentPublishTo", null);
if (isNewNode)
{
TreeNode parentNode = tp.SelectSingleNode("DiscoveRx", kinaseAliasPath, "en-US");
node.Insert(parentNode);
//vm.CheckIn(node, null, null);
newKinaseCount++;
}
else
{
node.Update();
updatedKinaseCount++;
vm.CheckIn(node, null, null);
WorkflowInfo wi = wm.GetNodeWorkflow(node);
if (node.IsPublished)
{
wm.AutomaticallyPublish(node, wi, null);
}
}
}
}
ArchiveItems(archivedKinaseCount, "dx.kinasedatasheet.selectarchivekinases");
}
You now also don't need all of those temporary variables from dr columns since they will only be used once. Removing those will make your method much shorter and more readable.
Just create a new method and send the values as parameters.
void SetNodeValues(Node node, DataRow row)
{
string title = dr["Title"].ToString();
....
node.SetValue("Title", title);
...
}
You might be able to do it all with a for loop (untested and not match your variables)
foreach(var col in Table.Columns)
node.SetValue(col.Name, dr[col]);
If you were using an ORM, you could send an object instead of the DataRow but that is beyond the scope of this question.
Related
i want that my variable var repFolderTree hold old value with new value .
foreach (DataRow row in _dt.Rows)
{
string strFolderData = row["ReportFolder"].ToString();
var repFolderTree = crcr.GetAllReportsHierarchical(username, strFolderData);
repFolderTree.FolderName = "All Reports";
uxAllCatalogHierarchical.Text = string.Format("<div class=\"hierarchicalCatalog\">{0}</div>", HierarchicalCatalogView(repFolderTree, 0, showFolder));
}
public CrissCrossLib.Hierarchical.CrcReportFolder GetAllReportsHierarchical(string username,string path)
{
var hierItems = GetAllReportsHierarchicalNoCache(username, path);
m_cacheManager.AllReportsHierarchicalCacheByUsername.Add(username, hierItems);
return hierItems;
}
private string HierarchicalCatalogView(CrcReportFolder rootFolder, int level, string showFolder)
{
_dt = _ssrsDAC.GetReportListByUser(Convert.ToInt32(Session["LoginID"]));
StringBuilder sb = new StringBuilder();
sb.Append("<div class=\"folderBox\">");
string scrollTo = "";
if (PathMatch(showFolder, rootFolder.Path))
scrollTo = " scrollToFolder";
sb.AppendFormat("<div class=\"folderName{1}\">{0}</div>", rootFolder.FolderName, scrollTo);
string show = "none";
if (level == 0 || PathContains(showFolder, rootFolder.Path))
show = "block";
sb.AppendFormat("<div class=\"folderChildren\" style=\"display:{0}\">", show);
foreach (CrcReportFolder subFolderLoop in rootFolder.SubFolders)
sb.Append(HierarchicalCatalogView(subFolderLoop, level + 1, showFolder));
foreach (CrcReportItem itemLoop in rootFolder.Reports)
{
string str = itemLoop.DisplayName;
DataRow[] foundAuthors = _dt.Select("ReportName = '" + str + "'");
if (foundAuthors.Length != 0)
{
sb.Append("<div class=\"reportRow\">");
sb.AppendFormat("<a class=\"reportLink vanillaHover\" href=\"Report.aspx?path={0}\" >{1}</a>",
Server.UrlEncode(itemLoop.ReportPath), itemLoop.DisplayName);
if (!string.IsNullOrEmpty(itemLoop.ShortDescription))
sb.AppendFormat("<div class=\"reportInfo\">{0}</div>", itemLoop.ShortDescription);
sb.Append("<div class=\"clear\"></div></div>");
}
}
sb.Append("</div></div>");
return sb.ToString();
}
i have a control where i am listing all the value that i am getting from
var repFolderTree = crcr.GetAllReportsHierarchical(username, strFolderData);
so every time loop after that i lost the last value and contain the current value. so i want that i can get all the value after the loop and bind on this control that i am doing in this this line of code
uxAllCatalogHierarchical.Text = string.Format("<div class=\"hierarchicalCatalog\">{0}</div>", HierarchicalCatalogView(repFolderTree, 0, showFolder));
i think my code make some scene for you .
you can use List or Collection to store all the values , with Add operation to add the var value.
List<object> repFolderTree = new List<object>();
foreach (DataRow row in _dt.Rows)
{
string strFolderData = row["ReportFolder"].ToString();
var repFolderTree = crcr.GetAllReportsHierarchical(username, strFolderData);
repFolderTree .Add(repFolderTree );
repFolderTree.FolderName = "All Reports";
uxAllCatalogHierarchical.Text = string.Format("<div class=\"hierarchicalCatalog\">{0}</div>", HierarchicalCatalogView(repFolderTree, 0, showFolder));
}
Need help to get the 1st row record and return record as string in the << >> after while() loop.
There are a lot of columns in one row, I'm having a problem to declare it as string st? like usually string st = new string() please help to correct it
Thanks
public string Get_aodIdeal(string SubmittedBy)
{
String errMsg = "";
Guid? rguid = null;
int isOnContract = 0;
int isFreeMM = 0;
string _FileName;
DateTime InstallDateTime = DateTime.Now;
string FileDate = ToYYYYMMDD(DateTime.Now);
errMsg = "Unknown Error.";
SqlConnection conn = null; SqlCommand cmd = null;
string st = null;
conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["iDeal"].ConnectionString);
cmd = new SqlCommand();
string SQL = "select TOP 1 * from table1 Order by SubmittedOn desc";
SqlDataAdapter sqd = new SqlDataAdapter(SQL, conn);
cmd.CommandTimeout = 1200;
conn.Open();
SqlDataReader sqr;
//sqd.SelectCommand.Parameters.Add("#Submitted", SqlDbType.Int).Value = PostID;
sqr = sqd.SelectCommand.ExecuteReader();
while (sqr.Read())
st = new string{
rguid = cmd.Parameters["#rguid"].Value as Guid?,
ridno = int.Parse(sqr["ridno"].ToString()),
SubmittedOn= DateTime.Parse(sqr["SubmittedOn"].ToString()),
SubmittingHost = sqr["SubmittingHost"].ToString(),
ServiceAgreementNo = sqr["ServiceAgreementNo"].ToString(),
DocumentID = sqr["DocumentID"].ToString(),
Source = sqr["Source"].ToString(),
FileName = sqr["FileName"].ToString(),
FileType = sqr["FileType"].ToString(),
FileDate = DateTime.Parse(sqr["FileDate"].ToString()),
InstallTime = DateTime.Parse(sqr["InstallTime"].ToString()),
CalenderCode = cmd.Parameters["CalenderCode"].Value as Guid,
isFreeMM = bool.Parse(sqr["isFreeMM"].ToString()),
isOnContract = bool.Parse(sqr["isOnContract"].ToString()),
isProcessed = bool.Parse(sqr["isProcessed"].ToString()),
ProcessedByFullName = sqr["ProcessedByFullName"].ToString(),
isDelete = bool.Parse(sqr["isDelete"].ToString()),
version = int.Parse(sqr["Version"].ToString()),
LastUpdatedBy = DateTime.Parse(sqr["LastUpdatedBy"].ToString()),
LastUpdatedOn = DateTime.Parse(sqr["LastUpdatedOn"].ToString()),
shopGuid = sqr["shopGuid"].ToString(),
MacID = sqr["MacID"].ToString(),
MSISDN = sqr["MSISDN"].ToString()
}
You can use a StringBuilder for this purpose as like the following:
StringBuilder strBuilder= new StringBuilder();
while (sqr.Read())
{
strBuilder.AppendFormat("PostID : {0}{1}",sqr["PostID"].ToString(),Environment.NewLine);
strBuilder.AppendFormat("dateposted : {0}{1}",sqr["dateposted"].ToString(),Environment.NewLine);
// And so on Build your string
}
Finally the strBuilder.ToString() will give you the required string. But More smarter way is Create a Class with necessary properties and an Overrided .ToString method for display the output.
Let AodIdeal be a class with an overrided ToString() method. And Let me defined it like the following :
public class AodIdeal
{
public int PostID { get; set; }
public string dateposted { get; set; }
public string Source { get; set; }
// Rest of properties here
public override string ToString()
{
StringBuilder ObjectStringBuilder = new StringBuilder();
ObjectStringBuilder.AppendFormat("PostID : {0}{1}", PostID, Environment.NewLine);
ObjectStringBuilder.AppendFormat("dateposted : {0}{1}",dateposted, Environment.NewLine);
ObjectStringBuilder.AppendFormat("Source : {0}{1}", Source, Environment.NewLine);
// and so on
return ObjectStringBuilder.ToString();
}
}
Then you can create an object of the class(let it be objAodIdeal), and make use of its properties instead for the local variables. And finally objAodIdeal.ToString() will give you the required output.
Example usage
AodIdeal objAodIdeal= new AodIdeal();
while (sqr.Read())
{
objAodIdeal.PostID = int.Parse(sqr["PostID"].ToString());
objAodIdeal.dateposted= sqr["dateposted"].ToString();
// assign rest of properties
}
string requiredString= objAodIdeal.ToString();
I am creating a method which returns datatable and an int value.I have create a method which returns only datatable.Please take a look on the code
public static DataTable ShutterstockSearchResults(string url)
{
int TotalCont=0;
DataTable dt = new DataTable();
try
{
//intigration using Basic Aouth with authrization headers
var request = (HttpWebRequest)WebRequest.Create(url);
var username = "SC";
var password = "SK";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
TotalCount = myojb.total_count;
dt.Columns.Add("Id");
dt.Columns.Add("Discription");
dt.Columns.Add("Small_Thumb_URl");
dt.Columns.Add("Large_Thumb_URL");
dt.Columns.Add("Prieview_URL");
dt.Columns.Add("ContributorID");
dt.Columns.Add("aspect");
dt.Columns.Add("image_type");
dt.Columns.Add("is_illustration");
dt.Columns.Add("media_type");
foreach (var item in myojb.data)
{
var row = dt.NewRow();
row["ID"] = item.id;
row["Discription"] = item.description;
row["Small_Thumb_URl"] = item.assets.small_thumb.url;
row["Large_Thumb_URL"] = item.assets.large_thumb.url;
row["Prieview_URL"] = item.assets.preview.url;
row["ContributorID"] = item.contributor.id;
row["aspect"] = item.aspect;
row["image_type"] = item.image_type;
row["is_illustration"] = item.is_illustration;
row["media_type"] = item.media_type;
dt.Rows.Add(row);
}
// List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
return dt;
}
I want to return datatable and TotalCont.please help
Generally speaking, a method can only return one type.
You have two options:
1) Create a class that has a DataTable and an int field, such as:
public class MyReturnType
{
public DataTable TheDataTable {get; set;}
public int TotalCount {get; set;}
}
And return this type from your method.
2) You can add an out parameter to your method:
public static DataTable ShutterstockSearchResults(string url, out totalCount)
And assign to totalCount within your method.
public static Tuple<DataTable, int> ShutterstockSearchResults(string url)
{
[...]
return new Tuple<DataTable, int>(dt, totalCount);
}
public static void SomeConsumerMethod()
{
var result = ShutterstockSearchResults(myPath);
DataTable dt = result.Item1;
int totalCount = result.Item2;
}
To answer the comments in Klaus answer:
public class MyReturnType
{
public DataTable TheDataTable {get; set;}
public int TotalCount {get; set;}
}
and in your method:
public static MyReturnType ShutterstockSearchResults(string url)
{
MyReturnType result=new MyReturnType();
int TotalCont=0;
DataTable dt = new DataTable();
try
{
//intigration using Basic Aouth with authrization headers
var request = (HttpWebRequest)WebRequest.Create(url);
var username = "SC";
var password = "SK";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
TotalCount = myojb.total_count;
dt.Columns.Add("Id");
dt.Columns.Add("Discription");
dt.Columns.Add("Small_Thumb_URl");
dt.Columns.Add("Large_Thumb_URL");
dt.Columns.Add("Prieview_URL");
dt.Columns.Add("ContributorID");
dt.Columns.Add("aspect");
dt.Columns.Add("image_type");
dt.Columns.Add("is_illustration");
dt.Columns.Add("media_type");
foreach (var item in myojb.data)
{
var row = dt.NewRow();
row["ID"] = item.id;
row["Discription"] = item.description;
row["Small_Thumb_URl"] = item.assets.small_thumb.url;
row["Large_Thumb_URL"] = item.assets.large_thumb.url;
row["Prieview_URL"] = item.assets.preview.url;
row["ContributorID"] = item.contributor.id;
row["aspect"] = item.aspect;
row["image_type"] = item.image_type;
row["is_illustration"] = item.is_illustration;
row["media_type"] = item.media_type;
dt.Rows.Add(row);
}
// List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
result.TheDataTable=dt;
result.TotalCount=TotalCount;
return result:
}
Your method needs an additional out parameter if you want to "return" more than one value. Just pass an uninitialized variable of the desired type into your method and assign that variable inside.
public void Test()
{
int i;
DataTable ShutterstockSearchResults("Some string", out i);
}
your ShutterstockSearchResults method needs to be modified accordingly:
public static DataTable ShutterstockSearchResults(string url, out int outParam)
{
outParam = 10;
// do other stuff
}
If you do not change outParam any further inside ShutterstockSearchResults, it will have the value 10 after returning to Test.
You can accomplish this with a Tuple. Consider the following simple example:
public class EmptyClass
{
public static void Main(){
EmptyClass something = new EmptyClass ();
Tuple<String, int> tuple = something.returnMe ();
Console.WriteLine ("Item 1: " + tuple.Item1);
Console.WriteLine ("Item 2: " + tuple.Item2);
}
public EmptyClass ()
{
}
public Tuple<String, int> returnMe() {
return Tuple.Create ("Hello", 2);
}
}
I convert XML into datatable and now want to convert data table into XML again.
I have database in which four XML's are there and have to change that text xml
public ActionResult getChangeContent(string arg, string content)
{
char[] a = { ':' };
string[] id = arg.Split(a);
decimal tid = Convert.ToDecimal(id[0]);
decimal jid = Convert.ToDecimal(id[1]);
string groupname = id[2];
var gp = (from Trans_Mast in r2ge.Transcription_Master where Trans_Mast.Transcription_Id == tid && Trans_Mast.Entity_Id == jid select Trans_Mast).Distinct();
foreach (var g in gp)
{
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(g.Text_xml)));
DataTable text = ds.Tables[0];
for (int i = 0; i < text.Rows.Count; i++)
{
if (text.Rows[i]["group"].Equals(groupname))
{
text.Rows[i]["Text_Text"] = content;
}
text.AcceptChanges();
}
ConvertDatatableToXML(text);
}
return View();
}
public string ConvertDatatableToXML(DataTable dtTemp)
{
MemoryStream str = new MemoryStream();
dtTemp.WriteXml(str, true);
str.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(str);
string xmlstr;
xmlstr = sr.ReadToEnd();
return (xmlstr);
}
Data set is changed but there is no affect on XML.. any suggestion please..
use this piece of code :
private static string ConvertDataTableToXML(DataTable dtBuildSQL)
{
DataSet dsBuildSQL = new DataSet();
StringBuilder sbSQL;
StringWriter swSQL;
string XMLformat;
sbSQL = new StringBuilder();
swSQL = new StringWriter(sbSQL);
dsBuildSQL.Merge(dtBuildSQL, true, MissingSchemaAction.AddWithKey);
dsBuildSQL.Tables[0].TableName = “Table”;
foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
{
col.ColumnMapping = MappingType.Attribute;
}
dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
XMLformat = sbSQL.ToString();
return XMLformat;
}
Code below is me trying to do just that. It returns all rows but only like DEFAULT VALUES (0, empty string, empty date...) and "Allow Nulls" is false for all columns in my db table. I am truly stuck. I am still in process of learning c#, so if someone could please explain to me WHAT am I doing wrong here? Is there a better way to do this?
public List<XNarudzbe> GetXNarudzbe()
{
var listXnar = new List<XNarudzbe>();
using (SqlConnection NConnection = new SqlConnection(Params.ConnectionStr))
{
NConnection.Open();
using (var cmd = new SqlCommand("SELECT * FROM [dbo].[XDATA_NARUDZBE]", NConnection))
{
SqlDataReader reader = cmd.ExecuteReader();
int id = reader.GetOrdinal("ID");
int dt_get = reader.GetOrdinal("DT_GET");
int rn_datum = reader.GetOrdinal("RN_DATUM");
int datum = reader.GetOrdinal("DATUM");
int dt_stamp = reader.GetOrdinal("DT_STAMP");
int art_id = reader.GetOrdinal("ART_ID");
int cijena_k = reader.GetOrdinal("CIJENA_K");
int cijena_mp = reader.GetOrdinal("CIJENA_MP");
int cijena_vp = reader.GetOrdinal("CIJENA_VP");
int faktura = reader.GetOrdinal("FAKTURA");
int isporuceno = reader.GetOrdinal("ISPORUCENO");
int iznos_k = reader.GetOrdinal("IZNOS_K");
int iznos_p = reader.GetOrdinal("IZNOS_P");
int naruceno = reader.GetOrdinal("NARUCENO");
int narudzba = reader.GetOrdinal("NARUDZBA");
int otpremnica = reader.GetOrdinal("OTPREMNICA");
int pdv = reader.GetOrdinal("PDV");
int povrat_k = reader.GetOrdinal("POVRAT_K");
int povrat_p = reader.GetOrdinal("POVRAT_P");
int pp_id = reader.GetOrdinal("PP_ID");
int preporuka = reader.GetOrdinal("PREPORUKA");
int rabat = reader.GetOrdinal("RABAT");
int rn_id = reader.GetOrdinal("RN_ID");
int skart = reader.GetOrdinal("SKART");
int user_id = reader.GetOrdinal("USER_ID");
int var_n = reader.GetOrdinal("VAR_N");
int var_v = reader.GetOrdinal("VAR_V");
int veleprodaja = reader.GetOrdinal("VELEPRODAJA");
int vraceno = reader.GetOrdinal("VRACENO");
int isporuka_id = reader.GetOrdinal("ISPORUKA_ID");
int otpremljeno = reader.GetOrdinal("OTPREMLJENO");
int promjena = reader.GetOrdinal("PROMJENA");
int rj_id = reader.GetOrdinal("RJ_ID");
int zakljucano = reader.GetOrdinal("ZAKLJUCANO");
if (reader.HasRows)
{
while (reader.Read())
{
var recXNar = new XNarudzbe();
recXNar.id = reader["ID"] as decimal? ?? 0M; // reader.GetDecimal(id);
recXNar.dt_get = reader.GetDateTime(dt_get);
recXNar.rn_datum = reader.GetDateTime(rn_datum);
recXNar.datum = reader.GetDateTime(datum);
recXNar.dt_stamp = reader.GetDateTime(dt_stamp);
recXNar.art_id = reader.GetDecimal(art_id);
recXNar.cijena_k = reader.GetDecimal(cijena_k);
recXNar.cijena_mp = reader.GetDecimal(cijena_mp);
recXNar.cijena_vp = reader.GetDecimal(cijena_vp);
recXNar.faktura = reader.GetDecimal(faktura);
recXNar.isporuceno = reader.GetDecimal(isporuceno);
recXNar.iznos_k = reader.GetDecimal(iznos_k);
recXNar.iznos_p = reader.GetDecimal(iznos_p);
recXNar.naruceno = reader.GetDecimal(naruceno);
recXNar.narudzba = reader.GetDecimal(narudzba);
recXNar.otpremnica = reader.GetDecimal(otpremnica);
recXNar.pdv = reader.GetDecimal(pdv);
recXNar.povrat_k = reader.GetDecimal(povrat_k);
recXNar.povrat_p = reader.GetDecimal(povrat_p);
recXNar.pp_id = reader.GetDecimal(pp_id);
recXNar.preporuka = reader.GetDecimal(preporuka);
recXNar.rabat = reader.GetDecimal(rabat);
recXNar.rn_id = reader.GetDecimal(rn_id);
recXNar.skart = reader.GetDecimal(skart);
recXNar.user_id = reader.GetDecimal(user_id);
recXNar.var_n = reader.GetDecimal(var_n);
recXNar.var_v = reader.GetDecimal(var_v);
recXNar.veleprodaja = reader.GetDecimal(veleprodaja);
recXNar.vraceno = reader.GetDecimal(vraceno);
recXNar.isporuka_id = reader.GetString(isporuka_id);
recXNar.otpremljeno = reader.GetString(otpremljeno);
recXNar.promjena = reader.GetString(promjena);
recXNar.rj_id = reader.GetString(rj_id);
recXNar.zakljucano = reader.GetString(zakljucano);
listXnar.Add(recXNar);
}
}
reader.Close();
}
}
return listXnar;
}
There is a better way ( You need to just do it once and it will help in future). Derive a class from DbDataReader that will take sqldatareader in the constructor:
public class CustomReader : DbDataReader
{
private readonly SqlDataReader sqlDataReader;
//Set the sqlDataReader
public CustomReader(SqlDataReader sqlDataReader)
{
this.sqlDataReader = sqlDataReader;
//Cache the names
this.CacheColumns();
}
private Dictionary<string,int> nameOrdinals = new Dictionary<string, int>();
private void CacheColumns()
{
int fieldCount= this.sqlDataReader.FieldCount;
for (int i = 0; i <= fieldCount-1; i++)
{
string name=sqlDataReader.GetName(i);
nameOrdinals.Add(name,i);
}
}
public override object this[string name]
{
get
{
int ordinal=this.nameOrdinals[name];
return this.GetValue(ordinal);
}
}
//Custom implementation
public string GetString(string name)
{
int ordinal = this.nameOrdinals[name];
return this.GetString(ordinal);
}
//Custom implementation
public string GetString(string name,string defaultValue)
{
int ordinal = this.nameOrdinals[name];
if (this.IsDBNull(ordinal))
{
return defaultValue;
}
return this.GetString(ordinal);
}
//return from sqlDataReader
public override string GetString(int ordinal)
{
return sqlDataReader.GetString(ordinal);
}
public override void Close()
{
sqlDataReader.Close();
}
So what I have done is passed the SqlDataReader in custom class that can cache the column names with the positions. Then you are free to call the Custom implementation using the delegate sqldatareader or write your own functions on top - like I have done for string. Little bit of work initially but you can put all checks here like check for DbNull etc and return default values based on that.
SqlCommand sqlCommand = new SqlCommand("select * from cats",sqlConnection);
SqlDataReader reader = sqlCommand.ExecuteReader();
CustomReader customReader = new CustomReader(reader);
List<Cat> list = new List<Cat>();
while (customReader.Read())
{
Cat cat = new Cat();
cat.Id = customReader.GetString("id");
cat.Name = customReader.GetString("name");
list.Add(cat);
}
You may need to check the names of the columns coming back so may be store in lower case and then read in lower case. Your code doesnt need to do getordinal anymore and it is much cleaner as well.
There are several ways to do this using the SqlDataReader and DataTable....
IEnumerable<DataRow> list0 = dt.AsEnumerable();
OR
List<DataRow> list1 = new List<DataRow>(dt.Select());
OR
List<DataRow> list2 = dt.AsEnumerable().ToList();
For simple examples of DataTable take a look at this.....
http://www.nakdev.somee.com/#2&2AD97ECBE2AE41D08191F6E4C773D8A9&cs
Well it turns out that the code in my first post is OK! The mistake was in my POCO definition.
This is what caused the problem :
...
private DateTime _dt_get;
public DateTime dt_get
{
get { return _dt_get; }
set { value = _dt_get; } // <-- !!! insted of set { _dt_get = value; }
}
...
Thx for any help...