If you want to read information related to Hindi essay and Marathi essay and travel , then you must visit this website
Imagination ^ ∞ == Intelligence
Tuesday, May 4, 2021
Thursday, November 13, 2014
if Session is NULL then Close Popup and Redirect Parent window to some location
using JavaScript and Asp.net
VeerKMS='Project home folder name'
if (Session["UserId"]==null)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "opener.location.href ='/VeerKMS/Login.aspx';self.window.close();", true);
return;
}
Display Window Before Closing Current PopUp window
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "setTimeout(function(){window.close();},500);", true);
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Data Saved Successfully.');", true);
Refresh parent window using invisible button from child window
<asp:Button style="display:none" ID="invisibleButton" runat="server" OnClick="RemoveRecordFromGrid" />
<script type="text/javascript" language="javascript">
function WindowClose()
{
var form1=window.opener.document.getElementsByTagName("form")[0];
//alert(form1.ctl00_ctl00_cphMaster_cphkycmaster_invisibleButton);
form1.ctl00_ctl00_cphMaster_cphkycmaster_invisibleButton.click();
window.close();
}
</script>
protected void RemoveRecordFromGrid(object sender, EventArgs e)
{
Refresh_GrdViewAccountDetails();
}
Tuesday, May 27, 2014
Sql Server Tricks and Tips
From Long Hour Thinking Today I got Some Ideas About Dynamic Searching.
When We have to search with Multiple Search Conditions like
select * from Customer where
Name='CustomerNm' and CustNo='CustNO' and
CustID='CustID' and IsActive=1
then we can use it like
declare @SQL Nvarchar(4000);
set @SQL='select * from tbl_suspiciousaccounts where 1=1 ';
if(CustomerNm is not null)
BGEIN
set @SQL=@SQL +' and cutomername= '+ CustomerNM
END
if(CustomerID is not null)
BGEIN
set @SQL=@SQL +' and CustID= '+ CustomerID
END
see that SMART Usage of 1=1 condition;
Update Local Table Using OpenQuery
update D
set D.LongName=L.LONGNAME
from
OPENQUERY(CBSLINKED,'SELECT LONGNAME,PRDACCTID,LBRCODE FROM D009022 ') L
JOIN tbl_SuspiciousAccounts D
ON L.PRDACCTID=D.PrdId and L.LBRCODE=D.LbrCd
where D.LongName is null
set D.LongName=L.LONGNAME
from
OPENQUERY(CBSLINKED,'SELECT LONGNAME,PRDACCTID,LBRCODE FROM D009022 ') L
JOIN tbl_SuspiciousAccounts D
ON L.PRDACCTID=D.PrdId and L.LBRCODE=D.LbrCd
where D.LongName is null
Using Several UNION ALL
( select * from table1
group by ...
order by ...)
UNION ALL
( select * from table2
group by ...
order by ...)
UNION ALL
( select * from table3
group by ...
order by ...)
Note: Always use Bracket is Union All
Use Union All When We have to append Result of several Tables with each others.
Using Scheduler RUN Stored Procedures
Create Following CommandC:\Users\BsgIt>sqlcmd -E -S "BSGIT-PC\SQLEXPRESS2008R2" -d "BIAMLKYC_22April" -Q
"exec PrintMessage"
Then.....
Create the schedule
- Open task scheduler from Start >> Administrative Tools >> Task Scheduler
- Click “Create Basic Task” and enter a relevant name, e.g. Daily SQL Backup
- Under “Triggers” select ‘Daily’ and then choose a time to run the backup.
Try to choose a time when your database traffic is low, typically in the early hours of the morning. Also make sure that it doesn’t overlap with other scheduled tasks like Windows Updates that may reboot the server. - Under “Action” select ‘Start a program’ and browse to the script you created earlier
Note: Same Can be Use For Backup Databases.
Wednesday, April 23, 2014
Java Script Tutors with Asp.net
While Using showModalDialog (window.showModalDialog) of JavaScript
you can close Current Child Window and Refresh Parent Page Using Following:
set location of current window to opener and refresh current window.
This will give Location (URL) of parent window who opened child window.
window.opener.location
function ClickbtnBindGridView()
{
window.opener.location.href = window.opener.location;
window.close();
}
{
window.opener.location.href = window.opener.location;
window.close();
}
and we can call using Script Manager in asp.net Code Behind :
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "ClickbtnBindGridView();", true);
Above Functions Works well For Firefox and Chrome
for Internet Explorer we can use :
On Parent Form :
JavaScript:
<script type="text/javascript">
function OpenChildWindow() {
//open a new dialog window
var sFeatures = "dialogHeight: 200px;";
sFeatures += "dialogWidth: 400px;";
sFeatures += "center: yes;";
sFeatures += "edge: sunken;";
sFeatures += "scroll: no;";
sFeatures += "status: yes;";
sFeatures += "resizeable: no;";
var url = 'ChildForm.aspx?SomeValue=12345';
entryWindow = window.showModalDialog(url, 'ChildForm', sFeatures);
if (entryWindow == true) {
alert("Watch for CurrTime & ChildWin labels," +
" its going to update as new window saved.");
//this would trigger the update panels
//update as the button is part of the UP
window.document.getElementById('btnHiddenForUpdate').click();
}
else {
//No change will happen to the parent page as child page did nothing
alert("Nothing on the page will change " +
"as the new child window was cancelled.");
}
}
</script>
HTML :
<form id="form1" runat="server">
<asp:ScriptManager ID="smParent" runat="server" />
<div id="divUpdatePanel">
<asp:UpdatePanel ID="upParent" runat="server">
<ContentTemplate>
<asp:Label ID="lblCurrTime" runat="server" Text="CurrTime:">
</asp:Label> <br />
<asp:Label ID="lblChildWinValue" runat="server"
Text="ChildWin Value:"></asp:Label><br />
<br /><a href="javascript:OpenChildWindow();">
Click to open the Child Window</a><br />
<input type="button" id="btnHiddenForUpdate"
runat="server" style="display:none"
onserverclick="btnHiddenForUpdate_ServerClick" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div id="divNormalUpdatePanel">
<asp:Panel ID="pnlFullPostback" runat="server">
<asp:Label ID="lblPageLoadTime" runat="server"
Text="PageLoadTime:"></asp:Label>
</asp:Panel>
</div>
</form>
Child Form can be 2 ways
Method 1
JavaScript:
<script type="text/javascript">
function WindowClose() {
window.returnValue = true;
window.close();
}
function WindowCancel() {
window.returnValue = false;
window.close();
}
</script>
HTML:
<form id="form1" runat="server">
<div>
<input id="Button2" type="button" value="Update" runat="server" onclick="WindowClose();" title="CLose Button" />
<input type="button" value="Close" onclick="WindowCancel();" title="CLose Button" />
</div>
</form>
Method 2
JavaScript
<script type="text/javascript">
function UpdateClick() {
window.returnValue = true;
window.close();
}
</script>
HTML
<asp:Button ID="btnUpdate" Text="Update" runat="server" CssClass="Button" OnClick="btnUpdate_Click" />
<asp:Button ID="btnCancel" Text="Cancel" runat="server" CssClass="Button" OnClientClick="javascript:window.close();" />
Above Functions Works well For Firefox and Chrome
for Internet Explorer we can use :
On Parent Form :
JavaScript:
<script type="text/javascript">
function OpenChildWindow() {
//open a new dialog window
var sFeatures = "dialogHeight: 200px;";
sFeatures += "dialogWidth: 400px;";
sFeatures += "center: yes;";
sFeatures += "edge: sunken;";
sFeatures += "scroll: no;";
sFeatures += "status: yes;";
sFeatures += "resizeable: no;";
var url = 'ChildForm.aspx?SomeValue=12345';
entryWindow = window.showModalDialog(url, 'ChildForm', sFeatures);
if (entryWindow == true) {
alert("Watch for CurrTime & ChildWin labels," +
" its going to update as new window saved.");
//this would trigger the update panels
//update as the button is part of the UP
window.document.getElementById('btnHiddenForUpdate').click();
}
else {
//No change will happen to the parent page as child page did nothing
alert("Nothing on the page will change " +
"as the new child window was cancelled.");
}
}
</script>
HTML :
<form id="form1" runat="server">
<asp:ScriptManager ID="smParent" runat="server" />
<div id="divUpdatePanel">
<asp:UpdatePanel ID="upParent" runat="server">
<ContentTemplate>
<asp:Label ID="lblCurrTime" runat="server" Text="CurrTime:">
</asp:Label> <br />
<asp:Label ID="lblChildWinValue" runat="server"
Text="ChildWin Value:"></asp:Label><br />
<br /><a href="javascript:OpenChildWindow();">
Click to open the Child Window</a><br />
<input type="button" id="btnHiddenForUpdate"
runat="server" style="display:none"
onserverclick="btnHiddenForUpdate_ServerClick" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div id="divNormalUpdatePanel">
<asp:Panel ID="pnlFullPostback" runat="server">
<asp:Label ID="lblPageLoadTime" runat="server"
Text="PageLoadTime:"></asp:Label>
</asp:Panel>
</div>
</form>
Child Form can be 2 ways
Method 1
JavaScript:
<script type="text/javascript">
function WindowClose() {
window.returnValue = true;
window.close();
}
function WindowCancel() {
window.returnValue = false;
window.close();
}
</script>
HTML:
<form id="form1" runat="server">
<div>
<input id="Button2" type="button" value="Update" runat="server" onclick="WindowClose();" title="CLose Button" />
<input type="button" value="Close" onclick="WindowCancel();" title="CLose Button" />
</div>
</form>
Method 2
JavaScript
<script type="text/javascript">
function UpdateClick() {
window.returnValue = true;
window.close();
}
</script>
HTML
<asp:Button ID="btnUpdate" Text="Update" runat="server" CssClass="Button" OnClick="btnUpdate_Click" />
<asp:Button ID="btnCancel" Text="Cancel" runat="server" CssClass="Button" OnClientClick="javascript:window.close();" />
Sunday, April 13, 2014
Tutorial: How to do Cookieless ASP.NET Forms Authentication
Background
A cookie is a piece of text that a Web site can park on a user's machine to be retrieved
and reused later. The information stored consists of harmless name-value pairs.
Cookies store the ID of the session and browsers transparently move their contents
back and forth between the Web server and the local user's machine. When a cookie-enabled
browser receives a response packet, it looks for attached cookies and stores their
content to a text file in a particular folder in the local Windows directory. Next,
when the browser sends a request to the site, it looks in the cookies folder for
a cookie that originated from that domain. If found, the cookie is automatically
attached to the outgoing packet. The cookie hits the server application where it
is detected, extracted, and processed. In the end, cookies make Web sites much easier
to navigate because they provide the illusion of continuity on top of a user's experience
that necessarily spans over multiple requests.
Problem of Cookies
Cookies were alleged to contain dangerous programs capable of stealing valuable
information even beyond the physical boundaries of the machine. Cookies are not
programs and never run like programs; other software that gets installed on your
machine, though, can use the built-in browser support for cookies to do bad things
remotely. Furthermore, cookies are at risk of theft. Once stolen, a cookie that
contains valuable and personal information can disclose its contents to malicious
hackers and favor other types of Web attacks. In summary, by using cookies you expose
yourself to risks that can be zeroed off otherwise
Because cookies are data written to your browser from the server. This prefigures
some potential security risks and an overall situation less then ideal. (In some
cases and countries, it's even illegal for an application to require cookies to
work.)
If you take a look at your site's statistics regarding browsers used to access pages,
you might be surprised to discover that a significant share of users connect with
cookies disabled. This poses a point for you as a developer.
Solutions
The main reason for cookieless sessions in ASP.NET is that users—for whatever reasons—may
have cookies disabled on their browsers. Like it or not, this is a situation you
have to face if your application requires session state. Cookieless sessions embed
the session ID in the URL and obtain a two-fold result. On the one hand, they provide
a way for the Web site to correctly identify the user making the request. On the
other hand, though, they make the session ID clearly visible to potential hackers
who can easily steal it and represent themselves as you.
To implement cookieless sessions you don't have to modify your programming model—a
simple change in the web.config file does the trick—but refactoring your application
to avoid storing valuable information in the session state is strongly recommended
too. At the same time, reducing the lifetime of a session to less than the default
20 minutes can help in keeping your users and your site safe.
How to implement cookieless authentication in ASP.net?
Step 1: Adjust the web.config file.
Interestingly enough, you don't have to change anything in your ASP.NET application
to enable cookieless sessions, except the following configuration setting.
<sessionState cookieless="true"
/>
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="30"
name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseUri" enableCrossAppRedirects="true"/>
</authentication>
Step 2: Adjust all of the URL navigations in aspx files.
Be careful, the following code breaks the session:
<a runat="server" href="/test/page.aspx">Click</a>
To use absolute URLs, resort to a little trick that uses the ApplyAppPathModifier
method on the HttpResponse class. The ApplyAppPathModifier method takes a string
representing a URL and returns an absolute URL that embeds session information.
<a runat="server"
href=”<% =Response.ApplyAppPathModifier("page.aspx")%>”
>Click</a>
Step 3: Adjust all of the URL navigations in aspx.cs files.
If the URL is set in the code, you need to do it in the following way:
this.Tab2.Url = Response.ApplyAppPathModifier("Page.aspx");
Step 4: Adjust all of the authentication method in your login page.
After the username and password have been verified, we need to do the following
things to set the cookieless login state.
// Create a new ticket used for authentication
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
username, // Username
associated with ticket
DateTime.Now, //
Date/time issued
DateTime.Now.AddMinutes(10),
// Date/time to expire
true, // "true"
for a persistent user cookie
string.Empty, //
User-data
string.Empty //
Path cookie valid for
);
// Hash the ticket
string hash = FormsAuthentication.Encrypt(ticket);
//The following is the cookie way for your
reference
//HttpCookie cookie = new HttpCookie(
// FormsAuthentication.FormsCookieName,
// Name of auth cookie
// hash); // Hashed
ticket
// Add the cookie to the list for outgoing response
//Response.Cookies.Add(cookie);
//The following is the cookieless way we
want:
FormsAuthentication.SetAuthCookie(username, false); //this
set the cookieless data. Response.Redirect(Response.ApplyAppPathModifier(Request.QueryString["ReturnUrl"]));
Monday, April 7, 2014
Best Informative Site
http://www.functionx.com/index.htm
Well Bloggers
http://igoro.com/
http://askjonskeet.com/browse/latest
http://msdn.microsoft.com/en-us/magazine/cc163512.aspx
some other use full blogs
http://mvkinfo.blogspot.in/
Sunday, March 30, 2014
I wanted to test that a particular class could be successfully serialized into the View State of a page and then successfully de-serialized in a post back. This is interesting because the view state is maintained in the request/response, rather than on the server, me we need to simulate the manner in which a browser would transfer this information.
Setting up a Web Page
So the starting point is to get an ASP.Net page that can test out the functionality we are after and report success or failure. This is simple enough, fire up Visual Studio (I’m using 2008 SP1) and create a new ASP.Net Application (File -> New -> Project -> Web -> ASP.Net Web Application), I’m calling mine “PostBackDemo”
’m just going to work with the Default.aspx page that is created for you and adding a single button to the page, I’m leaving it aptly named “Button1”. If you double click on the button VS will drill through to the code behind where you should now have two methods, one that runs on page load and another when Button1 is clicked.
At this point I’m going to add in a class to test, sticking with original scenario I’m going to verify that am instance of this class can be placed into View State and pulled back out on a post back. I’m adding in a very uninteresting Person class that has two string properties as shown below, note that I’ve marked it as serializable otherwise we won’t be able to put into View State.
1
2
3
4
5
6
| [Serializable] public class Person { public string FirstName { get; set; } public string LastName { get; set; } } |
Now I’m going to fill out the code file for my ASPX page to add a person into View State when a page is requested and to read it back out when Button1 is clicked. The page will then write out [PASS] or [FAIL] and send the response back.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
| using System; namespace PostBackDemo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Load a new person into View State on intial request if (!Page.IsPostBack) { Person test = new Person(); test.FirstName = "Rowan"; test.LastName = "Miller"; ViewState["CURRENT_PERSON"] = test; } } protected void Button1_Click(object sender, EventArgs e) { //Try and pull a person back out of View State Person test = ViewState["CURRENT_PERSON"] as Person; //Check if the person came back OK if (test != null && test.FirstName.Equals("Rowan") && test.LastName.Equals("Miller")) { Response.Write("[PASS]"); } else { Response.Write("[FAIL]"); } //Send outcome back to requester Response.End(); } } } |
At this point you should be able to run your project and when clicking the button a simple “[PASS]” should be written out for you.
Writing an Automated Test
We are going to create a unit test using the inbuilt test framework in Visual Studio, for the purpose of this demo our test is going to rely on the page being available on a given url but if you combine this post with my last post on hosting pages within a unit test using Web Dev Server you can accomplish a truly automated solution.
So I’m just adding a new Test Project to my solution (File -> Add -> New Project -> Test -> Test Project), I’m calling mine TestProject. I’m just going to add my test code into the TestMethod1() that is created for you in UnitTest1.cs. Now the code to achieve what we want is actually pretty simple, I’ve posted a few topics now that use Systme.Net.HttpWebRequest and System.Net.WebResponse to hit resources over http, this one is the same except that we need to extract some content out of the initial response and include it when we post back.
The code and comments pretty much cover it so I’ll just point out a couple of things;
- The initial response contains two hidden controls called __VIEWSTATE and __EVENTVALIDATION we simply need to copy the content of these controls and include them in our second request. View State is pretty obvious and includes the serialized version of our person instance. Event Validation isn’t so obvious, this is an internal construct of ASP.Net that is used to help guarantee the integrity of the page content, you can read more on that topic at http://msdn.microsoft.com/en-us/magazine/cc163512.aspx.
- You’ll also notice that I’m including “&Button1=Button1” at the end of the content, this simply identifies that Button1 was clicked and ASP.Net raises the ‘Clicked’ event on Button1 for us when it sees this.
- The other noteworthy part of the code is the use of a delegate to perform the writing of content to the post back request stream, you could equally have this logic tucked into a method somewhere.
If you had a method defined such as public void WriteContent(IAsyncResult asynchronousResult) you could simply call IAsyncResult res = request.BeginGetRequestStream(new AsyncCallback(WriteContent), request);
So with all that covered here is my test code;
Note that you will need to add a reference to System.Web and System.XML in your test project and the corresponding using statements at the top of UnitTest1.cs.
I’ll also just reiterate that you will need to have the aspx page available and replace the first string variable in the code below with the url of your page, if you want your test to deal with spinning up the page see my last post.
Note that you will need to add a reference to System.Web and System.XML in your test project and the corresponding using statements at the top of UnitTest1.cs.
I’ll also just reiterate that you will need to have the aspx page available and replace the first string variable in the code below with the url of your page, if you want your test to deal with spinning up the page see my last post.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| [TestMethod] public void TestMethod1() { //The url of the page you want to test string url = "<a href="http://localhost:49907/default.aspx">http://localhost:49907/default.aspx</a>"; //Perform an initial request of page HttpWebRequest reqInitial = (HttpWebRequest)WebRequest.Create(url); WebResponse resInitial = reqInitial.GetResponse(); //Extract the ASP.Net content from the page string viewstate = ""; string eventvalidation = ""; XmlTextReader xmlRead = new XmlTextReader(resInitial.GetResponseStream()); while (xmlRead.Read()) { if (xmlRead.Name == "input" && xmlRead.GetAttribute("id") == "__VIEWSTATE") { viewstate = xmlRead.GetAttribute("value"); } else if (xmlRead.Name == "input" && xmlRead.GetAttribute("id") == "__EVENTVALIDATION") { eventvalidation = xmlRead.GetAttribute("value"); } } //Build the ASP.Net content to be included in the postback string postBackContent = string.Format("__VIEWSTATE={0}&__EVENTVALIDATION={1}", HttpUtility.UrlEncode(viewstate), System.Web.HttpUtility.UrlEncode(eventvalidation)); //Add the content to notify Button1 was clicked postBackContent += "&Button1=Button1"; //Build the post back request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Referer = url; request.ContentType = "application/x-www-form-urlencoded"; //Create a delegate to send content into the request //You would probably implement this as a seperate method that could be re-used AsyncCallback contentLoader = delegate(IAsyncResult asynchronousResult) { //Pull request out of async state HttpWebRequest req = (HttpWebRequest)asynchronousResult.AsyncState; //Turn our content into binary data and send it down the request stream byte[] content = Encoding.UTF8.GetBytes(postBackContent); System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult); postStream.Write(content, 0, content.Length); postStream.Close(); }; //Use the delegate to pour our content down the request IAsyncResult res = request.BeginGetRequestStream(contentLoader, request); //We are going to lock while we wait for a response but you could perform other //operations while the request is processed res.AsyncWaitHandle.WaitOne(); //Pull the final content back out of the response WebResponse resPostback = request.GetResponse(); StreamReader streamFinalContent = new StreamReader(resPostback.GetResponseStream()); string result = streamFinalContent.ReadLine(); Assert.AreEqual("[PASS]", result); } |
The Exploration Process
Coming up with this approach code was actually quite simple, once I had the web page up and running I used an HTTP tracing utility to work out what was getting sent to and from my browser and then just wrote code to mimic that. I was using Http Debugger Pro from http://www.httpdebugger.com/ but there are plenty of alternatives out there.
Source: http://romiller.com/2009/02/18/programmatic-asp-net-post-back/
Subscribe to:
Posts (Atom)