To do searching in an array with some keyword - c#

I have an array which is like
books={'java 350','Photoshop 225','php 210','JavaScript 80','python 180','jquery 250'}
my input for search as be like "ph2" it retrieve both Photoshop 225,php 210 in drop-down menu what is the exact string function to do this task or any set codes available to do this task.
I'm using some build in function like
if (array.Any(keyword.Contains))
and
if (array.Contains(keyword))
it's doesn't help what exactly i want any one pls help me to solve this thanks in advance.....

More flexible approach:
using Microsoft.VisualBasic; // add reference
using Microsoft.VisualBasic.CompilerServices;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main (string[] args)
{
string[] books = { "java 350", "Photoshop 225", "php 210", "JavaScript 80", "python 180", "jquery 250" };
string input = "*" + string.Join ("*", "ph2".ToArray ()) + "*"; // will be *p*h*2*
var matches = books.Where (x => LikeOperator.LikeString (x, input, CompareMethod.Text));
}
}
}

Related

Display csv read data in console application in c#

I am completely new to programming and trying to get the complete row data from csv file based on column value in c#. Example data is as follows:
Mat_No;Device;Mat_Des;Dispo_lvl;Plnt;MS;IPDS;TM;Scope;Dev_Cat
1111;BLB A601;BLB A601;T2;PW01;10;;OP_ELE;LED;
2222;ALP A0001;ALP A0001;T2;PW01;10;;OP_ELE;LED;
If user enters a Mat_No he gets the full row data of that particular number.
I have two files program.cs and filling.cs
overViewArea.cs contain following code for csv file reading:I dont know how to access the read values from program.cs file and display in console
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
namespace TSDB
{
class fillData
{
public static fillData readCsv()
{
fillData getData= new fillData ();
using (var reader = new StreamReader(#"myfile.csv"))
{
List<string> headerList = null;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if(headerList==null)
{
headerList = line.Split(';').ToList();
}
else
{
var values = line.Split(';');
for(int i = 0; i< headerList.Count; i++)
{
Console.Write(headerList[i] + "=" + values[i]+";");
}
Console.WriteLine();
}
}
}
return fillData;
}
}
}`
Program.cs has following code
class Program
{
static void Main(string[] args)
{
fillData data= fillData.readCsv();
Console.ReadLine();
}
}
First, please, do not reinvent the wheel: there are many CSV readers available: just use one of them. If you have to use your own routine (say, for a student project), I suggest extracting method. Try using File class instead of Stream/StreamReader:
// Simple: quotation has not been implemented
// Disclamer: demo only, do not use your own CSV readers
public static IEnumerable<string[]> ReadCsvSimple(string file, char delimiter) {
return File
.ReadLines(file)
.Where(line => !string.IsNullOrEmpty(line)) // skip empty lines if any
.Select(line => line.Split(delimiter));
}
Having this routine implemented, you can use Linq to query the data, e.g.
If user enters a Mat_No he gets the full row data of that particular
number.
Console.WriteLine("Mat No, please?");
string Mat_No_To_Filter = Console.ReadLine();
var result = ReadCsvSimple(#"myfile.csv", ';')
.Skip(1)
.Where(record => record[0] == Mat_No_To_Filter);
foreach (var items in result)
Console.WriteLine(string.Join(";", items));

C# } For Loop Issues [duplicate]

This question already has answers here:
Value getting changed in the iteration before the call begins
(3 answers)
Closed 6 years ago.
Hello so my school has records that i needed to access but i forgot my user id, so i made a program that would download any possible PDF and search them for my name. If it found mine it would alert me however when the program was down and said "We found a file containing Sean File Name is : xxxxxx.pdf" The actual number part would be off by however much the for loop is incremented by even though this was on a separate method! BTW School name will be starred out!
*B y the way! In Search() I used i-10 as a temporary fix, but I was thinking their must be a better way *
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using BitMiracle.Docotic.Pdf; // pdf parser / viewer
using System.IO;
using System.Threading;
namespace XXXXXXX_TEMP
{
class Program
{
static void Main(string[] args)
{
Program p1 = new Program();
p1.Start();
}
private void Start()
{
WebClient wc = new WebClient();
for (int i = 200000; i < 999999999; i = i + 10)
{
try
{
wc.DownloadFile("XXXXXXXXXXXXXXXXXXXXXX/" + i + ".pdf", i + ".pdf");
}
catch (WebException) {
continue;
}
PdfDocument pdf = new PdfDocument(i + ".pdf");
Thread a = new Thread(() => Search(i, pdf));
a.Start();
if (i == 999999) {
Console.ReadLine();
}
}
}
private void Search(int i, PdfDocument pdf)
{
i = i - 10;
String html = pdf.GetText();
if (html.ToLower().Contains("sean"))
{
Console.WriteLine("Found File Containing Sean! File Name Is : " + i + ".pdf\n");
Console.WriteLine("PDF Text = " + html);
}
}
}
}
What you've run into is called closing over the loop variable. You should carefully study the linked answer as well as the blog entry it links to.
The immediate solution to your problem is to pass a copy of i to the thread. That is:
int index = i;
Thread a = new Thread(() => Search(index, pdf));
However, you might find that starting all those threads seriously bogs down your system, and leaving all those threads hanging could potentially eat up resources and lead to an out of memory exception. A cleaner way to do it is to call ThreadPool.QueueUserWorkItem, like this:
ThreadPool.QueueUserWorkItem(o => Search(index, pdf));
Or, in newer versions of .NET:
Task.Run(() => Search(index, pdf));
See Simplest way to do a fire and forget method in C#? for more information about fire-and-forget threads.

Does not contain definition after reference has been added

I am VERY new to C# so it is possible this is a really easy problem, but even after all my reading I cant find a way to add the definitions Visual Studio 2010 wants despite having added the using statements and the references on the MSDN docs page for each expression.
My Error:
System.windows.forms does not contain a definition for document
I added the reference "presentationframework" based on something I was reading on the Microsoft site. Thanks to some of the comments below I discovered I was apparently mixing two different ways to get text from the box. All I need to be able to do is paste content into the textbox, and get the contents of the box when i press a button. Can someone tell (or better yet show) me definitively how to do this without mixing strategies?
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Controls.RichTextBox;
using System.Windows.Forms;
using System.Windows.Controls;
using System.Collections;
namespace WindowsFormsApplication1
{
public partial class HackController : Form
{
ArrayList ipList = new ArrayList();
ArrayList acctList = new ArrayList();
int myAcct = 0;
string myIp = "";
public HackController()
{
InitializeComponent();
}
public void sync_Click(object sender, EventArgs e)
{
string data = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text;// ERROR HERE
string[] lines = Regex.Split(data, "\n");
Regex ipMatch = new Regex(#"\d+.\d+.\d+.\d+");
Regex acctMatch = new Regex(#"#\d+");
foreach(string line in lines)
{
foreach(Match m in ipMatch.Matches(line))
{
ipList.Add(m);
}
foreach( Match m in acctMatch.Matches(line))
{
acctList.Add(m);
}
}
}
}
}
Here's a (rather strange) sample showing one way to display data in a WinForms RichTextBox control. (Sorry, but it's the only sample I can find in my programming because I'm usually using Developer Express WinForms controls instead of the basic .Net ones.)
But first, to be 100% sure you are not mixing WinForms and WPF, make sure that when you create the project you select WinForms as the project template type (not WPF). And when you drag-and-drop the RichTextBox control from the Visual Studio toolbox onto your form, make sure it is the WinForms RichTextBox, not the WPF one.
You can check this by looking in the .Designer.cs file, and find the definition of the RTB control created by the Visual Studio designer. It should look something like this:
this.rtbResults = new System.Windows.Forms.RichTextBox();
...
...
//
// rtbResults
//
this.rtbResults.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rtbResults.Location = new System.Drawing.Point(12, 52);
this.rtbResults.Name = "rtbResults";
this.rtbResults.Size = new System.Drawing.Size(640, 133);
this.rtbResults.TabIndex = 17;
this.rtbResults.Text = "";
...
...
private System.Windows.Forms.RichTextBox rtbResults;
The important thing being that it says "System.Windows.Forms.RichTextBox", not something else.
OK, here's my strange example, which displays the results of a Scrabble cheater program:
/// <summary>
/// Method to display the results in the RichTextBox, prefixed with "Results: " and with the
/// letters J, Q, X and Z underlined.
/// </summary>
private void DisplayResults(string resultString)
{
resultString = UnderlineSubString(resultString, "J");
resultString = UnderlineSubString(resultString, "Q");
resultString = UnderlineSubString(resultString, "X");
resultString = UnderlineSubString(resultString, "Z");
rtbResults.Rtf = #"{\rtf1\ansi " + "Results: " + resultString + "}";
}
/// <summary>
/// Method to apply RTF-style formatting to make all occurrences of a substring in a string
/// underlined.
/// </summary>
private static string UnderlineSubString(string theString, string subString)
{
return theString.Replace(subString, #"\ul " + subString + #"\ul0 ");
}
This uses Microsoft's proprietary Rich Text Format, but RichTextBox can also use straight text. And this demo only writes to the RTB, it doesn't read from it, although doing that is fairly trivial.
Hope this helps.

String overflowing when concatting

I'm trying to make a program packer but i always fail because when i concat three strings(one contains prefix of source, one contains executable content, other contains suffix of source) content overflows into suffix. Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
using System.IO.Compression;
namespace ProgramPacker
{
public partial class Form1 : Form
{
static string prefix = #"using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ProgramPacker
{
class Program
{
static string inside = #" + "\"";
static string suffix = "\";\n" + #"static void Main(string[] args)
{
string temp = Path.GetRandomFileName() +" + "\"" + #".exe" + "\"" + #";
BinaryWriter sw = new BinaryWriter(new FileStream(temp, FileMode.Create));
sw.Write(inside);
sw.Flush();
sw.Close();
System.Diagnostics.Process.Start(temp);
}
}
}";
public string code = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
BinaryReader br = new BinaryReader(new FileStream(openFileDialog1.FileName, FileMode.Open));
byte[] data = new byte[br.BaseStream.Length];
br.Read(data, 0, (int)br.BaseStream.Length);
br.Close();
string inside = Encoding.UTF7.GetString(data);
code = string.Concat(prefix, string.Concat(inside, suffix));
}
private void button2_Click(object sender, EventArgs e)
{
Console.Write(code);
CSharpCodeProvider cs = new CSharpCodeProvider();
ICodeCompiler compile = cs.CreateCompiler();
CompilerParameters param = new CompilerParameters();
param.GenerateInMemory = false;
param.ReferencedAssemblies.Add("mscorlib.dll");
param.ReferencedAssemblies.Add("System.dll");
param.ReferencedAssemblies.Add("System.Core.dll");
param.GenerateExecutable = true;
param.OutputAssembly = Environment.CurrentDirectory + "/a.exe";
param.WarningLevel = 4;
CompilerResults comp = compile.CompileAssemblyFromSource(param, code);
foreach (CompilerError error in comp.Errors)
{
MessageBox.Show(error.Line + " " + error.Column + " " + error.ErrorText);
}
MessageBox.Show(comp.PathToAssembly);
MessageBox.Show("Finish!");
}
}
}
It outputs:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ProgramPacker
{
class Program
{
static string inside = #"?ãÎoüoy±ôãøÿ?ÿQÔh¦Rt!?^ÿyóë=G:Fÿ»??¿Ç/}òKÿ?úõßû3õMù?c·?Äûòëoª?À_Û>LÖïá^öÿ·õ©üüòcÊ?ª??÷Ô?î:^ȯÏäG¶?ù ?ñË?oñëy:ôã7??ò#ÚyN?w¿=?ëÆ÷ëÛßTëºÓ»yßüø]áå{ö/àïªêL©Oÿ;ú5rù% ä¸?1)Ï?¥?y®ÿ]0QL8û×ÖGòów±?øÿèü[?ª~éá¿ÿó£üüJ~ܹ
Êw¡h??/?úçeñÈ_?¿?ü½L^ywü7?,ùÅû¿ß£ó÷w?É~Ç????ê?ÿQÌyç¿??¹Cö×vZ__>?? ûïx?_ü"õ!ì; ;ùõåÇ?ú3*­¿ #ÿV?èÿ¿Ë??/½P¶y?â¡??ùñÿÑæä/A¶_ò?v??ÿ?ÿQtÄx÷w?O'N?u$ÿk÷U«yÆò?£.Y?ùw(?ßÔ6ÿ]2ÿeUÆò¿?ضö·ßO~ü#*y£Jæ·Ä w yóYëï´
õ}y¡ä¨ù÷YPdú?Z©Óé¼R?æg?ÀSyà쬽Éÿ­ûÁ?ym>ut?ÿA??>?¿[ôçF ê´)9ß9xÿ£¿?
åùïyí ÁTlù
-ùñ?Òÿ·!·
E?£üO5÷]çºy?7Áè¿?Zô?(å§
#ü¥úõ®?o«âû]0Èßä7¿à??¿õ?d?ѵ;Jü_K?úAMìT>Àü1mR0sâ¿ê¨õ{äö×ó??¿.úÿõ½Eä?ÔïÿÎÿ±³v'ÿûìw ?»oÃø1±WtB
É¡wì&øuå£Îÿ?Éw?|úWÿ=ö÷_ÿ·?y®YWöwû¿ßß?Öe'û?%?yß/×Àî-yÿ.?8åóù?ûÇÚ6ÿÂßøï?Áàï?{8Zy?¿Å5yø ÇpÏ9=ó»üÑ>Õ?Èÿ?Y¿,?ëÿ?Êçÿì_}E?÷Ûú|î$ò÷ø}Jÿ^Êtò¿?#á|ò{Ø`<ªÿQ?QLæ½õo)¿ü&¿áÂÿ¼ó¿_÷7yMå8)¿Ùo'¿õ±üü=~#LÚ¿ó§¢Ë÷üO?Æ?å÷WJÍ$¾¸øW?A?Òÿ(09Áÿà³_ëÿù3l?SWYµßô÷¤~?ÀG¿ñ
??Às%ÍyÑ;Ò¸!ÿ?_Iÿ¼¼í/Ôrö
?T´ôÑùyǹßE~üV?ñ¿C~VßùuÿG X8|._¼Å_:Æü-?îü:?øì?|W ¤ÃÓW01?$å×?Û#ùIÿû·1:4û½ü._y^òÙNó?º1?ßIÍ?ÿ¿ß_~|ÖùX?#?në_B?¡µ~_×ãÿhãèïØÏßì¡yïôk_y;HÿÛyÿàâ/sÀ??? $ìw0Jüßü«#?ûo?¿îËX
´úÏ?Æ?Y>øçÿFpyÅÿèËöyK¡²Ì`}ù½Ò¿íÿÀñn"?Í?ëOëi»ò¹Î~çÿ?_òüîÿh£ôáêDøÏÿ¶?ç·fy ÄúçÿÖÿ?yÿ?¿?ã0ÿ¿Ë÷åå?ÿQ|ü/ü9¿?÷×Hè×ÉÏ#õ??æ?ÿâ?x?ß?5µ}~Øy¾ß^øè{¿
y{íü;Òÿ¿óú7¤¡î?» yû?ÀÓøiP?ÿÀ_ôK?Gëªíá#??ú%íwS×ñ¿¨#Û¦ÿÿÛªy\]¼÷Z~yR~ü¶ÿ£hû???ÇãÿQVèÿ©?÷{O?Gë¬ ??¡ø\«L` æcëí¿ ½?»?ü?oë¼Ätÿ>ò÷£­_¯ÖiÄ?¯ÿÓ¿÷Ï?(c¦äàéûèó?ü£´çÕè4üy_
r?qÆ¿ø'?KÿÀ_ó×xùkÔ¿FõkÌ~õ¯1y5Ú_ã'??n~âר~å¯ñkü»¿Æø×رÿÿ5~?_ã7ø5~Í_ã?Z4ÔrñkL~ò׸?5Òßûÿ??ñïñnQ¦?yYÕò³vÇ;¥ùrZÍ?åÅg}õæÙöÁGiÓfËYVVËü³®óæ£ßãè7NgM?/&åuJrustInfo>
</assembly>
;
}
}
}
Any help?
EDIT: Why is everyone down-voting? I just asked a question.
Don't use bare UTF7 or UTF8 strings, use Base64 encoding instead.
// given: byte[] data = new byte[...]
string inside = System.Convert.ToBase64String(data);
code = string.Concat(prefix, string.Concat(inside, suffix));
// in your target code
sw.Write(System.Convert.FromBase64String(inside));
You've run into a problem of representation, one that you're not likely to fix with your code as-is.
However, you can choose to follow a similar approach with just minor modifications (which don't actually compress your program much at all).
Remove the # from the definition of the string inside. This is one of the causes of your problems.
You can't just put a BELL character or NUL character in-line in your string, instead write out their unicode escape sequences:
string inside = String.Concat(
data.Select(b => String.Format(#"\u{0:X4}", b)));
Now, in your suffix code, reinterpret your inside string as characters which you cast to bytes:
sw.Write(inside.Select(c => (byte)c).ToArray()); // hardly efficient
I was able to use these modifications and successfully "pack" and execute the following:
C:\temp>type hello.cs
using System;
class M {
static void Main(string[] args) {
System.IO.File.Create("hello.world");
}
}
C:\temp>csc hello.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.
C:\temp>pack.exe hello.exe
3584 bytes
C:\temp>a.exe
C:\temp>dir *.world
Volume in drive C is OSDisk
Volume Serial Number is AABD-D663
Directory of C:\temp
03/22/2012 16:36 0 hello.world
1 File(s) 0 bytes
0 Dir(s) 279,351,762,944 bytes free
Better use CodeCompileUnit to generate C# code from a C# program:
http://msdn.microsoft.com/en-us/library/system.codedom.codecompileunit.aspx
You can also use this to compile the generated ATS into an assembley.
Or parse your template parts from files. That would make the code much more readable.
You can't just express executable binary code as a C# string without escaping it. At least you need to replace any occurrences of the double-quote character ('"') with a sequence of two double-quote characters. I would be very surprised if that's the only problem you encounter, however.
Note that the string might contain control characters that cause the screen to display the string in a garbled way, but that wouldn't necessarily cause the code containing that string to compile improperly. For example, if you have a verbatim string containing a backspace ("stac{backspace}koverflow", say), the character after the backspace would overwrite the character before the backspace, so viewing the string on the screen would give an inaccurate representation of its contents ("stakoverflow"). The compiler would presumably see the full 14-character string including the backspace.

C# API generator

I have a few dll files and I want to export all public classes with methods separated by namespaces (export to html / text file or anything else I can ctrl+c/v in Windows :) ).
I don't want to create documentation or merge my dlls with xml file. I just need a list of all public methods and properties.
What's the best way to accomplish that?
TIA for any answers
Very rough around the edges, but try this for size:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace GetMethodsFromPublicTypes
{
class Program
{
static void Main(string[] args)
{
var assemblyName = #"FullPathAndFilenameOfAssembly";
var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyName);
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);
var methodsForType = from type in assembly.GetTypes()
where type.IsPublic
select new
{
Type = type,
Methods = type.GetMethods().Where(m => m.IsPublic)
};
foreach (var type in methodsForType)
{
Console.WriteLine(type.Type.FullName);
foreach (var method in type.Methods)
{
Console.WriteLine(" ==> {0}", method.Name);
}
}
}
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
var a = Assembly.ReflectionOnlyLoad(args.Name);
return a;
}
}
}
Note: This needs refinement to exclude property getters/setters and inherited methods, but it's a decent starting place
Have you had a look at .NET Reflector from RedGate software. It has an export function.
You can start here with Assembly.GetExportedTypes()
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexportedtypes.aspx

Categories