Thursday, December 21, 2017

Secure you Asp .NET by Web.config & Global.ascx?

Add to Global.ascx

protected void Application_BeginRequest(object sender,EventArgs e)

    {

        //to remove x frame
        Response.AddHeader("X-Frame-Options", "DENY");
        var application = sender as HttpApplication;
        if (application != null && application.Context != null)
        {
        //to remove server header like iis 8.5
        application.Context.Response.Headers.Remove("Server");
        }
    }

Add to Web.Config

<system.webServer>


  <!--this section will add / remove the headers from Response-->
<httpProtocol>

   <customHeaders>
   <add name="Content-Security-Policy" value="default-src https: data: 'unsafe-inline' 'unsafe-eval'" />
   <add name="X-Content-Type-Options" value="nosniff" />
   <add name="X-XSS-Protection" value="1; mode=block" />
   <!-- avoid clickjacking-->
   <add name="X-Frame-Options" value="SAMEORIGIN" />
   <!--will remove header like ASP .NET version-->
   <remove name="X-Powered-By"/>
   </customHeaders>
</httpProtocol>



<security >

     <requestFiltering>
      <!--will not allow below http methods in application-->
      <verbs>
        <add verb="TRACE" allowed="false" />
        <add verb="HEAD" allowed="false" />
        <add verb="OPTIONS" allowed="false" />
      </verbs>        
      </requestFiltering>
</security>



</system.webServer>


Add to Web.Config

  <system.web>

 <customErrors mode="On" defaultRedirect="~/WebPagesError/ErrorPage.aspx"  >
       
    </customErrors>

    <!--Encrypt ViewState  -->
    <pages viewStateEncryptionMode="Always" validateRequest="true" enableViewState="true" enableViewStateMac="true"  controlRenderingCompatibilityVersion="3.5"/>
    
    
    <!--request should be httponly -->
    <httpCookies httpOnlyCookies="true"  />

    <!--preventing response to give system info like iis/asp .net etc  -->
    <httpRuntime enableVersionHeader="false" />
    <machineKey validation="3DES"/>
    

  </system.web>



SessionID Validation?

Step 1:


 protected void Page_Load(object sender, EventArgs e)
    {


if (!IsPostBack )
        {          
            #region for session validation
            Guid guid = Guid.NewGuid();
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
                {
                    HttpCookie cookie = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"];
                    cookie.Value = guid.ToString();
                    HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-2.0);
                    HttpContext.Current.Request.Cookies.Remove("ASP.NET_SessionId");
                    HttpContext.Current.Request.Cookies.Add(cookie);
                }
            }
}

Step 2:  Add to Global.ascx  

if you have any logout button then add it to Button Click event to remove session. otherwise only add this section to Global.ascx




 void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

        Session.Clear();
        Session.Abandon();
        Guid guid = Guid.NewGuid();

        if (HttpContext.Current != null)
        {
            if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
            {
                string text1 = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value;
                HttpCookie cookie = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"];
                cookie.Value = guid.ToString();
                HttpContext.Current.Request.Cookies.Set(cookie);
                string text2 = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value;
            }
            if (HttpContext.Current.Response.Cookies["ASP.NET_SessionId"] != null)
            {
                HttpCookie cookie2 = HttpContext.Current.Response.Cookies["ASP.NET_SessionId"];
                cookie2.Value = guid.ToString();
                HttpContext.Current.Response.Cookies.Set(cookie2);
                string text3 = HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Value;
            }
            HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-2.0);
            HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-2.0);
        }


    }

Prevent CSRF attack?


public partial class MasterPage : System.Web.UI.MasterPage
{

Step 1:

    #region CSRF Prevention 
    private const string AntiXsrfTokenKey = "__AntiXsrfToken";
    private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
    private string _antiXsrfTokenValue;
    
    protected void Page_Init(object sender, EventArgs e)
    {
        //First, check for the existence of the Anti-XSS cookie
        var requestCookie = Request.Cookies[AntiXsrfTokenKey];
        Guid requestCookieGuidValue;

        //If the CSRF cookie is found, parse the token from the cookie.
        //Then, set the global page variable and view state user
        //key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad
        //method.
        if (requestCookie != null   && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
        {
            //Set the global token variable so the cookie value can be
            //validated against the value in the view state form field in
            //the Page.PreLoad method.
            _antiXsrfTokenValue = requestCookie.Value;

            //Set the view state user key, which will be validated by the
            //framework during each request
            Page.ViewStateUserKey = _antiXsrfTokenValue;
        }
        //If the CSRF cookie is not found, then this is a new session.
        else 
            //if(requestCookie==null)
        {
            //Generate a new Anti-XSRF token
            _antiXsrfTokenValue = Guid.NewGuid().ToString("N");

            //Set the view state user key, which will be validated by the
            //framework during each request
            Page.ViewStateUserKey = _antiXsrfTokenValue;

            //Create the non-persistent CSRF cookie
            var responseCookie = new HttpCookie(AntiXsrfTokenKey)
            {
                //Set the HttpOnly property to prevent the cookie from
                //being accessed by client side script
                HttpOnly = true,

                //Add the Anti-XSRF token to the cookie value
                Value = _antiXsrfTokenValue
            };

            //If we are using SSL, the cookie should be set to secure to
            //prevent it from being sent over HTTP connections
            if (FormsAuthentication.RequireSSL &&    Request.IsSecureConnection)
                responseCookie.Secure = true;

            //Add the CSRF cookie to the response
            Response.Cookies.Set(responseCookie);
        } 
    }   
    #endregion

Step 2:

  protected void Page_Load(object sender, EventArgs e)
    {
        #region CSRF
        //During the initial page load, add the Anti-XSRF token and user
        //name to the ViewState
        if (!IsPostBack)
        {
            //Set Anti-XSRF token
            ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;

            //If a user name is assigned, set the user name
            ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
        
        }
       
        //During all subsequent post backs to the page, the token value from
        //the cookie should be validated against the token in the view state
        //form field. Additionally user name should be compared to the
        //authenticated users name
        else
        {
            //Validate the Anti-XSRF token
            if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
            {
                throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
            }
        }



Tuesday, November 28, 2017

Linq To SQL Grouping & Joining & ( ? , : ) operators?




Grouping of Lists:


 var list = ssrsObj.GetData();

        var g=from p in list
              group p by  new {login= p.login, Name= p.Name} into grp
              select new 
              {
                 AssigneeLogin=grp.Key.login,
                 AssigneeName=grp.Key.Name,
                 IncCounts=grp.Count()
              };

Joining Two Lists:


var joinList = from p in list1
                    join q in list2
                    on p.AgentLogin.ToLower() equals q.AssigneeLogin.ToLower() into grp
                    from x in grp.DefaultIfEmpty()
                    select new  
                    {
                       //  below statement shows if value x is null replace it with other value
                      //  p == null ? 10 : p.CCounts
                      //  ?  mark says that if p == null ? then assign x == 10 where x== p.CCounts
                                                    
                        ssrslogin  = x  ==   null   ? p.AgentLogin : x.AssigneeLogin ,
                        ssrsname   = x == null ? p.AgentName : x.AssigneeName,
                        ssrscount  = x  ==  null ? 0 : x.ICounts,


                        calllogin = p == null ? x.AssigneeLogin : p.AgentLogin,
                        callname = p == null ? x.AssigneeName : p.AgentName,
                        callcount  = p == null ? 0 : p.CCounts,                                              

                    };

Tuesday, November 14, 2017

How to Prevent Asp .Net Button double click to store one record at a time ?

For Asp .Net Button Click

<asp:Button
 id="abc" 
runat="server"
UseSubmitBehavior="false"                                       

OnClientClick="this.disabled='true';this.value='Please Wait...';"
asp:Button/>


For Asp .Net Image Button

<asp:ImageButton 
id="abc" 
ImageUrl="..."
runat="server"
/>

Put below code in page load for specific button:


protected void Page_Load(object sender, EventArgs e)
{
abc.Attributes.Add("onclick","this.disabled='true';"   +ClientScript.GetPostBackEventReference(abc,null) +";this.src='Images/wait.png'  ; ");
}

Tuesday, September 19, 2017

6 Days of Allah ?



Allah said in Quran that HE create this univers in 6 days and earth in 2 days.


Here is proof:


Quranic Age of Universe and Earth:
Universe Age : 6 days
Earth Age: 2 days
2/6 = 1/3 = 0.33

Scientific Age of Universe and Earth:
Universe Age : 13.7 billion years
Earth Age: 4.57 billion years
4.57 / 13.7   = 1 / 3 = 0.33 

Allah 1 day is not same as Earth 1 day:

Theory of Relative by Albert Einstien
If the object is bigger, then time pass slowly like if you are near pyramids the time will pass slowly than some far from pyramids.
or
If you are near very big object like black hole and spend 5 years then come back to earth you will find 10 years are passed on earth.


Allah is the Greatest of everything ( Allahu Akbar  Ø§Ù„له أكبر ) in this Universe so time near Allah is very slowly passed than Earth time so  by the scientific query we can easily find the time of Allah one day which can be or cannot be exact.  ( Allah knows best  Ø§Ù„له اعلم)

13.7 billion years of earth = 6 days of Allah

13.7 / 6 = 2.28 billion years of earth = 1 day of Allah. (May be or may not be ) 



Monday, September 18, 2017

How to Run Powershell Script using C#?






Step1: Add System.Management.Automation.dll to project.

this is normaly not available so download it.

public string RunPowerShell()

{



Runspace runspace = RunspaceFactory.CreateRunspace();


//Opening Powershell RunSpace
runspace.Open();

//Opening pipeline to pass the powershell script
Pipeline pipeline = runspace.CreatePipeline();

//sending commands 
pipeline.Commands.AddScript(@"Get-ADUser  -Filter * -Properties displayName,mail,samaccountname,title,department,company,l,co,mobile,facsimileTelephoneNumber,manager,extensionAttribute2,extensionAttribute4,EmployeeType,canonicalName,enabled | select displayName,mail,samaccountname,title,department,company,l ,co,mobile,facsimileTelephoneNumber,manager,extensionAttribute2,extensionAttribute4,EmployeeType,canonicalName,enabled ");

//ending the script
pipeline.Commands.Add("Out-String");

//Creating PoweShell Object for result
Collection<PSObject> results = pipeline.Invoke();

//Closing Powershell RunSpace
runspace.Close();

StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
  {
    stringBuilder.AppendLine(obj.ToString());
  }
return stringBuilder.ToString();

}

Wednesday, July 12, 2017

How to Upload a Photo using Asp .Net File Upload?






Step 0:


Add <img src="defaultpic.jpg" runat="server" id="imgSoftLogo" width="50" height="50">




Step 1: On Upload Image Click Event



 protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
           // checking the file exists in <asp:FileUpload>
            if (btnFileUpload.HasFile == true  )
            {          
               // acceptable extentions
                List<string> extentions = new List<string> { ".jpg", ".gif", ".png" };

                // if file extention exists in acceptable extention
                if (extentions.Contains(  Path.GetExtension(btnFileUpload.FileName).ToLower()))
                {                                                  

                   // get the directory path complete path to save image into asp .net web folder
                    String filePath = Server.MapPath(@"~/SoftwareImages/" + btnFileUpload.FileName);
                   // saving the pic to folder
                   btnFileUpload.SaveAs(filePath);
                                     
                    // converting the pic 
                    image_base64String = ConvertImageTo_base64String(filePath);

                   imgSoftLogo.Src = @"data:image/gif;base64," + image_base64String;

                    Session["image"] = image_base64String;
                 
                }
                           
            }

        }
        catch (Exception ex) {  }
    }      


Step 2: Add Function to convert the File to image_base64String;


public string ConvertImageTo_base64String(string path)
    {
        using (System.Drawing.Image image = System.Drawing.Image.FromFile(path))
        {
            using (MemoryStream m = new MemoryStream())
            {
                image.Save(m, image.RawFormat);
                byte[] imageBytes = m.ToArray();
                image_base64String = Convert.ToBase64String(imageBytes);
            }
        }
        return image_base64String;

    }
    public string image_base64String { get; set; }


Step 3: Once Uploaded the pic will display on <Img> then save it to database.

database column is SoftwareImage

software.SoftwareImage = Session["image"].ToString();


Step 4: On Page Load

get the stored picture from database in string format and display it on page load.

1) loading from database if existed
imgSoftLogo.Src = @"data:image/gif;base64," + software.SoftwareImage;

2) if we are updating a new software and we have not updated the image yet and we also do not need to update the image so we will do the followings

// take the defaultpic.jpg

 string path = Server.MapPath(imgSoftLogo.Src);
 image_base64String = ConvertImageTo_base64String(path);
Session["image"] = image_base64String;








Sunday, April 23, 2017

How to Claim Accident in KSA?



May Allah protects you,


If you have car accident in KSA you should follow below steps to make your insurance claim.

Step 1:
Call Najm (9200 00560) and describe how accident was happen Najm will make his analysis and give you a paper narrating how many percent is your or 2nd party fault for the accident.


Step 2:
Take the car to workshop and get 3 quotation of labor cast of the car and parts needed.

Step 3:
Go to your carmaker service center and make quotation of parts.

Step 4:
Go to your bank, get the IBAN number on paper, and stamp by your bank.

Step 5:
Submit all papers to Najm, Najm will submit these papers to Insurance Company and wait for approval then repair your car.


Note:
Never Ever fix your car before Insurance approval (sometime insurance company send someone to re-check the car).
No need to go to Maroor (Traffic Police) for stamp.
No need to go to Insurance Company by yourself.

Thursday, March 9, 2017

Best Things for Hair and Skin

Good things for Hair, Skin


Name
Use For
Axiol Oil

Hair
Miracle cream for night

Skin
Tretinoin cream for baldness

Hair
Minoxidil (5% for men and 2% for women) daily at night

Hair

Best Recipe for Hair

Best Recipe for Hair


Name
Quantity
Details
Mustard Oil
1 Pao
Put it in pan on stove
Onion
1 Onion
Small Pcs
Methi Dana
1 table spoon
Grains
Carrot or Beet Root
1 Carrot
Small Pcs
Lemon
1 whole
With grain and Skin

How to make and use?

:: Put oil in a pan on stove when heated add all ingredients. Heat it for  5-7 minute.  Once cold, strain it. Use it daily. 

:: use it for 15 days and result will be good.


Link: youtube.com Sanam Bloach (The Morning Show) program 8 MAR 2017.

Secure you Asp .NET by Web.config & Global.ascx?

Add to Global.ascx protected void Application_BeginRequest(object sender,EventArgs e)     {         //to remove x frame         Resp...