How to read a word document in asp.net c# - ms-word

i'm just workin on a project in asp.net c# 3.5 windows application which requires to read word document. i want to know how to read the *.doc file character by character.... how can i do it?

Microsoft.Office.Interop.Word.Application WApp;
Microsoft.Office.Interop.Word.Document Wdoc;
WApp = new Microsoft.Office.Interop.Word.Application();
//Opening Word file
Thread.Sleep(5312);
Wdoc = WApp.Documents.Open(#"C:\Users\Doc.doc");
object start = 0;
object end = Wdoc.Characters.Count;
Range rng = Wdoc.Range(ref start, ref end);
int wordCount = Wdoc.Words.Count;
// Display retrieved (incomplete) text
rng.TextRetrievalMode.IncludeHiddenText = false;
rng.TextRetrievalMode.IncludeFieldCodes = false;
// Find phrase in text string
string WTest;
string[] Title;
Title = new string[10];
Title[1] = "word1 ";
Title[2] = "word2 ";
Title[3] = "word3 ";
Title[4] = "word4 ";
Title[5] = "word5 ";
Title[6] = "word6 ";
Title[7] = "word7 ";
Title[8] = "word8 ";
Title[9] = "word9 ";
int icount = 1;
int n = 1;
int i=1;
while (icount <= wordCount)
{
WTest = Wdoc.Words[icount].Text.ToString();
foreach(string element in Title)
{
if (Title[i] == WTest)
{
Assert.IsTrue(true);
icount++;
i++;
break;
}
else if (i == wordCount)
{
Assert.Fail("Doc has no Data");
break;
}
else
{
icount++;
}
break;
}
continue;
}
Wdoc.Close(true);
WApp.Quit();
}

Related

DOCX4J conditional paragaph update merge FieldUpdater Does not work

Using a legacy IF field code:
enter image description here
and content controls:
private static byte[] mergingDocxFileWithXml(File file, File fileXml) {WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file)
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart()
ArrayList<String> datas
List<Object> contentControls = ContentControl.getAllContentControl(mainDocumentPart)
List<String> arrayListXpathToBoucle = new ArrayList<>()
for (Object contenControl : contentControls) {
ContentControl cControl = new ContentControl(contenControl)
String xPath = cControl.getXPath()
String title = cControl.getTitle()
if (xPath != null) {
datas = XmlPath.getXmlDataFrom(fileXml, xPath)
}
switch (title) {
case "DateDuJour":
cControl.setValue(getDateDay())
break
case "checkbox":
String checkValue = new String(Character.toChars(0x2612))
if (datas[0] != "1") {
checkValue = new String(Character.toChars(0x2610))
}
cControl.setValue(checkValue)
break
case "Boucle_Ligne":
xPath = cControl.getTag()
int indexBoucleContent = getIndexContentBoucle(wordMLPackage.mainDocumentPart.getContent(), xPath)
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
int totalNode = nodeList.getLength()
for (int j = 0; j < totalNode; j++) {
wordMLPackage = mapingDataNode(j, cControl, contentControls, fileXml, dataXpath, wordMLPackage, indexBoucleContent, null, 0)
}
wordMLPackage.mainDocumentPart.getContent().remove(indexBoucleContent)
break;
case "Boucle_Colonne":
xPath = cControl.getTag()
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
int totalNode = nodeList.getLength()
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
String boucleValue = ""
for (int i = 0; i < totalNode; i++) {
datas = XmlPath.getXmlDataFrom(fileXml, dataXpath.get(0))
boucleValue += datas.get(i) + ", "
}
boucleValue = boucleValue.substring(0, boucleValue.length() - 2)
addValueInContentControl(contentControls, dataXpath.get(0), 0, boucleValue, null, wordMLPackage)
break
case "Boucle_Ligne_Table":
xPath = cControl.getTag()
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
int indexBoucleContent = getIndexContentBoucle(wordMLPackage.mainDocumentPart.getContent(), xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
int totalNode = nodeList.getLength()
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
int nodeIndex = 0
Tbl arraysBoucle = getArraysBoucle(wordMLPackage, indexBoucleContent)
Tr trContent
for (int i = 0; i < totalNode; i++) {
nodeIndex = i + 1
if (arraysBoucle.getContent().stream().count() > 1) {
trContent = WoeDocx4jFunction.getTr(arraysBoucle.getContent().get(1))
} else {
trContent = WoeDocx4jFunction.getTr(arraysBoucle.getContent().get(0))
}
wordMLPackage = mapingDataNode(i, cControl, contentControls, fileXml, dataXpath, wordMLPackage, indexBoucleContent, trContent, nodeIndex)
}
int lastIndexTr = wordMLPackage.getMainDocumentPart().getContent().get(indexBoucleContent).sdtContent.content.get(1).value.content.stream().count()
wordMLPackage.getMainDocumentPart().getContent().get(indexBoucleContent).sdtContent.content.get(1).value.content.remove(lastIndexTr - 1)
break
case "IMAGE":
datas = XmlPath.getXmlDataFrom(fileXml, xPath)
byte[] imageByte = base64ToImage(datas.get(0))
Inline inlineImage = newImage(wordMLPackage, imageByte)
cControl.setValue(null, inlineImage)
break
default:
String xpathBoucle = arrayListXpathToBoucle.find { it.startsWith(xPath) }
if (xpathBoucle != xPath) {
addValueInContentControl(contentControls, xPath, 0, "", fileXml,wordMLPackage)
}
break
}
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wordMLPackage= mergingFieldWordMlPackage(wordMLPackage)
FieldUpdater updater = new FieldUpdater(wordMLPackage)
updater.update(true);
wordMLPackage.save(outputStream);
return outputStream.toByteArray();
}
Docx4j's legacy field processing does not parse IF fields: http://webapp.docx4java.org/OnlineDemo/ecma376/WordML/IF.html
If you need to do that, you'll need to write code to do the parsing.
An alternative would be to use OpenDoPE conditional content controls. With one of these, the content of the SDT is included only if the associated XPath evaluates to true.

Split string to keywords in dart

If I have a string that says "This is a good example", is there any way to split it to the following output in dart:
This
This is
This is a
This is a good
This is a good example
I would do it like this:
String text = "This is a good example";
List<String> split = text.split(" ");
for (var i = 0; i < split.length; i++) {
print(split.sublist(0, i + 1).join(" "));
}
String str = "This is a good example";
final split = str.split(" ");
for (int i = 0; i < split.length; i++) {
String result = "";
for (int j = 0; j < i+1; j++) {
result += split[j];
if (j < i) {
result += " ";
}
}
print(result);
}
Result:
This
This is
This is a
This is a good
This is a good example
You could do something like this (easy way):
String myString = "This is a good example";
List<String> output = myString.split(" ");
String prev = "";
output.forEach((element) {
prev += " " + element;
print(prev);
});
Output:
This
This is
This is a
This is a good
This is a good example
If you'd like to simply split a string by word you could do it with the split() function:
String myString = "This is a good example";
List<String> output = myString.split(" ");
output.forEach((element) => print(element));
Output:
This
is
a
good
example

Is there a way to replace multiple keywords in a string and wrapping them with their own keyword?

Say I have a string:
typed = "need replace this ap"
str = "hello I need to replace this asap"
so the end result I want would be this:
newStr = "hello I <bold>need</bold> to <bold>replace</bold> <bold>this</bold> as<bold>ap</bold>"
please don't mind the weird syntax.
I wonder if the order would matter, for example:
typed = "applicable app"
str = "the app is very applicable in many applications"
The end result I wish should be:
newStr = "the <bold>app</bold> is very <bold>applicable</bold> in many <bold>app</bold>lications"
right? is this possible?
Hey,If You can ignore the weird HTML syntax here,
Then I have wrote a solution for you,
Paste this code in dart pad here
removeDuplicates(var typed, var str) {
Map<String, String> m = new Map<String, String>();
var n = typed.length;
String ans = "";
//for storing the "typed" string (word by word) into a map "m" variable for later searching purpose
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
m[temp] = temp;
temp = "";
} else {
temp = temp + typed[i];
}
}
//for storing the last word of the string "typed", coz loop will never find a space in last of the string
m[temp] = temp;
// map variable loop for search from map "m" in the "str" string, and matching if the word is present or not
var n2 = str.length;
String temp2 = "";
for (int j = 0; j < n2; j++) {
if (str[j] == " ") {
if (m.containsKey(temp2)) {
} else {
ans = ans + " " + temp2; //storing the "temp2" string into "ans" string, everytime it finds a space and if the string is not already present in the map "m"
}
temp2 = "";
} else {
temp2 = temp2 + str[j];
}
}
//for searching for the last word of the string "str" in map "m", coz loop will never find a space in last of the string,
if (m.containsKey(temp2)) {
} else {
ans = ans + " " + temp2;
}
return ans;
}
void main() {
String typed = "need replace this ap";
var str = "hello I need to replace this asap";
String answer = removeDuplicates(typed, str);
print(answer);
}
Here, I have made a method removeDuplicates() to simplify your work, You just have to pass those string in your method, and then it will return you the desired answer string by removing the duplicates, with a new string.
UPDATED CODE (TO SHOW HTML CODE):
removeDuplicates(var typed, var str) {
Map<String, String> m = new Map<String, String>();
var n = typed.length;
String ans = "";
//for storing the "typed" string (word by word) into a map "m" variable for later searching purpose
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
m[temp] = temp;
temp = "";
} else {
temp = temp + typed[i];
}
}
//for storing the last word of the string "typed", coz loop will never find a space in last of the string
m[temp] = temp;
print(m);
// map variable loop for search from map "m" in the "str" string, and matching if the word is present or not
var n2 = str.length;
String temp2 = "";
for (int j = 0; j < n2; j++) {
if (str[j] == " ") {
if (m.containsKey(temp2)) {
temp2 = "<bold>" + temp2 + "</bold> ";
ans = ans + " " + temp2;
} else {
ans = ans +
" " +
temp2; //storing the "temp2" string into "ans" string, everytime it finds a space and if the string is not already present in the map "m"
}
temp2 = "";
} else {
temp2 = temp2 + str[j];
}
}
//for searching for the last word of the string "str" in map "m", coz loop will never find a space in last of the string,
if (m.containsKey(temp2)) {
temp2 = "<bold>" + temp2 + "</bold> ";
temp2 = "";
} else {
ans = ans + " " + temp2;
temp2 = "";
}
return ans;
}
void main() {
var typed = "applicable app";
var str = "the app is very applicable in many applications";
String answer = removeDuplicates(typed, str);
print(answer);
}
UPDATE 2 (ALL THANKS TO PSKINK FOR THE str.replaceAllMapped APPROACH)
replaceWithBoldIfExists(String typed, String str) {
var n = typed.length;
List<String> searchList = new List<String>();
String temp = "";
int i = 0;
for (i = 0; i < n; i++) {
if (typed[i] == " ") {
searchList.add(temp);
temp = "";
} else {
temp = temp + typed[i];
}
}
searchList.add(temp);
String pat = searchList.join('|');
final pattern = RegExp(pat);
final replaced =
str.replaceAllMapped(pattern, (m) => '<bold>${m.group(0)}</bold>');
return replaced;
}
void main() {
var typed = "need replace this ap";
var str = "hello I need to replace this asap";
print(replaceWithBoldIfExists(typed, str));
}

get_value of a feature in IFeatureCursor

I'm trying to read the attribute "POSTCODE" of the features in IFeatureCursor. The FID was successful read but the "POSTCODE" was failed. The runtime error 'An expected Field was not found or could not be retrieved properly. Appreciate your advise. Paul
private void test2(IFeatureCursor pFeatc1)
{
IFeature feature = null;
IFields pFields;
int ctcur = 0;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indxid = pFields.FindField("FID");
int indxpost = pFields.FindField("POSTCODE");
object valu = feature.get_Value(indxid);
string valupost = feature.get_Value(indxpost);
string aValu = Convert.ToString(valu);
Debug.WriteLine("FID: " + aValu + " Postcode: " + valupost);
ctcur++;
feature = pFeatc1.NextFeature();
}
MessageBox.Show("count cursor = " + ctcur);
}
I have modified the program and successfully read the feature attribute 'POSTCODE'. I have added IFeatureClass.Search(queryFilter, true) to search the feature again by FID and save in a cursor then use the 'feature.get_Value' to read the attribute. Please see my updated code below. Thanks.
private void test2(IFeatureCursor pFeatc1)
{
IMxDocument mxdoc = ArcMap.Application.Document as IMxDocument;
IMap map = mxdoc.FocusMap;
IFeatureLayer flayer;
IMaps pMaps = mxdoc.Maps;
for (int i = 0; i <= pMaps.Count - 1; i++)
{
map = pMaps.get_Item(i);
IEnumLayer pEnumLayer = map.get_Layers(null, true);
pEnumLayer.Reset();
ILayer pLayer = pEnumLayer.Next();
while (pLayer != null)
{
if (pLayer.Name == "AddrKey")
{
Debug.WriteLine("Layer: " + pLayer.Name);
flayer = (IFeatureLayer)pLayer;
IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFeature feature = null;
IFields pFields;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indx = pFields.FindField("FID");
object valu = feature.get_Value(indx);
string sFID = Convert.ToString(valu);
IQueryFilter queryFilter = new QueryFilter();
queryFilter.WhereClause = ("FID = " + sFID);
Debug.WriteLine("FID: " + sFID);
queryFilter.SubFields = "POSTCODE";
int fieldPosition = pFeatureClass.FindField("POSTCODE");
IFeatureCursor featureCursor = pFeatureClass.Search(queryFilter, true);
while ((feature = featureCursor.NextFeature()) != null)
{
MessageBox.Show(feature.get_Value(fieldPosition));
}
feature = pFeatc1.NextFeature();
}
}
pLayer = pEnumLayer.Next();
}
}
}

Binary addition in java

I wrote a program for a binary addition in java. But the result is sometimes not right.
For example if i add 1110+111. The result should be 10101.
But my program throws out 10001.
Maybe one of you find the mistake.
import java.util.Scanner;
public class BinaryAdder {
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("First: ");
String input1 = scan.next("(0|1)*");
System.out.print("Second: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Result: " + add(input1, input2));
}
}
this function is much simpler :
public static String binaryAdd(String binary1,String binary2){
return Long.toBinaryString(Long.parseLong(binary1,2)+Long.parseLong(binary2,2));
}
you can change Long.parseLong into Integer.parseInt if you don't expect very large numbers, you can also replace parse(Long/Int) with parseUnsigned(Long/Int) since you don't expect your strings to have a minus sign do you ?
You are not considering the case when
help1 + help2 = 3
So your method String add(String binary1, String binary2) should be like this:
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if (sum == 3){
sb.append("1");
carry = 1;
}
else if(sum ==2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
I hope this could help you!
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
If sum is 2 then append "0" and carry = 1
What about when the sum is 3, append "1" and carry = 1
Will never be 4 or greater
Know I'm a bit late but I've just done a similar task so to anyone in my position, here's how I tackled it...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
System.out.println("Enter the value you want to be converted");
Scanner inp = new Scanner(System.in);
int num = inp.nextInt();
String result = "";
while(num > 0) {
result = result + Math.floorMod(num, 2);
num = Math.round(num/2);
}
String flippedresult = "";
for(int i = 0; i < result.length(); i++) {
flippedresult = result.charAt(i) + flippedresult;
}
System.out.println(flippedresult);
}
}
This took an input and converted to binary. Once here, I used this program to add the numbers then convert back...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
Scanner inp = new Scanner(System.in);
String decimalToBinaryString = new String();
System.out.println("First decimal number to be added");
int num1 = inp.nextInt();
String binary1 = decimalToBinaryString(num1);
System.out.println("Input decimal number 2");
int num2 = inp.nextInt();
String binary2 = decimalToBinaryString(num2);
int patternlength = Math.max[binary1.length[], binary2.length[]];
while(binary1.length() < patternlength) {
binary1 = "0" + binary2;
}
System.out.println(binary1);
System.out.println(binary2);
int carry = 0;
int frequency_of_one;
String result = "";
for(int i = patternlength -i; i >= 0; i--) {
frequency_of_one = carry;
if(binary1.charAt(i) == '1') {
frequency_of_one++;
}
if(binary2.charAt(i) == '1') {
frequency_of_one++;
}
switch(frequency_of_one) {
case 0 ;
carry = 0;
result = "1" + result;
break;
case 1 ;
carry = 0;
result = "1" + result;
break;
case 2;
carry = 1;
result = "0" + result;
breake;
case 3;
carry = 1;
result = "1" + result;
breake;
}
}
if(carry == 1) {
result = "1" + result;
}
System.out.println(result);
}
public static String decimalToBinaryString(int decimal1) {
String result = "";
while(decimal1 > 0) {
result = result + Math.floorMod(decimal1, 2);
decimal = Math.round(decimal1/2);
}
String flipresult = "";
for(int i = 0; i < result.length[]; i++) {
flipresult = result.charAt(i) + flippedresult;
}
return flippedresult;
}
}