Friday, August 14, 2015

Github installation An error occurred trying to DOWNLOAD 'http://github-windows.s3.amazonaws.com/GitHub.application'.

When I was downloading the Github for desktop I ran into an error. I am using Windows 10 In the first place I downloaded the GitHubSetup.exe file from GitHub.com and when I tried to install it, it said

An error occurred trying to download 'http://github-windows.s3.amazonaws.com/GitHub.application'.


I tried to download it directly from 'http://github-windows.s3.amazonaws.com/GitHub.application' but it could not download again and I stuck in following error

Application cannot be started. Contact the application vendor.


I googled around the internet and most suggestions were to delete the folder 2.0 which is located at
%LocalAppData%\Apps.
I did that again but it didn’t work.

Solution: (Some steps might not be required, I am only specifying the sequence of activities I did)

  1. Disabled the windows firewall
  2. Disabled antivirus
  3. Now I went to turn windows features on and off. In windows you can find it at the left of the control panel. But in Windows 10, I ran to C:\Windows\System32\OptionalFeatures.exe
  4. I selected all the check box associated with .NET framework, which asked me to restart the computer which I duly abide.
  5. During restart some settings could not be applied so it reverted back twice.
  6. Now I downloaded the GitHub and it was running fine.


Sunday, June 24, 2012

Restrict File download to unauthorized users

Following code is for allowing only the registered(logged in) users to download files
Step 1: Create a file Handler.ashx and write the following code. Since I am not using form authentication, I am checking the session variables which are set once the user successfully logs in. Please note the implementation of IRequiresSessionState interface, this is because the HttpHandler cannot access session parameters on its own.
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Web.Security; using System.Web.SessionState; public class Handler : IHttpHandler,IRequiresSessionState { public void ProcessRequest (HttpContext context) { try { if (context.Session["user"] != null) { string filename = context.Request.QueryString["File"]; //Validate the file name and make sure it is one that the user may access context.Response.Buffer = true; context.Response.Clear(); context.Response.AddHeader("content-disposition", "attachment; filename=" + filename); context.Response.ContentType = "octet/stream"; context.Response.WriteFile("~/downloads/" + filename); } else context.Response.Redirect("~/Default.aspx"); } catch (NullReferenceException ex) { context.Response.Redirect("~/Default.aspx"); } catch (System.Exception ex) { context.Response.Write(ex.ToString()); } } public bool IsReusable { get { return true; } } }
Step 2: There is a file titled Default.aspx from which users log in into the system and sets the session variable
protected void Button1_Click(object sender, EventArgs e) { //validation related code goes here Session["user"] = "TEST"; Response.Redirect("~/downloads.aspx"); }
Step 3: The html code in downloads.aspx
<a href="Handler.ashx?File=annex8.pdf">Click Here</a>

Further Reading
Here as well

Inheritence in C#, overriding base class

In the following code I am overriding the MasterPage class's onLoad event. What I am doing is, I check whether session variables have been set i.e. if the user has actually logged in into the system. I have created the baseclass titled baseClass.
public class baseClass : System.Web.UI.MasterPage
{
 public baseClass()
 {
  //
  // TODO: Add constructor logic here
  //
 }
    protected override void OnLoad(EventArgs e)
    {
        try
        {
            if (Session["usrPrivilege"].ToString().Equals("ADMIN"))
            {
                base.OnLoad(e);
            }
            else

                Response.Redirect("~/Default.aspx");
        }
        catch (NullReferenceException ex)
        {
            Response.Redirect("~/Default.aspx");
        }
        catch
        {
            base.OnLoad(e);
        }
        
    }
}
Now in the masterpage I wrote the following code, in this way I am sparing the onLoad eventhandler of my masterpage from checking session related information
public partial class Pages_ADMIN_MasterPage :baseClass
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
          
            if (IsPostBack == false)
            {
                //My code goes here
            }
        }
         
        catch (System.Exception ex)
        {
                 //My code for exception handling
        }
    }
}
For further reading you can click here

How to get Type of Exception in C#

Many times we have different ways to handle different kind of errors so we need to know the type of error that has occurred in the system. Here's a simple example in ASP.NET
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["usrPrivilege"].ToString().Equals("USER"))
            {
                //Your Code goes here
            }
        }
        catch (NullReferenceException ex)
        {
            Response.Redirect("~/login.aspx");
        }
        catch (AccessDeniedException ex) 
        {
          //Do something else
        }
        catch (System.Exception ex)
        {
               //Code for other type of exception
        }
    }

Friday, June 22, 2012

ASP.NET textboxes that take only numerical values as input

Following is a javascript code snippet for your ASP.NET test.aspx page. Please note the script checkNumber is for non-decimal numbers while checkNumber is for decimal numbers.


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>User Page</title>
    
    <script language="javascript" type="text/javascript">

function checkNumber(textBox, textEvent )
{
    var  code = textEvent.which; // Netscape Method
    
    if (code == null)
    {
        code = textEvent.keyCode;//IE 4 Method
    }
    
    if(code==13)
    {
    
        
        obj.focus();
        
    }
    if(!((code >= 48 && code <= 57) || (code == 8)))
    {
        return false;
    }
    return true;
}
function checkNumberWithDecimal(textBox, textEvent )
{
    var  code = textEvent.which; // Netscape Method
    if (code == null)
    {
        code = textEvent.keyCode;//IE 4 Method
    }
    if(code==13)
    {
    
        //var obj= getFrmObject(textBox);
        obj.focus();
        
    }
    if(!((code >= 48 && code <= 57) || (code == 8)||(code==46)))
    {
        return false;
    }
    return true;
}

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        <div style="float:left">Registration No</div>
        <div style="float:left"><asp:TextBox ID="txtRegNo" runat="server"></asp:TextBox></div>
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
And following is your code on

Page_Load

protected void Page_Load(object sender,EventArgs e)
{
      txtRegNo.Attributes.Add("OnKeyPress", "javascript:return                                     checkNumber(this,event);");

}     

Reading Excel File in C# dot Net



using System;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using Microsoft.Office.Interop.Excel;




private void Page_Load(object sender,EventArgs e)
{
      operateExcel("C:\\EXCEL.xls");
}
private void operateExcel(string pth)
    {
       
        DataSet dtset = new DataSet("MYEXCEL");
        try
        {
            //lvContent.Items.Clear();
            Workbook wbok = app.Workbooks.Open(pth, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);


            wbok = app.Workbooks.Open(pth, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            //WorksheetClass wshts = (Worksheets)wbok.Worksheets;

            Sheets wshts = wbok.Worksheets;
            Worksheet wsht = (Worksheet)wshts.get_Item(1);
         

            System.Data.DataTable dtbl = new System.Data.DataTable("MYEXCEL");
            dtset.Tables.Add(dtbl);

            DataColumn col = new DataColumn();
         
            col.ColumnName = "COL1";
            dtbl.Columns.Add(col);

            col = new DataColumn();
            col.ColumnName = "COL2";
            dtbl.Columns.Add(col);

            col = new DataColumn();
            col.ColumnName = "COL3";
            dtbl.Columns.Add(col);

           
            for (int i = 2; i < 10000 && wasLastnull < 3; i++)
            {
               
                Range rnge = wsht.get_Range("A" + i.ToString(), "I" + i.ToString());
                System.Array myvalues = (System.Array)rnge.Cells.Value2;
                System.Array vals = (System.Array)rnge.Cells.Value2;
                string a1 = "", a2 = "", a3 = "" ;
                try
                {
                   
                        a1 = vals.GetValue(1, 1).ToString();
                        a2 = vals.GetValue(1, 2).ToString();
                        a3 = vals.GetValue(1, 3).ToString();
                        DataRow dr = dtbl.NewRow();
                        dr["COL1"] = a1.ToString();
                        dr["COL2"] = a2.ToString();
                       dr["COL3"] = a3.ToString();
                      dtbl.Rows.Add(dr);
                       count = count + 1;
                    }

                catch (System.Exception ex)
                {
                    Label1.Text = ex.ToString() + "ERROR";
                }
           }
           
            app.Workbooks.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wsht);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbok);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
             
        }
        catch (System.Exception ex)
        {

        }
    }

Thursday, June 21, 2012

Display div alongside with links on mouse move and hide when mouse moves out

Literally I prefer to use ToolTip text or title attribute when I need to display simple information however many times we need a div element to do the trick to meet our business requirement. I had found following script in some site few months back but I do not remember which but with hope it might help others, I have pasted it here.

  <script type="text/javascript" language="JavaScript">

var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e)
       cX = e.pageX; cY = e.pageY;
}
function UpdateCursorPositionDocAll(e)
    cX = event.clientX; cY = event.clientY;
}
if(document.all) 
    document.onmousemove = UpdateCursorPositionDocAll; 
}
else 
    document.onmousemove = UpdateCursorPosition; 
}
function AssignPosition(d) {
if(self.pageYOffset) {
 rX = self.pageXOffset;
 rY = self.pageYOffset;
 }
else if(document.documentElement && document.documentElement.scrollTop) {
 rX = document.documentElement.scrollLeft;
 rY = document.documentElement.scrollTop;
 }
else if(document.body) {
 rX = document.body.scrollLeft;
 rY = document.body.scrollTop;
 }
if(document.all) {
 cX += rX; 
 cY += rY;
 }
d.style.left = (cX+10) + "px";
d.style.top = (cY+10) + "px";
}
function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d,cnt) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
dd.style.display = "block";
dd.innerHTML=cnt;
}
function ReverseContentDisplay(d) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
if(dd.style.display == "none") { dd.style.display = "block"; }
else { dd.style.display = "none"; }
}
</script>

The div Element

Setting text of the div element in runtime

protected void Page_Load(object sender,EventArgs e)
   {
    string content="I am loaded in runtime ";
    lnk1.Attributes.Add("onmouseover", 
"javascript:return ShowContent('myDiv','" + content + "'); return true;");
   lnk1.Attributes.Add("onmouseout", "javascript:return 
HideContent('myDiv'); return true;");

   }

Adding Controls in Run Time

There are many ways to add controls in runtime in ASP.NET, however the one I love is using the placeholder control. Its easy, you can place it inside the div element or td element of a table and add controls without worrying where the controls will appear inside the page. So add a placeholder inside the div element and add controls. Following code snippet shows you how to add Label Control during runtime

Adding Controls in runtime in C# ASP.NET

protected void Page_Load(object sender, EventArgs e) { addControls(); } protected void addControls(); { for(int i=0;i<5;i++) { Label lbl = new Label(); lbl.ID = "lbl" + app_code + "_" + priv_code; lbl.ToolTip = dsPriv.Tables[0].Rows[j][4].ToString(); lbl.Style.Add("margin-left", "40px"); lbl.Text = dsPriv.Tables[0].Rows[j][3].ToString(); PlaceHolder1.Controls.Add(lbl); LiteralControl lCntrl = new LiteralControl("
"); PlaceHolder1.Controls.Add(lCntrl); } }
and that's it

Tuesday, June 15, 2010

Fileupload inside UpdatePanel

I have a updatepanel in the master-page and fileupload control in the content page where it was not working despite my use of trigger
The I did the following trick
Step 1:
In the code file of the master page I did the following
public void RegisterPostbackTrigger(Control fullPostBack)
{
ScriptManager1.RegisterPostBackControl(fullPostBack);
}
Step 2:
In the HTML code of the content page I had following lines
Step 3:
Inside the page load event of content page I did the following
protected void Page_Load(object sender, EventArgs e)
{
try
{
((ASP.pages_admin_master_master)Page.Master).RegisterPostbackTrigger(btnUpload);

}
catch
{
}
}

Monday, May 24, 2010

IMPORTING EXCEL FILE INTO ASP.NET GRIDVIEW

protected void Button1_Click(object sender, EventArgs e)
{
string xConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("ExcelImport.xls") + ";" +
"Extended Properties=Excel 8.0;";

OleDbConnection objXConn = new OleDbConnection(xConnStr);
string sql = "SELECT * FROM [Salary$]";
OleDbCommand cmd = objXConn.CreateCommand();
cmd.CommandText = sql;
OleDbDataAdapter adpt = new OleDbDataAdapter();
adpt.SelectCommand = cmd;
DataSet ds = new DataSet();
adpt.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();


}

Tuesday, April 6, 2010

Sys.WebForms.PageRequestManagerParserErrorException

I was still getting "Sys.WebForms.PageRequestManagerParserErrorException" error despite trying suggestions in the various website. To place a dummy session did not work as well as I had to put many variables into session and then redirect it to page i.e. I required to use Response.Redirect anyways (Server.Transfer did not work as well). The session variables had to be created after a button "btnFinish" was clicked. I tried following line of code
and actually it worked.

ASP.NET AJAX and Sys.Webforms.PageRequestManagerServerErrorException



Using ASP.NET AJAX extensively in my latest project I've been sporadically running into the Sys.WebForms.PageRequestManagerParserErrorException. It got to the point that I was contemplating ripping out ASP.NET AJAX completely until this known issue had been ironed out. The various causes for this error are mentioned many different places, but for some samples, go here, here, and here.


Quoting from Eilon Lipton's blog posting, this particular exception is very common and can be caused by any one of the following:


  1. Calls to Response.Write():
    By calling Response.Write() directly you are bypassing the normal rendering mechanism of ASP.NET controls. The bits you write are going straight out to the client without further processing (well, mostly...). This means that UpdatePanel can't encode the data in its special format.

  2. Response filters:
    Similar to Response.Write(), response filters can change the rendering in such a way that the UpdatePanel won't know.

  3. HttpModules:
    Again, the same deal as Response.Write() and response filters.

  4. Server trace is enabled:
    If I were going to implement trace again, I'd do it differently. Trace is effectively written out using Response.Write(), and as such messes up the special format that we use for UpdatePanel.

  5. Calls to Server.Transfer():
    Unfortunately, there's no way to detect that Server.Transfer() was called. This means that UpdatePanel can't do anything intelligent when someone calls Server.Transfer(). The response sent back to the client is the HTML markup from the page to which you transferred. Since its HTML and not the special format, it can't be parsed, and you get the error.


The problem was I wasn't doing any of the above (who uses Response.Write in an ASP.NET application these days?) and I was still sporadically encountering the error - a show stopping error I might add. An error that is popped up in a javascript warning box completely undecipherable to the end user leaving an empty/useless/castrated UpdatePanel in its wake. This of course leaves the end user feeling likewise empty/useless/castrated (to say nothing of the developer).


This post here indicates that there is a problem with the RoleMangerModule or any time you set a cookie to the response in an AJAX callback, which can only be solved by doing one of the following:



  1. Disable caching of cookies in the RoleManager. (yuck)

  2. Handle the Application's Error event to clear the error from the Context selectively (eek).

  3. Disable EventValidation in the web form.
    <%@ Page Language="C#" EnableEventValidation="false" %>
    (gulp)


None of the above are entirely reasonable solutions (especially the last two), and the worst part was that my test page was just a simple contact page that did not change/set roles or cookies, or response.write, or set anything in the session, and wasn't receiving any Unicode character input, or even requiring a user to be logged in, or writing anything to the trace, or anything beyond the basics. And still it blew up. But only occasionally.


In order to faithfully reproduce the error, I finally determined that it must have something to do with sessions as it would only occur if the app pool had recycled and all browser windows had been closed. So, based on one of the comments in one of the above posts, even though I'm not touching session on one of the problem pages, I tried a hack in one of the problem page's Page_Load:


Session["FixAJAXSysBug"] = true;


And lo and behold, we're good to go! So even though I am not using Session on the problem page it must be attempting to set the initial session cookie using the Update Panel callback. So the solution is to make sure the initial session is set before any Update Panel callback takes place. How this got through into production is beyond me.


So if you're sporadically encountering the Sys.Webforms.PageRequestManagerServerErrorException, it could be for any of the above reasons or the fact that your dog/cat/stuffed teddy bear is sitting too close to your monitor. But give the last one a try in every page utilizing AJAX if you're using sessions in your application.


UPDATE: If the problem pages aren't even using session, just turn session off for the page:


<%@ Page EnableSessionState="false" ... %>

Or better yet, set it in your base class to always be off, and turn it on for the pages where you need it on.


UPDATE II: Further developments.





Wednesday, May 21, 2008

How to add a textbox inside a gridview

First add a gridview in your page and go to the source view of your page and find the gridview inside which you want to add the textbox and you can insert a code as below (the one in bold blue color) and it will add the textbox into the gridview when it is bound to the database object.

-------------------------------------------------------------
Just below it is the code with which you can access these individual textbox in the different rows.
-------------------------------------------------------------------------------------
for (int j = 0; j < GridView1.Rows.Count; j++)
{
Control cnt;
cnt = GridView1.Rows[j].Cells[3].Controls[1];
cnt = GridView1.Rows[j].FindControl("txtValue");
TextBox txtBx = (TextBox)cnt;
//write your code here to maniupulate the content of textbox



}

Monday, May 12, 2008

How to pass login parameter (username, password) of database to crystal report from code

using CrystalDecisions.Reporting;
using CrystalDecisions.ReportSource;
using CrystalDecisions.Shared;
using CrystalDecisions.Web;
private void displayReport()
{
try
{
CrystalReportViewer1.EnableDatabaseLogonPrompt = false;
ConnectionInfo connInfo = new ConnectionInfo();
TableLogOnInfo tblLogInfo = new TableLogOnInfo();
TableLogOnInfos tblLogInfos = new TableLogOnInfos();
connInfo.UserID = "usrName";
connInfo.Password = "passwd";
connInfo.ServerName = "database";
tblLogInfo.ConnectionInfo = connInfo;
tblLogInfos.Add(tblLogInfo);
CrystalReportViewer1.LogOnInfo = tblLogInfos;
CrystalReportViewer1.EnableParameterPrompt = false;
CrystalReportSource1.ReportDocument.FileName=Server.MapPath ("Reports\\crystNewMain.rpt");
}
Catch
{
}
}

Saturday, May 10, 2008

How to pass parameter to crystal report from ASP.NET

Suppose there is a crystal report which expects parameter id and section. Here’s the code that shows how to pass the parameter through ASP.net
Before this please do not forget to use following namespaces

using CrystalDecisions.Reporting;
using CrystalDecisions.ReportSource;
using CrystalDecisions.Shared;
using CrystalDecisions.Web;

private void displayReport(number id,string section)
{
try
{

CrystalReportViewer1.EnableParameterPrompt = false;
ParameterFields pFields = new ParameterFields();
ParameterField pField1 = new ParameterField();
ParameterField pField2 = new ParameterField();
ParameterDiscreteValue pDisValue1 = new ParameterDiscreteValue();
ParameterDiscreteValue pDisValue2 = new ParameterDiscreteValue();
pField1.Name = "id";
pField2.Name = "section";
pDisValue1.Value = id;
pField1.CurrentValues.Add(pDisValue1);
pFields.Add(pField1);
pDisValue2.Value = section;
pField2.CurrentValues.Add(pDisValue2);
pFields.Add(pField2);
CrystalReportViewer1.ParameterFieldInfo = pFields;
}
Catch
{
}
}

Friday, April 18, 2008

System.Data.OracleClient requires Oracle client software version 8.1.7 or greater

Cause
Security permissions were not properly set when the Oracle 9i Release 2 client was installed on Windows with NTFS. The result of this is that content of the ORACLE_HOME directory is not visible to Authenticated Users on the machine; this again causes an error while the System.Data.OracleClient is communicating with the Oracle Connectivity software from an ASP.NET using Authenticated User privileges.
Solution
To fix the problem you have to give the Authenticated Users group privilege to the Oracle Home directory.

  1. Log on to Windwos as a user with Administrator privileges.
  2. Start Window Explorer and navigate to the ORACLE_HOME folder.
  3. Choose properties on the ORACLE_HOME folder.
  4. Click the "Security" tab of the "Properties" window.
  5. Click on "Authenticated Users" item in the "Name" list.
  6. Uncheck the "Read and Execute" box in the "Permissions" list under the "Allow" column.
  7. Re-check the "Read and Execute" box under the "Allow" column
  8. Click the "Advanced" button and in the "Permission Entries" verify that "Authenticated Users" are listed with permission = "Read & Execute", and Apply To = "This folder, subfolders and files". If not, edit that line and make sure that "Apply To" drop-down box is set to "This folder, subfolders and files". This should already be set properly but it is important that you verify it.
  9. Click the "Ok" button until you close out all of the security properties windows. The cursor may present the hour glass for a few seconds as it applies the permissions you just changed to all subfolders and files.
  10. Reboot, to assure that the changes have taken effect.

Thursday, April 17, 2008

Running a stored procedure from ASP dot net

Suppose there is a procedure
PROCEDURE PRC_VALIDATEUSER(usrName in VARCHAR,usrPwd in VARCHAR,
,usrValid out NUMBER) AS
BEGIN
/*…………*/
END;

Now in C# we write code the following way
Public Boolean validateUser(string pusrname,string pusrpass)
{
Try
{
OracleConnection con = new OracleConnection(appParams.connString);
//instead of appParams.connString use connection string for your database
con.Open();
sql = " begin validateuser(:uName,:uPasswd,:uValid); end;";
OracleParameter p1 = new OracleParameter();
p1.OracleType = OracleType.VarChar;
OracleParameter p2 = new OracleParameter();
p2.OracleType = OracleType.VarChar;
OracleParameter p3 = new OracleParameter();//dept
p3.OracleType = OracleType.Number;
p1.ParameterName = "uName";
p2.ParameterName = "uPasswd";
p3.ParameterName = "uValid";
p1.Value=pusrname;
p2.Value=pusrpass;
OracleCommand cmd = new OracleCommand(sql, con);
cmd.Parameters.Add(p1); cmd.Parameters.Add(p2); cmd.Parameters.Add(p3);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
if(p3.value==1)
return true;
else
return false;
}
Catch(System.exception ex)
{
return false;
}
}