Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, April 4, 2013

Capturing the Enter key to cause a button click


Let's explore two solutions to this problem. First, let us look at using JavaScript. With this solution, each textbox needs to have some JavaScript attached to the onKeyPress JavaScript event. I usually do this in the pageload method in the code-behind.

if (!IsPostBack)
{
   txtboxFirstName.Attributes.Add("onKeyPress",
                   "doClick('" + btnSearch.ClientID + "',event)");
 
}


Note: You pass into the JavaScript method the button's ClientID so that the JavaScript method can find the button and call its Click method.

Next, we need a JavaScript method called doClick in the ASP.NET form.

<SCRIPT type=text/javascript>
    function doClick(buttonName,e)
    {
        //the purpose of this function is to allow the enter key to
        //point to the correct button to click.
        var key;

         if(window.event)
              key = window.event.keyCode;     //IE
         else
              key = e.which;     //firefox
   
        if (key == 13)
        {
            //Get the button the user wants to have clicked
            var btn = document.getElementById(buttonName);
            if (btn != null)
            { //If we find the button click it
                btn.click();
                event.keyCode = 0
            }
        }
   }
</SCRIPT>


The next solution is using a Panel control. In this case, the panel is doing all the work.

 Collapse | Copy Code
<asp:Panel ID="panSearch" runat="server"
       DefaultButton="btnSearch" Width="100%" >
    <table width="100%">
   
    <tr>
     <td>First Name</td>
     <td ><asp:TextBox ID="txtboxFirstName"
           runat="server" ></asp:TextBox></td>
    </tr>
    ...

Thursday, March 28, 2013

Progress Bar in Update Panel in C#

Use below Code to have Progress Bar in ASP.net with C# using AJAX

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table>
<tr>
<td>
<asp:UpdateProgress runat="server" ID="UpdateProgress1"
DynamicLayout="false" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<img id="Img1" runat="Server" src="<Path of Gif or motion image file>" height="12"  alt=""/>
</ProgressTemplate>
</asp:UpdateProgress>
</td>
</tr>

</table>
</ContentTemplate>
</asp:UpdatePanel

Friday, March 22, 2013

Replace in Data binding Eval() in C#

Eval("ThumbnailCaption").ToString().Replace("X", String.Empty))

Monday, February 25, 2013

How to Start/Stop Service using Coding?



ServiceController controller = ServiceController.GetServices().Where(s => s.ServiceName == "ServiceName").FirstOrDefault();
if (controller == null)
{
      MessageBox.Show("Service is missing.");
      return;
}
if (controller.Status == ServiceControllerStatus.Stopped)
{
     controller.Start();
}
else if (controller.Status == ServiceControllerStatus.Running)
{
     controller.Stop();
 }

Thursday, January 24, 2013

cannot open window service on computer '.' in window application

Go  c://Program Files/ApplicationFolder/.exe Right click on .exe and go to Properties then go Compability Tab and check true to Run this Program as an administrator Level.

Tuesday, December 11, 2012

How to use HTTPS secure Page in URL in some Pages.


You may have to use https while Registration.

Please Add the Below code in Global.asax Page.

  protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var currentUrl = System.Web.HttpContext.Current.Request.Url;
            if (currentUrl.AbsoluteUri.Contains("Registration"))
            {
                if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
                {
                    //build the secure uri
                    var secureUrlBuilder = new UriBuilder(currentUrl);
                    secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
                    //use the default port.
                    secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString());
                    //redirect and end the response.
                    System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
                }
            }
        }

How to add JavaScript at runtime using C#

string Script=@”function ShowName() { var txt=document.getElementById(‘txtName’); alert(‘Your name is: ‘+txt.value); }”; 

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “ShowName”, Script, true);

Wednesday, November 7, 2012

Sorting XML in C# alphabetically and by order


Snippet
using System;
using System.Linq;
using System.Xml.Linq;
 
namespace ThrowAwayCSConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = @"<?xml version=""1.0"" encoding=""UTF-8\""?>
                    <websites> 
                        <site language=""Spanish"" name=""ExcĂ©lsior"" order=""2"">http://www.excelsior.com.mx/</site> 
                        <site language=""Japanese"" name=""TOKYO Web"" order=""3"">http://www.tokyo-np.co.jp/</site>
                        <site language=""Italian"" name=""Corriere della Sera"" order=""1"">http://www.corriere.it/</site>
                        <site language=""Spanish"" name=""SpanishTest1"" order=""4"">www.spanishtest1.com</site> 
                    </websites>";
 
            XDocument xdoc = XDocument.Parse(xml);
            XDocument xNewDoc = new XDocument();
 
            xNewDoc.Add(xdoc.Root);
 
            xNewDoc.Root.RemoveNodes();
            xNewDoc.Root.Add(xdoc.Root.Elements().OrderBy(e => e.Attribute("language").Value));
 
            Console.WriteLine("Before: \r\n{0}", xdoc.ToString());
            Console.WriteLine();
            Console.WriteLine("After: \r\n{0}", xNewDoc.ToString());
            Console.ReadLine();
        }
    }
}
Which produces this output:
Before:
<websites>
 <site language="Spanish" name="Excélsior" order="2">http://www.excelsior.com.mx/</site>
 <site language="Japanese" name="TOKYO Web" order="3">http://www.tokyo-np.co.jp/</site>
 <site language="Italian" name="Corriere della Sera" order="1">http://www.corriere.it/</site>
 <site language="Spanish" name="SpanishTest1" order="4">www.spanishtest1.com</site>
</websites>

After:
<websites>
 <site language="Italian" name="Corriere della Sera" order="1">http://www.corriere.it/</site>
 <site language="Japanese" name="TOKYO Web" order="3">http://www.tokyo-np.co.jp/</site>
 <site language="Spanish" name="Excélsior" order="2">http://www.excelsior.com.mx/</site>
 <site language="Spanish" name="SpanishTest1" order="4">www.spanishtest1.com</site>
</websites>

Monday, October 29, 2012

How to Get IP Address of our own Machine..


string strHostName = "";
strHostName = System.Net.Dns.GetHostName();

IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

IPAddress[] addr = ipEntry.AddressList;

string ip= addr[addr.Length - 1].ToString();


If you want to Retrive True IP Address then


string IPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (IPAddress == null) //may be the HTTP_X_FORWARDED_FOR is null
{
            IPAddress = Request.ServerVariables["REMOTE_ADDR"];//we can use REMOTE_ADDR
}



Friday, July 13, 2012

How to Pass Querry string in LinkButton in Gridview?

Introduction:

                       Here I am showing you how to pass more than One Querry string in LinkButton in Gridview.
                 
<asp:LinkButton ID="lnkAndMoreImage" runat="server" Text="Add Images" ForeColor="Blue" PostBackUrl='<%#"~/AdminView/AddProjectImages.aspx?ID="+Eval("ProjectID")+"&"+"Name="+Eval("ProjectName")%>' style="text-decoration:underline"></asp:LinkButton>

Thursday, July 12, 2012

Useful Built-in functions of SSRS.


The following functions are built-in Function.

Aggregate(field expr [,scope])
Returns an array containing the values of the grouped field. For example, =Code.AggrToString(Aggregate(Fields!Year.Value)) // In Code element Public Function AggrToString(o as object) As String Dim ar as System.Collections.ArrayList = o Dim sb as System.Text.StringBuilder = New System.Text.StringBuilder Dim n as Integer For n = 0 To ar.Count-1 sb.Append(ar(n)) If n <>

Asc(string)
Converts the first letter in the passed string to ANSI code.
Avg(field expr [,scope])
Returns the average value of the grouped field. Returns decimal if the argument type is decimal, otherwise double.

CBool(object)
Converts the passed argument to Boolean.

CByte(string)
Converts the passed argument to Byte.

CCur(string)
Converts the argument to type Currency (really Decimal).

Choose(number, expr1, expr2, ... exprn
Evaluates the number and return the result of the coorespodning exprn. For example, if number results in 3 then expr3 is returned.

CDate(string)
Converts a string to type DateTime

CDbl(object)
Converts the passed parameter to double.

Chr(int)
Converts the specified ANSI code to a character.

CInt(object)
Converts the argument to integer.

CLng(object)
Converts the argument to long.

Count(field expr [,scope])
Returns the number of values in the grouped field. Null values don't count.

Countrows([scope])
Returns the number of rows in the group.

Countdistinct(field expr [,scope])
Returns the number distinct values in the grouped field. Null values don't count.

CSng(object)
Converts the argument to Single.

CStr(object)
Converts the argument to String.

Day(datetime)
Returns the integer day of month given a date.

First(field expr [,scope])
Returns the first value in the group.

Format(string1 [,string2)
Format string1 using the format string2. Some valid formats include '#,##0', '$#,##0.00', 'MM/dd/yyyy', 'yyy-MM-dd HH:mm:ss'... string2 is a .NET Framework formatting string.

Hex(number)
Returns the hexadecimal value of a passed number.

Hour(datetime)
Returns the integer hour given a date/time variable.

Iif(bool-expr, expr2, expr3
The Iif function evaluates bool-expr and when true returns the result of expr2 otherwise the result of expr3. expr2 and expr3 must be the same data type.

InStr([ioffset,] string1, string2 [,icase])
1 based offset of string2 in string1. You can optionally pass an integer offset as the first argument. You can also optionally pass a 1 as the last argument if you want the search to be case insensitive.

InStrRev(string1, string2[,offset[,case]])
1 based offset of string2 (second argument) in string1 (first argument) starting from the end of string1. You can optionally pass an integer offset as the third argument. You can also optionally pass a 1 as the fourth argument if you want the search to be case insensitive.

Last(field expr [,scope])
Returns the last value in the group.

LCase(string)
Returns the lower case of the passed string.

Left(string)
Returns the left n characters from the string.

Len(string)
Returns the lenght of the string.

LTrim(string)
Removes leading blanks from the passed string.

Max(field expr [,scope])
Returns the maximum value in the group.

Mid
Returns the portion of the string (arg 1) denoted by the start (arg 2) and length (arg 3).

Min(field expr [,scope])
Returns the minimum value in the group.

Minute(datetime)
Returns the integer minute given a date/time variable.

Month(datetime)
Returns the integer month given a date.

MonthName(datetime)
Get the month name given a date. If the optional second argument is 'True' then the abbreviated month name will be returned.

Next(field expr [,scope])
Returns the value of the next row in the group.

Oct(number)
Returns the octal value of a specified number.

Previous(field expr [,scope])
Returns the value of the previous row in the group.

Replace
Returns a string replacing 'count' instances of the searched for text (optionally case insensitive) starting at position start with the replace text. The function form is Replace(string,find,replacewith[,start[,count[,compare]]]).

Right(string, number)
Returns a string of the rightmost characters of a string.

Rownumber()
Returns the row number.

RTrim(string)
Removes trailing blanks from string.

Runningvalue(field expr, string1 [,scope])
Returns the current running value of the specified aggregate function. string1 is an expression returning one of the following aggregate function: "sum", "avg", "count", "max", "min", "stdev", "stdevp", "var", "varp".

Second(datetime)
Returns the integer second given a date/time variable.

Space(number)
Returns a string containing the number of spaces requested.

Stdev(field expr [,scope])
Returns the standard deviation of the group.
Stdevp(field expr [,scope])
Returns the standard deviation of the group. Use stdevp instead of stdev when the group contains the entire population of values.

StrComp(string1, string2, compare)
Compares the strings; optionally with case insensitivity. When string1 < string1 =" string2:"> string2: 1

String(number, char)
Return string with the character repeated for the length.

StrReverse(string)
Returns a string with the characters reversed.

Sum(field expr [,scope])
Returns the total of the group.

Switch(bool-expr, result1 [, bool-expr-n, result-n])
The arguments are pairs of expression. When the bool-expr is true the result is returned. bool-expr-n is evaluated until one is results in true then the cooresponding result-n expression is returned.

Today()
Return the current date/time on the computer running the report.

Trim(string)
Removes whitespace from beginning and end of string.

UCase(string)
Returns the uppercase version of the string.
Var(field expr [,scope])
Returns the variance of the group.

Varp(field expr [,scope])
Returns the variance of the group. Use varp instead of var when the group contains the entire population of values.

Year(datetime)
Obtains the year from the passed date.

Weekday()
Returns the integer day of week: 1=Sunday, 2=Monday, ..., 7=Saturday given a date.

WeekdayName(iday [,abbr])
Returns the name of the day of week given the integer Weekday. The optional second argument will return the abbreviated day of week if 'True'.

Thursday, July 5, 2012

Prevent site from opening in IE8/9 compatibility mode when user has website in intranet zone.


Introduction
              
 In this article i will show you how to override the compatibilty mode in intranet.

Just you have to add following in web.config file.

<system.webServer>
<httpProtocol>
  <customHeaders>
    <clear />
    <add name="X-UA-Compatible" value="IE=edge" />
  </customHeaders>
</httpProtocol>
........................
....................

</system.webServer>

you have to just add the <httpProtocol>....</httpProtocol> tag as mentioned above  between <system.webserver> tage in web.config file

Sunday, July 1, 2012

Ajax SlideShow Example/Sample in c#


Introduction:

             Today I am going to show you the very useful sample and that is Slide show.I am showing you how to show slideshow using ajax.After Saving the images into the Folder we will going to use that images in Slide Show.

First you have to add ajax toolkit to your Project by adding a reference.

Then add a webpage Default.aspx to your project.and also make one folder name Images into project and put some images into the folder.

Default.aspx Page

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>AJAX Slidshow  Example</title>
    <style type="text/css">
        .Buttoncss
        {
            border: solid 1px #c0c0c0;
            background-color: silver;
            color: #ffffff;
            cursor: pointer;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <ajax:ToolkitScriptManager ID="scriptmanager1" runat="server">
    </ajax:ToolkitScriptManager>
    <div>
        <table style="border: Solid 3px green; width: 400px; height: 400px" cellpadding="0"
            cellspacing="0">
            <tr style="background-color: #33CC33">
                <td style="height: 10%; color: White; font-weight: bold; font-size: larger" align="center">
                    <asp:Label ID="lblTitle" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Image ID="imgslides" runat="server" Height="400px" Width="600px" />
                </td>
            </tr>
            <tr>
                <td align="center">
                    <asp:Label ID="lblimgdesc" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td align="center">
                    <asp:Button ID="btnPrevious" runat="server" Text="Prev Image" CssClass="Buttoncss" />
                    <asp:Button ID="btnPlay" runat="server" Text="Play" CssClass="Buttoncss" />
                    <asp:Button ID="btnNext" runat="server" Text="Next Image" CssClass="Buttoncss" />
                </td>
            </tr>
        </table>
        <ajax:SlideShowExtender runat="server" AutoPlay="true" ImageTitleLabelID="lblTitle"
            ImageDescriptionLabelID="lblimgdesc" Loop="true" NextButtonID="btnNext" PreviousButtonID="btnPrevious"
            PlayButtonID="btnPlay" PlayButtonText="Play" StopButtonText="Stop" TargetControlID="imgslides"
            SlideShowServicePath="Slideshow.asmx" SlideShowServiceMethod="GetSlides">
        </ajax:SlideShowExtender>
    </div>
    </form>
</body>
</html>

Now you have to Add the webservice by right click on project and Add the Item Webservice called SlideShow.asmx then remove the SlideShow.asmx.cs file just keep SlideShow.asmx and put the class file of it in App_Code Folder.for that you have to create App_Code Folder by right click on Project And add the Folder and add the SlideShow.cs file in it.


PlayButtonID - ID of the button that will allow you to play/stop the slideshow.

PlayButtonText - The text to be shown in the play button to play the slideshow.

StopButtonText - The text to be shown in the play button to stop the slideshow.

PreviousButtonID - ID of the button that will allow you to see the previous picture.

NextButtonID - ID of the button that will allow you to see the next picture.


PlayInterval - Interval in milliseconds between slide transitions in play mode.

ImageTitleLabelID - ID of Label displaying current picture's title.

ImageDescriptionLabelID - ID of Label describing current picture.

Loop - Setting this to true will allow you to view images in a round-robin Pattern.

AutoPlay - Setting this to true will play the slideshow automatically on render.

SlideShowServicePath - Path to the webservice that the extender will pull the images from.

SlideShowServiceMethod - The webservice method that will be called to supply images


Here we need to remember one point that is we need to write webmethods like following Pattern.

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public AjaxControlToolkit.Slide[] GetSlides()
{
……
……
}
Here I have used the .Buttoncss for Next,Previous and Play Button

SlideShow.cs Page Code 

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]

public class Slideshow : System.Web.Services.WebService
{

    public Slideshow()
    {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public AjaxControlToolkit.Slide[] GetSlides()
    {
        string[] imagenames = System.IO.Directory.GetFiles(Server.MapPath("~/Images"));
        AjaxControlToolkit.Slide[] photos = new AjaxControlToolkit.Slide[imagenames.Length];
        for (int i = 0; i < imagenames.Length; i++)
        {
            string[] file = imagenames[i].Split('\\');
            photos[i] = new AjaxControlToolkit.Slide("Images/" + file[file.Length - 1], file[file.Length - 1], "");
        }
        return photos;
    }
}

SlideShow.asmx code

<%@ WebService Language="C#" CodeBehind="~/App_Code/Slideshow.cs" Class="Slideshow" %>

In SlideShow.asmx Page CodeBehind Specify the class file SlideShow which we put in App_Code folder and in that all the Logic of slide show is there.

string[] imagenames = System.IO.Directory.GetFiles(Server.MapPath("~/Images"));  //This will Fetch all the Images from the Images Folder
        AjaxControlToolkit.Slide[] photos = new AjaxControlToolkit.Slide[imagenames.Length];
//This will store the all the photos in photos object.

        for (int i = 0; i < imagenames.Length; i++)
        {
            string[] file = imagenames[i].Split('\\');
            photos[i] = new AjaxControlToolkit.Slide("Images/" + file[file.Length - 1], file[file.Length - 1], "");
        }
        return photos;

This Loop will rounded by number of Images.Photos[i] contains images information.Name,ImagePath and its Description.

new AjaxControlToolkit.Slide("Images/" + file[file.Length - 1], file[file.Length - 1], "");
This contains three parameter.
1.Image Path
2.Image Name
3.Image Description.Here I just pass Empty string in Image Description but you can pass this Parameter.


Download the Sample Code from Here
 Download