Pages

Monday 31 December 2012

Fix: System.Data.SqlClient.SqlException: Login failed for user

Data Source=localhost;Initial Catalog=ASPNETDB; Integrated Security=SSPI;

Add this Persist Security Info=False;

Data Source=localhost; Initial Catalog=PERSONAL;User ID=personal; Integrated Security=SSPI;Persist Security Info=False;

Solution: your current security settings do not allow this file to be downloaded

a.    Open Internet Explorer.
b.    Click Tools and then options.
c.    Click on the security tab.
d.    Select the Internet Zone.
e.    Click on the Custom Level Button and then scroll down to Download.
f.     Make sure to enable File download.
g.    Click Apply and Ok
h.    Restart Internet Explorer and check if that helps.

Friday 21 December 2012

Solution : The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

The Problem

Over the past several years I’ve found myself running into the same problem over and over so I thought I’d blog the solution so at least I don’t waste time figuring it out again.  So, when do you need this?  The answer for me is that I want to be able reference a web site without having to expose the underlying site structure.  For example, on the home page of my business, I want people to be able to type http://73rdstreet.com/Home and be taken to http://www.73rdstreet.com/HomeSite/Home.aspx.

The Symptom

You may see errors that say something like:
Server Error in Application … HTTP Error 404.0 – Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
MapRequestHandler StaticFile
And the screen may show something like this.
x
If this happens, read on.

Theory

The first thing to understand is that IIS by default will pass to the asp.net process only the requests that have a certain file extension.  That is, aspx,ashx,etc.  Basically, only file extensions that have a handler defined for them to be processed by.  Other URL’s that don’t meet the criteria are not passed to IIS.  This includes no file extension at all.  There is a good reason for this.  One, it makes processing of things like images (jpg’s, gif’s, etc.) faster because they do not every have to be processed through the asp.net worker process.  Secondly, it lowers the exposure of the asp.net worker process so that it is less likely to be compromised.
So, the first thing that has to be done is to tell IIS to pass all requests through using something called Wild Card Mapping.  Then, once this is done, the request comes through to the asp.net worker process regardless of what it is.  As we know, the place that we would have to process this is an HttpModule.  The reason is that since it’s not a page yet, we have no idea what to do with it.  Basically modules let you tap into the request at different stages.  To do the rewrite from ../Home to ../HomeSite/Home.aspx we want to tap into the Application_BeginRequest event.  The Context.RewritePath method is called at that point to force a new path based on what we want (hopefully not hard coded).
After the ReWritePath is set, the page is processed as if is going to the correct page.

How To Set Wild Card Mapping in IIS6

To Set Wild Care Mapping in IIS6 you need to do the following.
Run inetmgr and navigate to the Properties page of the website you want to set.
test
Then, from the properties page, click the Configuration button as shown below.
t
Then, press the insert button on the configuration screen and see the following screen and then click on the insert button.
t[6]
Now, insert your asp.net isapi dll.  On my system, the file is here:  C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll.  Make sure to uncheck the box "Verify that file exists".
t[9]
That’s it! Now, all requests will be processed through you asp.net pipeline so you will be able to intercept anything on the URL you want.  Be careful though, you may get more than you ask for!

How To Set Wildcard Mapping in IIS7

In IIS7 things are a little different.  First thing you need to do is unlock the config section "handlers". You do this by bring up a DOS prompt and entering the command:
C:\Windows\System32\inetsrv>appcmd.exe unlock config /section:system.webserver/handlers
Then, you can set your wildcard handler in your web.config file as follows.
Now, the default handlers will be executed in your web.config file, and of course, all the defaults for that are in the chain of files that inherits from.  For more details on that, see this FAQ: Configuration Files FAQs (web.config, machine.config…).
You may need to add the wildcard mapper handler to your web.config.  To do this, you would put the following in your web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="WildCard" path="*" verb="*" type="sampletype" resourceType="Unspecified" />
        </handlers>
    </system.webServer>
</configuration>
Now, you should be set. See the next section for a good method for actually doing the remapping, which is why we went down this path in the first place.

Implementing a URL ReWriter for Mapping ../Home to ../HomeSite/Home.aspx

So, as discussed in the theory section above, you could write your own code to map what you want to where you want it.  You could put in your global.asax some code for the Application_BeginRequest and make a big case statement for everything you want to do.  Well, as we know, that would give your code a bad smell and we don’t want that because soon, you will find yourself using cut and paste and other problematic crutches.
So, to avoid all that, and do what Scott Guthrie suggests, use the open source package UrlRewriter.NET.  It’s light-weight and configurable through a small section in your web.config. Before putting in the what to do, here are the steps to make UrlRewriter work in a very simple way (the way I use it on my company home page.
In your <System.web> of your web.config place a definition for a new config section where you will put your rewrites
<configuration>
    <configSections>
      <section name="rewriter" requirePermission="false" 
        type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter"/>

Then, put the module that actually does the work of the rewrite as described in the theory section above
<system.web>
   <httpModules>
     <add name="UrlRewriter" 
           type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
     </httpModules>
       ..
Then, further down in your web.config put
<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules>
     <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
And, Finally to actually do the redirect you need to put a new <rewriter> tag with a list of redirects in it.
<rewriter>
  <rewrite url="~/Home" to="~/pages/Home.aspx"/>
</rewriter>
That’s it!  You are done.  Hope this helps, or at least helps me the next time I’m searching for the same problem (for the 4th time at least).

Reference URL
http://peterkellner.net/2008/08/24/urlrewrite-with-aspnet-urlrewriter-wildcard-mapping-iis6-iis7/

Thursday 20 December 2012

Resizing an image without losing the image quality in ASP.Net

private static System.Drawing.Image RezizeImage(System.Drawing.Image img, int maxWidth, int maxHeight)
    {
        if (img.Height < maxHeight && img.Width < maxWidth) return img;
        using (img)
        {
            Double xRatio = (double)img.Width / maxWidth;
            Double yRatio = (double)img.Height / maxHeight;
            Double ratio = Math.Max(xRatio, yRatio);
            int nnx = (int)Math.Floor(img.Width / ratio);
            int nny = (int)Math.Floor(img.Height / ratio);
            Bitmap cpy = new Bitmap(nnx, nny, PixelFormat.Format32bppArgb);
            using (Graphics gr = Graphics.FromImage(cpy))
            {
                gr.Clear(Color.Transparent);

                // This is said to give best quality when resizing images
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic;

                gr.DrawImage(img,
                    new Rectangle(0, 0, nnx, nny),
                    new Rectangle(0, 0, img.Width, img.Height),
                    GraphicsUnit.Pixel);
            }
            return cpy;
        }

    }

    private static MemoryStream BytearrayToStream(byte[] arr)
    {
        return new MemoryStream(arr, 0, arr.Length);
    }

    public static void HandleImageUpload(string p_postedImageFileName, int width, int height, Stream toStream, string path)
    {
        FileStream fs = default(FileStream);
        string originalFileName = HttpContext.Current.Server.MapPath(path + p_postedImageFileName.Replace(" ", "").Replace("%20", ""));
        fs = new FileStream(originalFileName, FileMode.Open);
        BinaryReader br = new BinaryReader(fs);
        byte[] binaryImage = br.ReadBytes((int)fs.Length);
        br.Close();
        fs.Close();

        System.Drawing.Image img = RezizeImage(System.Drawing.Image.FromStream(BytearrayToStream(binaryImage)), width, height);
        img.Save(toStream, System.Drawing.Imaging.ImageFormat.Png);
    }

Get Mime Type using C#

 public static string GetMimeType(string fileName)
    {
        string mimeType = "application/unknown";
        string ext = System.IO.Path.GetExtension(fileName).ToLower();
        RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(ext);
        if (regKey != null && regKey.GetValue("Content Type") != null)
            mimeType = regKey.GetValue("Content Type").ToString();
        return mimeType;
    }

Convert into Title Case using C#

public static string TitleCase(string thePhrase)
    {
        StringBuilder newString = new StringBuilder();
        StringBuilder nextString = new StringBuilder();
        string[] phraseArray;
        string theWord;
        string returnValue;
        phraseArray = thePhrase.Split(null);
        for (int i = 0; i < phraseArray.Length; i++)
        {
            theWord = phraseArray[i].ToLower();
            if (theWord.Length > 1)
            {
                if (theWord.Substring(1, 1) == "'")
                {
                    //Process word with apostrophe at position 1 in 0 based string.
                    if (nextString.Length > 0)
                        nextString.Replace(nextString.ToString(), null);
                    nextString.Append(theWord.Substring(0, 1).ToUpper());
                    nextString.Append("'");
                    nextString.Append(theWord.Substring(2, 1).ToUpper());
                    nextString.Append(theWord.Substring(3).ToLower());
                    nextString.Append(" ");
                }
                else
                {
                    if (theWord.Length > 1 && theWord.Substring(0, 2) == "mc")
                    {
                        //Process McName.
                        if (nextString.Length > 0)
                            nextString.Replace(nextString.ToString(), null);
                        nextString.Append("Mc");
                        nextString.Append(theWord.Substring(2, 1).ToUpper());
                        nextString.Append(theWord.Substring(3).ToLower());
                        nextString.Append(" ");
                    }
                    else
                    {
                        if (theWord.Length > 2 && theWord.Substring(0, 3) == "mac")
                        {
                            //Process MacName.
                            if (nextString.Length > 0)
                                nextString.Replace(nextString.ToString(), null);
                            nextString.Append("Mac");
                            nextString.Append(theWord.Substring(3, 1).ToUpper());
                            nextString.Append(theWord.Substring(4).ToLower());
                            nextString.Append(" ");
                        }
                        else
                        {
                            //Process normal word (possible apostrophe near end of word.
                            if (nextString.Length > 0)
                                nextString.Replace(nextString.ToString(), null);
                            nextString.Append(theWord.Substring(0, 1).ToUpper());
                            nextString.Append(theWord.Substring(1).ToLower());
                            nextString.Append(" ");
                        }
                    }
                }
            }
            else
            {
                //Process normal single character length word.
                if (nextString.Length > 0)
                    nextString.Replace(nextString.ToString(), null);
                nextString.Append(theWord.ToUpper());
                nextString.Append(" ");
            }
            newString.Append(nextString);
        }
        returnValue = newString.ToString();
        return returnValue.Trim();
    }

Create Paging in Repeater with Selected Page

public int PageNumber
    {
        get
        {
            if (ViewState["PageNumber"] != null)
                return Convert.ToInt32(ViewState["PageNumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["PageNumber"] = value;
        }
    }
    public int PageIndex
    {
        get
        {
            return (ViewState["PageIndex"] == null ? 0 : Convert.ToInt32(ViewState["PageIndex"]));
        }
        set
        {
            ViewState["PageIndex"] = value;
        }

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindRepeater();
        }
    }
    private void BindRepeater()
    {
        IshanDataset.OpeningPostRow[] list;
        IshanDataset.OpeningPostDataTable dt = OpeningPost.GetAllOpeningPosts();
        list = dt.OrderBy(p => p.SortOrder).ToArray();
       
        PagedDataSource pgitems = new PagedDataSource();
        pgitems.DataSource = list;
        pgitems.AllowPaging = true;
        pgitems.PageSize = 10;
        pgitems.CurrentPageIndex = PageNumber;
        if (pgitems.PageCount > 1)
        {
            rptPages.Visible = true;
            ArrayList pages = new ArrayList();
            for (int i = 0; i < pgitems.PageCount; i++)
                pages.Add((i + 1).ToString());
            rptPages.DataSource = pages;
            rptPages.DataBind();
        }
        else
            rptPages.Visible = false;
        repOpeningPosts.DataSource = pgitems;
        repOpeningPosts.DataBind();
    }
   
    protected void rptPages_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            int pageno = Convert.ToInt32(e.Item.DataItem);
            LinkButton lkbPage = e.Item.FindControl("btnPage") as LinkButton;
            lkbPage.PostBackUrl = Request.RawUrl;
            lkbPage.CommandArgument = pageno.ToString();
            lkbPage.Text = (pageno).ToString();
          
            if (PageIndex == pageno)
            {
                lkbPage.CssClass = "lnkselect";
            }
        }
    }
    protected void btnPage_Click(object sender, EventArgs e)
    {
        LinkButton lkbPage = sender as LinkButton;
        int pageno = Convert.ToInt32(lkbPage.CommandArgument);
        PageIndex = pageno;
        PageNumber = pageno - 1;
        BindRepeater();
    }


<asp:Repeater ID="repOpeningPosts" runat="server">
    <HeaderTemplate>
        <ul>
    </HeaderTemplate>
    <ItemTemplate>
        <li style="width: 100%; float: left; padding-top: 15px;">
            <div style="float: left;">
                <h5>
                    <a href="#" style="color: #4b4b4b; text-decoration: underline;">
                        <%# Eval("PostTitle")%></a>
                </h5>
            </div>
            <div style="float: right; width: 500px; padding-left: 15px; font-size: 11px; text-align: right;
                text-decoration: underline; font-weight: bold;">
                <i>
                    <%# DataBinder.Eval(Container.DataItem, "ClosingDate", "{0:dd MMMM yyyy}") %></i>
            </div>
            <div style="clear: both; padding-top: 10px;">
                <p style="color: #151515; font-size: 12px;">
                    <%# Common.Strip(Eval("Description").ToString()).ToString().Length > 150 ? Common.Strip(Eval("Description").ToString()).ToString().Substring(0, 150) + " ..." :
                                                                                                                                   Common.Strip(Eval("Description").ToString()).ToString()
                    %></p>
                <a href="#" style="float: right; color: #bd384d; font-size: 12px;">Read More...</a>
            </div>
        </li>
    </ItemTemplate>
    <FooterTemplate>
        </ul>
    </FooterTemplate>
</asp:Repeater>
<asp:Repeater ID="rptPages" runat="server" OnItemDataBound="rptPages_ItemDataBound">
    <HeaderTemplate>
        <div style="float: left;">
            <b>Page:</b>&nbsp;
        </div>
        <div style="float: left;">
    </HeaderTemplate>
    <ItemTemplate>
        <asp:LinkButton ID="btnPage" CommandName="Page" runat="server" OnClick="btnPage_Click" CssClass="lnkpaging">
        </asp:LinkButton>&nbsp;
    </ItemTemplate>
    <FooterTemplate>
        </div>
    </FooterTemplate>
</asp:Repeater>

Wednesday 19 December 2012

Creating Paging in Repeater Control

<asp:Repeater ID="Repeater1" runat="server">
        <HeaderTemplate>
            <table>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td>
                    <asp:Label runat="server" ID="lblContactName" Text='<%# Eval("Name") %>' />
                </td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>
    </asp:Repeater>
    <table>
        <tr>
            <td>
                <asp:PlaceHolder ID="plcPaging" runat="server" />
                <br /><asp:Label runat="server" ID="lblPageName" />
            </td>
        </tr>
    </table>
 C# Coding
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
      {
            FetchData(10, 0);    
}
      else
      {
            plcPaging.Controls.Clear();
            CreatePagingControl();
}                      
}
private void FetchData(int take, int pageSize)
{          
using (NorthwindDataContext dc = new NorthwindDataContext())
      {
            var query = from p in dc.Customers
                        .OrderBy(o => o.ContactName)
                        .Take(take)
                        .Skip(pageSize)
                        select new
                        {
                              ID = p.CustomerID,
                              Name = p.ContactName,
                              Count = dc.Customers.Count()
};
               
PagedDataSource page = new PagedDataSource();
            page.AllowCustomPaging = true;
            page.AllowPaging = true;
            page.DataSource = query;
            page.PageSize = 10;
            Repeater1.DataSource = page;
            Repeater1.DataBind();
            if (!IsPostBack)
            {
                  RowCount = query.First().Count;
CreatePagingControl();
}
}
}
private void CreatePagingControl()
{  
for (int i = 0; i < (RowCount / 10) + 1; i++)
      {
            LinkButton lnk = new LinkButton();                
            lnk.Click += new EventHandler(lbl_Click);
            lnk.ID = "lnkPage" + (i + 1).ToString();
            lnk.Text = (i + 1).ToString();
            plcPaging.Controls.Add(lnk);
            Label spacer = new Label();
            spacer.Text = "&nbsp;";
            plcPaging.Controls.Add(spacer);
}
}


void lbl_Click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
      int currentPage = int.Parse(lnk.Text);
      int take = currentPage * 10;
      int skip = currentPage == 1 ? 0 : take - 10; 
      FetchData(take, skip);
}
VB Coding
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not IsPostBack) Then
             FetchData(10, 0)
       Else
             plcPaging.Controls.Clear()
             CreatePagingControl()
       End If
End Sub
Private Sub FetchData(ByVal take As Integer, ByVal pageSize As Integer)
Using dc As New NorthwindDataContext()
             Dim query = From p In dc.Customers.OrderBy(Function(o) o.ContactName).Take(take).Skip(pageSize) _
                          Select New
                                          p.ContactName, Count = dc.Customers.Count()
                                          p.CustomerID, Name = p.ContactName, Count
                                          ID = p.CustomerID, Name
Dim page As New PagedDataSource()
                  page.AllowCustomPaging = True
                  page.AllowPaging = True
                  page.DataSource = query
                  page.PageSize = 10
                  Repeater1.DataSource = page
                  Repeater1.DataBind()
                  If (Not IsPostBack) Then
                        RowCount = query.First().Count
CreatePagingControl()
                  End If
End Using
End Sub
Private Sub CreatePagingControl()
For i As Integer = 0 To (RowCount / 10)
             Dim lnk As New LinkButton()
                  AddHandler lnk.Click, AddressOf lbl_Click
                  lnk.ID = "lnkPage" & (i + 1).ToString()
                  lnk.Text = (i + 1).ToString()
                  plcPaging.Controls.Add(lnk)
                  Dim spacer As New Label()
                  spacer.Text = "&nbsp;"
                   plcPaging.Controls.Add(spacer)
Next i
End Sub
Private Sub lbl_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lnk As LinkButton = TryCast(sender, LinkButton)
       Dim currentPage As Integer = Integer.Parse(lnk.Text)
       Dim take As Integer = currentPage * 10
       Dim skip As Integer = If(currentPage = 1, 0, take - 10)
       FetchData(take, skip)
End Sub

RecordPerPage
Support link

http://www.codeguru.com/csharp/.net/net_asp/controls/article.php/c12925/ASPNET-Tip-Creating-Paging-for-a-Repeater-Control.htm

http://www.dotnetcurry.com/ShowArticle.aspx?ID=345