In Microsoft Access functions like DLookup - DMax or Dcount help the programmer to read a column from a table of a SQL Server database.
How do you do the same task in Visual Studio?
For example how can I find the ID of a user (John) in tblUsers table.
tblUsers columns: ID, Username, Password, .....
I've already added the SQL Server database to the Data Source.
Any kind of advice is much appreciated.
ow. Even in Access, that isn't proper.
Go read up on DAO, ADO, and, if you're using Visual Studio to write .Net applications, the system.data namespace.
in general, when accessing relational data via non-database program code, including the vba you're using in Access, you'd retrieve a reference to a Recordset object and query each record's fields as object properties.
If you want to visualize all of the data, click Database Explorer (see the tab at the bottom of the solution explorer), then expand your data connections and right click the name of the table, then click 'show table data'. If you want only the id's or names etc, I usually just create an SQL script to run, and run it when I want to browse certain data.
To simply create a script, while you're viewing all the data, click the script button above the table your viewing. Then you can execute your script
SELECT * FROM tblUsers WHERE User = 'John';
I hope I've understood your questions correctly.
I followed DougM and ended up with the following code. I will add it here just in case somebody else has the same question:
using System.Data.SqlClient; should be added to the reference section
private void button1_Click(object sender, EventArgs e)
{
string fltr = "UserName='Ando'";
MessageBox.Show(ReadOrderData(fltr));
}
public string ReadOrderData(string filter)
{
string connectionString = "Data Source=sqlServer-servername;Initial Catalog=database name;Integrated Security=True";
string queryString = "SELECT User_ID, UserName FROM tblUsers WHERE " + filter + ";";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
return reader[0].ToString();
//Console.WriteLine(String.Format("{0, {1",
// reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
return "Null";
Related
I'm quite new to Oracle and never used that before, now, I'm trying to query an Oracle database from a .Net Core Web Application having nuget package oracle.manageddataaccess.core installed and using an alias as the Data Source but I'm receiving the following error:
If I use the full connection string the query will work correctly
ORA-12154: TNS:could not resolve the connect identifier specified
at OracleInternal.Network.AddressResolution..ctor(String TNSAlias, SqlNetOraConfig SNOConfig, Hashtable ObTnsHT, String instanceName, ConnectionOption CO)
at OracleInternal.Network.OracleCommunication.Resolve(String tnsAlias, ConnectionOption& CO)
at OracleInternal.ConnectionPool.PoolManager`3.ResolveTnsAlias(ConnectionString cs, Object OC)
at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession, OracleConnection connRefForCriteria, String instanceName)
So, from a few links I could understand that there is a tsnnames.ora file which must contain the map between connect identifiers and connect descriptors. And that this file can be found at the machine on which the Oracle has been installed with the path ORACLE_HOME\network\admin.
Question is:
Does the alias name that I'm using in my connection string which reads as Data Source: <alias_name>; User ID=<user>; Password=<password> need to be specified in the tsnnames.ora file? I don't have access to the machine where the Oracle database resides on otherwise I would have checked it earlier.
Here's the code snippet for more info: connection string and query values are mocked out
public static string Read()
{
const string connectionString = "Data Source=TestData;User ID=User1;Password=Pass1";
const string query = "select xyz from myTable";
string result;
using (var connection = new OracleConnection(connectionString))
{
try
{
connection.Open();
var command = new OracleCommand(query) { Connection = connection, CommandType = CommandType.Text };
OracleDataReader reader = command.ExecuteReader();
reader.Read();
result = reader.GetString(0);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
return result;
}
Is this enough or something else needs to be added/changed in here? Or probably the issue is with the tsnNames.ora file which might not contain the alias name here?
Thanks in advance
For the Data source
Data Source=TestData;User Id=myUsername;Password=myPassword;
Your tnsnames.ora probably should have the below entry
TestData=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)))
Since
Data Source=TestData;User Id=myUsername;Password=myPassword;
is same as
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
Due to some bad practices from one of our internal users. We need to transfer all activities (mails, notes, etc) from one contact to another contact. I was trying to achieve this via UI and I could not find a way to do this.
Is this possible? I'm looking for any way to achieve this, wether is CRMTool, SSIS, UI or any other way. Only admins will do this so we do not need anything fancy as it will be done maybe 4 times a year to clean up some data.
Thanks a lot :)
Tried using UI but no success.
I can think of two ways to do these updates.
The first method is selecting a view on an activity where the owner is listed (i.e. All Phone Calls) and exporting to Excel. This downloads a XLSX with some hidden columns at the start where IDs for the records are kept. You then update the owner column with the new owner (take care of copying the exact fullname), and then importing the Excel spreadsheet again. You would need to repeat this export/import steps for each activity type (phone calls, email, etc.). So this might be impractical if you have a large volume of date, because of the need to repeat and because there are max numbers of records that you can export.
The other way to do this is using some .NET code. Of course, to do this you will need to use Visual Studio 2019.
If that's the case, this will do the trick:
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
namespace ChangeActivitiesOwner
{
class Program
{
static void Main(string[] args)
{
string connectionString = "AuthType=Office365;Url=<TODO:URL>;Username=<TODO:User>;Password=<TODO:Pass>;";
string oldUserFullname = ""; // TODO: place here fullname for the user you want to overwrite
string newUserFullname = ""; // TODO: place here fullname for the user you want to overwrite with
CrmServiceClient client = new CrmServiceClient(connectionString);
IOrganizationService service = client.OrganizationWebProxyClient != null ? client.OrganizationWebProxyClient : (IOrganizationService)client.OrganizationServiceProxy;
QueryByAttribute qbyaOldUser = new QueryByAttribute("systemuser");
qbyaOldUser.AddAttributeValue("fullname", oldUserFullname);
Guid olduserid = (Guid)service.RetrieveMultiple(qbyaOldUser)[0].Attributes["systemuserid"];
QueryByAttribute qbyaNewUser = new QueryByAttribute("systemuser");
qbyaNewUser.AddAttributeValue("fullname", newUserFullname);
Guid newuserid = (Guid)service.RetrieveMultiple(qbyaNewUser)[0].Attributes["systemuserid"];
foreach (string activity in new string[]{ "task", "phonecall", "email", "fax", "appointment", "letter", "campaignresponse", "campaignactivity" }) // TODO: Add other activities as needed!!!
{
QueryExpression query = new QueryExpression(activity)
{
ColumnSet = new ColumnSet("activityid", "ownerid")
};
query.Criteria.AddCondition(new ConditionExpression("ownerid", ConditionOperator.Equal, olduserid));
foreach (Entity e in service.RetrieveMultiple(query).Entities)
{
e.Attributes["ownerid"] = new EntityReference("systemuser", newuserid);
service.Update(e);
}
}
}
}
}
Please complete the lines marked with "TODO" with your info.
You will need to add the packages Microsoft.CrmSdk.CoreAssemblies, Microsoft.CrmSdk.Deployment, Microsoft.CrmSdk.Workflow, Microsoft.CrmSdk.XrmTooling.CoreAssembly, Microsoft.IdentityModel.Clients.ActiveDIrectory and Newtonsoft.Json to your solution, and use .NET Framework 4.6.2.
Hope this helps.
There is a strange problem that has been found in Oracle DB with Visual Studio by my project. First I open my Toad to check Oracle function like as below picture:
When I have put 3 parameter's value into SF_GET_COMP_SVAL, it is working ,and then when I have tried it in my project as following, it also works very well.
using (OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["OracleDbContext"].ToString()))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = "select PG_AIS.SF_GET_COMP_SVAL('3','2','1') from dual";
try
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch
{
}
}
}
However it can't be working when I use Paramters mode like as following code
cmd.CommandText="select PG_AIS.SF_GET_COMP_SVAL(:a1,:a2,:a3) from dual"; cmd.Parameters.Add("a2", "1");
cmd.Parameters.Add("a3", "2");
cmd.Parameters.Add("a1", "3");
why????
I wasted half day and have found the ODAC problem in my case, why can't insert into data with paramters in Visual Studio platform , because of parameters name , if fact in my MySql and MSSql there don't need to follow the sequence with parameter , but unfortunately in the Oracle it can't change ordering ,the parameter's depends on index sequence so that you can change any parameter's name
cmd.CommandText="select PG_AIS.SF_GET_COMP_SVAL(:a1,:a2,:a3) from dual";
cmd.Parameters.Add("a1", "3");
cmd.Parameters.Add("a2", "2");
cmd.Parameters.Add("a3", "1");
or
cmd.CommandText="select PG_AIS.SF_GET_COMP_SVAL(:a1,:a2,:a3) from dual";
cmd.Parameters.Add("xx", "3");
cmd.Parameters.Add("a2", "2");
cmd.Parameters.Add("a3", "1");
parameter a1 or xx is the same (depends on index sequence not parameter name)
both codes can get the same result.
PS: Hopefully it will be modify soon by Oracle Provider.
I have found another method to deal with this problem , please try it
OracleCommand command = new OracleCommand(query, connection)
{ CommandType = CommandType.Text, BindByName = true };
PS:http://www.codeproject.com/Articles/208176/Gotcha-sharp-Using-Named-Parameters-with-Oracl <-- it could be a great way to deal with
I'm starting using DevExpress XtraReports for the company project. My problem is the following:
I have a stored procedure that extracts the data, given three paramaters: startDay, endDay and developer ID, and this SP is inside a .dbml file.
Following this example http://www.devexpress.com/Support/Center/p/B223095.aspx, we have the this method:
static void report_DataSourceDemanded(object sender, System.EventArgs e)
{
Reports.WeeklyTimesheet report = (Reports.WeeklyTimesheet)sender;
DataClasses1DataContext context = new DataClasses1DataContext();
System.Data.Linq.ISingleResult<WeeklyTimesheetUserReportResult> res = >context.WeeklyTimesheetUserReport(Convert.ToDateTime("2012/01/16"), >Convert.ToDateTime("2012/01/20"), 52);
var result = from orderDetail in res select orderDetail;
report.DataSource = res.ToList();
}
Which is the only way i've found (that works) to pass parameters to the SP for the report.
What can i do so the report comes with the data i am sucessfully bringing but is not binding into the report? The attached images will illustrate this point better.
I have to point that when i made that report in the images, were originally formatted from a dataset using the wizard (hence why is ordered), but i have no idea how i can format it instead using the .dbml file.
Thanks in advance.
http://imgur.com/YQ7RE
XtraReport have xrTables, xrLabel controls, they will let you to create custom report and after that you can bind those cell etc and modify the XRControl bindings of the report in the following manner:
[C#]
...
// Original
//this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
// new DevExpress.XtraReports.UI.XRBinding("Text", null, "Symbols.Description")});
// Modified
this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Description")});
...
Refer these links and samples..
Binding a Report to an Entity Framework object at runtime
[ How to
use LINQ to SQL data source to create a Master-Detail report
example
I've got a bunch of screenshots and some screenshot meta data I'm trying to display in an ASP.NET MVC 3 web application, I'm trying to retrieve the data from my databse but I get this error:
LINQ to Entities does not recognize the method 'System.Drawing.Image
ByteArrayToImage(Byte[])' method, and this method cannot be translated
into a store expression.
Here's my code:
var screenshotData = (from screenshots in db.screenshots
where screenshots.projects_ID == projectID
select new ImageInformation
{
ID = screenshots.id,
Language = screenshots.language,
Screenshot = Utility.ByteArrayToImage(screenshots.screen_shot),
ProjectID = screenshots.projects_ID
});
foreach (ImageInformation info in screenshotData)
{
this.Add(info);
}
ImageInformation is just a simple class that contains the defintion the information stored (ID, Language, Screenshot, ProjectID).
Here's my ByteArrayToImage function:
public static Image ByteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
Can anybody tell me why I receive this error when this code runs?
Thanks.
I think it's because, with LINQ-to-Entities, the code is turned into server-side query and it can't do that in this case. I don't think you can mix client-side code like this directly with L2E.
I would suspect you will have to do the conversion from byte->image after you've retrieved the data from the database as a distinct step.
You can't do the function in a LINQ to Entities query... one option:
1) have a byte[] property on the object you are instantiating (ImageInformation) and copy the data in there along with another propery to read the image from this ImageInformation object.