Archive for the ‘ASP.NET’ Category

10/30/11
Fahad Zia
tags:  

Postback with ASP.NET button inside Facebox


http://weblogs.asp.net/kariemsoudy/archive/2009/11/02/buttons-inside-facebox-popup-don-t-postback-fix.aspx

06/02/11
Fahad Zia

Disabling Calendar Days in Telerik RadDatePicker


Its not easy as setting a property. Check the solution here:
http://www.telerik.com/community/code-library/aspnet-ajax/calendar/disabling-calendar-days.aspx

09/28/10
Fahad Zia

ProcessBatchData: Value does not fall within the expected range


This may apply to other funtions that use xml file but in my case i was using ProcessBatchData with correctly formatted xml string as the argument (atleast thats what thought since I could open the xml string fine in IE and Visual Studio debugger). After hours of debugging and googling i found out that it was because i was using single quotes in xml declaration!:
Wrong :

string strXML = "<?xml version='1.0' encoding='UTF-8'?>"

Correct:

string strXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" 

Page where i found this:
http://pholpar.wordpress.com/2010/02/05/how-to-change-the-order-of-the-fields-on-a-sharepoint-form-using-code/

06/03/10
Fahad Zia

iTextSharp Image Resize


I have been using iTextSharp to export SPListItem to PDF. This item also has picture URL to show in PDFs. Everything worked fine except when I tried to put an image inside table cell, the image will resize itself to fill the cell(this is by design). And if the picture is big in dimensions it would cover tthe whole page with picture. I tried using various methods included in iTextSharp.text.Image object but the result was still not what i wanted. So i ended up using ScaleAbsolute with dimensions that i find using .NET code.
Here is the code that resizes the picture in memory and uses its dimensions in iTextSharp.text.Image.ScaleAbsolute :

Document pDoc = new Document(PageSize.A4, 30, 30, 40, 5);
using (Stream streamMainPic = GetPictureStream(list, strMainPicture))
{
    if (streamMainPic != null)
    {
        iTextSharp.text.Image imgMain = iTextSharp.text.Image.GetInstance(streamMainPic);
        imgMain.Border = 0;                                
        imgMain.SetAbsolutePosition(pDoc.Left + 145, pDoc.Top - 300);

        //Resize picture to fit 380x150 ratio if its bigger
        int intMaxWidth = 380;
        int intMaxHeight = 150;
        using (Stream streamMain2 = GetPictureStream(list, strMainPicture))
        {
            Bitmap bmpMain = new Bitmap(streamMain2);
            if (bmpMain.Height > intMaxHeight || bmpMain.Width > intMaxWidth)
            {
                double dblHeightRatio = Convert.ToDouble(intMaxHeight) / Convert.ToDouble(bmpMain.Height);
                double dblWidthRatio = Convert.ToDouble(intMaxWidth) / Convert.ToDouble(bmpMain.Width);
                double dblScaleRatio;

                //Use the smaller ratio
                if (dblHeightRatio > dblWidthRatio)
                {
                    dblScaleRatio = dblWidthRatio;
                }
                else
                {
                    dblScaleRatio = dblHeightRatio;
                }

                int intNewHeight = Convert.ToInt32(bmpMain.Height * dblScaleRatio);
                int intNewWidth = Convert.ToInt32(bmpMain.Width * dblScaleRatio);

                imgMain.ScaleAbsolute((float)intNewWidth,
                                       (float)intNewHeight);
            }
        }
        pDoc.Add(imgMain);
    }
    }
private static Stream GetPictureStream(SPList list, string strMainPicture)
        {
            Stream stream1;
            try
            {
                WebRequest reqImg = WebRequest.Create(new Uri(strMainPicture.Replace("../..", list.ParentWeb.Url)));
                reqImg.UseDefaultCredentials = true;
                WebResponse img = reqImg.GetResponse();
                StreamReader reader = new StreamReader(img.GetResponseStream());
                stream1 = reader.BaseStream;
            }
            catch (Exception ex)
            {
                stream1 = null;
            }
            return stream1;
        }
12/17/09
Fahad Zia
tags:   ,

Download BLOB in SQL Server using SSRS and ASP.NET


I came across a requirement recently where I have to let the user download files from the links displayed in SSRS report. Here’s how I approached it:
1. Provide an ASP.NET page(requestfile.aspx) that would query the BLOB column in the database and return the file by reading required column values from querystring.
2. Provide link from SSRS report to the ASP.NET page and pass it the querystring values it needs

Here is the ASP.NET page (requestfile.aspx) code that reads information from querystring and returns the BLOB as file:

/// <summary>
    /// Query the database to download BLOB column as file
    /// </summary>    
    protected void Page_Load(object sender, EventArgs e)
    {
        string strTableName = "";
        string strColumnName = "";
        string strPKColumnName = "";
        string strPKColumnValue = "";
        string strFileName = "";
        string strConnectionString = "Data Source=.;Initial Catalog=xx;Trusted_Connection=True;";
        byte[] data=null;

        strTableName = Request.QueryString["tbl"].ToString();
        strColumnName = Request.QueryString["colName"].ToString();
        strPKColumnName = Request.QueryString["pkColName"].ToString();
        strPKColumnValue = Request.QueryString["pkColValue"].ToString();
        strFileName = Request.QueryString["filename"].ToString();

        string strSQL = string.Format("SELECT {0} FROM {1} WHERE {2}={3};",
                                        strColumnName,
                                        strTableName,
                                        strPKColumnName,
                                        strPKColumnValue);
        using (SqlConnection conn = new SqlConnection(strConnectionString))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(strSQL,conn);
            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                data = (byte[])rdr[strColumnName];
                break;
            }
            if (data.Length > 0)
            {
                Response.Buffer = true;
                Response.ContentType = string.Format("application/{0}",Path.GetExtension(strFileName));
                Response.AddHeader("content-disposition",string.Format("attachment;filename={0}",strFileName));
                Response.BinaryWrite(data);
                Response.Flush();
            }
            conn.Close();
        }
    }

Now in SSRS i created an embedded function called WriteJavascriptString:

Function WriteJavascriptString (FileName As String, _
			TblName As String, _
			ColName As String, _
			PKColName As String, _
			PKColValue As String) As String
	Return "javascript:void window.open('http://localhost:4127/website/requestfile.aspx?filename=" & FileName & "&tbl=" & TblName & "&colName=" & ColName & "&pkcolName=" & PKColName & "&pkColValue=" & PKColValue & "','_blank')"
End Function

ColName is the BLOB column i.e. of type varbinary. TblName is the table that has this column, PKColName is the column name that unqiuely identifies the row and PKColValue is its value.

and finally this code is linked to the field text boxes on the report by right clicking the text box then “Properties”->”Navigation” tab->”Jump to URL” and writing the expression as shown below:

=IIf(IsNothing(First(Fields!Document_blob.Value, "dsDocuments")),"",Code.WriteJavascriptString(First(Fields!Document_filename.Value, "dsDocuments"),"DOCUMENTS_TBL","Document_blob","DocID",Parameters!DocID.Value))
10/19/09
Fahad Zia
tags:   ,

Uploaded jpg image not getting displayed in SharePoint


I was working on an upload image web part that would upload image to a SharePoint picture library. Strangely some of the pictures would get uploaded but when I would copy the URL to the image it will display as blank image as shown below:

blankimage

This did not make sense to me since when i would go to the picture library I could see the thumbnail and even the preview image EXCEPT the actual image. Spending more time on it I found out that the image that was not getting displayed had CMYK color profile which isn’t supported by browsers. Ok but why would it display as thumbnail and preview? The answer is when you upload image in SharePoint it optimizes and generates thumbnail and preview image on the fly so if you actually see the path of the thumbnail you will see “/t” and for preview you will see “/w” in the image src property.

Ok now that I know the image was CMYK how can I stop the user to upload CMYK or maybe convert it to RGB as SharePoint does? In my case I showed an error if they tried to upload CMYK image.

//=================================================================

public static string GetImageFlags(System.Drawing.Image MyImage)
{
   ImageFlags FlagVals = (ImageFlags)Enum.Parse(typeof(ImageFlags), MyImage.Flags.ToString());
   return FlagVals.ToString();
}

//=================================================================

public static bool IsCMYK(System.Drawing.Image MyImage)
{
   bool ReturnVal;
   if ((GetImageFlags(MyImage).IndexOf("Ycck") > -1) || (GetImageFlags(MyImage).IndexOf("Cmyk") > -1))
   {
    ReturnVal = true; 
   }
   else
   { 
     ReturnVal = false; 
   }
   return ReturnVal;
}

I got this code from: http://www.maxostudio.com/Tut_CS_CMYK.cfm. And then when user uploads image we can test it like this:

//CMYK color space not allowed
Bitmap bitmap = new Bitmap(fuPic.PostedFile.InputStream);
if (IsCMYK(bitmap))
{                    
  lblErr.Visible = true;
  lblErr.Text = "* CMYK color space not allowed. Please try again";
  return;
}