Telerik reporting: problem getting DataSource to be recognized at design time - datasource

I am new to Telerik reporting. I have been trying to follow this KB article, more or less.
The approach described there bypasses the Wizard. I need to bypass the Wizard because the database is SQL Server 2000 and the Wizard demands 2005 or later.
I drag and drop a sqlDataAdapter to the report from the Toolbox. The adapter is configured in the report's constructor.
When I add a text field to my report and go to its properties page and click on the ellipsis [...] button for Value and the click "Fields" in the lower left section of the dialog, the pane to the right says "No Data Source".
How to get the datasource to be recognized at design-time? What am I missing? Thanks
namespace EventsReportingClassLibrary
{
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using Telerik.Reporting;
using Telerik.Reporting.Drawing;
/// <summary>
/// Summary description for Report1.
/// </summary>
public partial class Report1 : Telerik.Reporting.Report
{
private SqlConnection CNN;
private SqlDataAdapter DA
{
get { return sqlDataAdapter1; // dropped from the toolbox onto report}
}
private string ConnectionString
{
get { return "server=server5\\SQL2K;Initial Catalog=foo;User Id=foo2;Password=foo3;Pooling=yes"; }
}
public Report1()
{
InitializeComponent();
CNN = new SqlConnection(ConnectionString);
DA.SelectCommand = new SqlCommand("select * from myView",CNN);
DA.SelectCommand.CommandType = CommandType.Text;
this.DataSource = DA;
}
private void Report1_NeedDataSource(object sender, System.EventArgs e)
{
// fires at run-time if datasource of this report is null
}
}
}

Related

on button click subtract 1 from my database table column quantity asp.net vb sql

I have an asp.net web form and when a button event is clicked i would like to have one of my database table columns called quantity subtract from its already stored integer number.
I am aware some sort of SQL statement will be needed to minus the quantity column by 1 but am unsure of how to achieve this.
any feedback would be appreciated.
Create a stored procedure as an update query.
USE [MyDB]
GO
Create Procedure [dbo].[myproc]
(
#SomeID bigint,
)
as
set nocount on
update MyTable set
MyField=SomeMath-SomeMath,
where SomeID=#SomeID
Then need to link it on the web page (aspx.cs)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _MyPage : System.Web.UI.Page
{
DataSet ds = new DataSet();
SqlConnection con;
//Here we declare the parameter which we have to use in our application
SqlCommand cmd = new SqlCommand();
SqlParameter Id = new SqlParameter();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection("server=(local); database=mydb;uid=myuser;pwd=Mypass");
cmd = new SqlCommand("myproc", con);
cmd.Parameters.Add("#ID", SqlDbType.BigInt);
cmd.Parameters["#ID"].Value = MyValue;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("ThanksPage.aspx");
}
}

Why can't I connect to SQL Server 2016 Express from VS

I am new at this. I am doing an ASP.NET tutorial, but I can't I connect to SQL Server 2016 Express from VS. I get the error below:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: Instance failure.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace tree_view_control_tutorial_2
{
public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData(null);
}
}
private void GetData(string searchTerm)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spSearchStudents", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter searchParameter = new SqlParameter("#SearchTerm", searchTerm);
cmd.Parameters.Add(searchParameter);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
}
How do I fix this? Thanks!
Your connection string in web.config should be like below one.
<connectionStrings>
<add name="DBCS"
connectionString="Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Since you are getting instance failure,it is problem with the creation of instance of SQL server,just check whether the SQL server is up and running when you execute your application.
To check the services,just type services.msc in your run dialogue window.
Figured it out! My connection string is on the Web.config page which is XML, not C#, so the Data Source should have been ".\SQLEXPRESS" (one \ only!)

DataTable, WCF and Constraints issue

i'm using DataTable to transfer through WCF channel.
I know, thats a bad solution, however it's a necessary by system design.
So, i've encountered a problem...
In this code, as you can see, i'm populating datatable with dataadapter.
using (var session = DatabaseManager.SessionFactory.OpenSession())
{
using (var conn = session.Connection as MySqlConnection)
{
var adapter = new MySqlDataAdapter(string.Format("SELECT * FROM {0}", dt.TableName), conn);
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(dt);
dt.AcceptChanges();
}
}
When i checking DataTable constraints property, on server-side, right after filling, it's filled. And it's ok.
BUT! When datatable comes to client side, constraints vanished. AcceptChanges not working here for me...
BaseDataTable code snippet:
public class BaseDataTable : DataTable
{
public string TableDescription { get; set; }
public DateTime ProcessTime { get; set; }
public bool IsEditable { get; set; }
public BaseDataTable()
{
}
public BaseDataRow GetNewRow()
{
BaseDataRow row = (BaseDataRow)NewRow();
return row;
}
public class BaseDataRow : DataRow
{
internal BaseDataRow(DataRowBuilder builder) : base(builder) { }
}
}
**BUT! When i'm sendind to client NOT A CUSTOM TYPED DataTable, but a common DataTable filled with DataAdapter all properties filled properly**
Already checked:
Set DataTable RemotingFormat = SerializationFormat.Binary/Xml -- No effect
Make sure DataTable is attributed as DataContract. can you show how you are defining dt ?
Please make sure that dt which is of type DataTable is exposed as DataContract.
Hope it helps.

display list data in textblock verses datagrid, sharepoint webpart

i'm building a silverlight webpart. i simply want to display sharepoint list data in a textblock verses a datagrid because i'm only planning to return one item from the list. i've managed to get my desired result in a datagrid but i'm not sure how to modify my code so i can display my data in a textblock.
i thought i could simple write
texblock1.text = projects;
but it throws an error.
here's the code behind in my xaml main page-------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
namespace something{
public class Project{
public string Title {get; set;}
}
public partial class MainPage : UserControl
{
public string SiteUrl { get; set; }
private ListItemCollection _projects;
//private Web _web = null;
//private string _lastErrorMessage = null;
public MainPage()
{
InitializeComponent();
ClientContext context = new ClientContext(ApplicationContext.Current.Url);
context.Load(context.Web);
List Projects = context.Web.Lists.GetByTitle("projects");
context.Load(Projects);
CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
string camlQueryXml = "<View><Query><Where><Eq><FieldRef Name=\"NameLast\" /><Value Type=\"Boolean\">1</Value></Eq></Where></Query></View>";
query.ViewXml = camlQueryXml;
_projects = Projects.GetItems(query);
context.Load(_projects);context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnRequestSucceeded), null);
}
private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
{
// This is not called on the UI thread.
Dispatcher.BeginInvoke(BindData);
}
private void BindData()
{
List<Project> projects = new List<Project>();
foreach (ListItem li in _projects)
{
projects.Add(new Project()
{
Title = li["Title"].ToString(),
});
}
dataGrid1.ItemsSource = projects; // must be on UI thread
}
}
}
To run code in the UI thread use code as follows:
Dispatcher.BeginInvoke(() => {
//add code here to which are to be executed on the UI thread
});

Nhibernate 2.1 with Spring on .net 4 throws System.ExecutionEngineException

I've got a website that works on .Net 3.5 running Nhibernate 2.1.0.4000. We are using spring as our ProxyFactory.
Everything works fine. I have tried to upgrade the project to .Net 4.0 using the wizard. It all went smoothly.
But as soon as the code tries to do anything with Nhibernate I get a very unfriendly exception of System.ExecutionEngineException. There is no stack trace and no inner exception.
We are using a NhibernateHelper class (below) and I've played around with it and the Session gets configured ok (no exception). The details havn't changed any from teh .net 3.5 version
The fist attempt to get something from the DB fails
The session is opened in the handler at the start of the request (not shown below).
We are also using unity which is setup on Appliation start (not sure if that has any bearing)
The First call to Nhibernate is
var emp = NHibernateHelper.CurrentSession.Get<SMS.DomainModel.Employee>(-200694);
I just want an error message that means something and gives me something to go on.
I've tried looking at NhibernateProfiler and all that is registered is the start of a session.
Any help is much appreciated
NhibernateHelper Class is as follows
using System;
using System.Configuration;
using System.IO;
using System.Reflection;
using FluentNHibernate;
using FluentNHibernate.Cfg;
using HibernatingRhinos.NHibernate.Profiler.Appender;
using log4net;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Event;
using NHibernate.Tool.hbm2ddl;
using SMS.Infrastructure.Persistence.Logging;
using SMS.Infrastructure.Persistence.Mappings;
using Configuration=NHibernate.Cfg.Configuration;
using System.Data.SqlClient;
namespace SMS.Infrastructure.Persistence
{
public static class NHibernateHelper
{
static readonly ILog Log = LogManager.GetLogger(typeof(NHibernateHelper));
static Configuration configuration;
public static ISessionFactory SessionFactory
{
get
{
return Singleton.sessionFactory;
}
}
// Lazy singleton pattern from http://www.yoda.arachsys.com/csharp/singleton.html
class Singleton
{
static Singleton() { }
internal static readonly ISessionFactory sessionFactory = CreateSessionFactory();
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
public static ISession CurrentSession
{
get { return SessionFactory.GetCurrentSession(); }
}
static ISessionFactory CreateSessionFactory()
{
try
{
Log.Info("Creating NHibernate session factory");
NHibernateProfiler.Initialize();
configuration = new Configuration();
try
{
// Try to configure NHibernate automagically...
configuration.Configure();
}
catch (HibernateConfigException e)
{
if (e.InnerException is IOException)
{
// Otherwise specify a file name manually.
configuration.Configure("hibernate.cfg.xml");
}
else
throw;
}
Log.Info("Registering custom SMS event listeners");
RegisterCustomListeners(configuration);
// Has someone specified a default_schema? No? try and guess
// it from the (Enterprise Library :/ ) query string.
if (!configuration.Properties.ContainsKey("default_schema"))
{
Log.Info("Setting default schema");
configuration.SetProperty("default_schema", GetDefaultSchema());
}
ISessionFactory sessionFactory = Fluently.Configure(configuration)
.Mappings(m =>
{
m.HbmMappings.AddFromAssemblyOf<BusinessUnitTypeMapping>();
m.FluentMappings.AddFromAssemblyOf<BusinessUnitTypeMapping>();
})
.BuildSessionFactory();
Log.Info("Session factory was configured successfully");
return sessionFactory;
}
catch (Exception ex)
{
throw new ArgumentNullException(ex.ToString());
}
}
/// <summary>
/// NHibernate allows custom event listeners to be registered in
/// config files or programmatically. Due to the re-use of configs in
/// SMS, we chose to do it via code.
///
/// This is how we extend NHibernate for SMS, and this is why
/// NHibernate is the best ORM..!
/// </summary>
static void RegisterCustomListeners(Configuration config)
{
if (config == null)
throw new ArgumentNullException("config");
// Event listeners for audit logging.
//config.SetListener(ListenerType.PreInsert, new AuditEventListener());
//config.SetListener(ListenerType.PreUpdate, new AuditEventListener());
//config.SetListener(ListenerType.PreDelete, new AuditEventListener());
// Event listener for wiring up .NET events between parent/child
// objects, and the intermediary mapping for Tasks.
//
// Warning: be careful with the order in which these listeners are
// added!!!
//
// BindEventsOnLoadListener must come before
// TaskAddresseeLoadEventListener for example otherwise OSM Task
// Decorators don't attach properly.
config.SetListeners(ListenerType.PostLoad, new IPostLoadEventListener[]
{
new BindEventsOnLoadListener(),
new TaskAddresseeLoadEventListener()
});
}
/// <summary>
/// Optional step: destroy and re-create the database scheme based on
/// the mapping files. Gives you a totally clean database in between
/// testing each fixture.
/// </summary>
public static void ExportDatabaseSchema(string fileName)
{
if (configuration == null)
CreateSessionFactory();
Log.InfoFormat("Exporting DDL to {0}", fileName);
var exporter = new SchemaExport(configuration);
exporter.SetOutputFile(fileName);
exporter.Execute(true, false, false);
}
public static void ExportFluentMappings(string directoryName)
{
Log.InfoFormat("Exporting fluent mappings to {0}", directoryName);
var model = new PersistenceModel();
model.AddMappingsFromAssembly(Assembly.GetAssembly(typeof(BusinessUnitTypeMapping)));
model.WriteMappingsTo(directoryName);
}
/// <summary>
/// hibernate's default_schema is worked out programmatically from the
/// Enterprise Library connection string. E.g.
/// Initial Catalog=OSM2Tests --> default_schema = SMS2Tests.dbo
/// </summary>
public static string GetDefaultSchema()
{
try
{
DatabaseSettings settings = DatabaseSettings.GetDatabaseSettings(new SystemConfigurationSource());
var connectionstring = ConfigurationManager.ConnectionStrings[settings.DefaultDatabase].ConnectionString;
var initialCatalog = new SqlConnectionStringBuilder(connectionstring).InitialCatalog;
return String.Format("{0}.dbo", initialCatalog);
}
catch (Exception)
{
throw new Exception("Could not get default schema from connection string.");
}
}
}
}
I was able to fix a similar problem by removing references to NHProf.