How to compare the value before split? - c++-cli

I have got a problem with my program as they are extract the whole html tags when I am trying to compare between two tags " and the Enabled">". What I want my program to do is to find the tags in the php source called mystrings1 to see if they does exist then find the tags called mystrings2 with value "enabled" on the same line as the mystrings1 for each matches, then extract the mystrings1 value.
On my program, it reads the whole tags like this:
[PHP]
<p id='mystrings1'>user data 1</p><p id="images">
Images </td> | Link </td> | Delete </td> | <span id="mystrings2">Enabled</td>
[/PHP]
Here's the form code:
#include "StdAfx.h"
#include "Form1.h"
using namespace MyProject;
System::Void Form1::timer1_Tick(System::Object^ sender, System::EventArgs^ e)
{
timer1->Enabled = false;
timer1->Stop();
try
{
String ^URL1 = "http://mysite.com/myscript.php?user=test&pass=test";
HttpWebRequest ^request1 = safe_cast<HttpWebRequest^>(WebRequest::Create(URL1));
HttpWebResponse ^response1 = safe_cast<HttpWebResponse^>(request1->GetResponse());
StreamReader ^reader1 = gcnew StreamReader(response1->GetResponseStream());
String ^str1 = reader1->ReadToEnd();
String ^pattern1 = "(<p id='mystrings1'>(.*?)</p>(.*?)<span id=\"mystrings2\">Enabled</td>)";
MatchCollection ^matches1 = Regex::Matches(str1, pattern1);
Match ^m1 = Regex::Match(str1, pattern1);
for each (Match ^x1 in matches1)
{
array<String^> ^StrArr1 = x1->Value->ToString()->Split();
MessageBox::Show(x1->Value->ToString());
}
}
catch (Exception ^ex)
{
}
}
Please can someone tell me how i can compare the tags between mystrings1 and mystrings2 with value "enabled" to see if it have found the matches, then display the messagebox with the mystrings1 value?
Any advice would be much appreciated.

this code might help you
// set str1 to a constant string for testing
String^ str1 = "<p id='mystrings1'>user data 1</p><p id=\"images\"> Images</td> | Link </td> | Delete </td> | <span id=\"mystrings2\">Enabled</td>";
// the pattern is the key part to figure out
String ^pattern1 = "<p\\sid='mystrings1'>(?<mystrings1value>[^<>]+)</p>.*<span\\sid=\\\"mystrings2\\\">Enabled";
Regex^ r = gcnew Regex (pattern1, RegexOptions::IgnoreCase);
Match ^m1 = r->Match(str1);
if (m1->Success)
{
MessageBox::Show (m1->Groups["mystrings1value"]->Value);
}

Related

How to avoid splitting of word with case

Below is the text that I want to split:
string content = "Tonight the warning from the Police commissioner as they crack down on anyone who leaves there house without a 'reasonable excuse'
(TAKE SOT)"
string[] contentList = content.split(' ');
I do not want to split the word i.e (TAKE SOT), if there is a text within parentheses and in an upper case then how to avoid splitting of the part.
Thanks
The split method can have two parameters.The first one delimits the substrings in this instance.The second one is the maximum number of elements expected in the array.
The following code snippet work for me, you can refer to it.
string content = "Tonight the warning from the Police commissioner as they crack down on anyone who leaves there house without a 'reasonable excuse' (TAKE SOT)";
string[] contents = content.Split(" ", content.Substring(0, content.IndexOf("(")).Split(" ").Length);
And this is the result of the code:
I use the method Split(String, Int32, StringSplitOptions)
Later after doing some research I found a solution for the problem:
public class Program
{
public static void Main()
{
string BEFORE_AND_AFTER_SOUND_EFFECT = #"\(([A-Z\s]*)\)";
List<string> wordList = new List<string>();
string content = "Tonight the warning from the Police commissioner as they (VO) crack down on anyone who leaves there house without a 'reasonable excuse' (TAKE SOT) INCUE:police will continue to be out there.";
GetWords(content, wordList, BEFORE_AND_AFTER_SOUND_EFFECT);
foreach(var item in wordList)
{
Console.WriteLine(item);
}
}
private static void GetWords(string content, List<string> wordList, string BEFORE_AND_AFTER_SOUND_EFFECT)
{
if(content.Length>0)
{
if (Regex.IsMatch(content, BEFORE_AND_AFTER_SOUND_EFFECT))
{
int textLength = content.Substring(0, Regex.Match(content, BEFORE_AND_AFTER_SOUND_EFFECT).Index).Length;
int matchLength = Regex.Match(content, BEFORE_AND_AFTER_SOUND_EFFECT).Length;
string[] words = content.Substring(0, Regex.Match(content, BEFORE_AND_AFTER_SOUND_EFFECT).Index - 1).Split(' ');
foreach (var word in words)
{
wordList.Add(word);
}
wordList.Add(content.Substring(Regex.Match(content, BEFORE_AND_AFTER_SOUND_EFFECT).Index, Regex.Match(content, BEFORE_AND_AFTER_SOUND_EFFECT).Length));
content = content.Substring((textLength + matchLength) + 1); // Remaining content
GetWords(content, wordList, BEFORE_AND_AFTER_SOUND_EFFECT);
}
else
{
wordList.Add(content);
content = content.Substring(content.Length); // Remaining content
GetWords(content, wordList, BEFORE_AND_AFTER_SOUND_EFFECT);
}
}
}
}
Thanks.

(Xebium) How to random string to be a variable to input in a field

I try to test a case that has to random a string to input in field by using xebium with fitnesse.
I try to use below command but it doesn't work.
| $fname= | is | storeValue | on | var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZ'; var fname = ''; for (var i=0; i<6; i++)var rnum = Math.floor(Math.random()*chars.length); fname += chars.substring(rnum,rnum+1); |
Thank you for attention :)
We are using special type parser and template strings for this purpose.
For example, function:
bool LastLogonTimeLessThan( DateTimeWrapper time)
{
return time.Value < GetLastAccessTime();
}
Then you can add custom parser for this type, see tutorial here: https://github.com/imanushin/NetRunner/wiki/Parsing
Parser can be:
public static void DateTimeWrapper(string inputLine)
{
if("{today}".Equals(inputLine)
return new DateTimeWrapper(DateTime.Now)
return new DateTimeWrapper(DateTime.Parse(inputLine))
}

Example Program to insert a row using BAPI with JCO3

I am trying to "insert" (or) "add a row" to Purchase Requisition using standard BAPI (PurchaseRequisition.CreateFromData).
I am using JCo3. The example in JCo3 indicates that we should use table.appendRow() OR table.insertRow() methods. I am trying with table.appendRow() & table.appendRows(1). When i try to insert a row, i dont get any error and the row is not inserted.
Below is the program i am trying to execute.
/** Below are the inputs required for this program to run /
/ Step 1 **/
String BAPI_NAME = "BAPI_REQUISITION_CREATE";
/** Step 2 **/
String query_input_column1 = "DOCUMENTY_TYPE";
String query_input_column1_value = "NB";
String query_input_column2 = "PREQ_NAME";
String query_input_column2_value = "Name";
String query_input_column3 = "ACCTASSCAT";
String query_input_column3_value = "U";
String query_input_column4 = "DELIV_DATE";
String query_input_column4_value = "20131101";
String query_input_column5 = "MATERIAL";
String query_input_column5_value = "DELL-RQ2013";
String query_input_column6 = "QUANITY";
int query_input_column6_value = 10100;
/** Step 3 **/
String targetTableUnderBAPI = "REQUISITION_ITEMS";
/** Step 4 **/
/** For the confirmation read the value from export parameter after insertion execution **/
String result_column1 = "NUMBER";
JCoDestination destination = null;
try {
destination = JCoDestinationManager.getDestination(DestinationManager.DESTINATION_NAME1);
JCoRepository repository = destination.getRepository();
JCoContext.begin(destination);
JCoFunction function = repository.getFunction(BAPI_NAME);
if(function == null)
throw new RuntimeException(BAPI_NAME + " not found in SAP.");
System.out.println("BAPI Name from function object: " + function.getName());
//function.getImportParameterList().setValue(query_input_column1, query_input_column1_value);
JCoTable table = function.getTableParameterList().getTable(targetTableUnderBAPI); //it is taken from the response value of metadata
//System.out.println("No of Columns: "+ table.getNumColumns());
System.out.println("Trying to execute append row");
table.appendRow();
table.setValue(query_input_column1,query_input_column1_value);
table.setValue(query_input_column2,query_input_column2_value);
table.setValue(query_input_column3,query_input_column3_value);
//table.setValue(query_input_column4,new java.util.Date(query_input_column4_value));
//skipped Other columns related code
try{
function.execute(destination);
}
catch(AbapException e){
System.out.println(e.toString());
return;
}
System.out.println("Let us check the result from export parameter");
String exportParamStructure = (String)function.getExportParameterList().getValue(result_column1); //getStructure(result_column1); // getValue(result_column1);
System.out.println("Resulting PR#: "+exportParamStructure);
} catch (JCoException e) {
e.printStackTrace();
}
finally
{
try {
JCoContext.end(destination);
} catch (JCoException e) {
e.printStackTrace();
}
}
I did not understand how to read the response and am trying to fetch it from exportParameters!!
Can anybody share a piece of code to insert and
getting confirmation response (do we get the PREQ_NO in response?)
I am adding date field value as "20131101", but not sure if the format and approach is right?
when i try to add Quantity column value, i get an error message complaining this column is not part of BAPIEBANC. But the column is visible in BAPIEBANC type.
any configuration on SAP side to be checked?
should i activate any fields in JCo side? if so, how
Please note that my knowledge on SAP is very limited.
Waiting for an expert's response.
Thanks.
First, you should take a look at SAP JCo documentation, e.g.
http://help.sap.com/saphelp_nw04/helpdata/en/6f/1bd5c6a85b11d6b28500508b5d5211/content.htm
Regarding your code:
Adding (one) row to the table looks right on first sight.
Your code says QUANITY instead of QUANTITY.
You should add date values as java.util.Date; if creating a Date from a String format, you should use java.text.DateFormat.parse(). See http://docs.oracle.com/javase/6/docs/api/java/util/Date.html (this is however Java specific and has nothing to do with JCo).
If changing anything in SAP, never forget to call BAPI_TRANSACTION_COMMIT in the end to finish the logical unit of work (aka transaction) or nothing will actually be changed.
If you don't like to fiddle with the more or less complicated and verbose JCo API, try using Hibersap which gives you a much nicer programming model when calling functions in SAP ERP: http://hibersap.org.
However, you will still need a basic understanding on how SAP function modules work technically (such as parameter types or data types) as well as on the domain specific model which lies behind them (in your case, creating a requisition). I.e. you may need to communicate with your SAP experts.
Here I added 2 types of insertion :
insertval() function for user defined module resides in sap with the help of abap programmer
Its an standard module for insert a ticket using jco to SOLMAN system. First you have to analyse import, export, table & structure parameters, and according to that you have to pass values and retrieve response. In second function it will return ticket n° after successfull insertion of ticket in solman.
I hope this sample code will help you, it worked for me.
public class jco
{
static String DESTINATION_NAME1 = "ABAP_AS_WITHOUT_POOL";
static String DESTINATION_NAME2 = "ABAP_AS_WITH_POOL";
static
{
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "192.1.1.1");
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "01");
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "500");
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "uname");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "pwd");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "en");
createDestinationDataFile(DESTINATION_NAME1, connectProperties);
connectProperties.setProperty(DestinationDataProvider.JCO_POOL_CAPACITY, "3");
connectProperties.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT, "10");
createDestinationDataFile(DESTINATION_NAME2, connectProperties);
System.err.println("hai");
}
static void createDestinationDataFile(String destinationName, Properties connectProperties)
{
File destCfg = new File(destinationName+".jcoDestination");
try
{
try (FileOutputStream fos = new FileOutputStream(destCfg, false)) {
connectProperties.store(fos, "for tests only !");
}
}
catch (IOException e)
{
throw new RuntimeException("Unable to create the destination files", e);
}
}
public void insertval() throws JCoException
{
JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME1);
JCoFunction jf=destination.getRepository().getFunction("ZUSER_DET");
jf.getImportParameterList().setValue("FIRST_NAME","member");
jf.getImportParameterList().setValue("LAST_NAME","c");
jf.getImportParameterList().setValue("USER_NO","1000");
jf.execute(destination);
System.out.println(jf);
}
public void insertticket() throws JCoException
{
JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME2);
System.out.println("test"+"\n");
JCoFunction jf=destination.getRepository().getFunction("BAPI_NOTIFICATION_CREATE");
JCoTable jt1=jf.getTableParameterList().getTable("APPX_HEADERS");
JCoTable jt2=jf.getTableParameterList().getTable("APPX_LINES");
JCoTable jt3=jf.getTableParameterList().getTable("APPX_LINES_BIN");
JCoTable jt4=jf.getTableParameterList().getTable("NOTIF_NOTES");
JCoTable jt5=jf.getTableParameterList().getTable("NOTIF_PARTNERS");
JCoTable jt6=jf.getTableParameterList().getTable("NOTIF_SAP_DATA");
JCoTable jt7=jf.getTableParameterList().getTable("NOTIF_TEXT_HEADERS");
JCoTable jt8=jf.getTableParameterList().getTable("NOTIF_TEXT_LINES");
JCoStructure jfn1=jf.getImportParameterList().getStructure("NOTIF_EXT");
JCoStructure jfn2=jf.getImportParameterList().getStructure("NOTIF_CRM");
JCoStructure jfn3=jf.getImportParameterList().getStructure("IBASE_DATA");
jfn1.setValue("NUMB","1234");
jfn1.setValue("REFNUM","123");
jfn1.setValue("TYPE_NOTIF","SLFN");
jfn1.setValue("SUBJECT","tl");
jfn1.setValue("PRIORITY","2");
jfn1.setValue("LANGUAGE","EN");
jfn1.setValue("CATEGORY","Z01");
jfn2.setValue("CODE","0011");
jfn2.setValue("CODEGROUP","0011");
jfn2.setValue("CATEGORY","Z01");
jfn3.setValue("INSTANCE","489");
jfn3.setValue("IBASE","500");
jt1.appendRow();
jt1.setValue("DESCR","practise");
jt2.appendRow();
jt2.setValue("LINE","CVXCVXCV");
jt3.appendRow();
jt3.setValue("LINE","second text line");
jt4.appendRow();
jt4.setValue("TYPE_NOTE","my");
jt4.setValue("IDENT","hoe twwrtgw");
jt4.setValue("DESCRIPTION","its description ");
jt5.appendRow();
jt5.setValue("PARNR","new ");
jt5.setValue("TYPE_PAR","FN");
jt5.setValue("FUNC_PAR","EN");
jt5.setValue("PAR_ACTIVE","1");
jt6.appendRow();
jt6.setValue("INSTN","0020214076");
jt6.setValue("COMP","FI-AA");
jt6.setValue("SYSTYPE","P");
jt6.setValue("SYSID","PRD");
jt6.setValue("MANDT","900");
jt8.appendRow();
jt8.setValue("TXT_NUM","1");
jt8.setValue("TDFORMAT",">X");
jt8.setValue("TDLINE","/(performing all test)");
jf.execute(destination);
String jfex=jf.getExportParameterList().getString("REFNUM");
System.out.println("hi "+jfex);
}

Selenium: Get unique value?

Just using selenium to fill out some forms for me. I need it to generate a unique value for my username field. How can I do that?
I've got
Command: type
Target: id_of_my_field
Value: username+unique_value ???
You can use javascript to do that:
Value: javascript{'username'+Math.floor(Math.random()*100000)}
This will append a 6 digit random number to your username.
See this SO question and answers for more details and other ways to do this...
My solution which works well for me:
Save the following TEXT as a .js file and add to the Options->Options "Selenium Core Extensions" list...
Selenium.prototype.doTypeRandomName = function(locator)
{
/**
* Sets the value of an input field to a random "name"
* as though you typed it in.
*/
// All locator-strategies are automatically handled by "findElement"
var element = this.page().findElement(locator);
/* The following block generates a random name 8 characters in length */
var allowedChars = "abcdefghiklmnopqrstuvwxyz";
var stringLength = 8;
var randomstring = '';
for (var i=0; i<stringLength; i++) {
var rnum = Math.floor(Math.random() * allowedChars.length);
randomstring += allowedChars.substring(rnum,rnum+1);
}
// Replace the element text with the new text
this.browserbot.replaceText(element, randomstring);
}
Once done, you can simply select the TypeRandomName command in Selenium for each text box where you want a random "name" to be generated.
Steps for a globally reusable solution is as follows
1) Download sideflow.js from Download here
2) Add following lines into it :
Selenium.prototype.doTypeRandomName = function(locator) {
/**
* Sets the value of an input field to a random email id,
* as though you typed it in.
*
* #param locator an element locator
*/
// All locator-strategies are automatically handled by "findElement"
var element = this.page().findElement(locator);
/* The following block generates a random email string */
var allowedChars = "abcdefghiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var stringLength = 8;
var randomstring = '';
for (var i=0; i<stringLength; i++) {
var rnum = Math.floor(Math.random() * allowedChars.length);
randomstring += allowedChars.substring(rnum,rnum+1);
}
// Replace the element text with the new text
this.browserbot.replaceText(element, randomstring);
};
3) Save the file
4) Go to Selenium ide -> options -> options ->Selenium Core extensions -> give reference of your file there.
5) Now your randomname function will appear in auto-intellisense and will be as "typerandomname" command category.
6) Sample usage could be (if base url is google.com)
<tr>
<td>open</td>
<td>/</td>
<td></td>
</tr>
<tr>
<td>typerandomname</td>
<td>css=input[class='gbqfif']</td>
<td></td>
</tr>
Hope this helps you
Here is a way to generate unique numbers without using JavaScript in your code: (i used Java)
DateFormat dateFormat = new SimpleDateFormat("ddHHmmss"); /* Here you create object of the class DateFormat, and SPECIFY THE FORMAT (ddHHmmss). (Don`enter code here`t forget to import class Date(ctrl+shift+o if you are using Eclipse)) */
Date date = new Date(); /* Here you create object of the class Date. (Dont forget to import class Date. (Dont forget to import class Date(ctrl+shift+o if you are using Eclipse)) */
String random_number = dateFormat.format(date); /* Assign your current Date(something like 19184123) (ddHHmmSS) to a local variable(it require a String) */
yourWebDriver().findElemnt(By.cssSelector("input#someId")).sendKeys("test"+random_number+"#tester.com"); /* send keys to your input injecting random number */
Such method will give truly unique number that will never repeat itself, because it use your current time...
You can add even further randomness if include mile seconds into DateFormat

Need help in displaying data insider marquee

I want to display news inside the marquee markup in my banking application but its not happening.Please somebody help me what is the error in my code.Here is my code:
<marquee bgcolor="silver" direction="left" id="marq1" runat="server" behavior="scroll" scrolldelay="80" style="height: 19px" width="565">
<%
String se = Session["countnews"].ToString();
for (int i = 0; i < int.Parse("" +se); i++)
{ %>
<strong><%Response.Write(" " + Session["news"+i] + " "); %></strong>
<% } %>
</marquee>
public class News
{
DataSet ds = new DataSet("Bank");
SqlConnection conn;
String check;
SqlDataAdapter sda;
int i;
public string News_Name;
public int Count_News;
public int newsticker()
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BankingTransaction"].ConnectionString.ToString());
check = "Select NewsTitle from News where NewsStatus = 'A'";
sda = new SqlDataAdapter(check, conn);
sda.Fill(ds, "News");
if (ds.Tables[0].Rows.Count > 0)
{
for (i = 0; i < ds.Tables[0].Rows.Count; i++)
{
News_Name =i+ ds.Tables[0].Rows[i].ItemArray[0].ToString();
}
Count_News = ds.Tables[0].Rows.Count; }
else
{
News_Name =0+ "Welcome to WestSide Bank Online Web site!";
Count_News = 1;
}
return int.Parse(Count_News.ToString());
}
protected void Page_Load(object sender, EventArgs e)
{
News obj = new News();
try
{
obj.newsticker();
Session["news"] = obj.News_Name.ToString();
Session["countnews"] = obj.Count_News.ToString();
}
catch (SqlException ex)
{
Response.Write("Error in login" + ex.Message);
Response.Redirect("Default.aspx");
}
finally
{
obj = null;
}
}
Session["news"+i]
But you're not putting anything called ‘news’-plus-an-integer into Session scope. You're iterating over a dataset and storing each title (mysteriously prefixed by an integer) as the ‘News_Name’ property in a single News object. Each write to ‘News_Name’ overwrites the previous one, so only the last title gets stored at the end in Session["news"].
In any case, Session is a troublesome place to be storing per-page data: Session is for data that persists over multiple page loads, and can interfere if the user is loading two pages at once.
Also, you're Response.Write()ing a string without HTMLEncode()ing it on the way out, which is bad news for security (especially on a ‘banking site’!) if the title of the news might have a ‘<’ character in it. And I'm not quite sure why you're taking the ‘newscount’ integer, converting it to string, converting it to string again, converting it to string again then finally parsing it back to an integer. (?)
In general this seems like an uncomfortable mix of classic-ASP and codebehind techniques. It seems to me it should be possible to write this a whole lot simpler using something like:
<asp:Repeater DataSourceID="TickerSource" runat="server">
<ItemTemplate><strong>
<%# Eval("NewsTitle") %>
</strong></ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="TickerSource" runat="server"
SelectCommand="SELECT NewsTitle FROM News WHERE NewsStatus='A'"
ConnectionString="<%$ ConnectionStrings:BankingTransaction %>"
/>
[Disclaimer: I've never actually written a line of ASP.NET in my life, so this may not work as-is. Edits from more .NET-savvy users welcome.]