Crystal Reports C# - c#

I have a multitable c# report based on a database I have created underneath using SQL. I am using the following code to try and set the datasource and have tried many different variations but cannot get the information from my database to show up properly in my report. Any help is greatly appreciated. The dataset is populating. Additionally the single table reports properly fill with data only the multitable reports aren't working.
UPDATE: The report now shows data from one table using report.Database.Tables["Invoices"].setDataSource(posDataSet.Tables["Invoices"]); However using the same logic on the table that generates the detail lines does not show any data.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;
namespace SureSalePos
{
public partial class Reporter : Form
{
private PosDatabaseDataSet posDataSet;
public Reporter(PosDatabaseDataSet dataToReportOn)
{
InitializeComponent();
posDataSet = dataToReportOn;
//InvoiceReport ir = new InvoiceReport();
// this.reportViewer.LocalReport.ReportPath = ir.FileName;
}
private void Reporter_Load(object sender, EventArgs e)
{
ConnectionInfo myConnectionInfo = new ConnectionInfo();
myConnectionInfo.ServerName = "";// "PosDatabaseDataSet";
myConnectionInfo.DatabaseName = "";//"PosDatabase.mdf";
myConnectionInfo.UserID = string.Empty;
myConnectionInfo.Password = string.Empty;
setDBLOGONforREPORT(myConnectionInfo);
//this.reportViewer.RefreshReport();
}
private void setDBLOGONforREPORT(ConnectionInfo myconnectioninfo)
{
InvoiceReport report = new InvoiceReport();
report.DataSourceConnections.Clear();
// For each table set the source from your dataset
report.Database.Tables["Invoices"].SetDataSource(posDataSet.Tables["Invoices"]);
report.Database.Tables["InvoiceItems"].SetDataSource(posDataSet.Tables["InvoiceItems"]);
//report.Database.Tables["People"].SetDataSource(posDataSet.Tables["People"]);
report.Database.Tables["Preferences"].SetDataSource(posDataSet.Tables["Preferences"]);
//report.Database.Tables["Skus"].SetDataSource(posDataSet.Tables["Skus"]);
crystalReportViewer1.ReportSource = report;
crystalReportViewer1.RefreshReport();
}
private void crystalReportViewer1_Load(object sender, EventArgs e)
{
}
}
}
EDIT: Updated Code above September 22

You shouldn't need to set the login since you are supplying the report data. Try the following:
report.DataSourceConnections.Clear();
// For each table set the source from your dataset
report.Database.Tables["TableName"].SetDataSource(posDataSet.Tables["TableName"]);
crystalReportViewer1.ReportSource = report;
crystalReportViewer1.RefreshReport();

Related

Comparing multiple XML files

I am re-wording this from an original post I made: I have two XML files, and they are related to a given year each. For example, 18/19 and 17/18. They conform to the same structure and below is small sample from one of these files. What I want is, in C#, to compare all records in these files where the Given Name, the Family Name, the NI Number and the Date of birth are the same, BUT the Learner Ref Number is different. I need to be able to compare, then push only these records into a data table so I can then push them into a spreadsheet (the spreadsheet bit I can do). I currently have the below as a starting block, but am still very much stuck.
Firstly, I have my Import button press for which:
private void Btn_Import_Click(object sender, RoutedEventArgs e)
{
ILRChecks.ILRReport.CrossYear();
}
Then this goes to look at the Class of which eventually pushes the file to my location:
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ILRValidation;
using InfExcelExtension;
namespace ILRChecks
{
internal static partial class ILRReport
{
internal static void CrossYear()
{
DataSet ds_CrossYearChecks =
ILRValidation.Validation.CrossYearChecks(Global.fileNames);
string output = Path.Combine(Global.foldername, "ULIN_Issues" +
".xlsx");
ds_CrossYearChecks.ToWorkBook(output);
}
}
}
And this is the bit I'm stuck on, which is the production of finding the differences:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ILRValidation
{
public static partial class Validation
{
public static DataSet CrossYearChecks(DataSet ds_CrossYearChecks)
{
return CrossYearChecks(ds_CrossYearChecks);
}
public static DataSet CrossYearChecks(string[] xmlPath)
{
DataSet ds_xmlCrossYear = new DataSet();
return CrossYearChecks(ds_xmlCrossYear);
}
}
}
XML:
<Learner>
<LearnRefNumber></LearnRefNumber>
<ULN></ULN>
<FamilyName></FamilyName>
<GivenNames></GivenNames>
<DateOfBirth></DateOfBirth>
<Ethnicity></Ethnicity>
<Sex></Sex>
<LLDDHealthProb></LLDDHealthProb>
<NINumber></NINumber>
<PriorAttain></PriorAttain>
<MathGrade></MathGrade>
<EngGrade></EngGrade>
<PostcodePrior></PostcodePrior>
<Postcode></Postcode>
<AddLine1></AddLine1>
<AddLine3></AddLine3>
<Email></Email>
<LearnerEmploymentStatus>
<EmpStat>10</EmpStat>
<DateEmpStatApp>2015-09-01</DateEmpStatApp>
<EmpId>153421665</EmpId>
<EmploymentStatusMonitoring>
<ESMType>LOE</ESMType>
<ESMCode>4</ESMCode>
</EmploymentStatusMonitoring>
<EmploymentStatusMonitoring>
<ESMType>EII</ESMType>
<ESMCode>4</ESMCode>
</EmploymentStatusMonitoring>
</LearnerEmploymentStatus>
<LearningDelivery>
<LearnAimRef></LearnAimRef>
<AimType></AimType>
<AimSeqNumber></AimSeqNumber>
<LearnStartDate></LearnStartDate>
<LearnPlanEndDate></LearnPlanEndDate>
<FundModel></FundModel>
<ProgType></ProgType>
<StdCode></StdCode>
<DelLocPostCode></DelLocPostCode>
<CompStatus></CompStatus>
<SWSupAimId></SWSupAimId>
<LearningDeliveryFAM>
<LearnDelFAMType></LearnDelFAMType>
<LearnDelFAMCode></LearnDelFAMCode>
<LearnDelFAMDateFrom></LearnDelFAMDateFrom>
</LearningDeliveryFAM>
<LearningDeliveryFAM>
<LearnDelFAMType></LearnDelFAMType>
<LearnDelFAMCode></LearnDelFAMCode>
</LearningDeliveryFAM>
<LearningDeliveryFAM>
<LearnDelFAMType></LearnDelFAMType>
<LearnDelFAMCode></LearnDelFAMCode>
</LearningDeliveryFAM>
<LearningDeliveryFAM>
<LearnDelFAMType></LearnDelFAMType>

Class in ASP.NET Partial Class in App_Code

I created a class for connection and using with register.aspx without any problem. When i try to move codes from register.aspx.cs to regpartial.cs then i get an conflict error: "connection conn = new connection();"
I would like to move codes register.aspx.cs to mypartial.cs. I think it will be better but i'm not sure how can i solve conflict problem.
Register.aspx.cs (final)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using test.App_Code;
namespace test
{
public partial class register: System.Web.UI.Page
{
private void Page_Load(object sender, EventArgs e)
{
}
Connection.cs (final try)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
namespace test.App_Code
{
public class connection
{
public SqlConnection connect()
{
SqlConnection conn= new SqlConnection("Data Source=******;Initial Catalog=****;Integrated Security=False;User Id=****;Password=*****;MultipleActiveResultSets=True");
baglanti.Open();
return (conn);
}
}
regpartial.cs (Final try)
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace test.App_Code.partials
{
connection conn = new connection();
public partial class regpartial : register
{
}
}
In general you shouldn't have much code inside your aspx.cs files.
You want to separate the logic that is directly your view/presentation logic (stuff that makes the .aspx pages work) from your business logic (sequencing, transformation, validation), and finally you want to have your Data Access / Resource Access to be isolated.
I'd also recommend using Dapper.NET over raw ADO.NET/SqlConnection.
I'm going to string together a very basic example of how you can separate this. This is not guaranteed to compile c# code but it will very close pseudocode.
Inside registration.aspx.cs
private void btnRegister_Click(object sender, EventArgs e)
{
var email = txtEmail.Text;
var password = txtPassword.Text;
var registration = new Registration { Email = email, Password = password }
var bizService = new RegistrationService();
var response = bizService.Register(registration);
if(response.Success) Response.Redirect("~/registration/success");
ltlError.Text = response.FailureMessage;
}
RegistrationService.cs
public class RegistrationService {
public RegistrationResponse Register(Registration req)
{
var regDAL = new RegistrationAccess();
var isEmailDuplicated = regDal.DoesEmailExist(req.Email)
if(isEmailDuplicated)
return new RegistrationResponse {
Success = false,
FailureMessage = "Email exists, did you mean to login instead?
}
regDAL.InsertNewRegistration(req)
return new RegistrationResponse { Success = true };
}
}
Lastly you should have a RegistrationAccess.cs that contains only code for reading and writing to SQL Server / other database / file system.
Note how the aspx.cs file has no knowledge of RegistrationAccess. Your view should not be directly calling the database. The other thing to note is that RegistrationService has no knowledge of the view. It receives a Registration type, then executes business logic and calls out to the DAL. The DAL class will have zero knowledge of both the view and the RegistrationService, it will know only one thing, the database.
This is the basis of a very simple ASP.NET webforms solution. A better solution would use the MVP/MVVM patterns and the Dependency Inversion Principle but those aren't worth using if you don't understand basic separation of concerns yet.

export IDM download list using C#

I have to make a program to back up my IDM download list every day, because there is other ones using my computer and they removing my download list.
IDM API only lets me add download to IDM list, so is there any library or other way to back up my IDM download list using C#?
thanks for helping
Thanks to #Setsu found out a solution. there is a key in registry which contains all of the URLs. the key is HKEY_CURRENT_USER\Software\DownloadManager and it contains keys which contains values named Url0 with the URL in it.
As an example HKEY_CURRENT_USER\Software\DownloadManager\85\Url0 contains one of added link to IDM download list.
So I searched all of the HKEY_CURRENT_USER\Software\DownloadManager subkeys for Url0 and saved the values to a list box using this code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace IDMListSaver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\DownloadManager");
string[] keys = key.GetSubKeyNames();
for (int i = 0; i <= key.SubKeyCount-1; i++)
{
key = key.OpenSubKey(keys[i]);
Object o = key.GetValue("Url0");
if (o != null)
{
listBox1.Items.Add(o);
}
key = Registry.CurrentUser.OpenSubKey("Software\\DownloadManager");
}
}
}
}
It definitely can get better, but it solved my problem until here.
So thanks again #Setsu

Rss Reader in visual C# express edition

Hi I am trying to create a RSS reader in visual C# express. I need to read the rss feed into a text box when the form loads. I have never worked with RSS feeds before and all the examples I have come across are done in visual studio and it seems that I cant use this:
(XmlReader reader = XmlReader.Create(Url))
This is what I have got so far. It doesn't work.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var s = RssReader.Read("http://ph.news.yahoo.com/rss/philippines");
textBox1.Text = s.ToString();
}
public class RssNews
{
public string Title;
public string PublicationDate;
public string Description;
}
public class RssReader
{
public static List<RssNews> Read(string url)
{
var webResponse = WebRequest.Create(url).GetResponse();
if (webResponse == null)
return null;
var ds = new DataSet();
ds.ReadXml(webResponse.GetResponseStream());
var news = (from row in ds.Tables["item"].AsEnumerable()
select new RssNews
{
Title = row.Field<string>("title"),
PublicationDate = row.Field<string>("pubDate"),
Description = row.Field<string>("description")
}).ToList();
return news;
}
}
I am not sure what I should do. Please help.
Well your code is working as expected, since you are returning a List of RSSNews items, but you are assigning it to the textbox in a wrong way. Doing textBox1.Text = s.ToString(); will give System.Collections.Generic.List.... as a result.
Your method is reading RssNews items from the dataset and return around 23 items against the feed. You need to iterate through these items and display its text in the textbox, or better if you may use GridView or similar control to show these results.
You may try the following code in your Main method:
var s = RssReader.Read("http://ph.news.yahoo.com/rss/philippines");
StringBuilder sb = new StringBuilder();
foreach (RssNews rs in s)
{
sb.AppendLine(rs.Title);
sb.AppendLine(rs.PublicationDate);
sb.AppendLine(rs.Description);
}
textBox1.Text = sb.ToString();
This will create a string for each item of RssNews and will display the result in textBox1.

C#: execute a function stored in a string variable

Is it possible to write a simple and fast function in C# that will execute arbitrary methods from a string? For example, if I set MyString="MessageBox.Show("Some Message")" and then call ExecuteString(MyString), a message box would pop up with "Some Message" in it.
(I've probably made some sort of error in the above code. I don't yet know C#; I'm trying to evaluate whether it would be appropriate for a specific project.)
You should be able to use this and wrap the code required to run a string into a function.
Essentially what you're doing is wrapping the small bit of C# code in a Program.Mainstyle function, referencing some assemblies for basic functionality (maybe including your own assembly) then run the compiled program in memory.
It's likely a bit of more overhead than you need to simply run one or two lines of code mind you.
http://support.microsoft.com/kb/304655
what you appear to be looking for is CS-Script
Alas, C# is not a dynamic language in that way. You can't really do this easily, and if it's really something you need to do, consider using a .Net language more in line with your needs, like IronPython or IronRuby.
Your best available alternative is to use the CodeDom namespace, as this truly convoluted and heinous example from this forum thread shows:
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Windows.Forms;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SampleLib.SampleType test = new SampleLib.SampleType();
private void button1_Click(object sender, EventArgs e)
{
// Dynamically build and call the method
label1.Text = test.MyText;
}
private void button2_Click(object sender, EventArgs e)
{
StringBuilder DynamicCode = new StringBuilder();
DynamicCode.Append("namespace TestDynamic");
DynamicCode.Append("{");
DynamicCode.Append("public class DynamicCode");
DynamicCode.Append("{");
DynamicCode.Append("public static void EditText(SampleLib.SampleType t)");
DynamicCode.Append("{");
DynamicCode.Append("t.MyText = \"Goodbye!\";");
DynamicCode.Append("}");
DynamicCode.Append("}");
DynamicCode.Append("}");
string CodeString = DynamicCode.ToString();
System.IO.FileInfo fi = new System.IO.FileInfo(Application.ExecutablePath);
CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
CompilerParameters CompileParams = new CompilerParameters(new string[] { fi.DirectoryName + "\\SampleLib.dll" },
fi.DirectoryName + "\\Dynamic.dll");
CompileParams.MainClass = "DynamicCode";
CompileParams.GenerateExecutable = false;
//CompileParams.GenerateInMemory = true;
CompilerResults r = provider.CompileAssemblyFromSource(CompileParams, new string[] {CodeString});
foreach (CompilerError er in r.Errors)
{
Console.WriteLine(er.ErrorText);
}
}
private void button3_Click(object sender, EventArgs e)
{
// Dynamically call assembly
System.IO.FileInfo fi = new System.IO.FileInfo(Application.ExecutablePath);
Assembly dynAsm = Assembly.LoadFile(fi.DirectoryName + "\\Dynamic.dll");
if (dynAsm != null)
{
object o = dynAsm.CreateInstance("TestDynamic.DynamicCode", true);
Type t = dynAsm.GetType("TestDynamic.DynamicCode");
t.GetMethod("EditText").Invoke(o, new object[]{test});
}
}
}
}

Categories