|
I need to extract the last data so i used the following code in MVC controller:
var cmpid = db.complaint_master.Where(m => m.uid == id && m.isvalid == 0 && m.dateofcomplaint == date).Select(m => m.compid).LastOrDefault();
i am getting an error:
LINQ to Entities does not recognize the method 'Int32 LastOrDefault[Int32](System.Linq.IQueryable`1[System.Int32])' method, and this method cannot be translated into a store expression.
Please help
|
|
|
|
|
You have two options:
1. Sort the data in descending order, and use FirstOrDefault :
var cmpid = db.complaint_master
.Where(m => m.uid == id && m.isvalid == 0 && m.dateofcomplaint == date)
.Select(m => m.compid)
.OrderByDescending(id => id)
.FirstOrDefault()
;
2. Load all of the results into memory before using LastOrDefault :
var cmpid = db.complaint_master
.Where(m => m.uid == id && m.isvalid == 0 && m.dateofcomplaint == date)
.Select(m => m.compid)
.AsEnumerable()
.LastOrDefault()
;
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
i want to develop a wcf service which will send encrypted message / response to client and client will decrypt it and same way client will send data in encrypted format which wcf service decrypt it before taking any action.
i hard that wcf has message inspector which can do it but not getting any easy understanding sample code to achieve the same. so please give me a sample code how to achieve it. also give me sample code for both wcf service and client side code.
please do not tell me to use certificate rather guide me what kind of code i need to write at service end and client to encrypt/decrypt data. please discuss here or redirect me to relevant article. thanks
tbhattacharjee
|
|
|
|
|
Tridip Bhattacharjee wrote: give me a sample code how to achieve it. also give me sample code for both wcf service and client side code. You have been a CodeProject member long enough to know that this site does not provide code to order.
|
|
|
|
|
Gimme gimme never gets,
don't you know your manners yet?
|
|
|
|
|
I am trying to develop a appliction in asp.net webapi and knockoutjs VM, Please help me how to create new page and how to redirect to a new page from home page or masterpage.
|
|
|
|
|
I have the following:
<asp:linkbutton id="LinkButton1" runat="server" onclick="LinkButton1_Click">Find Project :
<asp:textbox id="FindProject" runat="server" text="" cssclass="submit">
<asp:SqlDataSource ID="MySqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT * from myTable
WHERE Active= 'True'
AND myTable.Project = COALESCE(NULLIF(@FindProject, ''), myTable.Project)">
<SelectParameters>
<asp:ControlParameter ControlID="FindProject" Name="FindProject"
PropertyName="Text" />
</SelectParameters>
<asp:gridview id="GridView1" runat="server" datasourceid="MySqlDataSource1" ...="">
...
The SQL is simple and works ok with all of the values below in SSMS:
--declare @FindProject varchar(20) = 'A_Project'
--declare @FindProject varchar(20) = NULL
declare @FindProject varchar(20) = ''
select * from MyTable
WHERE Active = 'True'
AND MyTable.Project = COALESCE(NULLIF(@FindProject, ''), MyTable.Project )
Currently I can find an individual record with the linkbutton and FindProject textbox, it works ok
I want the page to show all records when the page is initially loaded, which it doesn't, it's just an empty list.
|
|
|
|
|
Try setting CancelSelectOnNullParameter[^] to false :
<asp:SqlDataSource ID="MySqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT * from myTable WHERE Active= 'True' AND myTable.Project = COALESCE(NULLIF(@FindProject, ''), myTable.Project)"
CancelSelectOnNullParameter="False"
>
<SelectParameters>
<asp:ControlParameter
ControlID="FindProject"
Name="FindProject"
PropertyName="Text"
/>
</SelectParameters>
</asp:SqlDataSource>
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
excellent thanks, it worked.
|
|
|
|
|
please help
Im using MySql database and asp.net c#
I have a listview like this
<asp:listview id="listview1" runat="server">
<item template="">
"
"
"
<%# val("pic ") %>
and its working now im struggling with paging .
i tried a datapager n i failed please help ...
which tool to use if i want to click a picture
from the listview and see full products details.
Thanks
|
|
|
|
|
Hi All,
I am getting the following error when I try to run my ASP.Net web-forms application with my database credentials but I run the same application with my other colleagues database credentials I am not getting the error, then I thought may be my Db credentials are messed up then I tried to see if any difference exists in my authentication/authorization credentials, but I didn't find any difference between his credentials and my credentials. I am not understanding what could be the error and where am I missing, I am searching and trying to find the reason, but in this meantime if you know the solution please help me.
Here is my error on the VS crashing
[Window Title]
Visual Studio Just-In-Time Debugger
[Main Instruction]
An unhandled Microsoft .NET Framework exception occurred in w3wp.exe [3596].
The Just-In-Time debugger was launched without necessary security permissions. To debug this process, the Just-In-Time debugger must be run as an Administrator. Would you like to debug this process?
[V] View process details [Yes, debug w3wp.exe] [No, cancel debugging]
[Expanded Information]
Process Name: w3wp.exe
User Name: IIS APPPOOL\ELMS [Elevated]
And when I try to see it in the Windows log here it is
Faulting application name: w3wp.exe, version: 7.5.7601.17514, time stamp: 0x4ce7afa2
Faulting module name: clr.dll, version: 4.0.30319.18444, time stamp: 0x52717f9a
Exception code: 0xc00000fd
Fault offset: 0x0000000000009f66
Faulting process id: 0x141c
Faulting application start time: 0x01d07b8b53af8a8c
Faulting application path: c:\windows\system32\inetsrv\w3wp.exe
Faulting module path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Report Id: a1f85976-e77e-11e4-8858-08002703e456
Please help me if this can be because of my settings in the IIS or SQL Server or Windows credentials in this meantime I am searching in the code for any possible problems. Thanks in advance.
"There is enough hatred in the world, lets spread love compassion and affection."
|
|
|
|
|
Thanks I got it resolved, I had some problems in my database auth tables hence a function getting called repeatedly and killing the Worker process. I have resolved it.
"There is enough hatred in the world, lets spread love compassion and affection."
|
|
|
|
|
hello :
how can i please build graph has two part ( bi-part) , have like node friends facebook and posts facebook , link between two nodes( node friend and node post ) may be : like , comment and share ??
and how please can use library JoinJS to do it
thank you very much
|
|
|
|
|
You'll have to ask a much more specific question if you want a useful response.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
here i am trying to save memory stream data into zip files which could be many segment. please see my below code which works fine.
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection(@"Data Source=BBATRIDIP\SQLSERVER2008R2;Initial Catalog=test;Integrated Security=True"))
{
string query = String.Format(@"SELECT [FilePath],[FileName],[FileData] FROM [TestTable]");
SqlCommand cmd = new SqlCommand(query, sqlConn);
cmd.Connection.Open();
System.IO.MemoryStream memStream = null;
ZipFile zip = new ZipFile();
zip.MaxOutputSegmentSize = 1024 * 1024;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
byte[] data = (byte[])reader["FileData"];
memStream = new System.IO.MemoryStream(data);
string strFile = reader["FilePath"].ToString() + "\\" + reader["FileName"].ToString();
ZipEntry ze = zip.AddEntry(strFile, memStream);
}
}
zip.Save(@"e:\MyCustomZip.zip");
memStream.Dispose();
MessageBox.Show("Job Done");
}
}
i doubt the problem could be that approach stores the zip content in memory. Hence, when the zip content is huge, say exceeds 5 GB then then it crashes. so one guy said write to fileOutputStream mapped to physical file
guide me how to achieve to write to fileOutputStream mapped to physical file ?
i got a write up from this url http://gotoanswer.com/?q=Creating+Zip+file+from+stream+and+downloading+it
see the below code because i doubt probably this way i may be able to write to fileOutputStream mapped to physical file here is the code
MemoryStream stream = new MemoryStream();
dt.WriteXml(stream);
stream.Seek(0,SeekOrigin.Begin);
using (ZipFile zipFile = new ZipFile())
{
zipFile.AddEntry("Report.xml", "", stream);
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("content-disposition", "attachment; filename=Report.zip");
zipFile.Save(Response.OutputStream);
}
probably this line write to fileOutputStream mapped to physical file, just guide me am i on the right direction?
My Objective
i have to call a web service which will supply large stream of data and i need to save that stream to zip file but zip will not be created at server side rather it will be created at client end. due to large stream of data i need to break the zip file into small segment say 500MB or 1GB. one after one segment will download at client side one by one. when first one will end then user will get a file save dialog to save second segment. when all segment will be completed at client side then client could extract all segment to get one folder which may have many files and sub folder.
just guide me with code sample or suggestion how to achieve it with best performance. i have some constraint like i could not save stream data in multiple segment zip file at server side first and then start the download all segment one by one. so please read my requirement and guide me how to achieve it with best performance for large data.
if anyone observe this line of code
byte[] data = (byte[])reader["FileData"];
memStream = new System.IO.MemoryStream(data);
so i am storing something in memory stream first which is not good when data size would be huge. so guide me how could i achieve my task without using memory stream. rather directly i want to push the stream of data to dotnet zip library which will write each segment to OutputStream one by one.
looking for best guidance. thanks
tbhattacharjee
|
|
|
|
|
Should this be in the c# forum?
Your calling a MsgBox
|
|
|
|
|
u just notice only MsgBox. could not find out solution for my situation. u r amazing guy.
tbhattacharjee
|
|
|
|
|
The example you referenced shows how to load a file on the server into a memory stream, and then convert it to a zip or compressed file, and then package the file for download. Then it will prompt the browser to download the zip file.
The 2nd example on your reference shows a better way to write the code, the first example that you copied is the version that doesn't work very well, and has problems. Use the 2nd example.
But in hindsight, the codes function doesn't match what you want to do.
Could of swore that you want to upload the compressed file to the server.
So in button click, on the client machine, in the first code block where you read the file data from the database, you just read the reader, and get the bytes and store them in a buffer. Then close the database, exit the data function.
Now chop up the bytes into 4096 blocks or what ever value you choose.
So measure the byte buffer and get it's length, then divide the length by 4096, that's how many loops you need.
And then seek or start at 0, and grab 4096 chuck of bytes, then write the file, grad the next 4096 chunk of bytes, write the file and so on.
Make sure your files exist in a temp storage place like App_Data.
Get that working smooth first before you try to upload the files to the server.
|
|
|
|
|
Hi All,
I am using an asp.net application page to show the contents on the page with line break and OR image on the line break, I am not yet done with image itself, the problem is image appears at an inappropriate space or never appears as I have been trying with several options. Here I am putting this code that I am currently using. Can you please advice me or help me with any idea or code snippet or link any thing can be helpful, thank and your help is much appreciated as I am getting tired with this, searching on the internet no help so far but still trying.
Thanks in advance and here is the code.
<ol>
<li id="first-option" class="first-option">
<div class="paren"></div>
<div class="full col">
<label for="txtFirstName">First Name</label>
<asp:TextBox ID="txtFirstName" runat="server" ClientIDMode="Static" Enabled="false" />
</div>
<div class="full col">
<label for="txtLastName">Last Name</label>
<asp:TextBox ID="txtLastName" runat="server" ClientIDMode="Static" Enabled="false" />
</div>
<div class="full col">
<label for="txtBirthDate">Date of Birth</label>
<elms:DateTextBox ID="txtBirthDate" runat="server" ClientIDMode="Static" />
</div>
<div class="full col">
<label for="txtEmailAddress">Email Address</label>
<asp:TextBox ID="txtEmailAddress" runat="server" ClientIDMode="Static" />
</div>
<div class="full col">
<label for="txtEmailAddress2">Verify Email Address</label>
<asp:TextBox ID="txtEmailAddress2" runat="server" ClientIDMode="Static" />
</div>
</li>
<li id="or-divider" class="or-divider"><span></span></li>
<li id="second-option" class="second-option">
<div class="paren"></div>
<div class="full col">
<label for="txtStarsId" runat="server">STARS ID</label>
<asp:TextBox ID="txtStarsId" runat="server" ClientIDMode="Static" />
</div>
</li>
</ol>
<div class="action-buttons">
<asp:Button ID="btnSave" ClientIDMode="Static" runat="server" Text="Save" />
<asp:Button ID="btnCancel" ClientIDMode="Static" runat="server" Text="Cancel" />
</div>
CSS here, but with this the OR appears at the bottom and over the save and cancel buttons, which is not good and the numbers 1 and 2 appears over the first li's items, not useful and I don't why 1 appears only half, please help me if you can
or-divider
{
position:absolute;
border:none;
left:50%;
top:50%;
transform:translate(-50%,-50%);
}
.or-divider > span
{
background:transparent url('../../../images/OR-Small.png') no-repeat top center;
background-color:White;
position:absolute;
font-size:1.3em;
font-weight:bold;
top: inherit;
display: inline-block;
left: 40%;
height:20px;
width:80px;
z-index:1000;
}
<h1>or-divider + li</h1>
{
padding-top:30px;
}
.my-container > ol > li > span:first-child
{
display:block;
margin-bottom:5px;
}
.my-container > ol > li:first-child > select,
.my-container > ol > li:first-child > .chosen-container
{
width:100%;
margin-bottom:5px;
}
div.paren
{
position:absolute;
left:25px;
top:0;
height:47px;
width:15px;
background:transparent url('../../../images/Close-Paren.png') no-repeat left top;
}
<h1>first-option,</h1>
<h1>second-option</h1>
{
position:relative;
padding-left:50px;
}
<h1>first-option</h1>
{
background:transparent url('../../../images/1.png') no-repeat 2px 3px;
}
<h1>second-option</h1>
{
min-height:40px;
background:transparent url('../../../images/2.png') no-repeat left 33px;
}
<h1>second-option div.paren</h1>
{
background-position:left 30px;
height:77px;
}
"There is enough hatred in the world, lets spread love compassion and affection."
|
|
|
|
|
You can only set CSS properties that the span tag supports. Google span tag, the W3 website will show you what the element currently supports.
A span tag is just an inline-element that supports text. I know you can make a span tag a button as well, and do some other stuff with it.
But if the element is text empty, it won't display, to the best of my knowledge.
I would hard code the image location, and not use the dots. You can drag the image to the CSS file and it should calculate the path.
I know there's a way to use the 2nd class as a child or the 1st class, but you should make sure it works first before until you get really good at typing CSS off the top of your head.
left 50% - 50% of what?
You should Google li as well and see what you can do with it.
.li_divider
{
border:none;
left:50%;
}
span.li_divider
{
background:transparent url('/images/OR-Small.png') no-repeat top center;
background-color:White;
font-size:1.3em;
font-weight:bold;
}
Similiar Issue to look at.
http://stackoverflow.com/questions/16068683/the-background-image-in-the-span-wont-show-without-any-text-in-the-span-tag[^]
|
|
|
|
|
I am using table value parameter for insertion into four table and four table value parameters are used but after the insertion my application gets hangs on any one can assist.
|
|
|
|
|
I'm not able to visual that. Perhaps you should post the code you wrote for this.
Do you read the How to get an answer to your question?
If it's a database update or write, it's usually because an error occurred and you didn't close your connection.
Try Catch Finally
|
|
|
|
|
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
If Not Page.IsValid Then Return
Dim blnIsUpdate As Boolean = False
Dim hasedBytes As Byte()
Dim strPassword As String = String.Empty
Dim md5Hasher As New MD5CryptoServiceProvider()
If Not litUserId.Text.Trim().Length.Equals(0) Then blnIsUpdate = True
Dim cnnContact As New SqlConnection(AppSettings("DbSqlPortal"))
Dim cmdContact As New SqlCommand("spAdminSaveUsers", cnnContact)
Dim IDs As Integer = Nothing
Dim trnContact As SqlTransaction = Nothing
cmdContact.CommandType = CommandType.StoredProcedure
hasedBytes = md5Hasher.ComputeHash(New UTF8Encoding().GetBytes((txtPassword.Text.Trim() & txtEmail.Text.Trim())))
' GetDistrictID()
'If GetDistrictId() > 0 Then
' DisplayMessage(Me.Master.MessageBox, "A User with same District and Same user role already exists.", "Record Exists", MessageBoxTypes.Warning)
'Else
Try
With cmdContact.Parameters
If blnIsUpdate Then
.Add("@UserId", SqlDbType.BigInt).Value = CInt(litUserId.Text.Trim())
Else
.Add("@UserId", SqlDbType.BigInt).Value = DBNull.Value
End If
.Add("@FullName", SqlDbType.NVarChar).Value = txtFullName.Text.Trim()
.Add("@Email", SqlDbType.NVarChar).Value = txtEmail.Text.Trim()
.Add("@Password", SqlDbType.VarChar).Value = base64Encode(txtPassword.Text)
'txtPassword.Text.Trim()
'Convert.ToBase64String(hasedBytes)
.Add("@SecurityQuestion", SqlDbType.VarChar).Value = ddlSecurityQuestions.SelectedItem.Text
.Add("@SecurityAnswer", SqlDbType.VarChar).Value = txtAnswer.Text.Trim()
.Add("@UserTypes", SqlDbType.TinyInt).Value = ddlUserTypes.SelectedValue
.Add("@IsActive", SqlDbType.Bit).Value = chkActive.Checked
.Add("@DistrictId", SqlDbType.TinyInt).Value = CheckBoxList1.SelectedValue
.Add("@IsAdmin", SqlDbType.Bit).Value = chkAdmin.Checked
.Add("@IPAddress", SqlDbType.VarChar).Value = Request.UserHostAddress
.Add("@Result", SqlDbType.Char, 1).Direction = ParameterDirection.Output
.Add("@ReturnId", SqlDbType.BigInt).Direction = ParameterDirection.Output
If ChkIsReportAble.Checked = False Then
.Add("@IsReportable", SqlDbType.Bit).Value = False
Else
.Add("@IsReportable", SqlDbType.Bit).Value = ChkIsReportAble.Checked
End If
If ChkIsReportAble.Checked Then
.Add("@ReporintPerson", SqlDbType.TinyInt).Value = CInt(ddlReporintUser.SelectedValue)
Else
.Add("@ReporintPerson", SqlDbType.TinyInt).Value = DBNull.Value
End If
End With
cnnContact.Open()
trnContact = cnnContact.BeginTransaction()
cmdContact.Transaction = trnContact
cmdContact.ExecuteNonQuery()
If CChar(cmdContact.Parameters("@Result").Value).Equals("E"c) Then
' Msg.Text = "The Record has been Successfully Submitted !"
DisplayMessage(Me.Master.MessageBox, "A User with same Email already exists.", "Record Exists", MessageBoxTypes.Warning)
'MessageBoxShow(Page, "This Record Exists Try with some other record!")
litUserId.Text = String.Empty
Return
End If
trnContact.Commit()
litUserId.Text = (cmdContact.Parameters("@ReturnId").Value)
If blnIsUpdate Then
Dim cmdsDistrict As New SqlCommand("spAdminDeleletUserAssociationNews", cnnContact)
cmdsDistrict.CommandType = CommandType.StoredProcedure
Try
With cmdsDistrict.Parameters
.Add("@UserId", SqlDbType.TinyInt).Value = litUserId.Text
.Add("@Result", SqlDbType.Char, 1).Direction = ParameterDirection.Output
End With
trnContact = cnnContact.BeginTransaction()
cmdsDistrict.Transaction = trnContact
cmdsDistrict.ExecuteNonQuery()
trnContact.Commit()
Catch ex As Exception
End Try
End If
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(2) {New DataColumn("DistrictId", GetType(Integer)), New DataColumn("DistrictName", GetType(String)), New DataColumn("UserID", GetType(Integer))})
Dim i As Integer = 0
Do While (i < CheckBoxList1.Items.Count)
If CheckBoxList1.Items(i).Selected Then
Dim id As Integer = Integer.Parse(CheckBoxList1.Items(i).Value)
Dim name As String = CheckBoxList1.Items(i).Text
Dim country As String = litUserId.Text
dt.Rows.Add(id, name, country)
End If
i = (i + 1)
Loop
If dt.Rows.Count > 0 Then
' cnnContact = New SqlConnection(AppSettings("DbSqlPortal"))
Using cmd As New SqlCommand("Insert_Customers")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = cnnContact
cmd.Parameters.AddWithValue("@tblCustomers", dt)
cmd.ExecuteNonQuery()
End Using
End If
Dim dt2 As New DataTable()
'Dim cnnCdf As SqlConnection = Nothing
dt2.Columns.AddRange(New DataColumn(3) {New DataColumn("TehsilId", GetType(Integer)), New DataColumn("TehsilName", GetType(String)), New DataColumn("DistrictId", GetType(Integer)), New DataColumn("UserID", GetType(Integer))})
Dim i2 As Integer = 0
Do While (i2 < CheckBoxList2.Items.Count)
If CheckBoxList2.Items(i2).Selected Then
Dim id As Integer = Integer.Parse(CheckBoxList2.Items(i2).Value)
hdnThil = id
Dim name As String = CheckBoxList2.Items(i2).Text
Dim country As String = litUserId.Text
Dim tId As Integer = GetDistrictIDoftehsilIds(CheckBoxList2.Items(i2).Value)
dt2.Rows.Add(id, name, tId, country)
End If
i2 = (i2 + 1)
Loop
If dt2.Rows.Count > 0 Then
Using cmd As New SqlCommand("Insert_Customersfourth")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = cnnContact
cmd.Parameters.AddWithValue("@tblCustomersfourth", dt2)
cmd.ExecuteNonQuery()
End Using
End If
Dim dt3 As New DataTable()
dt3.Columns.AddRange(New DataColumn(3) {New DataColumn("UCID", GetType(Integer)), New DataColumn("UCName", GetType(String)), New DataColumn("TehsilId", GetType(Integer)), New DataColumn("UserID", GetType(Integer))})
Dim i3 As Integer = 0
Do While (i3 < CheckBoxList3.Items.Count)
If CheckBoxList3.Items(i3).Selected Then
Dim id As Integer = Integer.Parse(CheckBoxList3.Items(i3).Value)
hdnUC = id
Dim name As String = CheckBoxList3.Items(i3).Text
Dim country As String = litUserId.Text
Dim Ucid As Integer = GetTehsilIDIds(CheckBoxList3.Items(i3).Value)
dt3.Rows.Add(id, name, Ucid, country)
End If
i3 = (i3 + 1)
Loop
If dt3.Rows.Count > 0 Then
Using cmd As New SqlCommand("Insert_CustomersThird")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = cnnContact
cmd.Parameters.AddWithValue("@tblCustomersThird", dt3)
cmd.ExecuteNonQuery()
End Using
End If
Dim dt4 As New DataTable()
dt4.Columns.AddRange(New DataColumn(3) {New DataColumn("VillageId", GetType(Integer)), New DataColumn("VillageName", GetType(String)), New DataColumn("UcID", GetType(Integer)), New DataColumn("UserID", GetType(Integer))})
Dim i4 As Integer = 0
Do While (i4 < CheckBoxList4.Items.Count)
If CheckBoxList4.Items(i4).Selected Then
Dim id As Integer = Integer.Parse(CheckBoxList4.Items(i4).Value)
hdnVillage = id
Dim name As String = CheckBoxList4.Items(i4).Text
Dim country As String = litUserId.Text
Dim Ucid As Integer = GetUCIDIds(CheckBoxList4.Items(i4).Value)
dt4.Rows.Add(id, name, Ucid, country)
End If
i4 = (i4 + 1)
Loop
If dt4.Rows.Count > 0 Then
Using cmd As New SqlCommand("Insert_CustomersSecond")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = cnnContact
cmd.Parameters.AddWithValue("@tblCustomersSecond", dt4)
cmd.ExecuteNonQuery()
End Using
End If
' Catch ex As Exception
'End Try
cnnContact.Close()
Dim strMessage As String = "A new User has successfully been created and saved."
If blnIsUpdate Then strMessage = "The selected User has successfully been updated and saved."
'lblMesssages.InnerText = "Welcome"
DisplayMessage(Me.Master.MessageBox, strMessage, "User Saved Successfully", MessageBoxTypes.Success)
SendMAilMessage()
' MVSearch.ActiveViewIndex = 0
SearchUsers()
'DisplayInitialPage()
Catch ex As Exception
If trnContact IsNot Nothing Then trnContact.Rollback()
DisplayMessage(Me.Master.MessageBox, "An unexpected error occurred while saving the Record. Please retry.", "Record Not Saved", MessageBoxTypes.Error)
Finally
DisposeDataObjects(, , cmdContact, cnnContact)
End Try
End Sub
|
|
|
|
|
How do you know this works?
cnnContact.Open()
trnContact = cnnContact.BeginTransaction()
cmdContact.Transaction = trnContact
cmdContact.ExecuteNonQuery()
Usually you try to keep your SQL more compact in a separate clean function.
Consider a simple request for an ID
This example opens the connection, reads the reader, closes the reader,
With the Try Catch Finally, if the connection or command fails, then the finally will close the connection.
Dim connStr As string = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
Dim query as string = "SELECT ID FROM TABLE"
Dim conn as New SqlConnection(query)
Dim cmd as New SqlCommand(query, conn)
Try
conn.open()
Dim reader as SQLDataReader = cmd.ExecuteReader()
while reader.Read()
pValue = reader.GetInt32(0)
End While
reader.Close()
Catch ex as SQLException
'If there is an error, this will tell you why, so fix the error
' but without the finally, the conn will be left open,
'So if you get too many conn open to the sql server, the sql server will hang
Finally
conn.Close()
End Try
modified 17-Apr-15 13:55pm.
|
|
|
|
|
Dear I am using finally at the end to dispose all the objects after transaction commit , what you suggest how to modify my code ? which i have wrote above
|
|
|
|
|