Why the code below doesnt work ?
string Tmp_actionFilepath = #"Temp\myaction.php";
// change the id and the secret code in the php file
File.Copy(#"Temp\settings.php", Tmp_actionFilepath, true);
string ActionFileContent = File.ReadAllText(Tmp_actionFilepath);
string unique_user_id = textBox5.Text.Trim();
string secret_code = textBox1.Text.Trim();
ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent.Replace("SECRET_CODE", secret_code);
File.WriteAllText(Tmp_actionFilepath, ActionFileContent);
Here is the content of setting.php
<?php
session_start();
$_SESSION["postedData"] = $_POST;
/////////////////////////////////////////////////////////
$_SESSION["uid"] = "UNIQUE_USER_ID";
$_SESSION["secret"] = "SECRET_CODE";
/////////////////////////////////////////////////////////
function findThis($get){
$d = '';
for($i = 0; $i < 30; $i++){
if(file_exists($d.$get)){
return $d;
}else{
$d.="../";
}
}
}
$rootDir = findThis("root.cmf");
require_once($rootDir."validate_insert.php");
What is wrong with the code above ? After compiling the code in c#, i noticed the file myaction.php is created, but the values : UNIQUE_USER_ID and SECRET_CODE doesn't change, I tried also to copy/paste these values to make sure they are same. But the code always doesn't work
String.Replace returns a new string as strings are immutable. It does not replace the string you are calling it on.
You should replace:
ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent.Replace("SECRET_CODE", secret_code);
with:
ActionFileContent = ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent = ActionFileContent.Replace("SECRET_CODE", secret_code);
On top of that you should really change your variable names so they follow the regular C# naming conventions (i.e. use actionFileContent instead of ActionFileContent).
you have to set the result of the replace string method on a string.
string Tmp_actionFilepath = #"Temp\myaction.php";
// change the id and the secret code in the php file
File.Copy(#"Temp\settings.php", Tmp_actionFilepath, true);
string actionFileContent = File.ReadAllText(Tmp_actionFilepath);
string unique_user_id = textBox5.Text.Trim();
string secret_code = textBox1.Text.Trim();
// set the result of the Replace method on the string.
actionFileContent = ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id)
.Replace("SECRET_CODE", secret_code);
File.WriteAllText(Tmp_actionFilepath, actionFileContent);
Related
There are other similar questions that have been asked and answered, but none of those answers work in what I'm trying to do, or there isn't enough information for me to know how to implement it in my own code. I've been at it for two days and now must ask for help.
I have a script task in an SSIS package where I need to do a match and replace on a large XML file that contains thousands of Record Identifier tags. Each one contains a number. I need those numbers to be consecutive and increment by one. For example, within the xml file, I am able to find tags that appear like this:
<ns1:recordIdentifier>1</ns1:recordIdentifier>
<ns1:recordIdentifier>6</ns1:recordIdentifier>
<ns1:recordIdentifier>223</ns1:recordIdentifier>
<ns1:recordIdentifier>4102</ns1:recordIdentifier>
I need to find and replace those tags with consecutive increments like so:
<ns1:recordIdentifier>1</ns1:recordIdentifier>
<ns1:recordIdentifier>2</ns1:recordIdentifier>
<ns1:recordIdentifier>3</ns1:recordIdentifier>
<ns1:recordIdentifier>4</ns1:recordIdentifier>
The code I have so far is causing all the numbers to be "1" with no incrementation.
I've tried dozens of different methods, but nothing has worked yet.
Any ideas as to how I can modify the below code to increment as desired?
public void Main()
{
string varStart = "<ns1:recordIdentifier>";
string varEnd = "</ns1:recordIdentifier>";
int i = 1;
string path = Dts.Variables["User::xmlFilename"].Value.ToString();
string outPath = Dts.Variables["User::xmlOutputFile"].Value.ToString();
string ptrn = #"<ns1:recordIdentifier>\d{1,4}<\/ns1:recordIdentifier>";
string replace = varStart + i + varEnd;
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null && i>0)
{
File.WriteAllText(outPath, Regex.Replace(File.ReadAllText(path),
ptrn, replace));
i++;
}
}
}
You were on the right path with the Replace method, but will need to use the MatchEvaluater parameter when you increment.
string inputFile = Dts.Variables["User::xmlFilename"].Value.ToString();
string outPutfile = Dts.Variables["User::xmlOutputFile"].Value.ToString();
string fileText = File.ReadAllText(inputFile);
//get any number between elements
Regex reg = new Regex("<ns1:recordIdentifier>[0-9]</ns1:recordIdentifier>");
string xmlStartTag = "<ns1:recordIdentifier>";
string xmlEndTag = "</ns1:recordIdentifier>";
//assuming this starts at 1
int incrementInt = 1;
fileText = reg.Replace(fileText, tag =>
{ return xmlStartTag + incrementInt++.ToString() + xmlEndTag; });
File.WriteAllText(outPutfile, fileText);
I have this string :
"<figure><img
src='http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg'
href='JavaScript:void(0);' onclick='return takeImg(this)'
tabindex='1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>"
How can I retrieve this link :
http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg
All string are the same type so somehow I need to get substring between src= and href. But I don't know how to do that. Thanks.
If you parse HTML don't not use string methods but a real HTML parser like HtmlAgilityPack:
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html); // html is your string
var linksAndImages = doc.DocumentNode.SelectNodes("//a/#href | //img/#src");
var allSrcList = linksAndImages
.Select(node => node.GetAttributeValue("src", "[src not found]"))
.ToList();
You can use regex:
var src = Regex.Match("the string", "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
In general, you should use an HTML/XML parser when parsing a value from HTML code, but with a limited string like this, Regex would be fine.
string url = Regex.Match(htmlString, #"src='(.*?)'").Groups[1].Value;
If your string is always in same format, you can easily do this like so :
string input = "<figure><img src='http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg' href='JavaScript:void(0);' onclick='return takeImg(this)' tabindex='1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>";
// link is between ' signs starting from the first ' sign so you can do :
input = input.Substring(input.IndexOf("'")).Substring(input.IndexOf("'"));
// now your string looks like : "http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg"
return input;
string str = "<figure><imgsrc = 'http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg'href = 'JavaScript:void(0);' onclick = 'return takeImg(this)'tabindex = '1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>";
int pFrom = str.IndexOf("src = '") + "src = '".Length;
int pTo = str.LastIndexOf("'href");
string url = str.Substring(pFrom, pTo - pFrom);
Source :
Get string between two strings in a string
Q is your string in this case, i look for the index of the attribute you want (src = ') then I remove the first few characters (7 including spaces) and after that you look for when the text ends by looking for '.
With removing the first few characters you could use .IndexOf to look for how many to delete so its not hard coded.
string q =
"<figure><img src = 'http://myphotos.net/image.ashx?type=2&image=Images\\2\\9\\11\\12\\3\\8\\4\\7\\685621455625.jpg' href = 'JavaScript:void(0);' onclick = 'return takeImg(this)'" +
"tabindex = '1' class='myclass' width='55' height='66' alt=\"myalt\"></figure>";
string z = q.Substring(q.IndexOf("src = '"));
z = z.Substring(7);
z = z.Substring(0, z.IndexOf("'"));
MessageBox.Show(z);
This is certainly not the most elegant way (look at the other answers for that :)).
I am automating a process using c#. My script would look like below,
UPDATE Table
SET param_val = REPLACE(param_val,'Proxy430/','Proxy440/')
WHERE param_key = 'PROXY_URL';
UPDATE Table
SET param_val = REPLACE (param_val, '.420/', '.430/')
WHERE param_val LIKE '%.420/%';
For every month, we will upgrade the version like 44 in place of 43 and 43 in place of 42 and run this script. To automate, i've written C# code and used below code
string text = File.ReadAllText(filePath);
text.Replace(oldvale, newvalue);
File.WriteAllText(filepath, text);
But, issue is it can replace one word only. How to replace two texts in a file. In my case, Proxy430 should be replaced as Proxy440 and Proxy440 into Proxy450 in single shot.
How to achieve this?
If you call replace in the right order you can accomplish two replacements on a single line.
string TestString = #"UPDATE Table
SET param_val = REPLACE(param_val, 'Proxy430/', 'Proxy440/')
WHERE param_key = 'PROXY_URL';
UPDATE Table
SET param_val = REPLACE(param_val, '.420/', '.430/')
WHERE param_val LIKE '%.420/%'; ";
const string oldFrom = "Proxy430";
const string oldTo = "Proxy440";
const string newFrom = "Proxy440";
const string newTo = "Proxy450";
string result = TestString.Replace(newFrom, newTo).Replace(oldFrom, oldTo);
Console.WriteLine(result);
The output is:
UPDATE Table
SET param_val = REPLACE(param_val, 'Proxy440/', 'Proxy450/')
WHERE param_key = 'PROXY_URL';
UPDATE Table
SET param_val = REPLACE(param_val, '.420/', '.430/')
WHERE param_val LIKE '%.420/%';
The problem is you don't assign the return value of Replace method. Replace doesn't modify this string it returns replaced string.
Change it like this:
text = text.Replace(oldvale, newvalue);
Here's a fiddle.
If the things are really sequential numerically, you can do something like this:
string text = File.ReadAllText(filePath);
for (int i=lowestVersion; i < highestVersion; i++)
{
var oldValue = i.ToString() + "0";
var newValue = (i+1).ToString() + "0";
text.Replace(oldValue , newvalue);
}
File.WriteAllText(filepath, text);
You can create a custom method for this.
private void MultipleReplace(string text, string[] oldValues, string[] newValues)
{
for (int i = 0; i < old.Length; i++)
{
text = text.replace(oldValues[i], newValues[i]);
}
}
You need to consider the order of replacements, because once you replace Proxy430 by Proxy440, you can no longer replace Proxy440 by Proxy450, because that'll also replace the values updated in the previous iteration.
Example:
string text = File.ReadAllText(filePath);
string[] oldValues = { "Proxy440", "Proxy430" };
string [] newValues = { "Proxy450", "Proxy440" };
MultipleReplace(text, oldValues, newValues);
File.WriteAllText(filepath, text);
Why doesn't this work ?
string myString = "test";
int i = myString.Length; // i = 4
myString.PadLeft(5, '_'); // "myString" is should be equal to "_test", but it still "test"
i = myString.Length; // i = 4 (should be 5)
Most string methods don't change string itself, but return new string, so use it like this:
myString = myString.PadLeft(5, '_');
EDIT: Ahh yes, all methods. I thought about methods that don't return string and somehow ended with not entirely true sentence.
i have already configured SMS gateway & some php code.Now my project is thatone convert it to Csharp with minor changes,
probably i have to write new code.but so.. experienced guys from you i wanted to know is that possible ? Sample code below.
enter code here
$username = "abcdsoft";
$password = "softsoft";
//GET parametrar
//$source = $_GET['sourceaddr'];
//$dest = $_GET['destinationaddr'];
//$message_in = $_GET['message'];
enter code here
$source = $_GET['msisdn'];
$dest = $_GET['shortcode'];
$message_in = $_GET['msg'];
those are most top lines.below code i changed.(php to csharp)
enter code here
string username ='abcdsoft';
string password = 'abcdabcd';
int source = ['sourceaddr'];
int dest = ['shortcode'];
string message_in = ['msg'];
Is this way is correct ?
Almost.
Need to use double-quotes for the string
Request.QueryString is the ASP.NET equivalent to the PHP $_GET.
Also, apparently C# is a bit more strongly typed than PHP, so you need to explicitly convert the query string params to integers.
Code should be like this:
string username = "abcdsoft";
string password = "abcdabcd";
int source = int.Parse(Request.QueryString["sourceaddr"]);
int dest = int.Parse(Request.QueryString["shortcode"]);
string message_in = int.Parse(Request.QueryString["msg"]);