How to get result of a RFC - c#

I am totally new when it comes to fetching the data from a SAP RFC. I am following many links to make a connection to the SAP with the following set of codes.
<appSettings>
<add key=”ServerHost” value=”127.0.0.1″/>
<add key=”SystemNumber” value=”00″/>
<add key=”User” value=”sample”/>
<add key=”Password” value=”pass”/>
<add key=”Client” value=”50″/>
<add key=”Language” value=”EN”/>
<add key=”PoolSize” value=”5″/>
<add key=”PeakConnectionsLimit” value=”10″/>
<add key=”IdleTimeout” value=”600″/>
</appSettings>
cs file
SAPSystemConnect sapCfg = new SAPSystemConnect();
RfcDestinationManager.RegisterDestinationConfiguration(sapCfg);
RfcDestination rfcDest = null;
rfcDest = RfcDestinationManager.GetDestination(“Dev”);.
Now I don't know how to call a specific RFC and get its result in Dataset or a list. I have installed SAP.net Connector also.
Please help.

After creating a working RFC destination you have to create an IRfcFunction object using the RfcDestionation-Method CreateFunction:
var rfc_read_table = rfcDest.CreateFunction("RFC_READ_TABLE");
now you can use the created object to set parameters. Import/Export-Parameters can be set or retrieved using the SetValue or GetValue-methods:
// we want to read from table kna1 (customer master data)
rfc_read_table.SetValue("QUERY_TABLE", "kna1");
// Delimiter ';'
rfc_read_table.SetValue("DELIMITER", ";");
table paramters are accessed using method GetTable. It returns an IRfcTable object representing the table parameter:
var fieldsTable = rfc_read_table.GetTable("FIELDS");
// append a new row
fieldsTable.Append();
// set value for field "FIELDNAME" on new row
fieldsTable.SetValue("FIELDNAME", "mandt");
fieldsTable.Append();
fieldsTable.SetValue("FIELDNAME", "kunnr");
now you can execute the function
rfc_read_table.Invoke(rfcDest);
RFC_READ_TABLE returns its data in parameter table "data" of type TAB512 with a single field called "WA". After invoking the function, create a new IRfcTable object using method GetTable and iterate over its contents.
var returnTable = rfc_read_table.GetTable("DATA");
foreach(IRfcStructure row in returnTable)
{
string[] fieldValues = row.GetValue("WA").Split(';');
// process field values
}
please note that this is just an example. The function module RFC_READ_TABLE for instance isn't released for customers, so no support from SAP for using this function. I hope i got the syntax right, i don't have an IDE available right now and can't check for errors.

Related

How to get values from Custom Actions Config File?

I have created a custom action in WIX tool set. When i created a custom action project a config file was created by default.
Inside my config files i have some hard coded values which i want to use in my project. But i am getting null when i try to retrieve values from config.
How my config file looks like-:
<configuration>   
<appSettings>       
<add key="Employee" value="Ram,Piya,Ishani,Rahul"/>         
</appSettings>
</configuration>
How my custom action code looks like-:
[CustomAction]       
public static ActionResult CheckInfo(Session session)       
{                       
var names = ConfigurationManager.AppSettings["Employee"].Split(',');  
List<string> ls = new List<string>();
foreach(string s in names)
ls.Add(s);         
if (ls.Count > 0 && ls.Contains("Ram"))                   
return ActionResult.Success;
else  
{                   
MessageBox.Show("Current Employee does't exit", "Invalid info");           
return ActionResult.UserExit;  
}     
}
It is throwing error System.NullReferenceException: 'Object reference not set to an instance of an object.' at line (var names = ConfigurationManager.AppSettings["Employee"].Split(',');)
Requirement-:
How to retrieve values from config file in Custom Action Project?

RDL Report not rendering

I have this error when I generate the report.
Where can I set the connection of my rdl file?
AspNetCore.Reporting.LocalProcessingException: An error occurred during local report processing.;An error has occurred during report processing.
Query execution failed for dataset 'DataSet1'.
Login failed for user ''.
---> AspNetCore.ReportingServices.ReportProcessing.ProcessingAbortedException: An error has occurred during report processing.
Here's my code.
const int extension = 1;
var path = Path.Combine(_webHostEnvironment.WebRootPath, "Reports", "test.rdl");
var parameters = new Dictionary<string, string> { { "rp1", "Test Value to parameter" } };
var localReport = new LocalReport(path);
var result = localReport.Execute(RenderType.Pdf, extension, parameters);
return File(result.MainStream, "application/pdf");```
[1]: https://i.stack.imgur.com/XkwzU.jpg
Change your code like below:-
private readonly IHostingEnvironment _webHostEnvironment;
public HomeController( IHostingEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
public async Task<IActionResult> Print()
{
string mimetype = "";
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\test.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("rp1", "Test Value to parameter");
LocalReport localReport = new LocalReport(path);
var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimetype);
return File(result.MainStream, "application/pdf");
}
Also, don't forget to install some NuGet packages as needed.
Hope it will resolve your issue. for more details and connected things, you can read this article:-
http://blog.geveo.com/IntegratingRDLCReportsToNetCoreProjects
UPDATE
App.config
<connectionStrings>
<add
name="MyConnectionString"
connectionString="Data Source=DESKTOP-N41V6ER\SQLEXPRESS;Initial
Catalog=MyDatabase;User ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
User ID and Password means using SQL credentials, not Windows, but still very simple - just go into your Security section of your SQL Server and create a new Login. Give it a username and password, and give it rights to your database.
AGAIN UPDATE(Data Source Connect)
Now select the object and click next:-
below, the design of a simple report that allows displaying the (assume)product data in your connected database. then click finish.
then click the ok button:-
then you will find your database table in dataset:-
now you can drag and drop your data, which place you want to show in your report file.
.................................................................
.................................................................
AGAIN UPDATE(Data base Connect)
First right click on your report project- => Add=>New Item then you will show:-
above add an entity data model to the windows form project.then click Add.then:-
Above,click New Connection.
Above,click Continue.
Above, give your server name. my machine has just one (SQL server)installed for that i am using . and select SQL Server in Authentication box.
Above,then click Ok.you have obisouly select DB name which you want.
Above, type your DB name carefully which you already selected.
Above, I select my product table because I will show that. then click finish

Get connection string from registry for API

I had first created a web application in VB.Net. Now i am creating its mobile application using Ionic framework. Language is c#.
In web application i use to get the connection string from Registry add save it in a session. I used to do it in global.asax.
global.asax:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Dim mDBConnector As String = String.Empty
With Application
.Add("ProductRegistryKey", "Accord 2.0")
.Add("ProductGUID", "ea3asue4n43-mbk3-3nmn-n34n4h3j4n4n3")
.Add("ProductId", "1")
mDBConnector = WebHelper.GetDBConnector(Application.Item("ProductRegistryKey")
End With
End Sub
I am not using any session in my API, Since i have read that API is stateless and it is not a good practice. So how can i achieve this in my API?
The fifth DBName does not exist in the connection strings configuration, so when ConfigurationManager.ConnectionStrings[DBName] is called it returns null, which will cause the null reference error when you try to call member on null object.
Check to make sure the name being called exists in the web.config.
<connectionStrings>
<!-- ... -->
<add name="FifthDbName" ...... />
</connectionStrings>
You should also do some defensive coding and check for null before trying to access the property.
var setting = ConfigurationManager.ConnectionStrings[DBName];
if(setting != null) {
string DbConnector = setting.ConnectionString;
bool Connection1 = DbConnector.ToLower().StartWith("metadata");
if (Connection1 == true)
{
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder
efBuilder = new
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(DbConnector);
DbConnector = efBuilder.ProviderConnectionString;
}
}
//...

saving Textbox values for next time I run an application

I have a form with 30 text boxes which contain default setting I set in my code. the user has an option to change it , but I want to know how can I save the new values chosen by the user in one (or more) of those text boxes for next time I run the application.
thanks a lot
If you don't care about editing your saved file and don't intend to rename the textboxes or change the layout of them you can leave the ordering of values to the compiler. Use this for saving:
// first collect all values
List<string> allvalues = this.Controls.OfType<TextBox>().Select(x => x.Text).ToList();
// write to file
System.IO.File.WriteAllText("yourPath", String.Join(Environment.NewLine, allvalues));
and this for loading:
//load the values:
string [] alllines = System.IO.File.ReadAllLines("yourPath");
List<TextBox> allTextboxes = this.Controls.OfType<TextBox>().ToList();
for (int i = 0; i < allTextboxes.Count; i++)
{
allTextboxes[i].Text = alllines[i];
}
Explanation:
this.Controls.OfType<TextBox>() gets you all controls that are textboxes in your windows form.
String.Join(Environment.NewLine, allvalues) combines all values to a string separated by a newline.
the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. An example where we have a tag for setting Name mySetting and mySetting2 is shown
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="mySetting" value="myValue1"/>
<add key="mySetting2" value="myValue12" />
</appSettings>
</configuration>
In order to use config files you must add a reference to System.Configuration, so you can use ConfigurationManager class. Below is a sample for reading and writing to app.config file:
WRITE TO CONFIG From TEXTBOX:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["mySetting"].Value=textBox1.Text;
config.Save();
READ from Config:
var mySetting = ConfigurationManager.AppSettings["mySetting"];
Simple way to solve this problem:
//To write textbox values to file (may be used on form close)
using (System.IO.StreamWriter sw = new StreamWriter("values.txt"))
{
foreach (var control in this.Controls)
{
if (control is TextBox)
{
TextBox txt = (TextBox)control;
sw.WriteLine(txt.Name + ":" + txt.Text);
}
}
}
//To read textbox values from file (may be used on form load)
using (System.IO.StreamReader sr = new StreamReader("values.txt"))
{
string line = "";
while((line=sr.ReadLine()) != null)
{
//Ugly, but work in every case
string control = line.Substring(0, line.IndexOf(':') );
string val = line.Substring(line.IndexOf(':') + 1);
if(this.Controls[control] != null)
{
((TextBox)this.Controls[control]).Text = val;
}
}
}
Save values in file. For 30 text field you can use 30 lines or just comma separated values.
When user change the value then write new values in that file, so on next startup you will have new values in file and each time don't have to read old data.

Get media url including server part

Is it possible to get url with MediaManager.GetMediaUrl that always includes the server part?
Just to bump this up, in Sitecore 7 the AlwaysIncludeServerUrl option is also included in MediaUrlOptions (I don't know since which version of Sitecore)
Like this:
MediaUrlOptions muo = new MediaUrlOptions();
muo.AlwaysIncludeServerUrl = true;
String url = MediaManager.GetMediaUrl((MediaItem)item, muo);
I've discovered that the following will work for producing fully qualified urls for media items:
public static string GetMediaUrlWithServer(MediaItem mediaItem, Item item = null)
{
item = item ?? Sitecore.Context.Item;
var options = new UrlOptions {AlwaysIncludeServerUrl = true, AddAspxExtension = false};
var itemUrl = LinkManager.GetItemUrl(item, options);
var mediaOptions = new MediaUrlOptions {AbsolutePath = true};
var mediaUrl = MediaManager.GetMediaUrl(mediaItem, mediaOptions);
return itemUrl + mediaUrl;
}
The urls produced will be relative to item so you may want to supply a reference to your Home item instead of Sitecore.Context.Item
I just answered a similar question on Stack Overflow recently. I believe the answer applies to yours as well.
Short summary: there is no configuration to do this, you need to override some of the built-in methods to do this. See the above link for the exact details.
Yes, you can do that!
The correct way of setting this parameter is specifying within config file at linkManager section, where you have this anв the rest of settings regarding how you URLs will be resolved. Here's the whole section, you're interested in alwaysIncludeServerUrl parameter:
<linkManager defaultProvider="sitecore">
<providers>
<clear />
<add name="sitecore" type="Sitecore.Links.LinkProvider, Sitecore.Kernel"
alwaysIncludeServerUrl="true"
addAspxExtension="true"
encodeNames="true"
languageEmbedding="asNeeded"
languageLocation="filePath"
shortenUrls="true"
useDisplayName="false" />
</providers>
</linkManager>

Categories