Twitter Feed Popout byInfofru

Dawah

Backup Failed : System.Data.SqlClient.SqlError: Failed to pause catalog for backup. Backup was aborted.

So, not too long ago I was regular blogger but due to builds and examinations I am getting far from this stuff. Anyway, this morning when I was taking backup of the database located on one of our dedicated server. I hunt the following error.
System.Data.SqlClient.SqlError: Failed to pause catalog for backup. Backup was aborted.
In short, you are no more able to take backups. So I googled about this error but trust me, there is no much information regarding this stuff. So, to get rid of it, you quickly need to do the following steps.
1. Jump to the services console. (Control Panel-> Administrative Tools -> Services)2. Locate the SQL Server FullText Search and verify is it running.3. If it is not running then start it .... but hold on read the next point4. If it is running then verify what account which it is using under Log On tab.  (it should be Local System Account)5. Save the settings and make sure to restart the service and you are done.

Protecting images with Response Filter

In this article we will see how we can change the email addresses written on a website to images on the fly. The general opinion about this task is to revamp the form where we are asking user to input the email address and then generate an image which will display later instead of email address.Fortunately, Asp.net provides us with a feature called Response filter which allow us to alter the response generated by web server. By using Response filter we don’t need to alter the foundation of our application. We just need to plug that response filter in and our work is done.So to create a filter we need to create a class called “EmailFilter.CS” which will inherit from Stream.
public class EmailFilter : Stream{private string _path;private Stream _response;public EmailFilter(Stream response, string path){_response = response;_path = path;}
public override int Read(byte[] buffer, int offset, int count){return _response.Read(buffer, offset, count);}
public override void Write(byte[] buffer, int offset, int count){}} 
This can easily be read that we have two local variables which are getting set by our parameterized constructor and we have overrides two functions out of which the write function is really important. We are going to play with that function throughout the tutorial.Note:It is also important to mention here that we have removed some code for clarity but to use the stream class you need to override the some other functions and properties which you can find in code attached.
Now the next step is to write the code in Write method.
 
public override void Write(byte[] buffer, int offset, int count){string html = System.Text.Encoding.UTF8.GetString(buffer);string emailPattern = @"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
Regex objRegex = new Regex(emailPattern);MatchCollection objCol = objRegex.Matches(html);
foreach (Match m in objCol){string email = m.Value;Font objFont = new Font("Arial", 12, FontStyle.Bold);int width = (int) getTextWidth(email, objFont);Bitmap objBitmap = new Bitmap(width, 20);Graphics objGraphics = Graphics.FromImage(objBitmap);objGraphics.FillRectangle(Brushes.White, new Rectangle(0, 0, width, 20)); //getting white bgobjGraphics.DrawString(email, objFont, Brushes.Black, new Point(0, 0));string relpath = "images/" + Guid.NewGuid().ToString() + ".jpg";string saveFileName = _path + relpath;objBitmap.Save(saveFileName,System.Drawing.Imaging.ImageFormat.Jpeg);objGraphics.Dispose();objBitmap.Dispose();string imgMarkup = "<img src='" + relpath + "'/>";html = html.Replace(email, imgMarkup);}buffer = System.Text.Encoding.UTF8.GetBytes(html);_response.Write(buffer, offset, count);}protected float getTextWidth(string strText, Font f){float width = 0;Bitmap objBitmap = new Bitmap(1, 1);Graphics objGraphics = Graphics.FromImage(objBitmap);try{width = objGraphics.MeasureString(strText, f).Width;return width;}catch (Exception){return 0;}finally{objBitmap.Dispose();objGraphics.Dispose();}} 
The first four lines are easy to understand we are just storing the HTML generated by web server to a variable and we have created a regular expression object to check for the email addresses in out html.
In foreach loop we are generating the images of every email address using System.Drawing and saving the images in a temp location and finally disposing the objects.Now the main stuff is here, we are creating a string variable which will hold html image tag with source and then replace the email address with the image tag.
Whereas, getTextWidth is a simple function which measure the width of our text and return it so that we can have dynamic width for different size of texts.Let's use this response filter in our aspx page. To do that we need to write the following code in Page_Load 
protected void Page_Load(object sender, EventArgs e){Response.Filter = new EmailFilter(Response.Filter, Server.MapPath("/").ToString());}
It is worth to mention here the parameter. Our Response filter is just a class file and we donot have the Server path in classes but we still want to store the images using relative path so to do that we just pass the root path as parameter which we will use in Response Filter to save the image. To understand the situation correctly we need to write the following code in the form tag of our aspx.
<div>aghausman@gmail.com </br>aghausman@ciberstrategies.com</br>me@aghausman.net</br></div>
That is nothing but three simple email addresses. Now when you run the page you will see the following output. Notice that we have write three email addresses but it is showing only two. To see what went wrotn we have let's have a look at the source given below:[singlepic=27,500,200,web20,]
Notice that there is no html after the br of second image. It means there is some thing wrong with the response.write. Now to understand what happen we need to go back and read the last line of our Write function which is as follows
_response.Write(buffer, offset, count);
here we are simply passing what we have get from Write parameter but the matter of fact is that it is now changed. Remember, we have change our email address with the image tag so to compare let's see our first email address and frst generated image. 
Email Address : aghausman@gmail.comImage Text : <img src='images/da04a458-7ff4-41cb-b982-5724c1eadb84.jpg'/>
Notice that image tag is using more then double characters. so we need to change the last parameter count according to the new condition. for that let's see the Write method code again.
  
 
public override void Write(byte[] buffer, int offset, int count){string html = System.Text.Encoding.UTF8.GetString(buffer);string emailPattern = @"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
Regex objRegex = new Regex(emailPattern);MatchCollection objCol = objRegex.Matches(html);
int totCount = 0;foreach (Match m in objCol){string email = m.Value;Font objFont = new Font("Arial", 12, FontStyle.Bold);int width = (int) getTextWidth(email, objFont);Bitmap objBitmap = new Bitmap(width, 20);Graphics objGraphics = Graphics.FromImage(objBitmap);objGraphics.FillRectangle(Brushes.White, new Rectangle(0, 0, width, 20)); //getting white bgobjGraphics.DrawString(email, objFont, Brushes.Black, new Point(0, 0));string relpath = "images/" + Guid.NewGuid().ToString() + ".jpg";string saveFileName = _path + relpath;objBitmap.Save(saveFileName,System.Drawing.Imaging.ImageFormat.Jpeg);objGraphics.Dispose();objBitmap.Dispose();string imgMarkup = "<img src='" + relpath + "'/>";totCount += imgMarkup.Length;html = html.Replace(email, imgMarkup);}buffer = System.Text.Encoding.UTF8.GetBytes(html);_response.Write(buffer, offset, count + totCount);} 
We have only create an int variable before loop and on every loop we are adding the length of image tag to the variable and finally on response.write we are adding the count with the length of image tags we have generated. that's it.Now if we run the page we will see the following output:  
[singlepic=26,500,200,web20,]That's all, we have now replace the emal addresses written on our website to images. Just in case you don't want to write the page_load stuff on every page as it is very difficult then you can also use httpModule. For the see the following code
public class EmailToImages : IHttpModule{public void Dispose(){
}public void Init(HttpApplication application){HttpContext context = HttpContext.Current;
context.Response.Filter = new EmailFilter(context.Response.Filter, context.Server.MapPath("/"));}}<httpModules><add name="EmailToImage" type="LearnWebApp.EmailToImages, LearnWebApp"/></httpModules> 
Now to remove the temperory images you might need a code which delete the images in timely fashion. That's all.
 Orignal Article and source code will be find at : http://www.highoncoding.com/Articles/468_Protecting_Email_Addresses_Using_Response_Filters.aspx

Fill Asp Menu by Folder

In this post, we will see how can we fill the Asp Menu by specifying folder instead of some other data source. Following is the folder structure which this code is supportedRoot-> Folder 1 -> Files-> Folder 2 -> Files-> Folder 3 -> FilesI mean, if there is another folder in Folder 1 or Folder 2 or Folder 3. The code will not detect because it is not recursive.So Let's get down to the code
protected void Page_Load(object sender, EventArgs e){DirectoryInfo di = new DirectoryInfo(@"C:\\agha"); //Path of folder you want get file/folder fromDirectoryInfo[] objDi = di.GetDirectories();foreach (DirectoryInfo d in objDi){MenuItem objMenuItem = new MenuItem(d.Name);FileInfo[] objfi = d.GetFiles("*.*");foreach (FileInfo f in objfi){objMenuItem.ChildItems.Add(new MenuItem(f.Name));}Menu1.Items.Add(objMenuItem);}}

Get Primary key on Row Command (GridView)

 Some days back I got a query from one of my fellow, regarding a very normal situation I mean that’s the day to day task that we as a developers are doing. Here is the scenarioScenario: Consider you have a data grid view which show a list of products from northwind database and you want a link button which will edit the same grid view entry but in a separate page and on separate form with the help of the primary key which you may want to send to another page using query string or else.So the task is to get the primary key of the row on which the link button is pressed.Solution:Well, we can achieve this task from variety of methods. Let me just give you a quick list of how we can do this.
1. Have Hidden Field in Link button column2. Pass PK in command argument3. Using Data key names.
Ok, for basics I have created two pages one if default.aspx which holds the grid and the other is editform.aspx which will get the primary key sent by Default.aspxOn editForm.aspx add the following code on page load. 
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load   If Not Request.QueryString("Id") Is Nothing Then 'check if there is nothing in query string       Response.Write("Product Id Is : " + Request.QueryString("Id").ToString()) 'print the id   End IfEnd Sub 
Now for the for the different approaches let's read belowApproach 1 (Hidden field)Write the following grid view on default.aspx 
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  DataSourceID="SqlDataSource1"><Columns><asp:BoundField DataField="ProductName" HeaderText="ProductName" /><asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" /><asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" /><asp:TemplateField><ItemTemplate><asp:HiddenField ID="hfKey" runat="server" Value='<%#Eval("ProductID") %>' /><asp:LinkButton ID="Edit" CommandName="edt" runat="server">Edit</asp:LinkButton></ItemTemplate></asp:TemplateField></Columns></asp:GridView>  
 
 
  
Notice that, we have taken a hidden field just in the same column we have the link button and have it default value of out primary key field. Now on RowCommandEvent of the grid view write the following code 
 Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand    If e.CommandName.ToLower() = "edt"  Then       Dim lb As LinkButton = CType(e.CommandSource, LinkButton) 'getting clicked link button       Dim strKey As String = CType(lb.Parent.FindControl("hfKey"), HiddenField).Value 'getting PK Value       Response.Redirect("EditForm.aspx?id=" + strKey) 'redirecting    End IfEnd Sub  
I guess code does not need any explanation, so let's move on to the next approach.Approach 2We have a minor change the in Template Field of the Gridview we write in Default.aspx. replace that with the following code.  
<asp:TemplateField><ItemTemplate><asp:LinkButton ID="Edit" CommandName="edt" CommandArgument='<%#Eval("ProductId") %>' runat="server">Edit</asp:LinkButton></ItemTemplate></asp:TemplateField>
So, we have remove the hidden field we have added in the last approacha and simply add the command argument to the link button, now to catch the command argument and send it to edit form write the following code onRowCommand Event   
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As  System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand    If e.CommandName.ToLower() = "edt" Then       Dim strKey As String = e.CommandArgument  'Getting Pk Value from argument       Response.Redirect("EditForm.aspx?id=" + strKey) 'redirecting    End IfEnd Sub  
Approach 3:Ok, for this you need to add DataKeyNames Property to main GridViewMarkup. In other word, it is an attribute of grid view which can accept multiple values using "," but in our case we are using one. So when we add this attribute our grid markup will look like as follows
 
 
 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID ="SqlDataSource1"><Columns><asp:BoundField DataField="ProductName" HeaderText="ProductName" /><asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" /><asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" /><asp:TemplateField><ItemTemplate><asp:LinkButton ID="Edit" CommandName="edt" runat="server">Edit</asp:LinkButton></ItemTemplate></asp:TemplateField></Columns></asp:GridView>
 
 Notice that we have remove command argument from link button, now add the following code on the RowCommand Function.
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand    if e.CommandName.ToLower() = "edt" Then       Dim lb As LinkButton = CType(e.CommandSource, LinkButton)       Dim gvRow As GridViewRow = lb.BindingContainer 'Getting current row to get index       Dim strKey As String = GridView1.DataKeys(gvRow.RowIndex)(0).ToString()       Response.Redirect("EditForm.aspx?id=" + strKey) 'redirecting    End IfEnd Sub
In the above code we are getting the current row from which the link button is clicked because we need the index of the row to get the data key name value.So, now you have plenty of choices to select which approach you like to go with :) .Screen Cast : http://tinyurl.com/5fuj8e

Create dynamic controls with validation

Creating a dynamic control and render to a page is a simple task but what happen when you need to apply validation to that dynamic control.Here is the little snippet of that
TextBox objtext = new TextBox();Page.Form.Controls.Add(objtext);RequiredFieldValidator objReq = new RequiredFieldValidator();objtext.ID = "MyTextBox";objReq.ControlToValidate = objtext.ID;objReq.ErrorMessage = "Please tell us some thing";Page.Form.Controls.Add(objReq);

Pattern Matching of Hyper Link C#

Considering you have a string like"xyrsdsfdfshfds<a>sdjsgdjgsjdsd</a>yutrsgdhdg abcd yhsgjhgshdg<a href='yahoo.com'>xyz</a>";And you want to get all the links in the string which have hyper link specified. To get this job done try the following code.
string ptrn = "<a href='[^']+'>[^<]+</a>"; //<a href="http://[^"]+">([^<]+)</a> use that as wellstring strToCompare = "xyrsdsfdfshfds<a>sdjsgdjgsjdsd</a>yutrsgdhdg abcd yhsgjhgshdg<a href='yahoo.com'>xyz</a>";Regex objRegex = new Regex(ptrn);if (objRegex.IsMatch(strToCompare)){Response.Write(objRegex.Matches(strToCompare)[0].Value);// I am using this .. you can iterate in array and read all the values}

Map AdRotator to a folder

Few days before one of my fellow comes up with this challenge, the requirement is good but by using it you will lose control over two thing1. Navigate URL2. Impression PriorityIf you are ready to compromise on these two then the solution is here. Please bear in mind that this is not how to of Ad rotator control. It is related to advance use. To learn basics please visitAs you all know that Ad Rotator control accept an xml file to show advertisement. the scehma of the xml file is as follow. 
 <Advertisements>
 <Ad>
  <ImageUrl>/images/expand_blue.jpg</ImageUrl>
  <NavigateUrl>www.aghausman.net</NavigateUrl>
  <AlternateText>expand_blue.jpg</AlternateText>
  <Impressions>1</Impressions>
</Ad>
 <Advertisements>
 
So to make it work dynamically, I mean by mapping to a folder we need to write an xml file each time the page load. (You can use some alternative approaches as well) First, we write to set the Adrotator on out aspx page.
<asp:AdRotator ID="AdRotator1" runat="server" /> 
 Then to generate a file using any folder I write the following function
private void bindFiles()        {            string strPath = "/images/"; //Folder Path            DirectoryInfo di = new DirectoryInfo(Server.MapPath(strPath));            if (di.Exists)            {                string filename = Server.MapPath("/upload/temp.xml");                               XmlTextWriter objtw = new XmlTextWriter(filename, System.Text.UTF8Encoding.UTF8);                objtw.WriteStartDocument();                objtw.WriteStartElement("Advertisements");                               FileInfo[] objFile = di.GetFiles("*.jpg"); //you can extract multiple format of images                foreach (FileInfo f in objFile)                {                    objtw.WriteStartElement("Ad");                    objtw.WriteStartElement("ImageUrl");                    objtw.WriteString(strPath + f.Name);                    objtw.WriteEndElement();                                       objtw.WriteStartElement("NavigateUrl");                    objtw.WriteString("#"); // Passing # means no action                    objtw.WriteEndElement();                                              objtw.WriteStartElement("AlternateText");                    objtw.WriteString(f.Name);                    objtw.WriteEndElement();                           objtw.WriteStartElement("Impressions");                    objtw.WriteString("1"); //As we don't know of any priotiry, keep it 1 for every one                    objtw.WriteEndElement();                           objtw.WriteEndElement();                }                       objtw.WriteEndElement();                objtw.WriteEndDocument();                               objtw.Flush();                objtw.Close();            }        } 
   And on the load event of page write the following stuff. 
if  (!Page.IsPostBack) {bindFiles();AdRotator1.AdvertisementFile = "/upload/temp.xml"; }
That's the whole story.

Delete button with Javascript confirm in Datagrid

It is often a good practice to show a confirmation alert to the user when they select to delete any record. So for that, here is the quick code consider the following grid view. 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"CellPadding="3" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1"ForeColor="Black" GridLines="Vertical" Width="100%" onrowcommand="GridView1_RowCommand"><Columns><asp:BoundField DataField="CategoryID" HeaderText="CategoryID"InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" /><asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" /> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /><asp:TemplateField><ItemTemplate><asp:LinkButton ID="lbDelet" CommandName="del" runat="server" Text="Delete" OnClientClick="javascript:return confirm('Are you sure you want to delete ?');"></asp:LinkButton></ItemTemplate></asp:TemplateField></Columns><FooterStyle BackColor="#CCCCCC" /><PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" /><SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" /><HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" /><AlternatingRowStyle BackColor="#CCCCCC" /></asp:GridView 
Notice the last column which is template column and having a link button (ID = lbDelet). onClientClick is doing the main stuff.That's it cheers

Could not load file or assembly Microsoft.SqlServer.Management.Sdk.Sfc

Another sick error of the day, When you try to create connection string from SQLDatasource or even want to bind existing connection string. You might see a Message box saying
Could not load file or assembly 'Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
This error comes when you are trying to access SQL 2005 stuff from Visual Studio 2008.  So go to the link and download the following stuff
  • Microsoft SQL Server System CLR Types
  • Microsoft SQL Server 2008 Management Objects
  • Microsoft SQL Server 2008 Native Client