using c#.net can we read a line or symbol from a word file - c#-2.0

how can we read a line or symbol from any type of file using c#.net, we can read all the things which is available in the keyboard but we can not read other symbols is it possible to read other symbols using C#.net please anybudy can help me on this

Yes we can:
using System;
using System.IO;
namespace IOTest
{
public class program
{
public static void Main(string[] args)
{
using (Stream s = File.OpenRead(#"C:\AFile.file"))
{
using (StreamReader sr = new StreamReader(s))
{
Console.WriteLine(sr.ReadLine());
}
}
}
}
}
For symbols, you would need to use Regex or something like that...

Related

How to write a blank service binary for Windows?

I'm trying to create a service that does absolutely nothing for testing purposes. For that I need a binary that does absolutely nothing but services don't seem to start for just any executable, only ones specifically designed to be service binaries. I've tried to find information as to how to make service binaries but can't seem to find anything. Thanks in advance.
Check out the demo service in this little nuget library:
https://github.com/wolfen351/windows-service-gui
It should give you a good starting point for making a test service to use, it is a trivial implementation of a windows service that does nothing. Also the nuget package will help you run it! :)
Here is the heart of the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace DemoService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
Timer t1 = new Timer(AutoStopCallback, null, 15000, -1); // auto stop in 15 seconds for testing
}
private void AutoStopCallback(object state)
{
Stop();
}
protected override void OnStart(string[] args)
{
Thread.Sleep(2000);
base.OnStart(args);
}
protected override void OnStop()
{
Thread.Sleep(2000);
base.OnStop();
}
protected override void OnContinue()
{
Thread.Sleep(2000);
}
protected override void OnPause()
{
Thread.Sleep(2000);
}
}
}

PDF not loading from documents folder on App relaunch iOS

I have a pdf that I download from the server and save it. Next I open the file from the file path within a UIWebView. This works the first time I launch the app. When I relaunch the app again, even thought the file path is the same, the document does not open. Also, the document does exist in the document folder of the app.
I am doing something like :-
SaveToFolder.cs
var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), fileName);
using (FileStream destinationStream = File.Create(filePath))
{
await documentStream.CopyToAsync(destinationStream);
}
File path after saving the document first time :-
/var/mobile/Containers/Data/Application/C3EA2325-81CA-4EC9-8C03-479ACF7EE330/Documents/Insufficiency.pdf
File Path on app relaunch
/var/mobile/Containers/Data/Application/C3EA2325-81CA-4EC9-8C03-479ACF7EE330/Documents/Insufficiency.pdf
Is there something Iam doing wrong?
I have created a file in iOS for reading & writing file. Please have a look in iOS
using System;
using Xamarin.Forms;
using FileReader.iOS;
using System.IO;
using FileReader;
using Foundation;
using System.Linq;
using System.Threading.Tasks;
[assembly: Dependency(typeof(SaveAndLoadiOS))]
namespace FileReader.iOS
{
public class SaveAndLoadiOS : LoadAndSave
{
public static string DocumentPath
{
get
{
var documentURL = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User).Last();
return documentURL.Path;
}
}
public string CreatePath(string fileName)
{
return Path.Combine(DocumentPath, fileName);
}
public async Task SaveTextAsync(string fileName, string text)
{
string path = CreatePath(fileName);
if (IsFileExits(fileName))
{
File.Delete(path);
}
using (StreamWriter sw = File.CreateText(path))
await sw.WriteAsync(text);
}
public async Task<string> LaodTextAsync(string fileName)
{
string path = CreatePath(fileName);
using (StreamReader sr = File.OpenText(path))
return await sr.ReadToEndAsync();
}
public bool IsFileExits(string fileName)
{
return File.Exists (CreatePath(fileName));
}
}
}
For reading from my .CS class (subclass of ContentPage), Below is the code
var tempFileService = DependencyService.Get<LoadAndSave>();
var itemFile = await tempFileService.LaodTextAsync(tempFile.StoredFileName);
var rootobject = JsonConvert.DeserializeObject<Rootobject>(itemFile);
Where LoadAndSave is an interface as below
using System;
using System.Threading.Tasks;
namespace FileReader
{
public interface LoadAndSave
{
Task SaveTextAsync(string fileName, string text);
Task<string> LaodTextAsync(string fileName);
bool IsFileExits(string fileName);
}
}
Hope it helps.
I ran into the same issue a while ago. You can refer Can't find saved file (in device) after restarting the app
According to the answer
You shouldn't store raw file paths for persistence (or if you do, know that the root can move on you). A better practice would be to only store the relative part of the path and always attach it to the current "root" path in question (particularly if you might be sharing data across devices as with iCloud).
Maybe your root is changing as well. You can change your approach and append the filename with the default path to your documents folder like so in Xamarin:-
var docsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
filePath = docsPath +"/" + "Insuffeciency.pdf";
Also, consider changing your Personal folder to MyDocuments folder while saving the file.

Lucene does not index some words?

I use leucene.net for my site and it Index some of the words fine and correct but it doesn't index some words like "الله"!
I have see the indexed file with Luke and it shows that "الله"is not indexed.
I have used ArabicAnalyzer for indexing.
you can see my site at www.qoranic.com , if you search "مریم" it will be ok but if you search "الله" it shows nothing.
any idea is appreciated in forward.
The ArabicAnalyzer does some transformation to that input; it will transform the input الله to له. This is due to the usage of the ArabicStemFilter (and ArabicStemmer) which is documented with ...
Stemming is defined as:
Removal of attached definite article, conjunction, and prepositions.
Stemming of common suffixes.
This shouldn't be an issue since you should be parsing the user provided query through the same analyzer when searching, producing the same tokens.
Here's the sample code I used to see what terms an analyzer produced from a given input.
using System;
using Lucene.Net.Analysis.AR;
using Lucene.Net.Analysis.Tokenattributes;
using System.IO;
namespace ConsoleApplication {
public static class Program {
public static void Main() {
var luceneVersion = Lucene.Net.Util.Version.LUCENE_30;
var input = "الله";
var analyzer = new ArabicAnalyzer(luceneVersion);
var inputReader = new StringReader(input);
var stream = analyzer.TokenStream("fieldName", inputReader);
var termAttribute = stream.GetAttribute<ITermAttribute>();
while(stream.IncrementToken()) {
Console.WriteLine("Term: {0}", termAttribute.Term);
}
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}
You can overcome this behavior (remove the stemming) by writing a custom Analyzer which uses the ArabicNormalizationFilter, just as ArabicAnalyzer does, but without the call to ArabicStemFilter.
public class CustomAnalyzer : Analyzer {
public override TokenStream TokenStream(String fieldName, TextReader reader) {
TokenStream result = new ArabicLetterTokenizer(reader);
result = new LowerCaseFilter(result);
result = new ArabicNormalizationFilter(result);
return result;
}
}

How to force ASP.NET Web API to always return JSON?

ASP.NET Web API does content negotiation by default - will return XML or JSON or other type based on the Accept header. I don't need / want this, is there a way (like an attribute or something) to tell Web API to always return JSON?
Clear all formatters and add Json formatter back.
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
EDIT
I added it to Global.asax inside Application_Start().
Supporting only JSON in ASP.NET Web API – THE RIGHT WAY
Replace IContentNegotiator with JsonContentNegotiator:
var jsonFormatter = new JsonMediaTypeFormatter();
//optional: set serializer settings here
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
JsonContentNegotiator implementation:
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(
Type type,
HttpRequestMessage request,
IEnumerable<MediaTypeFormatter> formatters)
{
return new ContentNegotiationResult(
_jsonFormatter,
new MediaTypeHeaderValue("application/json"));
}
}
Philip W had the right answer but for clarity and a complete working solution, edit your Global.asax.cs file to look like this: (Notice I had to add the reference System.Net.Http.Formatting to the stock generated file)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace BoomInteractive.TrainerCentral.Server {
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication {
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//Force JSON responses on all requests
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
}
}
}
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
This clears the XML formatter and thus defaulting to JSON format.
Inspired by Dmitry Pavlov's excellent answer, I altered it slightly so I could plug-in whatever formatter I wanted to enforce.
Credit to Dmitry.
/// <summary>
/// A ContentNegotiator implementation that does not negotiate. Inspired by the film Taken.
/// </summary>
internal sealed class LiamNeesonContentNegotiator : IContentNegotiator
{
private readonly MediaTypeFormatter _formatter;
private readonly string _mimeTypeId;
public LiamNeesonContentNegotiator(MediaTypeFormatter formatter, string mimeTypeId)
{
if (formatter == null)
throw new ArgumentNullException("formatter");
if (String.IsNullOrWhiteSpace(mimeTypeId))
throw new ArgumentException("Mime type identifier string is null or whitespace.");
_formatter = formatter;
_mimeTypeId = mimeTypeId.Trim();
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
return new ContentNegotiationResult(_formatter, new MediaTypeHeaderValue(_mimeTypeId));
}
}
This has correct headers set. Seems a bit more elegant.
public JsonResult<string> TestMethod()
{
return Json("your string or object");
}
If you want to do that for one method only, then declare your method as returning HttpResponseMessage instead of IEnumerable<Whatever> and do:
public HttpResponseMessage GetAllWhatever()
{
return Request.CreateResponse(HttpStatusCode.OK, new List<Whatever>(), Configuration.Formatters.JsonFormatter);
}
this code is pain for unit testing but that's also possible like this:
sut = new WhateverController() { Configuration = new HttpConfiguration() };
sut.Configuration.Formatters.Add(new Mock<JsonMediaTypeFormatter>().Object);
sut.Request = new HttpRequestMessage();
for those using OWIN
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
becomes (in Startup.cs):
public void Configuration(IAppBuilder app)
{
OwinConfiguration = new HttpConfiguration();
ConfigureOAuth(app);
OwinConfiguration.Formatters.Clear();
OwinConfiguration.Formatters.Add(new DynamicJsonMediaTypeFormatter());
[...]
}
Yo can use in WebApiConfig.cs:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
public System.Web.Http.Results.JsonResult<MeineObjekt> Get()
{
return Json(new MeineObjekt()
{
Cod = "C4666",
Payment = 10.0m,
isEnough = false
});
}

How can I export to CSV in an ASP.NET MVC application?

I know this question has been asked and answered in several ways, but none of them get to the crux of the matter that I need to understand. In WebForms, we 'subvert' the rendering process and write straight to the Response's output stream. How does one achieve that using a Controller Action, to write CSV to a file for Excel?
Just to elaborate on Omu's FileHelpers answer, I was able to combine #shamp00's ideas here with this answer here in order to render a CSV to a FileContentResult via stream on the fly.
Given a FileHelpers DTO Model like so:
[DelimitedRecord(",")]
public class Foo
{
public string Name { get; set; }
public int Id { get; set; }
}
And a controller action:
public FileContentResult DownloadFoosCSV()
{
var foos = GetFoos(); // IEnumerable<Foo>
var fileHelper = new FileHelperEngine<Foo>();
using (var stream = new MemoryStream())
using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
{
fileHelper.WriteStream(streamWriter, foos);
streamWriter.Flush();
return File(stream.ToArray(), "application/csv", "NewFoos.csv");
}
}
You can try CsvActionResult described at http://develoq.net/2011/export-csv-actionresult-for-asp-net-mvc/
Same way you'd write any other file -- use FileResult and it's descendants.
I've been using this: http://www.filehelpers.net/ in an asp.net mvc application, look at the getting started guide, you should get it from there

Resources