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

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,                                              

                    };

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;








Tuesday, October 4, 2016

How to Query REST API ?



> domain\username:password must be authorize to query to the REST API.
> For POST HttpRequest is content type and use charset=utf-8 to convert.
> For GET HttpRequest is Accept


POST:


Uri address = new Uri(@"https://xx.xx.xx.xx:xxxx/abc/config/anything/");

HttpWebRequest request = WebRequest.CreateDefault(address) as HttpWebRequest;
request.Method = "POST";
request.Headers["Authorization"] = "Basic " + 
Convert.ToBase64String(Encoding.Default.GetBytes(@"domain\username:password"));
request.ContentType = "application/vnd.com.cisco.ise.identity.guestuser.2.0+xml; charset=utf-8";
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });

//Inserting data 

string data="xml data";


byte[] bytes = Encoding.UTF8.GetBytes(data);

request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
  // Send the data.
   requestStream.Write(bytes, 0, bytes.Length);
  requestStream.Close();
 }


Get By Name:


string name="";


Uri address = new Uri(@"https://xx.xx.xx.xx:xxxx/abc/config/anything/name/" +name +" ");


HttpWebRequest request = WebRequest.CreateDefault(address) as HttpWebRequest;

request.Method = "GET";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(@"domain\username:password"));
request.Accept = "application/vnd.com.cisco.ise.identity.guestuser.2.0+xml";
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
       
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string s = reader.ReadToEnd();

}

Get All:


Uri address = new Uri(@"https://xx.xx.xx.xx:xxxx/abc/config/anything/ ");


HttpWebRequest request = WebRequest.CreateDefault(address) as HttpWebRequest;

request.Method = "GET";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(@"domain\username:password"));
request.Accept = "application/vnd.com.cisco.ise.identity.guestuser.2.0+xml";
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
       
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string s = reader.ReadToEnd();

}

            


Monday, October 3, 2016

How to create a web service ?



Step1: Create the Web Service

Open Visual Studio create new web site. File > New >Website

Add an item as Web Service to the project. Webservice.asmx

Now create some web methods 


 [WebMethod]
 public string GetbyId(string name){}


if the response is in Custom Created Class then return that class object as below
 
[WebMethod]
[System.Xml.Serialization.XmlInclude(typeof(Students))]
 public string GetAll(string name){}


Public Class Student
{
public string name{get; set;}
public string rollnumber{get; set;}
}

Step 2: Publishing the Web Service

To publish the web service the procedure is same as publishing the website because as we created the Web Service under Web Site Project.




Sunday, September 18, 2016

FusionChart with C#,Linq,EntiyFramework,Asp .NET,Xml Best Way.



Step1:

-------------------------------------------Page Html-------------------------------------------------------
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>FusionChart Test</title
    <script src="FusionChart/fusioncharts.js" type="text/javascript"></script>
    <script src="FusionChart/fusioncharts.charts.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Literal ID="Literal1" runat="server"></asp:Literal>
   
    </div>
    </form>
</body>
</html>


-------------------------------------------------------------------------------------

Step2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using InfoSoftGlobal;

public partial class FusionChartTest : System.Web.UI.Page
{
  
    Entities ctx = new Entities();

    protected void Page_Load(object sender, EventArgs e)
    {

---------------Getting the required result and save into class-----------------------

        var model = ctx.Table
           
            .Where(o=>o.DateTime.Value.Year==DateTime.Now.Year)

            .GroupBy(o => new
            {
                Month =(int) o.DateTime.Value.Month,
                Year = o.DateTime.Value.Year
            })
            .Select(g => new SomeClass
            {
                Month = g.Key.Month,
                Year = g.Key.Year,
                Value = g.Count()
            })
            .OrderByDescending(a => a.Year)
            .ThenByDescending(a => a.Month)
            .ToList();

         List<SomeClass> list=new List<SomeClass>(model);
-------------------------------------------------------------------------------------



--------------------------Forming the xml to display as chart------------------------

         StringBuilder xmlData = new StringBuilder();

         xmlData.Append("<chart caption='Monthly Unit Sales' xAxisName='Month' yAxisName='Units' showValues='0' formatNumberScale='0' showBorder='1'>");
     
        foreach (var item in list)
       {
         xmlData.AppendFormat("<set label='{0}' value='{1}' />", item.Month + "," + item.Year, item.Value);
       }

        xmlData.Append ( "</chart>"); 
       
        Literal1.Text = InfoSoftGlobal.FusionCharts.RenderChart("FusionChart/Charts/line.swf", "", xmlData.ToString(), "browser_share", "640", "340", false, true);
    }
-------------------------------------------------------------------------------------
  

}

--------------------------------Custom Class to Save the Result----------------------

public class SomeClass
{
    public int Month { get; set; }
    public int Year { get; set; }
    public int Value { get; set; }
}
-------------------------------------------------------------------------------------


Thursday, March 17, 2016

How to Replace 0 with 1 in Linq to Entity ? (Linq if-statement)




Description:
first it is asking column1==0 ? if true 1 will assign to column1  for assignment here use : operator

Basic Example:
column1= = 0 ? 1 : column1

Real Example:

let value1 = Grp.Count(x => x.Column1== "value") == 0 ? 1 : Grp.Count(x => x.hours_to_resolve <= 3 && x.Column1== "value") 
/
 Convert.ToDouble(Grp.Count(x => x.Column1== "value") == 0 ? 1 : Grp.Count(x => x.Column1== "value"))

Sunday, November 29, 2015

Export to Excell GridView / Datatable / Dataset ?


Step 1: add this to Page where GridView exists.


 public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

Step 2: Add this class to Project.


  public class ExportToExcelClass
    {

        public void ExportToExcel(GridView gridview, string TitleforExcel)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.Clear();
            response.Buffer = true;
            response.ClearContent();
            response.ClearHeaders();
            response.Charset = "";
            string FileName = TitleforExcel + "_" + DateTime.Now + ".xls";
            StringWriter strwritter = new StringWriter();
            HtmlTextWriter htmltextwritter = new HtmlTextWriter(strwritter);
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
                    
            gridview.GridLines = GridLines.Both;
            gridview.HeaderStyle.Font.Bold = true;
            gridview.RenderControl(htmltextwritter);
            response.Write(strwritter.ToString());
            response.End();

        }

        public void ExportToExcel(DataSet ds, string TitleforExcel)
        {
            HttpResponse response = HttpContext.Current.Response;

            // first let's clean up the response.object
            response.Clear();
            response.Charset = "";
            string FileName = TitleforExcel + "_" + DateTime.Now + ".xls";
            // set the response mime type for excel
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName);

            // create a string writer
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    // instantiate a datagrid
                    DataGrid dg = new DataGrid();
                    dg.DataSource = ds.Tables[0];
                    dg.DataBind();
                    dg.RenderControl(htw);
                    response.Write(sw.ToString());
                    response.End();
                }
            }
        }

        public void ExportToExcel(DataTable dt, string TitleforExcel)
        {
            HttpResponse response = HttpContext.Current.Response;

            // first let's clean up the response.object
            response.Clear();
            response.Charset = "";
            string FileName = TitleforExcel + "_" + DateTime.Now + ".xls";
            // set the response mime type for excel
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName);

            // create a string writer
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    // instantiate a datagrid
                    DataGrid dg = new DataGrid();
                    dg.DataSource = dt;
                    dg.DataBind();
                    dg.RenderControl(htw);
                    response.Write(sw.ToString());
                    response.End();
                }
            }
        }
    }

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...