More webrequest in a text file - c#-4.0

I have this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Program
{
static void Main(string[] args)
{
//Consider making this configurable
const string sourceFile = "testSolar.txt";
const string pattern = "http://10.123.9.66:80";
Regex re = new Regex("^(http|https)://");
//var res = re.Match(str);
var webClient = new WebClient();
var times = new Dictionary<string, TimeSpan>();
var stopwatch = new System.Diagnostics.Stopwatch();
//Add header so if headers are tracked, it will show it is your application rather than something ambiguous
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Response-Tester-Client");
var urlList = new List<string>();
//Loop through the lines in the file to get the urls
try
{
stopwatch.Start();
using (var reader = new StreamReader(sourceFile))
{
while (!reader.EndOfStream)
{
var urNewList = new List<string>();
var line = reader.ReadLine();
//line = line.Substring(line.IndexOf(pattern));
//line.Split("\t");
var columns = line.Split('\t');
if (columns[2] == "R")
{
var url = columns[4] + "?" + columns[5];
urlList.Add(url);
}
}
}
}
catch (Exception e)
{
Console.WriteLine("An error occured while attempting to access the source file at {0}", sourceFile);
}
finally
{
//Stop, record and reset the stopwatch
stopwatch.Stop();
times.Add("FileReadTime", stopwatch.Elapsed);
stopwatch.Reset();
}
//Try to connect to each url
var counter = 1;
foreach (var url in urlList)
{
try
{
stopwatch.Start();
webClient.DownloadString(url);
}
catch (Exception e)
{
Console.WriteLine("An error occured while attempting to connect to {0}", url);
}
finally
{
stopwatch.Stop();
//We use the counter for a friendlier url as the current ones are unwieldly
times.Add("Url " + counter, stopwatch.Elapsed);
counter++;
stopwatch.Reset();
}
}
//Release the resources for the WebClient
webClient.Dispose();
//Write the response times
foreach (var key in times.Keys)
{
Console.WriteLine("{0}: {1}", key, times[key].TotalSeconds);
}
Console.ReadKey();
}
}
}
And I have three lines in a text file, like this:
2014-08-25 14:20:43,949 DEV belkbyavlahok0jrvoutn2xd 21 R O http://10.123.9.66:80/solr_3.6/wiewaswie_live/select/ qt=standard_a2aperson&q=*:*&fq=(nosyn_name_last_exact:(qxqroelofqxq))&fq=(nosyn_name_patronym_exact:(qxqharmsqxq))&spellcheck.q=(qxqroelofqxq qxqharmsqxq)&fq={!tag%3Dalldoctypes}doc_type:1&fq=date_main:[0 TO 18133112]&facet.query={!ex%3Dalldoctypes}doc_type:3 AND (b_public:1)&facet.query={!ex%3Dalldoctypes}doc_type:2 AND (b_public:1)&spellcheck=true&spellcheck.count=-3&start=0&sort=name_last asc, score desc&omitHeader=true
2014-08-25 14:20:45,478 DEV z5gyjtcexs41vra4yegqejcf 0 R . http://10.123.9.66:80/solr_3.6/combi_live/select/ qt=standard_a2aperson&q=(((((nosyn_name_last_b_exact:(qxqkuilenburgqxq))))))&fq=(nosyn_name_last_exact:(qxqbroekqxq))&spellcheck.q=(qxqbroekqxq kuilenburg)&fq=(fk_collectiontype:6)&spellcheck=true&spellcheck.count=-3&start=10&sort=date_main asc, score desc&omitHeader=true
2014-08-25 14:20:45,930 DEV hmb0uqzc10s0ounwdhpwmflp 1 R O http://10.123.9.66:80/solr_3.6/combi_live/select/ qt=standard_a2aperson&q=(((((nosyn_name_last_b_exact:(qxqkruijsqxq))))))&fq=(nosyn_name_first_exact:(qxqw*qxq))&fq=(nosyn_name_last_exact:(qxqtreurenqxq))&spellcheck.q=(qxqw*qxq qxqtreurenqxq kruijs)&spellcheck=true&spellcheck.count=-3&start=0&sort=date_main asc, score desc&omitHeader=true
But if I just have 1 line, like this:
2014-08-25 14:20:45,930 DEV hmb0uqzc10s0ounwdhpwmflp 1 R O http://10.123.9.66:80/solr_3.6/combi_live/select/ qt=standard_a2aperson&q=(((((nosyn_name_last_b_exact:(qxqkruijsqxq))))))&fq=(nosyn_name_first_exact:(qxqw*qxq))&fq=(nosyn_name_last_exact:(qxqtreurenqxq))&spellcheck.q=(qxqw*qxq qxqtreurenqxq kruijs)&spellcheck=true&spellcheck.count=-3&start=0&sort=date_main asc, score desc&omitHeader=true
then it works, but if I have more then I get an
The remote server returned an error: (404) Not Found.
Thank you for you help

Related

Generate Text File Upon Button Action and Save to local Drive using Acumatica

I am trying to generate a text file on an Action Button, with contents of a dataview created in a Graph Class and Save the file in my Local Drive. But i am unable to do it.
Please help me with the file generation...Thanks
I AM USING Acumatica Version 2019R2 (v 19.203.0042)
MY CODE GOES HERE...
public PXSelect<MayBankGIRO> Document; //this is my dataview
public PXAction<MayBankGiroFilter> createTextFile;
[PXUIField(DisplayName = "Create Text File")]
[PXButton()]
public virtual IEnumerable CreateTextFile(PXAdapter adapter)
{
string filepath = "C:\\Subhashish Dawn";
System.IO.StreamWriter sw = new System.IO.StreamWriter(filepath);
MayBankGIRO giroObject = this.Document.Current;
List<object> myListObject = new List<object> { };
FixedLengthFile flatFile = new FixedLengthFile();
foreach (MayBankGIRO dacRecord in this.Document.Select())
{
if (giroObject.ReordType == "00")
{
myListObject.Add(dacRecord.ReordType + "|" + dacRecord.CorporateID + "|" + dacRecord.ClientBatchID + "|");
}
else
{
myListObject.Add(dacRecord.ReordType + "|" + dacRecord.CorporateID + "|" + dacRecord.ClientBatchID + "|" + dacRecord.Country + "|");
string data = dacRecord.ReordType;
}
this.Document.Update(dacRecord);
}
flatFile.WriteToFile(myListObject, sw);
sw.Flush();
sw.FlushAsync();
string path = "DAWN" + ".txt";
PX.SM.FileInfo file = new PX.SM.FileInfo(Guid.NewGuid(), path, null, System.Text.Encoding.UTF8.GetBytes(**path**)); // what shall i substitite in place of **path**
throw new PXRedirectToFileException(file, true);
}
``````````````````````````````````````````````````````
Can anyone please specify what changes in have to make in the above code.
I utilize UploadFileMaintenance to do this. I'm not sure if this will meet your needs, but here is the core of my code that works for me.
byte[] labelBytes = Encoding.ASCII.GetBytes(myLabelData);
if(labelBytes.Length > 0)
{
string filename = "label-" + Guid.NewGuid().ToString() + ".txt";
PX.SM.FileInfo labelFileInfo = new FileInfo(filename, null, labelBytes);
UploadFileMaintenance upload = PXGraph.CreateInstance<UploadFileMaintenance>();
if (upload.SaveFile(labelFileInfo))
{
string targetUrl = PXRedirectToFileException.BuildUrl(labelFileInfo.UID);
throw new PXRedirectToUrlException(targetUrl, "Print Labels");
}
}
Assuming your Document object is the view you need and its Select() method returns all the data records you need inside your file, this should work:
// We need at least these, listing them for reference
using PX.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
// This is your dataview
public PXSelect<MayBankGIRO> Document;
// Your action delegate
public PXAction<MayBankGiroFilter> createTextFile;
[PXUIField(DisplayName = "Create Text File")]
[PXButton()]
public virtual IEnumerable CreateTextFile(PXAdapter adapter)
{
// You can use this method to print debug information for your customizations
// Just remove when you are done testing
PXTrace.WriteInformation("Generating records");
// We will build the content as a string list first
List<string> myList = new List<string> { };
// If the value of 'ReordType' can change for each record, you don't need this
MayBankGIRO giroObject = this.Document.Current;
foreach (MayBankGIRO dacRecord in this.Document.Select())
{
// Does 'ReordType' change for each record?
// if it does you may need to use 'dacRecord.ReordType' in this if instead
if (giroObject.ReordType == "00")
{
// This only works if all these members are strings or can be cast to strings
myList.Add(dacRecord.ReordType + "|" + dacRecord.CorporateID + "|" + dacRecord.ClientBatchID + "|");
}
else
{
// This only works if all these members are strings or can be cast to strings
myList.Add(dacRecord.ReordType + "|" + dacRecord.CorporateID + "|" + dacRecord.ClientBatchID + "|" + dacRecord.Country + "|");
}
}
PXTrace.WriteInformation("Generating file");
// Set the name
string filename = "DAWN" + ".txt";
// Use our download method
Download(myList, filename);
}
// We can define a static method to be able to reuse this later for other DACs
public static void Download(List<string> lines, string name)
{
var bytes = default(byte[]);
// Write all lines to stream
using (MemoryStream stream = new MemoryStream())
{
StreamWriter sw = new StreamWriter(stream);
foreach (string line in lines)
{
sw.WriteLine(line);
}
sw.Close();
stream.Position = 0;
bytes = stream.ToArray();
};
// Save content to file object
PX.SM.FileInfo textDoc = new PX.SM.FileInfo(name, null, bytes);
if (textDoc != null)
{
// Trigger file download
throw new PXRedirectToFileException(textDoc, true);
} else {
//TODO: You could raise an exception here also to notify the user
PXTrace.WriteInformation("Could not generate file");
}
}
Hi Markoan your code helped me to create the textfile but the content of the textfile is getting repeated with the first record of the data-view. My reord type have only three values "00" for the first record "01" for the 2nd to n-1 record and "99" for the nth record.
Though I have made few changes to your code
// We need at least these, listing them for reference
using PX.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
// This is your dataview
public PXSelect<MayBankGIRO> Document;
// Your action delegate
public PXAction<MayBankGiroFilter> createTextFile;
[PXUIField(DisplayName = "Create Text File")]
[PXButton()]
public virtual IEnumerable CreateTextFile(PXAdapter adapter)
{
// You can use this method to print debug information for your customizations
// Just remove when you are done testing
PXTrace.WriteInformation("Generating records");
// We will build the content as a string list first
List<string> myList = new List<string> { };
// If the value of 'ReordType' can change for each record, you don't need this
MayBankGIRO giroObject = this.Document.Current;
foreach (MayBankGIRO dacRecord in this.Document.Select())
{
// Does 'ReordType' change for each record?
// if it does you may need to use 'dacRecord.ReordType' in this if instead
myList.Add(dacRecord.ReordType + "|" + dacRecord.CustomerReferenceNumber + "|" + dacRecord.ClientBatchID + "|" + dacRecord.Country + "|");
}
PXTrace.WriteInformation("Generating file");
// Set the name
string filename = "DAWN" + ".txt";
// Use our download method
Download(myList, filename);
}
// We can define a static method to be able to reuse this later for other DACs
public static void Download(List<string> lines, string name)
{
var bytes = default(byte[]);
// Write all lines to stream
using (MemoryStream stream = new MemoryStream())
{
StreamWriter sw = new StreamWriter(stream);
foreach (string line in lines)
{
sw.WriteLine(line);
}
// sw.Close(); this was showing some error
stream.Position = 0; // "Cannot reach a closed stream" hence i added it in the next line
bytes = stream.ToArray();
sw.Close();
};
// Save content to file object
PX.SM.FileInfo textDoc = new PX.SM.FileInfo(name, null, bytes);
if (textDoc != null)
{
// Trigger file download
throw new PXRedirectToFileException(textDoc, true);
} else {
//TODO: You could raise an exception here also to notify the user
PXTrace.WriteInformation("Could not generate file");
}
}

Authentication Failed for get file using file service REST API Azure

I am trying to get a file using the shared key. I already get a list of files and directories by the shared key, but when I request to receive a specific file, I encounter this problem.
Code to generate shared key:
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace StorageRestApiAuth
{
internal static class AzureStorageAuthenticationHelper
{
internal static AuthenticationHeaderValue GetAuthorizationHeader(
string storageAccountName, string storageAccountKey, DateTime now,
HttpRequestMessage httpRequestMessage, string ifMatch = "", string md5 = "")
{
// This is the raw representation of the message signature.
HttpMethod method = httpRequestMessage.Method;
String MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
method.ToString(),
(method == HttpMethod.Get || method == HttpMethod.Head) ? String.Empty
: httpRequestMessage.Content.Headers.ContentLength.ToString(),
ifMatch,
GetCanonicalizedHeaders(httpRequestMessage),
GetCanonicalizedResource(httpRequestMessage.RequestUri, storageAccountName),
md5);
byte[] SignatureBytes = Encoding.UTF8.GetBytes(MessageSignature);
HMACSHA256 SHA256 = new HMACSHA256(Convert.FromBase64String(storageAccountKey));
string signature = Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));
returned.
AuthenticationHeaderValue authHV = new AuthenticationHeaderValue("SharedKey",
storageAccountName + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes)));
return authHV;
}
private static string GetCanonicalizedHeaders(HttpRequestMessage httpRequestMessage)
{
var headers = from kvp in httpRequestMessage.Headers
where kvp.Key.StartsWith("x-ms-", StringComparison.OrdinalIgnoreCase)
orderby kvp.Key
select new { Key = kvp.Key.ToLowerInvariant(), kvp.Value };
StringBuilder sb = new StringBuilder();
foreach (var kvp in headers)
{
StringBuilder headerBuilder = new StringBuilder(kvp.Key);
char separator = ':';
foreach (string headerValues in kvp.Value)
{
string trimmedValue = headerValues.TrimStart().Replace("\r\n", String.Empty);
headerBuilder.Append(separator).Append(trimmedValue);
separator = ',';
}
sb.Append(headerBuilder.ToString()).Append("\n");
}
return sb.ToString();
}
private static string GetCanonicalizedResource(Uri address, string storageAccountName)
{
StringBuilder sb = new StringBuilder("/").Append(storageAccountName).Append(address.AbsolutePath);
NameValueCollection values = HttpUtility.ParseQueryString(address.Query);
foreach (var item in values.AllKeys.OrderBy(k => k))
{
sb.Append('\n').Append(item).Append(':').Append(values[item]);
}
return sb.ToString().ToLower();
}
}
}
With this code I can get a list of directories and files, but I can’t get a specific file.
I'm use this url to request: https://myaccount.file.core.windows.net/myshare/mydirectorypath/myfile
Error sending request:
{
"Error": {
"Code": "AuthenticationFailed",
"Message": "Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.\nRequestId:4c9ca5be-301a-0045-29c9-f20135000000\nTime:2020-03-05T08:36:05.9908405Z",
"AuthenticationErrorDetail": "The MAC signature found in the HTTP request 'here is my key' is not the same as any computed signature. Server used following string to sign: 'GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:Thu, 05 Mar 2020 08:36:05 GMT\nx-ms-version:2017-04-17\n/my storage account/my share/myfile.JPG'."
}
}
I test in my site with your code and it works well. With your AzureStorageAuthenticationHelper and here it the following code that I get file content.
static void Main(string[] args)
{
GetFileContentAsyncREST("youraccount", "yourkey", CancellationToken.None).GetAwaiter().GetResult();
Console.WriteLine("Press any key to continue.");
Console.ReadLine();
}
private static async Task GetFileContentAsyncREST(string storageAccountName, string storageAccountKey, CancellationToken cancellationToken)
{
string uri = "https://xxxxx.file.core.windows.net/helloworld/directory/helloworld.txt";
Byte[] requestPayload = null;
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri)
{
Content = (requestPayload == null) ? null : new ByteArrayContent(requestPayload) })
{
DateTime now = DateTime.UtcNow;
httpRequestMessage.Headers.Add("x-ms-date", now.ToString("R", CultureInfo.InvariantCulture));
httpRequestMessage.Headers.Add("x-ms-version", "2017-04-17");
httpRequestMessage.Headers.Authorization = AzureStorageAuthenticationHelper.GetAuthorizationHeader(
storageAccountName, storageAccountKey, now, httpRequestMessage);
using (HttpResponseMessage httpResponseMessage = await new HttpClient().SendAsync(httpRequestMessage, cancellationToken))
{
if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
{
string content = await httpResponseMessage.Content.ReadAsStringAsync();
Console.Write(content);
}
}
}
}
}
For more details, you could refer to this storage rest api with auth sample.

Trying to download all URL's in html

Can anybody help me with this code?
I am trying to download all the URL's in this html http://mises.org/books/ (they are all pdf's )
I understand the basic logic, I think I just am messing up the regular expression. This is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace DownloadPdfs
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://mises.org/books/");
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?
string html = sb.ToString();
List<string> listoflinks = new List<string>();
string input = html;
Regex rx = new Regex(#"(?<="")[^""]+(?="")|[^\s""]\S*");
for (Match match = rx.Match(input); match.Success; match = match.NextMatch())
{
listoflinks.Add(match.ToString());
}
foreach (var v in listoflinks)
{
using (WebClient Client = new WebClient())
{
Client.DownloadFile(v,v);
}
}
}
}
}
Try the code below. The pattern will match the value of HREF attribute for anchors.
Regex rx = new Regex(#"href=""(?<Url>[^.""]+\.pdf)""",RegexOptions.IgnoreCase | RegexOptions.Multiline);
for (Match match = rx.Match(input); match.Success; match = match.NextMatch())
{
var link = match.Groups["Url"].Value;
listoflinks.Add(link);
}
Use a library to parse html like HtmlAgilityPack.
public List<string> GetLinks(string html)
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var linkNodes = htmlDoc.DocumentNode.SelectNodes("//a[#href]");
if (linkNodes == null)
{
return new List<string>();
}
var linkNodesWithLink = linkNodes.Where(x => x.Attributes.Contains("href")).ToList();
var links = linkNodesWithLink.Select(x => x.Attributes["href"].Value)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.ToList();
links = links.Distinct().ToList();
return links;
}

Selected Item getting lost on post back (Sharepoint wss3.0 webpart)

I am new Sharepoint developer and trying to create search webpart in window Sharepoint service 3.0 [Free edition], so far I can select multiple item from list box but when i trying to display selected item into textbox it getting lost.
Below is my code:
using System;
using System.Runtime.InteropServices;
using System.Data;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Xml.Serialization;
using System.Collections;
namespace Filter_WebPart
{
[Guid("6641a7a3-d2c4-4fda-9ef5-89596845bd6e")]
public class Filter_WebPart : System.Web.UI.WebControls.WebParts.WebPart
{
protected DataSet _dataset;
protected ListBox lstRegion;
protected ListBox lstMaterial;
protected HtmlButton btnSubmit;
protected HtmlInputText txtDisplay;
private string myExceptions = "";
//private int[] Index1;
protected override void CreateChildControls()
{
try
{
//Region Table / DataSet
lstRegion = new ListBox();
lstRegion.ID="lstRegion";
lstRegion.SelectionMode = ListSelectionMode.Multiple;
//lstRegion.EnableViewState = true;
//lstRegion.SelectedIndex = 0;
//Material Table / DataSet
lstMaterial = new ListBox();
lstMaterial.SelectionMode = ListSelectionMode.Multiple;
lstMaterial.EnableViewState = true;
btnSubmit = new HtmlButton();
btnSubmit.InnerText = "Filter";
btnSubmit.ServerClick += new EventHandler(btnSubmit_Click);
txtDisplay = new HtmlInputText();
//CommandButton
this.Controls.Add(lstRegion);
this.Controls.Add(lstMaterial);
this.Controls.Add(btnSubmit);
this.Controls.Add(txtDisplay);
}
catch(Exception ChildControlException)
{
myExceptions += "ChildControlException:" + ChildControlException.Message;
}
finally
{
//base.CreateChildControls();
}
}
protected override void OnPreRender(EventArgs e)
{
if(!this.Page.IsPostBack)
{
lstMaterial.DataSource = GetMaterialList();
lstMaterial.DataTextField = "Material Name";
lstMaterial.DataValueField = "Material Name";
lstMaterial.DataBind();
lstRegion.DataSource = GetRegionList();
lstRegion.DataTextField = "Region Name";
lstRegion.DataValueField = "Region Name";
lstRegion.DataBind();
txtDisplay.Value="1 time";
}
base.OnPreRender(e);
}
void btnSubmit_Click(object sender, EventArgs e)
{
string tmpStr="";
int k=0;
//int i=0;
lstMaterial.DataBind();
lstRegion.DataBind();
//int[] indx = lstRegion.GetSelectedIndices();
//for(i=0;i<indx.Length;i++)
//{
// tmpStr = tmpStr+","+lstRegion.Items[indx[i]].Text;
//}
//if(lstRegion.SelectedIndex >=0 )
//{
//for(i=0;i < lstRegion.Items.Count;i++)
//{
// //if(i==5 || i==10)
// //{
// // lstRegion.Items[i].Selected = true;
// //}
// if(lstRegion.Items[i].Selected)
// {
// tmpStr = lstRegion.Items[i].Text;
// }
// k=k+1;
//}
//}
foreach(ListItem RgItem in lstRegion.Items)
{
if(RgItem.Selected == true)
{
tmpStr = tmpStr +","+RgItem.Text;
k=k+1;
}
}
//for(i=0;i<lstRegion.Items.Count;i++)
//{
// if(lstRegion.Items[i].Selected == true)
// {
// txtDisplay.Value = txtDisplay.Value +","+lstRegion.Items[i].Text;
// k=k+1;
// }
//}
if(tmpStr != "" )
{txtDisplay.Value = tmpStr;}
else{
txtDisplay.Value = k.ToString();
btnSubmit.InnerText = "Done";}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
private DataSet GetRegionList()
{
_dataset = new DataSet();
DataTable _tbl = new DataTable();
DataColumn _tblcol = new DataColumn("Region Name");
_tbl.Columns.Add(_tblcol);
SPWeb web = SPContext.Current.Site.RootWeb;
SPList myList = web.Lists["Service Area"];
SPQuery query = new SPQuery();
query.Query = "";
SPListItemCollection items = myList.GetItems(query);
foreach (SPListItem item in items)
{
DataRow _row = _tbl.NewRow();
_row[0] = SPEncode.HtmlEncode(item["Region Name"].ToString());
_tbl.Rows.Add(_row);
}
_dataset.Tables.Add(_tbl);
return _dataset;
}
private DataSet GetMaterialList()
{
_dataset = new DataSet();
DataTable _tbl = new DataTable();
DataColumn _tblcol = new DataColumn("Material Name");
_tbl.Columns.Add(_tblcol);
SPWeb web = SPContext.Current.Site.RootWeb;
SPList myList = web.Lists["Material Master"];
SPQuery query = new SPQuery();
query.Query = "";
SPListItemCollection items = myList.GetItems(query);
foreach (SPListItem item in items)
{
DataRow _row = _tbl.NewRow();
_row[0] = SPEncode.HtmlEncode(item["Material Name"].ToString());
_tbl.Rows.Add(_row);
}
_dataset.Tables.Add(_tbl);
return _dataset;
}
protected override void RenderContents(HtmlTextWriter output)
{
try
{
this.EnsureChildControls();
lstRegion.RenderControl(output);
lstMaterial.RenderControl(output);
btnSubmit.RenderControl(output);
output.Write("<br>");
txtDisplay.RenderControl(output);
//base.RenderContents(output);
}
catch (Exception RenderContentsException)
{
myExceptions += "RenderException:" + RenderContentsException.Message;
}
finally
{
if (myExceptions.Length > 0)
{
output.WriteLine(myExceptions);
}
}
}
}
}
This should be working. I've tried your code on my 2010 farm and it works fine (should also work for WSS3).
Did you forget to do an iisreset after updating the assembly ?
Your best chance to finding a solution is to use the debugger. You can attach the debugger to the right w3wp.exe process. If you don't know which one, select them all. Then set a breakpoint on your event handler and check where you lose your selection.
You don't need to override OnInit, you can put EnsureChildControls() in btnSubmit_Click.

C# create configuration file

This code How can I create configuration file if so that i can change connection string easy
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 MySql.Data.MySqlClient;
using System.Web;
using mshtml;
namespace tabcontrolweb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=192.168.0.78;" +
"DATABASE=webboard;" +
"UID=aimja;" +
"PASSWORD=aimjawork;" +
"charset=utf8;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT urlwebboard FROM `listweb` WHERE `urlwebboard` IS NOT NULL AND ( `webbordkind` = 'เว็บท้องถิ่น' ) and `nourl`= 'n' order by province, amphore limit 4 ";
connection.Open();
Reader = command.ExecuteReader();
string[] urls = new string[4];
string thisrow = "";
string sumthisrow = "";
while (Reader.Read())
{
thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
System.IO.File.AppendAllText(#"C:\file.txt", thisrow + " " + Environment.NewLine);
sumthisrow = Reader.GetValue(Reader.FieldCount - 1).ToString();
}
for (int m = 0; m < 4 ; m++)
{
urls[m] = sumthisrow;
MessageBox.Show(urls[m]);
}
webBrowser1.Navigate(new Uri(urls[0]));
webBrowser1.Dock = DockStyle.Fill;
webBrowser2.Navigate(new Uri(urls[1]));
webBrowser2.Dock = DockStyle.Fill;
webBrowser3.Navigate(new Uri(urls[2]));
webBrowser3.Dock = DockStyle.Fill;
webBrowser4.Navigate(new Uri(urls[3]));
webBrowser4.Dock = DockStyle.Fill;
}
connection.Close();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//if (webBrowser1.Document != null)
//{
// IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2;
// if (document != null)
// {
// IHTMLSelectionObject currentSelection = document.selection;
// IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
// if (range != null)
// {
// const String search = "We";
// if (range.findText(search, search.Length, 2))
// {
// range.select();
// }
// }
// }
//}
}
}
}
You can create an XML configuration file looking like this :
<db-config>
<server>192.168.0.78</server>
<database>webboard</database>
<...>...</...>
</db-config>
Then, use XMLTextReader to parse it.
Here is a basic example of how you can use it to parse XML files :
using System;
using System.Xml;
namespace ReadXMLfromFile
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
XmlTextReader reader = new XmlTextReader ("books.xml");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
Console.ReadLine();
}
}
}
Hint : Use the ReadTofollowing() to get your values.
Once your XML DB Config Reader class is done, you use it each time you need a new connection, and you'll only need to change your DB Config XML file to change your DB Connections configuration.
Edit : there is an interesting article about Storing database connection settings in .NET here.
Use the default
System.Configuration.ConfigurationManager
that C# supports!
See: http://msdn.microsoft.com/en-us/library/bb397750.aspx

Resources