How to fix a problem with inserting data twice - c#

I have a code that upload files by an fileuploader, as well as a InsertCommand which inserts a data, belonging to that file.
That works fine, but if the string "maxId" has no result, he runs the button-code twice, upload the file twice and finally insert the data twice.
Any Ideas?
See my following code:
if (Bericht_Hochladen.HasFile)
{
SqlCommand commandMaxActionDocID = new SqlCommand("SELECT MAX(actiondoc_id) FROM tbl_action WHERE SUBSTRING(actiondoc_nr, 2, 7) ='" + newNumber.Substring(newNumber.Length - 7) + "'", conn);
string maxId = commandMaxActionDocID.ExecuteScalar().ToString();
if (maxId == "")
{
neue_nr = newNumber.ToString() + "_" + DateTime.Now.ToString("yyyy-MM-dd", ci) + "_" + docart + "_DOC001";
}
else
{
SqlCommand commandMaxActionDocNR = new SqlCommand("SELECT actiondoc_nr FROM tbl_action_1100 WHERE actiondoc_id = #maxId", conn);
commandMaxActionDocNR.Parameters.AddWithValue("#maxId", maxId.ToString());
string NrMitT = commandMaxActionDocNR.ExecuteScalar().ToString();
string count_str = NrMitT.Substring(NrMitT.Length - 3, 3);
int count_int = Int32.Parse(count_str);
count_int = count_int + 1;
count_str = count_int.ToString("000");
neue_nr = newNumber.ToString() + "_" + DateTime.Now.ToString("yyyy-MM-dd", ci) + "_" + docart + "_DOC" + count_str;
}
string dateiendung = Path.GetExtension(Bericht_Hochladen.FileName);
string todaydate = DateTime.Today.ToString("yyyy-MM-dd");
string dokumentname = neue_nr;
#region [Datenupload WebDAV]
Bericht_Hochladen.PostedFile.SaveAs(HttpContext.Current.Server.MapPath("~/TemporaryUploadedFiles/") + dokumentname + dateiendung);
SqlCommand commandVerweis = new SqlCommand("SELECT pfad_adresse FROM tbl_sys_pfad WHERE pfad_nr = 102", conn);
string verweis = (string)commandVerweis.ExecuteScalar();
//temporäreres Speichern auf dem WebServer
FileStream fstream = new FileStream(HttpContext.Current.Server.MapPath("~/TemporaryUploadedFiles/") + dokumentname + dateiendung, FileMode.OpenOrCreate, FileAccess.Read);
HttpWebRequest request_folder = (HttpWebRequest)WebRequest.Create(filepath);
request_folder.Credentials = new NetworkCredential(szUsername, szPassword);
try
{
// Specify the MKCOL method.
request_folder.Method = "MKCOL";
HttpWebResponse response_folder = (HttpWebResponse)request_folder.GetResponse();
Response.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filepath + dokumentname + dateiendung);
request.Credentials = new NetworkCredential(szUsername, szPassword);
try
{
request.Method = #"PUT";
request.ContentLength = fstream.Length;
request.AllowWriteStreamBuffering = true;
request.SendChunked = false;
request.KeepAlive = false;
Stream request_stream = request.GetRequestStream();
byte[] indata = new byte[1024];
int bytes_read = fstream.Read(indata, 0, indata.Length);
while (bytes_read > 0)
{
request_stream.Write(indata, 0, indata.Length);
bytes_read = fstream.Read(indata, 0, indata.Length);
}
fstream.Close();
request_stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
{
//MessageBox.Show("Couldn't upload file");
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
string del_URL = HttpContext.Current.Server.MapPath("~/TemporaryUploadedFiles/") + dokumentname + dateiendung;
File.Delete(del_URL);
#endregion
SqlCommand commandDocUpload = new SqlCommand("INSERT INTO tbl_action(actiondoc_action_id, actiondoc_nr, actiondoc_art, actiondoc_pfad, actiondoc_datum, actiondoc_endung, actiondoc_bem, sys_crt_user, sys_crt_timestamp, sys_deleted) VALUES (#actiondoc_action_id, #actiondoc_nr, #actiondoc_art, #actiondoc_pfad, #actiondoc_datum, #actiondoc_endung, #actiondoc_bem, #sys_crt_user, #sys_crt_timestamp, #sys_deleted)", conn);
commandDocUpload.Parameters.Add(new SqlParameter("#actiondoc_action_id", (string)Session["action_id"].ToString()));
commandDocUpload.Parameters.Add(new SqlParameter("#actiondoc_nr", neue_nr.ToString()));
commandDocUpload.Parameters.Add(new SqlParameter("#actiondoc_art", Session["dokument_art_volltext"].ToString()));
commandDocUpload.Parameters.Add(new SqlParameter("#actiondoc_pfad", neue_nr.ToString() + dateiendung.ToString()));
commandDocUpload.Parameters.Add(new SqlParameter("#actiondoc_datum", DateTime.Now.ToString("yyyy-MM-dd", ci)));
commandDocUpload.Parameters.Add(new SqlParameter("#actiondoc_endung", dateiendung.ToString()));
commandDocUpload.Parameters.Add(new SqlParameter("#actiondoc_bem", txtBeschreibungDoc.Text));
commandDocUpload.Parameters.Add(new SqlParameter("#sys_crt_user", (string)Session["login"].ToString()));
commandDocUpload.Parameters.Add(new SqlParameter("#sys_crt_timestamp", DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss", ci)));
commandDocUpload.Parameters.Add(new SqlParameter("#sys_deleted", "0"));
commandDocUpload.ExecuteNonQuery();
conn.Close();
if (IsPostBack)
{
//Do Something
return;
}
}

Try changing this line:
string maxId = commandMaxActionDocID.ExecuteScalar().ToString();
To this:
string maxId = Convert.ToString(commandMaxActionDocID.ExecuteScalar());
And for reference:
Difference between Convert.ToString() and .ToString()
I think what's going on is that your ExecuteScalar() is returning something the if statement doesn't recognize, and therefore it's just skipping over it, and then once the data gets added, the value gets populated. Do you have the code that calls the method? That might be helpful.
EDIT:
David, Try changing your control to this:
<div class="pull-left btn-mybtn"> <asp:Button ID="btnDateiHochladen" runat="server" Text="Hochladen" CssClass="font-regular btn-mybtn pull-right"/> </div>
Also, does your code behind (C#) have an OnCommand or OnClick event for this particular button?

Related

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

How do I export data from a GridView to a .txt

I'm working on a C# asp.net project and can't seem to get the "exporting to a .txt file from a grid view" to work.
protected void ExportGridToText() {
BindGridView();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
StringBuilder Rowbind = new StringBuilder();
Response.ContentType = "application/text";
Response.AddHeader("Content-Disposition", "attachment;filename=GlogData.txt");
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
Response.Cache.SetCacheability(HttpCacheability.NoCache);
gvLog.DataBind();
for (int i = 2; i < gvLog.Columns.Count; i++)
{
Rowbind.Append("\"" + gvLog.Columns[i].HeaderText + "\"" + ',');
}
Rowbind.Append("\n");
for (int j = 0; j < gvLog.Rows.Count; j++)
{
for (int k = 0; k < gvLog.Columns.Count; k++)
{
Rowbind.Append("\"" + gvLog.Rows[j].Cells[k].Text + "\"" + ',');
Rowbind.Replace("<", "<");
Rowbind.Replace(">", ">");
}
Rowbind.Append("\n");
}
gvLog.AllowPaging = false;
Response.Output.Write(Rowbind.ToString());
Response.Flush();
Response.End();
}
Evrytime I run the code I get a error message:
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed
Why is it giving me this error?
How do I fix it?
Is it possible to get the data from the source... This is under the get Button that populates the GridView:
protected void GetLogBtn_Click(object sender, EventArgs e)
{
string sBeginDate = BeginDate.Text;
string sEndDate = EndDate.Text;
JObject vResultJson = new JObject();
FKWebCmdTrans cmdTrans = new FKWebCmdTrans();
DateTime dtBegin, dtEnd;
if (sBeginDate.Length > 0)
{
try
{
dtBegin = Convert.ToDateTime(sBeginDate);
sBeginDate = FKWebTools.GetFKTimeString14(dtBegin);
vResultJson.Add("begin_time", sBeginDate);
}
catch
{
BeginDate.Text = "";
}
}
if (sEndDate.Length > 0)
{
try
{
dtEnd = Convert.ToDateTime(sEndDate);
sEndDate = FKWebTools.GetFKTimeString14(dtEnd);
vResultJson.Add("end_time", sEndDate);
}
catch
{
EndDate.Text = "";
}
}
try
{
string sFinal = vResultJson.ToString(Formatting.None);
byte[] strParam = new byte[0];
cmdTrans.CreateBSCommBufferFromString(sFinal, out strParam);
mTransIdTxt.Text = FKWebTools.MakeCmd(msqlConn, "GET_LOG_DATA", mDevId, strParam);
Session["operation"] = GET_LOG_DATA;
GetLogBtn.Enabled = false;
ClearBtn.Enabled = false;
Timer.Enabled = true;
}
catch (Exception ex)
{
StatusTxt.Text = "Fail! Get Log Data! " + ex.ToString();
}
}
This is under the BindGridView:
private void BindGridView()
{
try
{
string mTransid = mTransIdTxt.Text;
string strSelectCmd = "SELECT COUNT(*) FROM tbl_fkcmd_trans_cmd_result_log_data where trans_id = '" + mTransid + "'";
SqlCommand sqlCmd = new SqlCommand(strSelectCmd, msqlConn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
if (sqlReader.HasRows)
{
if (sqlReader.Read())
nCount = sqlReader.GetInt32(0);
}
sqlReader.Close();
sqlCmd.Dispose();
{
DataSet dsLog = new DataSet();
strSelectCmd = "SELECT * FROM tbl_fkcmd_trans_cmd_result_log_data where trans_id = '" + mTransid + "'";
SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, msqlConn);
// conn.Open();
da.Fill(dsLog, "tbl_fkcmd_trans_cmd_result_log_data");
DataView dvLog = dsLog.Tables["tbl_fkcmd_trans_cmd_result_log_data"].DefaultView;
gvLog.DataSource = dvLog;
gvLog.DataBind();
StatusTxt.Text = " Total Count : " + Convert.ToString(nCount) + " Current Time :" + DateTime.Now.ToString("HH:mm:ss tt");
}
}
catch (Exception ex)
{
StatusTxt.Text = ex.ToString();
}
}
I hope this helps
Thanks in advance
Following Code is For Excel Mainly...but its successfully converting gridview to .txt file just need a little workaround..
public void ExportToExcel(System.Web.UI.WebControls.GridView controlname, string sheetname)
{
HttpContext context = HttpContext.Current;
context.Response.ClearContent();
context.Response.Buffer = true;
context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sheetname + ".txt"));
context.Response.ContentType = "application/text";
// context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sheetname + ".xls"));
// context.Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
//Change the Header Row back to white color
controlname.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < controlname.HeaderRow.Cells.Count; i++)
{
controlname.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in controlname.Rows)
{
gvrow.BackColor = Color.White;
if (j <= controlname.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
controlname.RenderControl(htw);
context.Response.Write(sw.ToString());
context.Response.End();
}

How to add a contact to Yahoo using Oauth-2 in Asp.Net C#

I've been wrestling with this for a while now and can't seem to find a solution. The closest I've come is PHP code for Oauth-1 by Joe Chung (https://github.com/joechung/oauth_yahoo), but I can't get my head wrapped around it.
I'm using Asp.Net, and this code is in the ContactController. I have no trouble Getting contacts from Yahoo. The problem is Adding a contact to a user's Yahoo address book. The program proceeds through the Yahoo login process, and there are no errors. But the contact is not saved. I hope someone can take a look at this and tell me what I'm missing.
Thanks.
private string AddYahooContact(string responseFromServer, string contactIdForYahoo)
{
// Some of this from http://www.yogihosting.com/implementing-yahoo-contact-reader-in-asp-net-and-csharp/
responseFromServer = responseFromServer.Substring(1, responseFromServer.Length - 2);
string accessToken = "", xoauthYahooGuid = "", refreshToken = "";
string[] splitByComma = responseFromServer.Split(',');
foreach (string value in splitByComma)
{
if (value.Contains("access_token"))
{
string[] accessTokenSplitByColon = value.Split(':');
accessToken = accessTokenSplitByColon[1].Replace('"'.ToString(), "");
}
else if (value.Contains("xoauth_yahoo_guid"))
{
string[] xoauthYahooGuidSplitByColon = value.Split(':');
xoauthYahooGuid = xoauthYahooGuidSplitByColon[1].Replace('"'.ToString(), "");
}
else if (value.Contains("refresh_token"))
{
string[] refreshTokenSplitByColon = value.Split(':');
refreshToken = refreshTokenSplitByColon[1].Replace('"'.ToString(), "");
}
}
// How to build contactUrl from https://developer.yahoo.com/social/rest_api_guide/contacts-resource.html#contacts-xml_request_put
// This is Yahoo's address to add a contact
string contactUrl = "https://social.yahooapis.com/v1/user/" + xoauthYahooGuid + "/contacts";
// Much of this from https://developer.yahoo.com/dotnet/howto-rest_cs.html
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(contactUrl);
webRequest.Method = "POST";
webRequest.Headers["Authorization"] = "Bearer " + accessToken;
webRequest.ContentType = "application/x-www-form-urlencoded"; // Tried "application/x-www-form-urlencoded & application/xml" & "text/xml".
// Create the data we want to send
string yahooContact = BuildYahooContact(contactIdForYahoo);
byte[] byteData = UTF8Encoding.UTF8.GetBytes(yahooContact);
webRequest.ContentLength = byteData.Length;
using (Stream postStream = webRequest.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
responseFromServer = "";
try
{
using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
responseFromServer = reader.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return yahooContact;
}
private string BuildYahooContact(string contactIdForYahoo)
{
Guid contactId = Guid.Parse(contactIdForYahoo);
Models.Contact contact = GetContactForId(contactId); // And find the contact
string firstName = "";
string lastName = "";
if (contact.FullName != null)
{
int index = contact.FullName.IndexOf(" ");
if (index > 0)
{
firstName = contact.FullName.Substring(0, index);
lastName = (contact.FullName.Substring(index + 1));
}
else
{
lastName = contact.FullName;
}
}
StringBuilder data = new StringBuilder();
data.Append("<contact>");
data.Append("<fields><type>name</type><value>");
data.Append("<givenName>" + firstName + "</givenName><middleName/>");
data.Append("<familyName>" + lastName + "</familyName>");
data.Append("<prefix/><suffix/><givenNameSound/><familyNameSound/>");
data.Append("</value></fields>");
data.Append("<fields><type>address</type>");
data.Append("<value><street>" + contact.Address + "</street>");
data.Append("<city>" + contact.City + "</city>");
data.Append("<stateOrProvince>" + contact.State + "</stateOrProvince>");
data.Append("<postalCode>" + contact.Zip + "</postalCode>");
data.Append("<country>United States</country>");
data.Append("<countryCode>US</countryCode>");
data.Append("</value></fields>");
data.Append("<fields><type>notes</type><value>" + contact.Note + "</value></fields>");
data.Append("<fields><type>link</type><value>" + contact.Website + "</value></fields>");
data.Append("<fields><type>email</type><value>" + contact.Email + "</value></fields>");
data.Append("<fields><type>phone</type><value>" + contact.BusinessPhone + "</value><flags>WORK</flags></fields>");
data.Append("<fields><type>phone</type><value>" + contact.BestPhone + "</value><flags>MOBILE</flags></fields>");
data.Append("<fields><type>phone</type><value>" + contact.SecondPhone + "</value><flags>PERSONAL</flags></fields>");
data.Append("<categories><category><name>GoGoContract</name></category></categories>");
data.Append("</contact>");
return data.ToString();
}

Downloading file from redirecting URLs

I am trying to download mp3 from http://www.audiodump.com/. The site has a lot of redirections. However I managed getting a part of it working.
This is my method for getting all informations such as DL links, titles, mp3 durations.
private void _InetGetHTMLSearch(string sArtist)
{
if(_AudioDumpQuery == string.Empty)
{
//return string.Empty;
}
string[] sStringArray;
string sResearchURL = "http://www.audiodump.biz/music.html?" + _AudioDumpQuery + sArtist.Replace(" ", "+");
string aRet;
HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(sResearchURL);
webReq.Referer = "http://www.audiodump.com/";
try
{
webReq.CookieContainer = new CookieContainer();
webReq.Method = "GET";
using (WebResponse response = webReq.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
aRet = reader.ReadToEnd();
//Console.WriteLine(aRet);
string[] aTable = _StringBetween(aRet, "<BR><table", "table><BR>", RegexOptions.Singleline);
if (aTable != null)
{
string[] aInfos = _StringBetween(aTable[0], ". <a href=\"", "<a href=\"");
if (aInfos != null)
{
for(int i = 0; i < aInfos.Length; i++)
{
aInfos[i] = aInfos[i].Replace("\">", "*");
aInfos[i] = aInfos[i].Replace("</a> (", "*");
aInfos[i] = aInfos[i].Remove(aInfos[i].Length - 2);
sStringArray = aInfos[i].Split('*');
aLinks.Add(sStringArray[0]);
aTitles.Add(sStringArray[1]);
sStringArray[2] = sStringArray[2].Replace("`", "'");
sStringArray[2] = sStringArray[2].Replace("dont", "don't");
sStringArray[2] = sStringArray[2].Replace("lets", "let's");
sStringArray[2] = sStringArray[2].Replace("cant", "can't");
sStringArray[2] = sStringArray[2].Replace("shes", "she's");
sStringArray[2] = sStringArray[2].Replace("aint", "ain't");
sStringArray[2] = sStringArray[2].Replace("didnt", "didn't");
sStringArray[2] = sStringArray[2].Replace("im", "i'm");
sStringArray[2] = sStringArray[2].Replace("youre", "you're");
sStringArray[2] = sStringArray[2].Replace("ive", "i've");
sStringArray[2] = sStringArray[2].Replace("youll", "you'll");
sStringArray[2] = sStringArray[2].Replace("'", "'");
sStringArray[2] = sStringArray[2].Replace("'", "simplequotes");
sStringArray[2] = sStringArray[2].Replace("vk.com", "");
sStringArray[2] = _StringReplaceCyrillicChars(sStringArray[2]);
sStringArray[2] = Regex.Replace(sStringArray[2], #"<[^>]+>| ", "").Trim();
sStringArray[2] = Regex.Replace(sStringArray[2], #"\s{2,}", " ");
sStringArray[2] = sStringArray[2].TrimStart('\'');
sStringArray[2] = sStringArray[2].TrimStart('-');
sStringArray[2] = sStringArray[2].TrimEnd('-');
sStringArray[2] = sStringArray[2].Replace("- -", "-");
sStringArray[2] = sStringArray[2].Replace("http", "");
sStringArray[2] = sStringArray[2].Replace("www", "");
sStringArray[2] = sStringArray[2].Replace("mp3", "");
sStringArray[2] = sStringArray[2].Replace("simplequotes", "'");
aDurations.Add(sStringArray[2]);
}
}
else
{
//Console.WriteLine("Debug");
}
}
else
{
//Console.WriteLine("Debug 2");
}
//return aRet;
}
}
}
catch (Exception ex)
{
//return null;
////Console.WriteLine("Debug message: " + ex.Message);
}
}
I simply had to add referrer to prevent the search from redirection webReq.Referer = "http://www.audiodump.com/";
However when I want to download the mp3 I can't get it working. The urls are correct and checked with the ones I get when I download them manually rather than programmatically.
This is my mp3 download part:
private void _DoDownload(string dArtist, ref string dPath)
{
if (!Contain && skip <= 3 && !Downloading)
{
Random rnd = new Random();
int Link = rnd.Next(5);
_InetGetHTMLSearch(dArtist);
Console.WriteLine("--------------------------------> " + aLinks[0]);
string path = mp3Path + "\\" + dArtist + ".mp3";
if (DownloadOne(aLinks[Link], path, false))
{
hTimmer.Start();
Downloading = true;
}
}
else if (Downloading)
{
int actualBytes = strm.Read(barr, 0, arrSize);
fs.Write(barr, 0, actualBytes);
bytesCounter += actualBytes;
double percent = 0d;
if (fileLength > 0)
percent =
100.0d * bytesCounter /
(preloadedLength + fileLength);
label1.Text = Math.Round(percent).ToString() + "%";
if (Math.Round(percent) >= 100)
{
string path = mp3Path + "\\" + dArtist + ".mp3";
label1.Text = "";
dPath = path;
aLinks.Clear();
hTimmer.Stop();
hTimmer.Reset();
fs.Flush();
fs.Close();
lastArtistName = "N/A";
Downloading = false;
}
if (Math.Round(percent) <= 1)
{
if (hTimmer.ElapsedMilliseconds >= 3000)
{
string path = mp3Path + "\\" + dArtist + ".mp3";
hTimmer.Stop();
hTimmer.Reset();
fs.Flush();
fs.Close();
File.Delete(path);
Contain = false;
skip += 1;
Downloading = false;
}
}
}
}
private static string ConvertUrlToFileName(string url)
{
string[] terms = url.Split(
new string[] { ":", "//" },
StringSplitOptions.RemoveEmptyEntries);
string fname = terms[terms.Length - 1];
fname = fname.Replace('/', '.');
return fname;
} //ConvertUrlToFileName
private static long GetExistingFileLength(string filename)
{
if (!File.Exists(filename)) return 0;
FileInfo info = new FileInfo(filename);
return info.Length;
} //GetExistingFileLength
private static bool DownloadOne(string url, string existingFilename, bool quiet)
{
ServicePointManager.DefaultConnectionLimit = 20;
HttpWebRequest webRequest;
HttpWebResponse webResponse;
IWebProxy proxy = null; //SA???
//fmt = CreateFormat(
//"{0}: {1:#} of {2:#} ({3:g3}%)", "#");
try
{
fname = existingFilename;
if (fname == null)
fname = ConvertUrlToFileName(url);
if (File.Exists(existingFilename))
{
File.Delete(existingFilename);
}
webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A";
webRequest.Referer = "http://www.audiodump.com/";
preloadedLength = GetExistingFileLength(fname);
if (preloadedLength > 0)
webRequest.AddRange((int)preloadedLength);
webRequest.Proxy = proxy; //SA??? or DefineProxy
webResponse = (HttpWebResponse)webRequest.GetResponse();
fs = new FileStream(fname, FileMode.Append, FileAccess.Write);
fileLength = webResponse.ContentLength;
strm = webResponse.GetResponseStream();
if (strm != null)
{
bytesCounter = preloadedLength;
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
//Console.WriteLine(
//"{0}: {1} '{2}'",
// url, e.GetType().FullName,
//e.Message);
return false;
}
//exception
} //DownloadOne
The method _DoDownload() is executed from a timer which runs every 250 milliseconds. This way works perfectly on other sites. However audiodump is giving me hard time with these redirections.
I am not a genius with httprequest. I managed solving the search issue however the download part is freaking me out. Any advice on how to manage the download issue?
You just need to set referrer to the page from where you got that download link. For example you grabbed links to files from page "http://www.audiodump.biz/music.html?q=whatever", then when downloading file set that as Referrer, not just "http://www.audiodump.biz".

Read Credentials by txt file and try login c#?

I would create a loop for function and print message in catch for all logins failed and print "sucessful connected with...." for all good logins.
Now i tried with that code, but i get only one error in textbox of catch
Button1:
if (openFileDialog1.FileName != string.Empty)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
int count = 0;
string lineoflistemail;
while ((lineoflistemail = reader.ReadLine()) != null)
{
UserData d = new UserData();
string[] parts = lineoflistemail.Split(':');
count = parts.Length;
d.UserName = parts[0].Trim();
d.Password = parts[1].Trim();
data.Add(d);
}
foreach(UserData ud in data)
{
textBox1.Text += ("LOL" + ud.UserName + ud.Password + Environment.NewLine);
}
Second button code:
if (data.Count() == 0)
{
MessageBox.Show("Load user info first");
return;
}
for( hola = 0; hola < data.Count(); hola++)
{
var url = #"https://mail.google.com/mail/feed/atom";
var encoded = TextToBase64(data[0].UserName + ":" + data[1].Password);
var myweb = HttpWebRequest.Create(url) as HttpWebRequest;
myweb.Method = "POST";
myweb.ContentLength = 0;
myweb.Headers.Add("Authorization", "Basic " + encoded);
var response = myweb.GetResponse();
var stream = response.GetResponseStream();
textBox1.Text += ("Connection established with");
MessageBox.Show(hola.ToString());
}
}
catch (Exception ex)
{
textBox1.Text += ("Error connection. Original error: " + ex.Message);
}
}
The problem is that your try...catch is outside of your for loop. The first exception will exit the for loop, append the message to textBox1, then exit the button handler.
If you want to keep looping through even if there is an error, move the try...catch inside of the loop. Here's an example:
for( hola = 0; hola < data.Count(); hola++)
{
var url = #"https://mail.google.com/mail/feed/atom";
var encoded = TextToBase64(data[0].UserName + ":" + data[1].Password);
var myweb = HttpWebRequest.Create(url) as HttpWebRequest;
myweb.Method = "POST";
myweb.ContentLength = 0;
myweb.Headers.Add("Authorization", "Basic " + encoded);
try
{
var response = myweb.GetResponse();
var stream = response.GetResponseStream();
textBox1.Text += ("Connection established with");
MessageBox.Show(hola.ToString());
}
catch (Exception ex)
{
textBox1.Text += ("Error connection. Original error: " + ex.Message);
}
}

Categories