System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. imp - asp.net

hye....its kinda urgent...
iam using a temp folder to store images for the preview and when i try to save them a System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+ erreo is reported...
If FileUpload1.HasFile Then
Dim path As String = Server.MapPath("./TempImages/")
Dim oFileInfo As New FileInfo(FileUpload1.PostedFile.FileName)
Dim fileName As String = oFileInfo.Name
Dim fullFileName As String = path + "\\" + fileName
Dim imagePath As String = "TempImages/" + fileName
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
FileUpload1.PostedFile.SaveAs(fullFileName)
Image1.ImageUrl = imagePath
this is what iam doing and to save
If (FileUpload1.HasFile) Then
Dim strextension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
If (strextension.ToUpper() = ".JPG") Then
Dim imagetoberezised As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
Dim imageheight As Integer = imagetoberezised.Height
Dim imagewidth As Integer = imagetoberezised.Width
Dim maxheight As Integer = 120
Dim maxwidth As Integer = 80
imageheight = (imagewidth * maxheight) / imageheight
imagewidth = maxheight
If imageheight > maxheight Then
imageheight = (imagewidth * maxheight) / imageheight
imagewidth = maxheight
End If
Dim bitmap As New Bitmap(imagetoberezised, imagewidth, imageheight)
Dim stream As System.IO.MemoryStream = New MemoryStream()
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
stream.Position = 0
Dim img As Byte() = New Byte(stream.Length) {}
stream.Read(img, 0, img.Length)
Dim conn5 As New SqlConnection
conn5 = New SqlConnection
conn5.ConnectionString = "Server=aa-pc;Database=abcc;Uid=sa;Pwd=sa#123;"
Try
conn5.Open()
Dim sql As String = "update abcset abc_IMAGE = #eimg where PART_NO=" & Val(Part_List.SelectedValue)
Dim cmd5 As SqlCommand = New SqlCommand(sql, conn5)
Dim uploadimage As New SqlParameter("#eimg", SqlDbType.Image, img.Length)
uploadimage.Value = img
cmd5.Parameters.Add(uploadimage)
Dim id As Integer = Convert.ToInt32(cmd5.ExecuteScalar())
Catch
MsgBox("error")
Finally
conn5.Close()
End Try
End If
End If
it works well whilw we run it locally but not on server..

Try this, it work for me:
Dim path As String = Server.MapPath("~/TempImages")
Dim FileInfo As New IO.FileInfo(FileUpload1.PostedFile.FileName)
Dim fileName As String = FileInfo.Name
'sets the image path
Dim fullFileName As String = path + "\" + fileName
Dim imagePath As String = "TempImages/" + fileName
'If Not Directory.Exists(path) Then
If Not System.IO.Directory.Exists("directory path") Then
System.IO.Directory.Exists("directory path")
End If
FileUpload1.PostedFile.SaveAs(fullFileName)
Image1.ImageUrl = imagePath

Related

What is ZRangeValid means

This code is to read an excel file, what is ZRangeValid means and what is rs.fields(0).value referring to? Please explain my two questions
var strConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strXLPath + ";Extended Properties=\"Excel 12.0;HDR=YES;\";";
var conn = new ActiveXObject("ADODB.Connection");
conn.open(strConnString, "", "");
var rs = new ActiveXObject("ADODB.Recordset");
var rsrowCount = new ActiveXObject("ADODB.Recordset");
rs = conn.execute("select * from ZRangeValid");
if (rs.fields(0).value != 'YES') {
alert(strXLPath + " requested numbers spreadsheet is not valid.\nPlease validate the spreadsheet data and retry.")
rs = null;
rsSheet = null;
conn.close();
conn = null;
return false
}

the for loop check the user and every time the both if statement is checked i want only one statement should be checked

Dim LoginUser As MembershipUser = Membership.GetUser(HttpContext.Current.User.Identity.Name)
Dim sFormat As String = "00.00"
'Dim LoginUser = "P002"
Dim sqlapt As SqlDataAdapter = New SqlDataAdapter("select * from wpchannel", connection)
Dim sqlds As DataSet = New DataSet()
Dim sqldt As DataTable = New DataTable()
sqlapt.Fill(sqlds, "wpaccess")
sqldt = sqlds.Tables(0)
'Dim sum As Double
Dim row As DataRow
For Each row In sqldt.Rows
Dim strDetail As String
strDetail = row("username")
lbluserchk.Text = strDetail
If lbluserchk.Text = LoginUser.ToString Then
Dim sqlapt1 As SqlDataAdapter = New SqlDataAdapter("select * from wpchannel where username='" + LoginUser.ToString + "'", connection)
Dim sqlds1 As DataSet = New DataSet()
Dim sqldt1 As DataTable = New DataTable()
sqlapt1.Fill(sqlds1, "wpchannel")
sqldt1 = sqlds1.Tables(0)
Dim username As String = sqldt1.Rows(0).Item(1).ToString
Dim productid As String = sqldt1.Rows(0).Item(2).ToString
lblcheck1.Text = username.ToString
lblcheck2.Text = productid
'New check
Dim da As SqlDataAdapter
Dim ds As DataSet = New DataSet()
Dim dt As DataTable = New DataTable()
Dim sqlquery2 = "select convert(varchar(10), convert(datetime, dn.curdatetime),20) as DnDate ,DN.telcoid As TelecoId,round(convert(decimal(18,2),DN.USD),2) as USD,DN.DNStatus As DnStatus,count(*) as Total,sum(round(convert(decimal(18,2),DN.USD),2)) as subtotal from DN left join MO on DN.moid = mo.linkid where mo.channeltype in (select channelid from wpchannel where username='" + LoginUser.ToString + "') Group by convert(varchar(10), convert(datetime, dn.curdatetime),20),DN.telcoid,DN.USD,DN.DNStatus order by DnDate,dn.telcoid,dnstatus,USD"
da = New SqlDataAdapter(sqlquery2, connection)
da.Fill(ds, "MO")
dt = ds.Tables(0)
ViewState("dtpayment") = dt
Session("dtpayment") = dt
GridView1.DataSource = dt
GridView1.DataBind()
GridView1.FooterRow.Cells(2).Font.Bold = True
GridView1.FooterRow.Cells(2).ForeColor = Color.Black
GridView1.FooterRow.Cells(2).Text = " Grand Total:"
GridView1.FooterRow.Cells(2).HorizontalAlign = HorizontalAlign.Right
Dim sum As Double = Convert.ToDouble(dt.Compute("SUM(" + (dt.Columns(5).ColumnName) + ")", String.Empty))
Dim footernum As Double = sum.ToString
GridView1.FooterRow.Cells(3).Text = footernum.ToString()
Dim sumnum As Double = sum.ToString
lblsum.Text = sumnum.ToString()
ViewState("dt") = dt
ViewState("sort") = "Asc"
VerifyRenderingInServerForm(GridView1)
Exit For
Else
Dim cmd As SqlCommand
Dim da1 As SqlDataAdapter
Dim ds1 As DataSet = New DataSet()
Dim dt1 As DataTable = New DataTable()
'Dim sqlquery1 = "select convert(varchar(10), convert(datetime, dn.curdatetime),20) as DnDate ,DN.telcoid As TelecoId,round(convert(decimal(18,2),DN.USD),2) as USD,DN.DNStatus As DnStatus,count(*) as Total from DN left join MO on DN.moid = mo.linkid Group by convert(varchar(10), convert(datetime, dn.curdatetime),20),DN.telcoid,DN.USD,DN.DNStatus order by DnDate DESC,dn.telcoid,dnstatus,USD"
cmd = New SqlCommand
cmd.Connection = connection
cmd.CommandText = "logReport"
cmd.CommandType = CommandType.StoredProcedure
da1 = New SqlDataAdapter(cmd)
da1.Fill(ds1, "MO")
dt1 = ds1.Tables(0)
ViewState("dtpayment") = dt1
Session("dtpayment") = dt1
GridView1.DataSource = dt1
GridView1.DataBind()
GridView1.FooterRow.Cells(2).Font.Bold = True
GridView1.FooterRow.Cells(2).ForeColor = Color.Black
GridView1.FooterRow.Cells(2).Text = " Grand Total:"
GridView1.FooterRow.Cells(2).HorizontalAlign = HorizontalAlign.Right
Dim sum As Double = Convert.ToDouble(dt1.Compute("SUM(" + dt1.Columns(2).ColumnName + ")", String.Empty)) * Convert.ToDouble(dt1.Compute("SUM(" + dt1.Columns(4).ColumnName + ")", String.Empty))
Dim footernum As Double = sum
GridView1.FooterRow.Cells(3).Text = footernum.ToString()
Dim sumnum As Double = sum.ToString
lblsum.Text = sumnum.ToString()
ViewState("dt") = dt1
ViewState("sort") = "Asc"
VerifyRenderingInServerForm(GridView1)
Continue For
End If
'Exit Sub
Next row
Catch ex As Exception
Label1.Text = ex.ToString
'jscript = ("<script language=""JavaScript"">alert(""Error! Cannot conect to the database."");</script>")
'RegisterClientScriptBlock(x, jscript)
End Try

The thread was interrupted

I am using this code to update database with new values. But it return message The thread was interrupted. What does it mean? What is wrong with my code?
Dim connStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("DeskriptivaConnectionString").ConnectionString.ToString()
Dim txtName As Object = DirectCast(FormView1.FindControl("txtName"), TextBox)
Dim txtLastName As Object = DirectCast(FormView1.FindControl("txtLastName"), TextBox)
Dim txtInfo As Object = DirectCast(FormView1.FindControl("txtInfo"), TextBox)
Dim txtCity As Object = DirectCast(FormView1.FindControl("txtCity"), TextBox)
Dim txtPrize As TextBox = DirectCast(FormView1.FindControl("txtPrize"), TextBox)
Dim txtPhone As TextBox = DirectCast(FormView1.FindControl("txtPhone"), TextBox)
Dim txtMail As TextBox = DirectCast(FormView1.FindControl("txtMail"), TextBox)
Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "UPDATE Profiles SET #Name = Name, #LastName = LastName, #Info = Info, #City = City, #Prize = Prize, #Phone = Phone, #Mail = Mail WHERE (UserName = #UserName)"
cmd.Parameters.Add("#Name", System.Data.SqlDbType.NVarChar).Value = txtName.Text
cmd.Parameters.Add("#LastName", System.Data.SqlDbType.NVarChar).Value = txtLastName.Text
cmd.Parameters.Add("#Info", System.Data.SqlDbType.NText).Value = MakeLink(HtmlRemoval.StripTagsCharArray(txtInfo.Text))
cmd.Parameters.Add("#City", System.Data.SqlDbType.NVarChar).Value = txtCity.Text
cmd.Parameters.Add("#Prize", System.Data.SqlDbType.NVarChar).Value = txtPrize.Text
cmd.Parameters.Add("#Phone", System.Data.SqlDbType.NVarChar).Value = txtPhone.Text
cmd.Parameters.Add("#Mail", System.Data.SqlDbType.NVarChar).Value = txtMail.Text
cmd.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar).Value = Context.User.Identity.Name
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Response.Redirect(ResolveClientUrl("~/Profil/"))
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Use Response.Redirect(ResolveClientUrl("~/Profil/"), false) with Context.ApplicationInstance.CompleteRequest(); instead of Response.Redirect(ResolveClientUrl("~/Profil/"))
check Correct use of System.Web.HttpResponse.Redirect blog post for more information
and also your sql parameters # symbol is in wrong place. change as below
UPDATE Profiles SET
Name = #Name, LastName
= #LastName, Info =
#Info, City = #City,
Prize = #Prize, Phone
= #Phone, Mail = #Mail
WHERE (UserName =
#UserName)

Converting Bitmap to Byte

I have the following code:
Private Function SizeLogo(ByVal logoBytes As Byte()) As Byte()
Using originalMemStream As MemoryStream = New MemoryStream(logoBytes),
originalImage As System.Drawing.Image = System.Drawing.Image.FromStream(originalMemStream)
Dim width As Integer = originalImage.Width
Dim height As Integer = originalImage.Height
Dim targetWidth As Integer = 300
Dim targetHeight As Integer = 200
Dim newHeight As Integer = 0
Dim newWidth As Integer = 0
Using oBitmap As New Bitmap(300, 200)
Using oGraphic As Graphics = Graphics.FromImage(oBitmap)
Using oBrush As New SolidBrush(Color.White)
oGraphic.FillRectangle(oBrush, 0, 0, targetWidth, targetHeight)
End Using
Using oProduto As System.Drawing.Image = Drawing.Image.FromStream(originalMemStream)
Dim targetRatio As Decimal = CDec(targetWidth) / CDec(targetHeight)
Dim imageRatio As Decimal = CDec(width) / CDec(height)
If targetRatio > imageRatio Then
newHeight = targetHeight
newWidth = CInt(Math.Floor(imageRatio * CDec(targetHeight)))
Else
newHeight = CInt(Math.Floor(CDec(targetWidth) / imageRatio))
newWidth = targetWidth
End If
If newWidth > targetWidth Then newWidth = targetWidth
If newHeight > targetHeight Then newHeight = targetHeight
oGraphic.DrawImage(oProduto, 0, 0, newWidth, newHeight)
**Using thumbImage As Drawing.Image = oGraphic. .GetThumbnailImage(targetWidth, targetHeight, Nothing, IntPtr.Zero),
outMemStream As MemoryStream = New MemoryStream()
thumbImage.Save(outMemStream, ImageFormat.Jpeg)
Return outMemStream.ToArray()
End Using**
End Using
End Using
End Using
End Using
End Function
What I am trying to do is
Create 300width and 200height white bitmap
Draw and center image that was uploaded into center
My problem is I am unable to save the created image. Is this a conversion issue? I've highlighted code where I think I am failing at.
You will need to save the oBitmap. Also if you want to center the image within the 300 x 200 bitmap you will need to pass calculated x, y to oGraphic.DrawImage instead of passing 0, 0
Here is the code (note that I've changed the solid brush color to Red for clarity; make sure to change that to white for your case)
Private Function SizeLogo(ByVal logoBytes As Byte()) As Byte()
Using originalMemStream As MemoryStream = New MemoryStream(logoBytes),
originalImage As System.Drawing.Image = System.Drawing.Image.FromStream(originalMemStream)
Dim width As Integer = originalImage.Width
Dim height As Integer = originalImage.Height
Dim targetWidth As Integer = 300
Dim targetHeight As Integer = 200
Dim newHeight As Integer = 0
Dim newWidth As Integer = 0
Using oBitmap As New Bitmap(300, 200)
Using oGraphic As Graphics = Graphics.FromImage(oBitmap)
Using oBrush As New SolidBrush(Color.Red)
oGraphic.FillRectangle(oBrush, 0, 0, targetWidth, targetHeight)
End Using
Using oProduto As System.Drawing.Image = Drawing.Image.FromStream(originalMemStream)
Dim targetRatio As Decimal = CDec(targetWidth) / CDec(targetHeight)
Dim imageRatio As Decimal = CDec(width) / CDec(height)
If targetRatio > imageRatio Then
newHeight = targetHeight
newWidth = CInt(Math.Floor(imageRatio * CDec(targetHeight)))
Else
newHeight = CInt(Math.Floor(CDec(targetWidth) / imageRatio))
newWidth = targetWidth
End If
If newWidth > targetWidth Then newWidth = targetWidth
If newHeight > targetHeight Then newHeight = targetHeight
Dim x As Integer = 0
Dim y As Integer = 0
If (newWidth < targetWidth) Then
x = (targetWidth - newWidth) / 2
End If
If (newHeight < targetHeight) Then
y = (targetHeight - newHeight) / 2
End If
oGraphic.DrawImage(oProduto, x, y, newWidth, newHeight)
'uncomment this to save to file (just to test output)
'oBitmap.Save("D:\penguins.bmp")
Dim outMemStream As MemoryStream = New MemoryStream()
oBitmap.Save(outMemStream, ImageFormat.Jpeg)
Return outMemStream.GetBuffer()
End Using
End Using
End Using
End Using
End Function
the output image will look like

ODBC Select all command

The following code works fine when the limit is 0,1 when I limit them to 0,30 I cannot retrieve records I am sure that my database has enough number of records.
But I doubt the syntax after dr[3].ToString(); How to retrieve all of them.
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=malla_softmail2;" + "UID=xxx;" + "PASSWORD=xxx;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select * from awm_test where user=? limit= 0, 1", MyConnection);
cmd.Parameters.Add("#email", OdbcType.VarChar, 255).Value = "hello";
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
// throw new Exception();
}
if (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
//string d = dr[3].ToString();
//string f = dr[4].ToString();
//string g = dr[5].ToString();
Response.Write(a);
Response.Write(b);
Response.Write(c);
//Response.Write(d);
//Response.Write(f);
//Response.Write(g);
You're only processing the first record returned by your query. Try:
while (dr.Read()) {
string firstField = dr[0].ToString();
string secondField = dr[1].ToString();
string thirdField = dr[2].ToString();
// ...
}
You just need to read the rows in a loop with while(dr.Read()) {...do stuff for each row...} - each dr.Read() moves to the next row.

Resources