Message with new line character is displayed as html code - c#

I am using following code to post multiline message on facebook wall/page. but it is appear as shown in image (the text are different here). here is my code.
string path = "/me/feed";
string token = fbLoginDialog.FacebookOAuthResult.AccessToken;
dynamic messagePost = new ExpandoObject();
messagePost.message = #"Hello guys!
How are you?
Can you help me on this?";
var fb = new FacebookClient(token);
try { var postId = fb.Post(path, messagePost); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
I am using Facebook.dll Version: 5.0.1.0

Did you try Environment.NewLine?:
messagePost.message = "Hello guys!" + Environment.NewLine +
"How are you?"+ Environment.NewLine +
"Can you help me on this?";
Environment.NewLine is a platform independent property that inserts new line char for the selected environment.
Or maybe you have a problem with your syntax and it should be:
messagePost.message = #"Hello guys!\r\n How are you?\r\n Can you help me on this?";

I got it working using Facebook.6.0.22
download latest from here https://github.com/facebook-csharp-sdk/facebook-winforms-sample

Related

SSIS Script Task - input string was not in a correct format

I have a very very strange issue going on with SSIS and wanted to know if anyone else has had something similar.
In a Data Flow I have a Source that gets data from a MSSQL table and then feeds it to a data transformation Script Task.
The script task is as follows:
Script Task
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string SecurityHeader = (string)Variables.SecurityHeader;
string APIToken = (string)Variables.APIToken;
var AppFormID = (string)Row.AppFormID;
var AppClassName = (string)Row.AppClassName;
var Lat = Row.Latitude;
var Long = Row.Longitude;
var data = new
{
record = new
{
status = Row.Status.ToString(),
latitude = Row.Latitude,
longitude = Row.Longitude,
form_values = new Dictionary<string, string>()
}
};
if (Row.CreatedBy_IsNull == false) { data.record.form_values["1a09"] = Row.CreatedBy.ToString(); }
string jsonstring = JsonConvert.SerializeObject(data);
var client = new RestClient(AppURLRef);
var request = new RestRequest(Method.POST);
request.AddHeader(SecurityHeader, APIToken);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", jsonstring, ParameterType.RequestBody);
try
{
IRestResponse dataresponse = client.Execute(request);
if (dataresponse.StatusCode.ToString() == "Created")
{
var listobject = JsonConvert.DeserializeObject<Lists>(dataresponse.Content);
}
else
{
Row.OErrorMsg = dataresponse.ErrorMessage.ToString();
};
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " Data: " + ex.Data + " Inner Exception: " + ex.InnerException);
}
}
The Issue
When I run this without any break points I get a Message Box with the error "Input string was not in correct format"
Where this gets really weird is that when I put a break point in the code works perfectly, thus making getting a line error impossible.
Has anyone ever come across an issue like this before and if so how did you fix it?
Update
After following some advice I moved the try catch block up to the start of the script, this resulted in no change the try catch block was never hit.
I attempted to but a MessageBox.Show("") at the very top of the input process row and again this was not hit. Something is happening at a higher level than both of these thought I am unable to find out where or how this is occurring.
Again to reiterate the error is in a MessageBox, not in the output and nothing gets logged in the process tab. So this means no line numbers, no useful error messages that discusses where this error is occurring.
I managed to solve this, after commenting EVERYTHING out and removing all of the input columns the error was still occurring.
I put it down to another way Microsoft wants to punish me, I copied the code deleted the script task, added a new script task and copied the old code back in. Worked perfectly...
Thanks Microsoft!!
Put delay in catch block in next line to MessageBox.Show
you able to view message box .
Some time message box goes in back ground ( USe ALT +TAB to find it).

.Net.Mail new line

I am using .Net.Mail to send text messages but I am having trouble inserting a new line. I have searched the internet, including StackOverflow, for a method to do this. I have found several but non of them work. I am using StringBuilder to build the body of the message but appending a new line or empty line does cause a new line to be inserted into the message. I have also tried "\n" and several other methods but nothing seems to work. I have added my code below. Does anybody know how I can do this.
Thank you in advance for any help that may be offered.
string cellPhone = reader.GetString(reader.GetOrdinal("CellPhone"));
string suffix = reader.GetString(reader.GetOrdinal("Suffix"));
StringBuilder body = new StringBuilder();
cellPhone = cellPhone.Trim().Replace(" ", "").Replace("-", "").Replace("(", "").Replace(")", "");
if (!suffix.StartsWith("#"))
{
suffix = "#" + suffix;
}
string address = cellPhone + suffix;
reader.Close();
EMail email = new EMail("mail.yyy.com");
email.IsHTML = true;
email.Subject = "Sales Lead from yyy.com";
email.Add_ToAddress(address, false);
body.AppendLine(" ");
body.AppendLine("Name: " + this.tbSalesLeadName2.Text + "EMail: mailto: " + this.tbSalesLeadEmail2.Text);
if (!this.chkSalesLeadEmail2.Checked) //&& (!this.hidCellPhoneProvider.Value.Equals("0", StringComparison.InvariantCultureIgnoreCase)))
{
body.AppendLine("Phone: " + this.tbSalesLeadPhone2.Text);
body.AppendLine("Cell Phone: " + this.tbSalesLeadCellPhone.Text);
}
body.AppendLine(" ");
body.AppendLine(" ");
body.AppendLine("Comments: " + this.tbSalesLeadComments2.Text);
body.AppendLine(" ");
body.AppendLine(" ");
body.AppendLine("***To respond start a new text thread with the cell phone number listed above");
email.Body = body.ToString();
email.From = "xxx#yyy.com";
email.Send_Mail();
email.IsHTML = true;
You say that your body is in HTML format, but it isn't.
You have two options to fix that:
Set IsHTML to false, and your line breaks should work.
Format your body as real HTML, i.e., use HtmlEncode for your data and <br> for your line breaks.
As you are using email.IsHTML = true;, You should be able to put tag in your string builder object.. The code would look like,
body.AppendLine(" <br/>");
body.AppendLine(" <br/>");
body.AppendLine("Comments: " + this.tbSalesLeadComments2.Text + "<br/>");
body.AppendLine(" <br/>");
body.AppendLine(" <br/>");
body.AppendLine("***To respond start a new text thread with the cell phone number listed above<br/>");
email.Body = body.ToString();
You've specified that the email is HTML. New lines are ignored in HTML.
To actually render a line break you need to use <br /> or some other equivalent.
If you don't actually have any HTML to render, then simply specify that the email is not an HTML email and new lines will be rendered as new lines.
Thank you for your advice. Please ignore my earlier comment. Your suggestion did work I just needed to add "\n" where I wanted a new line.
I really appreciate your help.

automate downloading a file using c# programmatically

I have a project where I need to automatically download and process an excel file from a public web site.
the site is the following:
http://apps.ahca.myflorida.com/dm_web/(S(rhlzd0ac2qwvvccbyp3lx2or))/doc_results_fo.aspx
you can see a link called Export Results which downloads the excel file. This link does a postback and I have been looking all over the place to find a way to automate it without success.
This is the last code I tried:
try
{
byte[] b = webClient.DownloadData("http://apps.ahca.myflorida.com/dm_web/(S(eha2oijpqo5mro1aywok4lly))/doc_results_fo.aspx");
string s = System.Text.Encoding.UTF8.GetString(b);
var __EVENTVALIDATION = ExtractVariable(s, "__EVENTVALIDATION");
var forms = new NameValueCollection();
forms["__EVENTTARGET"] = "lbtSpreadsheet";
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = ExtractVariable(s, "__VIEWSTATE");
forms["mTbdate"] = "11%2F15%2F2011";
forms["__EVENTVALIDATION"] = __EVENTVALIDATION;
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var responseData = webClient.UploadValues(#"http://apps.ahca.myflorida.com/dm_web/(S(eha2oijpqo5mro1aywok4lly))/doc_results_fo.aspx", "POST", forms);
System.IO.File.WriteAllBytes(#"c:\tmp\FLORIDA.xls", responseData);
}
catch (Exception ex)
{
Console.Write(ex.StackTrace);
}
}
private static string ExtractVariable(string s, string valueName)
{
string tokenStart = valueName + "\" value=\"";
string tokenEnd = "\" />";
int start = s.IndexOf(tokenStart) + tokenStart.Length;
int length = s.IndexOf(tokenEnd, start) - start;
return s.Substring(start, length);
}
This is supposed to get the value of view state and other fields and issue a POST , but when I run it the file that gets downloaded is the page itself and not the excel file.
I am not sure if this is possible using WebClient, or I should use WebBrowser control (or similar controls), or maybe an atomated browsing tool that I can record a sequence of steps and run it every x days.
Any help will be greatly appreciated.
Thank you
I figured it out using Selenium .NET
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.SetPreference("browser.download.folderList", 2);
firefoxProfile.SetPreference("browser.download.dir", strFullpath);
firefoxProfile.SetPreference("browser.helperApps.neverAsk.openFile", "application/vnd.ms-Excel");
firefoxProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms-Excel");
IWebDriver driver = new FirefoxDriver(firefoxProfile);
driver.Navigate().GoToUrl(link);
driver.FindElement(By.Id(lookup)).Click();
driver.Quit();

Tesseract OCR simple example

Hi Can you anyone give me a simple example of testing Tesseract OCR
preferably in C#.
I tried the demo found here.
I download the English dataset and unzipped in C drive. and modified the code as followings:
string path = #"C:\pic\mytext.jpg";
Bitmap image = new Bitmap(path);
Tesseract ocr = new Tesseract();
ocr.SetVariable("tessedit_char_whitelist", "0123456789"); // If digit only
ocr.Init(#"C:\tessdata\", "eng", false); // To use correct tessdata
List<tessnet2.Word> result = ocr.DoOCR(image, Rectangle.Empty);
foreach (tessnet2.Word word in result)
Console.WriteLine("{0} : {1}", word.Confidence, word.Text);
Unfortunately the code doesn't work. the program dies at "ocr.Init(..." line. I couldn't even get an exception even using try-catch.
I was able to run the vietocr! but that is a very large project for me to follow. i need a simple example like above.
Ok. I found the solution here
tessnet2 fails to load
the Ans given by Adam
Apparently i was using wrong version of tessdata. I was following the the source page instruction intuitively and that caused the problem.
it says
Quick Tessnet2 usage
Download binary here, add a reference of the assembly Tessnet2.dll to your .NET project.
Download language data definition file here and put it in tessdata directory. Tessdata directory and your exe must be in the
same directory.
After you download the binary, when you follow the link to download the language file, there are many language files. but none of them are right version. you need to select all version and go to next page for correct version (tesseract-2.00.eng)! They should either update download binary link to version 3 or put the the version 2 language file on the first page. Or at least bold mention the fact that this version issue is a big deal!
Anyway I found it.
Thanks everyone.
A simple example of testing Tesseract OCR in C#:
public static string GetText(Bitmap imgsource)
{
var ocrtext = string.Empty;
using (var engine = new TesseractEngine(#"./tessdata", "eng", EngineMode.Default))
{
using (var img = PixConverter.ToPix(imgsource))
{
using (var page = engine.Process(img))
{
ocrtext = page.GetText();
}
}
}
return ocrtext;
}
Info: The tessdata folder must exist in the repository: bin\Debug\
I was able to get it to work by following these instructions.
Download the sample code
Unzip it to a new location
Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)
Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to)
Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs:
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Run (hit F5)
You should get this windows console output
Try updating the line to:
ocr.Init(#"C:\", "eng", false); // the path here should be the parent folder of tessdata
I had same problem, now its resolved. I have tesseract2, under this folders for 32 bit and 64 bit, I copied files 64 bit folder(as my system is 64 bit) to main folder ("Tesseract2") and under bin/Debug folder. Now my solution is working fine.
In my case I had all these worked except for the correct character recognition.
But you need to consider these few things:
Use correct tessnet2 library
use correct tessdata language version
tessdata should be somewhere out of your application folder where you can put in full path in the init parameter. use ocr.Init(#"c:\tessdata", "eng", true);
Debugging will cause you headache. Then you need to update your app.config
use this. (I can't put the xml code here. give me your email i will email it to you)
hope that this helps
Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing
Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing
Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.
Setup
To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.
Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.
VC++ Directories>Include Directories:
..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath)
C/C++>Preprocessor>Preprocessor Definitions:
_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
C/C++>Linker>Input>Additional Dependencies:
..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies)
Now you can include headers in your project's file:
include
include
Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.
When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
api->Init("D:\tessdataParentFolder\", ...
Sample
You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.
This worked for me, I had 3-4 more PDF to Text extractor and if one doesnot work the other one will ... tesseract in particular this code can be used on Windows 7, 8, Server 2008 . Hope this is helpful to you
do
{
// Sleep or Pause the Thread for 1 sec, if service is running too fast...
Thread.Sleep(millisecondsTimeout: 1000);
Guid tempGuid = ToSeqGuid();
string newFileName = tempGuid.ToString().Split('-')[0];
string outputFileName = appPath + "\\pdf2png\\" + fileNameithoutExtension + "-" + newFileName +
".png";
extractor.SaveCurrentImageToFile(outputFileName, ImageFormat.Png);
// Create text file here using Tesseract
foreach (var file in Directory.GetFiles(appPath + "\\pdf2png"))
{
try
{
var pngFileName = Path.GetFileNameWithoutExtension(file);
string[] myArguments =
{
"/C tesseract ", file,
" " + appPath + "\\png2text\\" + pngFileName
}; // /C for closing process automatically whent completes
string strParam = String.Join(" ", myArguments);
var myCmdProcess = new Process();
var theProcess = new ProcessStartInfo("cmd.exe", strParam)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
WindowStyle = ProcessWindowStyle.Minimized
}; // Keep the cmd.exe window minimized
myCmdProcess.StartInfo = theProcess;
myCmdProcess.Exited += myCmdProcess_Exited;
myCmdProcess.Start();
//if (process)
{
/*
MessageBox.Show("cmd.exe process started: " + Environment.NewLine +
"Process Name: " + myCmdProcess.ProcessName +
Environment.NewLine + " Process Id: " + myCmdProcess.Id
+ Environment.NewLine + "process.Handle: " +
myCmdProcess.Handle);
*/
Process.EnterDebugMode();
//ShowWindow(hWnd: process.Handle, nCmdShow: 2);
/*
MessageBox.Show("After EnterDebugMode() cmd.exe process Exited: " +
Environment.NewLine +
"Process Name: " + myCmdProcess.ProcessName +
Environment.NewLine + " Process Id: " + myCmdProcess.Id
+ Environment.NewLine + "process.Handle: " +
myCmdProcess.Handle);
*/
myCmdProcess.WaitForExit(60000);
/*
MessageBox.Show("After WaitForExit() cmd.exe process Exited: " +
Environment.NewLine +
"Process Name: " + myCmdProcess.ProcessName +
Environment.NewLine + " Process Id: " + myCmdProcess.Id
+ Environment.NewLine + "process.Handle: " +
myCmdProcess.Handle);
*/
myCmdProcess.Refresh();
Process.LeaveDebugMode();
//myCmdProcess.Dispose();
/*
MessageBox.Show("After LeaveDebugMode() cmd.exe process Exited: " +
Environment.NewLine);
*/
}
//process.Kill();
// Waits for the process to complete task and exites automatically
Thread.Sleep(millisecondsTimeout: 1000);
// This works fine in Windows 7 Environment, and not in Windows 8
// Try following code block
// Check, if process is not comletey exited
if (!myCmdProcess.HasExited)
{
//process.WaitForExit(2000); // Try to wait for exit 2 more seconds
/*
MessageBox.Show(" Process of cmd.exe was exited by WaitForExit(); Method " +
Environment.NewLine);
*/
try
{
// If not, then Kill the process
myCmdProcess.Kill();
//myCmdProcess.Dispose();
//if (!myCmdProcess.HasExited)
//{
// myCmdProcess.Kill();
//}
MessageBox.Show(" Process of cmd.exe exited ( Killed ) successfully " +
Environment.NewLine);
}
catch (System.ComponentModel.Win32Exception ex)
{
MessageBox.Show(
" Exception: System.ComponentModel.Win32Exception " +
ex.ErrorCode + Environment.NewLine);
}
catch (NotSupportedException notSupporEx)
{
MessageBox.Show(" Exception: NotSupportedException " +
notSupporEx.Message +
Environment.NewLine);
}
catch (InvalidOperationException invalidOperation)
{
MessageBox.Show(
" Exception: InvalidOperationException " +
invalidOperation.Message + Environment.NewLine);
foreach (
var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
SearchOption.AllDirectories))
{
loggingInfo += textFile +
" In Reading Text from generated text file by Tesseract " +
Environment.NewLine;
strBldr.Append(File.ReadAllText(textFile));
}
// Delete text file after reading text here
Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
}
}
}
catch (Exception exception)
{
MessageBox.Show(
" Cought Exception in Generating image do{...}while{...} function " +
Environment.NewLine + exception.Message + Environment.NewLine);
}
}
// Delete png image here
Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
Thread.Sleep(millisecondsTimeout: 1000);
// Read text from text file here
foreach (var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
SearchOption.AllDirectories))
{
loggingInfo += textFile +
" In Reading Text from generated text file by Tesseract " +
Environment.NewLine;
strBldr.Append(File.ReadAllText(textFile));
}
// Delete text file after reading text here
Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
} while (extractor.GetNextImage()); // Advance image enumeration...
Admittedly this is an older question when Tesseract 3 was the version available, but it came up in my search results while looking for a related issue and the question, and other answers, highlight the still valid issue of the difficulty of actually getting Tesseract installed, let alone configuring it to work correctly.
There is a far simpler solution (and using the updated Tesseract 5 engine) which does all the work for you, in IronOcr.
(Disclaimer: I do work for Iron Software, though I feel that others can benefit from this information, particularly as it relates to the question of using Tesseract OCR in C# which IronOcr excels at).
using IronOcr;
var Ocr = new IronTesseract(); // nothing to configure
Ocr.Configuration.WhiteListCharacters = "0123456789"; // If digit only
using (var Input = new OcrInput(#"example.tiff"))
{
OcrResult Result = Ocr.Read(Input);
foreach (var Page in Result.Pages)
{
// Page object
int PageNumber = Page.PageNumber;
string PageText = Page.Text;
int PageWordCount = Page.WordCount;
// null if we dont set Ocr.Configuration.ReadBarCodes = true;
OcrResult.Barcode[] Barcodes = Page.Barcodes;
System.Drawing.Bitmap PageImage = Page.ToBitmap(Input);
int PageWidth = Page.Width;
int PageHeight = Page.Height;
foreach (var Paragraph in Page.Paragraphs)
{
// Pages -> Paragraphs
int ParagraphNumber = Paragraph.ParagraphNumber;
String ParagraphText = Paragraph.Text;
System.Drawing.Bitmap ParagraphImage = Paragraph.ToBitmap(Input);
int ParagraphX_location = Paragraph.X;
int ParagraphY_location = Paragraph.Y;
int ParagraphWidth = Paragraph.Width;
int ParagraphHeight = Paragraph.Height;
double ParagraphOcrAccuracy = Paragraph.Confidence;
OcrResult.TextFlow paragrapthText_direction = Paragraph.TextDirection;
foreach (var Line in Paragraph.Lines)
{
// Pages -> Paragraphs -> Lines
int LineNumber = Line.LineNumber;
String LineText = Line.Text;
System.Drawing.Bitmap LineImage = Line.ToBitmap(Input); ;
int LineX_location = Line.X;
int LineY_location = Line.Y;
int LineWidth = Line.Width;
int LineHeight = Line.Height;
double LineOcrAccuracy = Line.Confidence;
double LineSkew = Line.BaselineAngle;
double LineOffset = Line.BaselineOffset;
foreach (var Word in Line.Words)
{
// Pages -> Paragraphs -> Lines -> Words
int WordNumber = Word.WordNumber;
String WordText = Word.Text;
System.Drawing.Image WordImage = Word.ToBitmap(Input);
int WordX_location = Word.X;
int WordY_location = Word.Y;
int WordWidth = Word.Width;
int WordHeight = Word.Height;
double WordOcrAccuracy = Word.Confidence;
if (Word.Font != null)
{
// Word.Font is only set when using Tesseract Engine Modes rather than LTSM
String FontName = Word.Font.FontName;
double FontSize = Word.Font.FontSize;
bool IsBold = Word.Font.IsBold;
bool IsFixedWidth = Word.Font.IsFixedWidth;
bool IsItalic = Word.Font.IsItalic;
bool IsSerif = Word.Font.IsSerif;
bool IsUnderLined = Word.Font.IsUnderlined;
bool IsFancy = Word.Font.IsCaligraphic;
}
foreach (var Character in Word.Characters)
{
// Pages -> Paragraphs -> Lines -> Words -> Characters
int CharacterNumber = Character.CharacterNumber;
String CharacterText = Character.Text;
System.Drawing.Bitmap CharacterImage = Character.ToBitmap(Input);
int CharacterX_location = Character.X;
int CharacterY_location = Character.Y;
int CharacterWidth = Character.Width;
int CharacterHeight = Character.Height;
double CharacterOcrAccuracy = Character.Confidence;
// Output alternative symbols choices and their probability.
// Very useful for spellchecking
OcrResult.Choice[] Choices = Character.Choices;
}
}
}
}
}
}

Domain checker (Whois)?

to all.
i developing a webpage using asp.net with c# language, in this webpage i have a textbox for taking url of the domain and button. when user enter domain name in the textbox and press the button the details of the domain will displaying in the other window. i take help from stackoverflow user and i get the code it is working fine, but when i type the domain name particularly ".in" doamins are not giving details. simply domain available message is displaying actually the domain is registered for example i tried "axisbank.co.in" in my page it is displaying the domain is available but actually it is already taken. I am sending my code please help me ( particularly .in domain names)
protected void Button1_Click(object sender, EventArgs e)
{
lblDomainName.Text = Session["WhoIs"].ToString();
string firstLevelbufData = null;
// Stores the bufData extracted from the webclient
try
{
// similarly we can select any server address for bufData mining
string strURL = "http://www.directnic.com/whois/index.php?query=" + txtDomain.Text;
WebClient web = new WebClient();
// byte array to store the extracted bufData by webclient
byte[] bufData = null;
bufData = web.DownloadData(strURL);
// got the bufData now convert it into string form
firstLevelbufData = Encoding.Default.GetString(bufData);
}
catch (System.Net.WebException ex)
{
// this exception will be fired when the host name is not resolved or any other connection problem
//txtResult.Text = ex.Message.ToString();//sasi
lblresult.Text = ex.Message.ToString();
return;
}
try
{
// first and last are the regular expression string for extraction bufData witnin two tags
// you can change according to your requirement
string first = null;
string last = null;
// chr(34) is used for (") symbol
first = "<p class=\"text12\">";
last = "</p>";
Regex RE = new Regex(first + "(?<MYDATA>.*?(?=" + last + "))", RegexOptions.IgnoreCase | RegexOptions.Singleline);
// try to extract the bufData within the first and last tag
Match m = RE.Match(firstLevelbufData);
// got the result
//txtResult.Text = m.Groups["MYDATA"].Value + "<br>";//sasi
lblresult.Text = m.Groups["MYDATA"].Value + "<br>";
// check if no information abour that domain is available
//if (txtResult.Text.Length < 10) txtResult.Text = "Domain "+ txtDomain .Text +" is Available";//sasi
if (lblresult.Text.Length < 10)
lblresult.Text = "Domain " + txtDomain.Text + " is Available";
}
catch (System.Net.WebException ex)
{
lblresult.Text = " Sorry the information is currently not available !! ";
}
}
help me thank you
http://www.directnic.com
does not have information about .co.in domain names.
Most of the whois sites won't allow you to fetch the results before filling in CAPTCHA.
http://registry.in/ is the official registry, try using whois protocol at whois.registry.in

Categories

Resources