Posts Tagged ‘Asp.Net’

Make IIS application

If You want to make an application that mange An IIS Virtual paths or application a very Good Reference will be at that link Mange IIS

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Html To JavaScript

If you want to render an html using some java script this link will be very useful to you Java To html

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Save Current Context

 

using (new Impersonator2(UserName, Environment.UserDomainName, Password)) 

 

{ 

    GenericPrincipal ContextIdentity = new GenericPrincipal(WindowsIdentity.GetCurrent(), null); 

 

    System.Web.HttpContext.Current.User = ContextIdentity; 

 

    Response.Redirect(Url);

 }

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Impersonator

public class Impersonator : IDisposable
    {
        #region Public methods.
        // ——————————————————————

        /// <summary>
        /// Constructor. Starts the impersonation with the given credentials.
        /// Please note that the account that instantiates the Impersonator class
        /// needs to have the ‘Act as part of operating system’ privilege set.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        public Impersonator2(
            string userName,
            string domainName,
            string password)
        {
            ImpersonateValidUser(userName, domainName, password);
        }

        // ——————————————————————
        #endregion

        #region IDisposable member.
        // ——————————————————————

        public void Dispose()
        {
        }

        // ——————————————————————
        #endregion

        #region P/Invoke.
        // ——————————————————————

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern int LogonUser(
            string lpszUserName,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int DuplicateToken(
            IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool CloseHandle(
            IntPtr handle);

        private const int LOGON32_LOGON_INTERACTIVE = 2;
        private const int LOGON32_PROVIDER_DEFAULT = 0;

        // ——————————————————————
        #endregion

        #region Private member.
        // ——————————————————————

        /// <summary>
        /// Does the actual impersonation.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        private void ImpersonateValidUser(
            string userName,
            string domain,
            string password)
        {
            WindowsIdentity tempWindowsIdentity = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUser(
                        userName,
                        domain,
                        password,
                        LOGON32_LOGON_INTERACTIVE,
                        LOGON32_PROVIDER_DEFAULT,
                        ref token) != 0)
            
60;       {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            impersonationContext = tempWindowsIdentity.Impersonate();
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CloseHandle(tokenDuplicate);
                }
            }
        }

        /// <summary>
        /// Reverts the impersonation.
        /// </summary>
        private void UndoImpersonation()
        {
            if (impersonationContext != null)
            {
                impersonationContext.Undo();
            }
        }

        private WindowsImpersonationContext impersonationContext = null;

        // ——————————————————————
        #endregion
    }

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Object Serialize TO Xml

Two Functions to Serialize and detribalize any objects to and from xml

 

 

private string Serialize(object obj) 

{ 

     if (obj == null) { return null; }

     XmlSerializer s = new XmlSerializer(obj.GetType()); 

     TextWriter w = new StringWriter(); 

     s.Serialize(w, obj); 

     w.Close();

     return w.ToString(); 

}

 

 

public static object Deserialize(Type type, string xml) 

{ 

 

 if (string.IsNullOrEmpty(xml)) 

 { 

     return Activator.CreateInstance(type); 

 } 

 

    XmlSerializer s = new XmlSerializer(type); 

    TextReader tr = new StringReader(xml); 

    return s.Deserialize(tr); 

}

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Create JavaScript From Code Behind

After You Create your JavaScript String In The Code Behind  go to the page load event and this to register the JavaScript to your page

Page.RegisterStartupScript("ScriptString", ScriptString);

 

as I said in my last post some times the id you assign for a control is not always the actual id given to it on the client side

so if you are making JavaScript and using controls id make sure to use control.ID

To change an html

document['docimagename'].src = '/images/imagename.gif'

docimagename is the name attribute of the image

Hide Control

document.getElementById('ControlID').style.visibility = 'hidden';

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Create Controls From Code Behind

I was Creating control that had fields created dynamically according to data passed

and according to the controls created some java scripts need to be added with them

and here are some tips I learned

the id you assign to the control in runtime some times is not the actual id of the control in the html client side code specially when this control created inside A Custom User Control..

So in order to get the actual client side control id to use it in JavaScript code use Control.ClientID to get it.

if you added an html control that runat server  in a Custom user control

this html control wont appear in the C# code behind code unless you add some thing like that.

protected global::System.Web.UI.HtmlControls.HtmlGenericControl MainDiv;

To render html code in a div that run at server use the following

MainDiv.InnerHtml = HtmlString;

 

you can create asp control and render it into html string using

StringWriter sw = new StringWriter();

control.RenderControl(new HtmlTextWriter(sw));

MainDiv.InnerHtml = sw.ToString();

 

How ever if the rendered asp control have some event handlers

those handlers wont be invoked for some strange reason I didn’t find out it yet.

 

but you can create controls with event handlers in other way by

using System.Web.UI.WebControls.Table;

usingSystem.Web.UI.WebControls.TableRow;

using System.Web.UI.WebControls.TableCell;

 

 

and finally after creating the control from code behind add it the controls of the cell …

TableCell.controls.add(control);

TableRow.cells.add(TableCell);

Table.Rows.add(TableRow);

 

some Times you need to add some tags like style and things like that to the control this can done using

Control.Attributes.add(StringKey,StringValue);

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Cancel Validation

some times when you are using the asp Validations and want to add cancel button to form

when this button is clicked the from is supposed to cancel all the registration operation still the required field validation shows up asking for a field value

Solution : set the Cancel button Property Cause validation to False

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

ASP Authenticates from your Database

If your application is using Forms Authentication and you want all the asp users and roles to be stored on your project database so that all your data are stored on one single database.

You can do that using aspnet_regsql Tool

Steps:

Open up the Visual Studio Command Prompt under VS Tools on the programs menu and in the command window type “aspnet_regsql”

A windows dialog will appear for you

image

Choose the “Configure SQL Server for application services” option and then select your machine name and the Database name for the database. This will create a bunch of database tables in the project database in order to manage users and profile information

 

Add a connection Strings section that maps to the project database . Ensure the section is nested under the Configuration element in the web.config file. It should look like the following:

 

   1: <connectionStrings>

   2:  

   3: <add name="MyLocalSqlServer"  connectionString="server=localhost; Integrated Security=SSPI; Database=DatabaseName" providerName="System.Data.SqlClient" />

   4:  

   5: </connectionStrings>

   6:  

Next, add the following provider entries for both the membership and role providers to the web.config file. These entries need to be listed under the System.Web element.

 

<!--Added Membershipprovider-->

 

<membership defaultProvider="AspNetSqlMembershipProvider">

 

<providers>

 

<remove name="AspNetSqlMemberShipProvider" />

 

<add name="AspNetSqlMembershipProvider" connectionStringName="MyLocalSqlServer" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />

 

</providers>

 

</membership>

 

<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">

 

<providers>

 

<remove name="AspNetSqlRoleProvider" />

 

<add connectionStringName="MyLocalSqlServer" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

 

</providers>

 

</roleManager> 

<!--End Added provider-->

 

The last step is to add your project users to the asp tables added to the database

if your users are static users you can add them using the WAT tool choose “Website->ASP .NET Configuration” from the menu bar and in the security section add the static users

 

if your project users are added/deleted/modified according to project scenario

 

You will need to take a look on the added asp stored procedures to your database and use them to do the task….

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

Sending Sms using Web service

Most of the time when you need your application to send SMS to users
You buy a URL service where you fill the parameters in the url and call it to send the SMS

But here the problem appears! , the problem is you don’t want the end user to see the called URL with all the parameters and the company password in it…
Because he can use this URL later on to send his own personal SMS !

So I have created a Web service that can send the SMS without showing up the called page.

 

[WebMethod]

public bool SendSms(string Msg,string Mobile)

{

   try

   {

     String getUri = "http://ServiceIP/

     user = CompanyUserAccount&password=CompanyPassword&PhoneNumber="

     + Mobile + "&Text=" + Msg + "&Sender=SenderName";

     WebRequest request = (WebRequest)WebRequest.Create(getUri);

     HttpWebResponse response = (HttpWebResponse)request.GetResponse();

     StreamReader responseReader = new StreamReader(response.GetResponseStream());

     String resultmsg = responseReader.ReadToEnd();

     responseReader.Close();

     return true;

  }

  catch (Exception)

  {

    return false;

  }

} 

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
 

 

View Abdel-Rahman Awad's profile on LinkedIn

Archives

 

Rss Feed Tweeter button Facebook button Linkedin button Delicious button Digg button