Monday, 14 October 2019
Friday, 30 August 2019
Add Custom property in page property and use in Sitefinity
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));
Bootstrapper.Initialized += Bootstrapper_Initialized;
}
void Bootstrapper_Initialized(object sender, Telerik.Sitefinity.Data.ExecutedEventArgs e)
{
if (e.CommandName == "Bootstrapped")
{
EventHub.Subscribe<IPagePreRenderCompleteEvent>((x) =>
{
if (!x.PageSiteNode.IsBackend)
{
var page = x.Page;
var siteNode = x.PageSiteNode;
if (!string.IsNullOrEmpty(siteNode.Attributes["IndigoPageTitle"]))
{
page.Header.Title = string.Format("{0}", siteNode.Attributes["IndigoPageTitle"]);
}
}
});
}
}
}
----------------------------------------------
Register your custom property as per below step
{
protected void Application_Start(object sender, EventArgs e)
{
SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));
Bootstrapper.Initialized += Bootstrapper_Initialized;
}
void Bootstrapper_Initialized(object sender, Telerik.Sitefinity.Data.ExecutedEventArgs e)
{
if (e.CommandName == "Bootstrapped")
{
EventHub.Subscribe<IPagePreRenderCompleteEvent>((x) =>
{
if (!x.PageSiteNode.IsBackend)
{
var page = x.Page;
var siteNode = x.PageSiteNode;
if (!string.IsNullOrEmpty(siteNode.Attributes["IndigoPageTitle"]))
{
page.Header.Title = string.Format("{0}", siteNode.Attributes["IndigoPageTitle"]);
}
}
});
}
}
}
----------------------------------------------
Register your custom property as per below step
Add meta to sitefinity website site
| ------Register user control and use below code for meta data-------- -----------------xml file <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <meta-data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <url> <newurl value="nav-dividends/nav-dividends"> <meta> <mAttributes>property</mAttributes> <mAttributesContent>mAttributesContent</mAttributesContent> <mContent>twitterCreator</mContent> </meta> <meta> <mAttributes>itemprop</mAttributes> <mAttributesContent>mAttributesContent</mAttributesContent> <mContent>twitterCreator</mContent> </meta> </newurl> <oldurl>http://localhost:60878/navs-dividends/nav-dividends</oldurl> </url> </meta-data> ---------------------- try { string myurl = Request.Url.ToString().ToLower().Trim(); string BrowseFileDomainName = ConfigurationManager.AppSettings["RootURL"].ToString(); DataSet listofpage = new DataSet(); listofpage.ReadXml(Server.MapPath(ConfigurationManager.AppSettings["pagemeta"].ToString())); myurl = HttpUtility.UrlDecode(myurl); if (BrowseFileDomainName.Contains(";")) { string[] domainstr = BrowseFileDomainName.Split(';'); if (domainstr.Length > 0) { foreach (string strdomain1 in domainstr) { //To Replace last forward slash from request string myurl = myurl.Replace(strdomain1, ""); } } } else { myurl = myurl.Replace(BrowseFileDomainName, ""); } if (myurl.Contains("/")) { myurl = (myurl.Substring(myurl.Length - 1, 1) == "/") ? myurl.Substring(0, myurl.Length - 1) : myurl; } //BrowseFileDomainName = (BrowseFileDomainName.Substring(BrowseFileDomainName.Length - 1, 1) == "/") ? BrowseFileDomainName.Substring(0, BrowseFileDomainName.Length - 1) : BrowseFileDomainName; if (myurl.Trim() == "") { myurl = "home"; } // Response.Write("myurl" + myurl); if (listofpage.Tables[0].Rows.Count > 0) { foreach (DataRow dr in listofpage.Tables[0].Rows) { if (listofpage.Tables[1].Rows.Count > 0) { foreach (DataRow dr1 in listofpage.Tables[1].Rows) { if (dr["url_id"].ToString().Trim().ToLower() == dr1["url_id"].ToString().Trim().ToLower()) { if (myurl.Equals(dr1["value"].ToString().Trim().ToLower())) { if (listofpage.Tables[2].Rows.Count > 0) { foreach (DataRow dr2 in listofpage.Tables[2].Rows) { try { if (dr1["newurl_id"].ToString().Trim().ToLower() == dr2["newurl_id"].ToString().Trim().ToLower()) { var page5 = (System.Web.UI.Page)Telerik.Sitefinity.Services.SystemManager.CurrentHttpContext.CurrentHandler; var creatorMetaTag = new System.Web.UI.HtmlControls.HtmlMeta(); creatorMetaTag.Attributes[dr2["mAttributes"].ToString().Trim().ToLower()] = dr2["mAttributesContent"].ToString().Trim(); creatorMetaTag.Content = dr2["mContent"].ToString().Trim(); page5.Header.Controls.Add(creatorMetaTag); } // page5.Header.InnerHtml = "<meta " + dr2["mAttributes"].ToString().Trim().ToLower() + "=\"" + dr2["mAttributesContent"].ToString().Trim() + "\" Content=\"" + dr2["mContent"].ToString().Trim() + "\"/>"; } catch (Exception ex) { } } } } } } } } } } catch (Exception ex) { } |
Wednesday, 31 July 2019
Monday, 13 May 2019
Delete functionality in sitefinity telerik:RadGrid
<telerik:RadGrid>
<MasterTableView DataKeyNames="ID,CategoryName,ParentCategoryID">
<Columns>
<telerik:GridTemplateColumn UniqueName="edit">
<ItemTemplate>
<asp:LinkButton ID="delete_LinkButton" runat="server" Text="delete" CommandName="delete"
CommandArgument='<%# Eval("ID")+";" + Eval("CategoryName") %>' OnCommand="delete_LinkButton_Click"></asp:LinkButton>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
protected void delete_LinkButton_Click(object sender, CommandEventArgs e)
{
try
{
if (e.CommandName == "delete")
{
if (e.CommandArgument.ToString().Contains(";"))
{
string info = e.CommandArgument.ToString();
string[] arg = new string[2];
char[] splitter = { ';' };
arg = info.Split(splitter);
int Cat_Id = Convert.ToInt16(arg[0]);
string Cat_Name = arg[1].ToString();
operation = "D";
int exists = CategoryManager.DeleteCategory(operation, Cat_Id, Cat_Name, null);
//int exists = 1;
if (exists == 1)
{
strDelMsg = "Deleted successfully!";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "SavedSuccess", "alert('" + strDelMsg + "');", true);
BindSchemeCategories();
}
else
{
strDelMsg = "This record cannot be deleted as it is mapped!";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "SavedSuccess", "alert('" + strDelMsg + "');", true);
}
}
else
{
strDelMsg = "This record cannot be deleted as it is mapped!";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "SavedSuccess", "alert('" + strDelMsg + "');", true);
}
}
}
catch (Exception ex)
{
}
}
<MasterTableView DataKeyNames="ID,CategoryName,ParentCategoryID">
<Columns>
<telerik:GridTemplateColumn UniqueName="edit">
<ItemTemplate>
<asp:LinkButton ID="delete_LinkButton" runat="server" Text="delete" CommandName="delete"
CommandArgument='<%# Eval("ID")+";" + Eval("CategoryName") %>' OnCommand="delete_LinkButton_Click"></asp:LinkButton>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
protected void delete_LinkButton_Click(object sender, CommandEventArgs e)
{
try
{
if (e.CommandName == "delete")
{
if (e.CommandArgument.ToString().Contains(";"))
{
string info = e.CommandArgument.ToString();
string[] arg = new string[2];
char[] splitter = { ';' };
arg = info.Split(splitter);
int Cat_Id = Convert.ToInt16(arg[0]);
string Cat_Name = arg[1].ToString();
operation = "D";
int exists = CategoryManager.DeleteCategory(operation, Cat_Id, Cat_Name, null);
//int exists = 1;
if (exists == 1)
{
strDelMsg = "Deleted successfully!";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "SavedSuccess", "alert('" + strDelMsg + "');", true);
BindSchemeCategories();
}
else
{
strDelMsg = "This record cannot be deleted as it is mapped!";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "SavedSuccess", "alert('" + strDelMsg + "');", true);
}
}
else
{
strDelMsg = "This record cannot be deleted as it is mapped!";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "SavedSuccess", "alert('" + strDelMsg + "');", true);
}
}
}
catch (Exception ex)
{
}
}
Tuesday, 2 April 2019
user control use in sitefinity and button submit time dropdown is reset with empty
Refrence: https://docs.telerik.com/devtools/aspnet-ajax/controls/ajaxmanager/how-to/load-user-controls
protected void Page_Load(object sender, EventArgs e)
{
//-----pramod
if (this.CurrentControl != string.Empty)
{
LoadMyUserControl(CurrentControl, this.Page);
}
}
protected void Page_Init(object sender, EventArgs e)
{
FunBindCategory();
}
private string CurrentControl
{
get
{
return this.ViewState["CurrentControl"] == null ? string.Empty : (string)this.ViewState["CurrentControl"];
}
set
{
this.ViewState["CurrentControl"] = value;
}
}
private void LoadMyUserControl(string controlName, Control parent)
{
parent.Controls.Clear();
UserControl MyControl = (UserControl)LoadControl(controlName);
string userControlID = controlName.Split('.')[0];
MyControl.ID = userControlID.Replace("/", "").Replace("~", "");
parent.Controls.Add(MyControl);
this.CurrentControl = controlName;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
this.LoadMyUserControl("~/UserControls/BackendModule/SchemeCategory Master/ucSchemeCategory.ascx", this.Page);
string test= drpcategory.SelectedValue;
}
protected void Page_Load(object sender, EventArgs e)
{
//-----pramod
if (this.CurrentControl != string.Empty)
{
LoadMyUserControl(CurrentControl, this.Page);
}
}
protected void Page_Init(object sender, EventArgs e)
{
FunBindCategory();
}
private string CurrentControl
{
get
{
return this.ViewState["CurrentControl"] == null ? string.Empty : (string)this.ViewState["CurrentControl"];
}
set
{
this.ViewState["CurrentControl"] = value;
}
}
private void LoadMyUserControl(string controlName, Control parent)
{
parent.Controls.Clear();
UserControl MyControl = (UserControl)LoadControl(controlName);
string userControlID = controlName.Split('.')[0];
MyControl.ID = userControlID.Replace("/", "").Replace("~", "");
parent.Controls.Add(MyControl);
this.CurrentControl = controlName;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
this.LoadMyUserControl("~/UserControls/BackendModule/SchemeCategory Master/ucSchemeCategory.ascx", this.Page);
string test= drpcategory.SelectedValue;
}
Monday, 25 March 2019
Thursday, 28 February 2019
Custom Field add in Umbraco CMS
This is folder structure
\App_Plugins\ChannelSelection
channelselection.controller.js
channelselection.html
package.manifest
file contain
------------channelselection.controller.js--------------------
angular.module("umbraco")
.controller("My.ChannelSelectionController",
function ($scope) {
$.ajax({
url: "/umbraco/api/Portfolio/GetDropdownList",
dataType: "json",
type: "GET",
error: function () {
//alert(" An error occurred.");
},
success: function (data) {
console.log(JSON.stringify(data));
$('#fillvalues').find("option").remove();
var option = $("<option/>");
// option.attr("value", "").text("Select Channel");
$("#fillvalues").append(option);
$.each(data, function (i, product) {
$.each(product.Channel, function (j, productj) {
option = $("<option/>");
option.attr("value", productj.Id).text(productj.Name);
$("#fillvalues").append(option);
// contentc += ' <li><a href="' + productj.link + '"><img src="' + productj.Image + '" alt="' + productj.Name + '" /></a></li>';
});
});
$('#fillvalues').val($scope.model.value);
}
});
//alert('Control loaded');
});
--------------------channelselection.html-------------
<div ng-controller="My.ChannelSelectionController">
<select id="fillvalues" ng-model="model.value"></select>
</div>
--------------------package.manifest---------------
{
//you can define multiple editors
propertyEditors: [
{
/*this must be a unique alias*/
alias: "My.ChannelSelection",
/*the name*/
name: "Channel Selection",
/*the html file we will load for the editor*/
editor: {
view: "~/App_Plugins/ChannelSelection/channelselection.html"
}
}
]
,
//array of files we want to inject into the application on app_start
javascript: [
'~/App_Plugins/ChannelSelection/channelselection.controller.js'
]
}
\App_Plugins\ChannelSelection
channelselection.controller.js
channelselection.html
package.manifest
file contain
------------channelselection.controller.js--------------------
angular.module("umbraco")
.controller("My.ChannelSelectionController",
function ($scope) {
$.ajax({
url: "/umbraco/api/Portfolio/GetDropdownList",
dataType: "json",
type: "GET",
error: function () {
//alert(" An error occurred.");
},
success: function (data) {
console.log(JSON.stringify(data));
$('#fillvalues').find("option").remove();
var option = $("<option/>");
// option.attr("value", "").text("Select Channel");
$("#fillvalues").append(option);
$.each(data, function (i, product) {
$.each(product.Channel, function (j, productj) {
option = $("<option/>");
option.attr("value", productj.Id).text(productj.Name);
$("#fillvalues").append(option);
// contentc += ' <li><a href="' + productj.link + '"><img src="' + productj.Image + '" alt="' + productj.Name + '" /></a></li>';
});
});
$('#fillvalues').val($scope.model.value);
}
});
//alert('Control loaded');
});
--------------------channelselection.html-------------
<div ng-controller="My.ChannelSelectionController">
<select id="fillvalues" ng-model="model.value"></select>
</div>
--------------------package.manifest---------------
{
//you can define multiple editors
propertyEditors: [
{
/*this must be a unique alias*/
alias: "My.ChannelSelection",
/*the name*/
name: "Channel Selection",
/*the html file we will load for the editor*/
editor: {
view: "~/App_Plugins/ChannelSelection/channelselection.html"
}
}
]
,
//array of files we want to inject into the application on app_start
javascript: [
'~/App_Plugins/ChannelSelection/channelselection.controller.js'
]
}
Wednesday, 27 February 2019
Json string read in 2.0 frame work and 4.5 frame work c sharp asp.net
Sample json data
{ "d" : { "results" : [ { "ReqId" : "761"]}}}
----------4.5 version---------
JToken token = JToken.Parse(json2);
JArray vacancies = (JArray)token.SelectToken("d.results");
----------2.0 version---------
JObject o = JObject.Parse(json2);
string name = (string)o["d"].ToString();
JObject p = JObject.Parse(name);
JArray vacancies = (JArray)p.SelectToken("results");//d.results
foreach (JToken m in vacancies)
{
Response.Write(m["ReqId"].ToString().Replace("<", "").Replace(">", "").Replace("\"", ""));
}
{ "d" : { "results" : [ { "ReqId" : "761"]}}}
----------4.5 version---------
JToken token = JToken.Parse(json2);
JArray vacancies = (JArray)token.SelectToken("d.results");
----------2.0 version---------
JObject o = JObject.Parse(json2);
string name = (string)o["d"].ToString();
JObject p = JObject.Parse(name);
JArray vacancies = (JArray)p.SelectToken("results");//d.results
foreach (JToken m in vacancies)
{
Response.Write(m["ReqId"].ToString().Replace("<", "").Replace(">", "").Replace("\"", ""));
}
Thursday, 14 February 2019
Convert Json String To DataTable C sharpasp .net
============================================
DataTable [] dt;
string JsonString = string.Empty;
ConvertJsonStringToDataTable jDt = new ConvertJsonStringToDataTable();
JsonString = ui_lbl_JsonString.Text;
dt = jDt.JsonStringToDataTable(JsonString);
=================Logic======================
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
public class ConvertJsonStringToDataTable
{
public DataTable[] JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
if (!ColumnsName.Contains("\\"))
{
ColumnsName.Add(ColumnsNameString);
}
}
}
catch (Exception ex)
{
throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
if (AddColumnName.Contains("\\"))
{
dt1.Columns.Add(AddColumnName.Replace("\\",""));
}
else
{
dt.Columns.Add(AddColumnName);
}
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
if (!RowDataString.Contains("\\"))
{
nr[RowColumns] = RowDataString;
}
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt1.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
if (RowDataString.Contains("\\"))
{
nr[RowColumns.Replace("\\", "")] = RowDataString.Replace("\\", "");
}
}
catch (Exception ex)
{
continue;
}
}
dt1.Rows.Add(nr);
}
return new DataTable[] { dt, dt1 };
}
}
DataTable [] dt;
string JsonString = string.Empty;
ConvertJsonStringToDataTable jDt = new ConvertJsonStringToDataTable();
JsonString = ui_lbl_JsonString.Text;
dt = jDt.JsonStringToDataTable(JsonString);
=================Logic======================
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
public class ConvertJsonStringToDataTable
{
public DataTable[] JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
if (!ColumnsName.Contains("\\"))
{
ColumnsName.Add(ColumnsNameString);
}
}
}
catch (Exception ex)
{
throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
if (AddColumnName.Contains("\\"))
{
dt1.Columns.Add(AddColumnName.Replace("\\",""));
}
else
{
dt.Columns.Add(AddColumnName);
}
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
if (!RowDataString.Contains("\\"))
{
nr[RowColumns] = RowDataString;
}
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt1.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
if (RowDataString.Contains("\\"))
{
nr[RowColumns.Replace("\\", "")] = RowDataString.Replace("\\", "");
}
}
catch (Exception ex)
{
continue;
}
}
dt1.Rows.Add(nr);
}
return new DataTable[] { dt, dt1 };
}
}
Add array value in hidden field and retrieve array value from hidden value
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
//For Add array
$("#selcity").on("change", function () {
var itemval = $("#selcity option:selected").val();
var itemtext = $("#selcity option:selected").text();
var items = JSON.parse($('#hdfield').val());
//Avaide duplicate
var bool = true;
for (var i = 0; i < items.length; i++) {
if (items[i][1] == itemval) {
bool = false;
}
}
// $("#selcity").each(function () {
// alert($(this).val() +'=='+ itemval+ ($(this).val() == itemval))
// if ($(this).val() == itemval) {
// bool = true;
// }
// })
if (bool) {
//For Add
var items1 = [itemtext, itemval]
items.push(items1)
console.log(JSON.stringify(items));
document.getElementById("Start").innerHTML = JSON.stringify(items);
$('#hdfield').val(JSON.stringify(items));
}
//For remove
// for (var i = 0; i < items.length; i++) {
// if (items[i][0] == "Mumbai") {
// items.splice(i, 1);
// }
// }
})
});
function pushvalue() {
var items = JSON.parse($('#hdfield').val());
var items1 = ["Nasik", 40]
items.push(items1)
console.log(JSON.stringify(items));
document.getElementById("Start").innerHTML = JSON.stringify(items);
$('#hdfield').val(JSON.stringify(items));
}
function hdread() {
var items = value = JSON.parse($('#hdfield').val());
for (var i = 0; i < items.length; i++) {
alert("hdread " + items[i][1] + '-' + items[i][0])
}
document.getElementById("Start").innerHTML = JSON.stringify(items);
}
</script>
</head>
<body>
<span >Start</span>
<div id='Start'></div>
<p>--------------</p>
<span>Then</span>
<div id='Then'></div>
<input type="hidden" id="hdfield" />
<select id="selcity" >
<option value="40" >Akola</option>
<option value="50" >Bhusawal</option>
<option value="60" >Raigad</option>
</select>
</body>
<script type="text/javascript" language="javascript">
var items = [
["Mumbai", 10],
["Jalgaon", 20],
["Pune", 30]
];
// for (var i = 0; i < items.length; i++) {
// if (items[i][1] == "10") {
// items.splice(i, 1);
// }
// }
console.log(items);
$('#hdfield').val(JSON.stringify(items));
console.log(JSON.stringify(items))
var value = $('#hdfield').val();
value = JSON.parse(value);
</script>
</html>
Tuesday, 29 January 2019
Web service call time given SSL error in ASP .net
<!-- User Validation API at LOGIN module Begin-->
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="UserValidateSoap">
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://localhost/abcd.asmx" binding="basicHttpBinding" bindingConfiguration="UserValidateSoap" contract="UserValidate.UserValidateSoap" name="UserValidateSoap" />
</client>
</system.serviceModel>
<!-- User Validation API at LOGIN module End-->
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="UserValidateSoap">
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://localhost/abcd.asmx" binding="basicHttpBinding" bindingConfiguration="UserValidateSoap" contract="UserValidate.UserValidateSoap" name="UserValidateSoap" />
</client>
</system.serviceModel>
<!-- User Validation API at LOGIN module End-->
Monday, 28 January 2019
Business Logic for Email send mail in C sharp in .net
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections;
namespace Business_Logic
{
public class AppHandler
{
private MailAddress emailRecipient;
private MailAddress emailRecipientCC;
private MailAddress emailSender;
private String emailTo;
private String emailCopy;
private String emailPriority;
private String emailSubject;
private String emailMessage;
private String emailSmtp;
private FileUpload[] emailfileUpload;
private string[] emailFile;
string[] arrFields = new string[1000];
string[] arrValues = new string[1000];
// Email To multiple
public String EmailTo
{
get { return emailTo; }
set { emailTo = value; }
}
// Email Receipient
public MailAddress EmailRecipient
{
get { return emailRecipient; }
set { emailRecipient = value; }
}
// Email Receipient CC
public MailAddress EmailRecipientCC
{
get { return emailRecipientCC; }
set { emailRecipientCC = value; }
}
// Files upload
public FileUpload[] UploadFiles
{
get { return emailfileUpload; }
set { emailfileUpload = value; }
}
public string[] AttachedFilePath
{
get { return emailFile; }
set { emailFile = value; }
}
//Email sender
public MailAddress EmailSender
{
get { return emailSender; }
set { emailSender = value; }
}
// Email copy
public String EmailCopy
{
get { return emailCopy; }
set { emailCopy = value; }
}
// Email Priority
public String EmailPriority
{
get { return emailPriority; }
set { emailPriority = value; }
}
//Email Subject
public String EmailSubject
{
get { return emailSubject; }
set { emailSubject = value; }
}
//Email Message
public String EmailMessage
{
get { return emailMessage; }
set { emailMessage = value; }
}
//Email Smtp address
public String EmailSmtp
{
get { return emailSmtp; }
set { emailSmtp = value; }
}
}
}
========================
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Business_Logic
{
public sealed class EmailHandler
{
private static char[] charSeparators = new char[] { };
private static String[] result;
private static String[] resultCC;
public static void SendMailMessage(AppHandler pMailApp)
{
try
{
MailMessage mailMsg = new MailMessage();
result = pMailApp.EmailRecipient.ToString().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for (int count = 0; count < result.Length; count++)
{
mailMsg.To.Add(new MailAddress(result[count]));
}
if (pMailApp.EmailRecipientCC != null)
{
if (!string.IsNullOrEmpty(pMailApp.EmailRecipientCC.ToString()))
{
resultCC = pMailApp.EmailRecipientCC.ToString().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for (int count = 0; count < resultCC.Length; count++)
{
mailMsg.CC.Add(new MailAddress(resultCC[count]));
}
}
}
mailMsg.IsBodyHtml = true;
//Email Sender
mailMsg.From = pMailApp.EmailSender;
//Email Subject
mailMsg.Subject = pMailApp.EmailSubject;
//Email Body
mailMsg.Body = pMailApp.EmailMessage;
//Email Priority
switch (pMailApp.EmailPriority.ToString())
{
case "Low" :
mailMsg.Priority = MailPriority.Low;
break;
case "Normal" :
mailMsg.Priority = MailPriority.Normal;
break;
case "High" :
mailMsg.Priority = MailPriority.High;
break;
}
//Attachments
if (pMailApp.AttachedFilePath != null)
{
for (int i = 0; i < pMailApp.AttachedFilePath.Length; i++)
{
Attachment attachFile= new Attachment(pMailApp.AttachedFilePath[i]);
mailMsg.Attachments.Add(attachFile);
}
}
//SMTP address
SmtpClient smtpClient = new SmtpClient(pMailApp.EmailSmtp);
// smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
throw (ex);
}
}
public static void SendMailMessagenewMultiple(AppHandler pMailApp)
{
try
{
MailMessage mailMsg = new MailMessage();
result = pMailApp.EmailTo.ToString().Split(';');
for (int count = 0; count < result.Length; count++)
{
mailMsg.To.Add(new MailAddress(result[count]));
}
if (pMailApp.EmailRecipientCC != null)
{
if (!string.IsNullOrEmpty(pMailApp.EmailRecipientCC.ToString()))
{
resultCC = pMailApp.EmailRecipientCC.ToString().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for (int count = 0; count < resultCC.Length; count++)
{
mailMsg.CC.Add(new MailAddress(resultCC[count]));
}
}
}
mailMsg.IsBodyHtml = true;
//Email Sender
mailMsg.From = pMailApp.EmailSender;
//Email Subject
mailMsg.Subject = pMailApp.EmailSubject;
//Email Body
mailMsg.Body = pMailApp.EmailMessage;
//Email Priority
switch (pMailApp.EmailPriority.ToString())
{
case "Low":
mailMsg.Priority = MailPriority.Low;
break;
case "Normal":
mailMsg.Priority = MailPriority.Normal;
break;
case "High":
mailMsg.Priority = MailPriority.High;
break;
}
//Attachments
if (pMailApp.AttachedFilePath != null)
{
for (int i = 0; i < pMailApp.AttachedFilePath.Length; i++)
{
Attachment attachFile = new Attachment(pMailApp.AttachedFilePath[i]);
mailMsg.Attachments.Add(attachFile);
}
}
//SMTP address
SmtpClient smtpClient = new SmtpClient(pMailApp.EmailSmtp);
// smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
throw (ex);
}
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections;
namespace Business_Logic
{
public class AppHandler
{
private MailAddress emailRecipient;
private MailAddress emailRecipientCC;
private MailAddress emailSender;
private String emailTo;
private String emailCopy;
private String emailPriority;
private String emailSubject;
private String emailMessage;
private String emailSmtp;
private FileUpload[] emailfileUpload;
private string[] emailFile;
string[] arrFields = new string[1000];
string[] arrValues = new string[1000];
// Email To multiple
public String EmailTo
{
get { return emailTo; }
set { emailTo = value; }
}
// Email Receipient
public MailAddress EmailRecipient
{
get { return emailRecipient; }
set { emailRecipient = value; }
}
// Email Receipient CC
public MailAddress EmailRecipientCC
{
get { return emailRecipientCC; }
set { emailRecipientCC = value; }
}
// Files upload
public FileUpload[] UploadFiles
{
get { return emailfileUpload; }
set { emailfileUpload = value; }
}
public string[] AttachedFilePath
{
get { return emailFile; }
set { emailFile = value; }
}
//Email sender
public MailAddress EmailSender
{
get { return emailSender; }
set { emailSender = value; }
}
// Email copy
public String EmailCopy
{
get { return emailCopy; }
set { emailCopy = value; }
}
// Email Priority
public String EmailPriority
{
get { return emailPriority; }
set { emailPriority = value; }
}
//Email Subject
public String EmailSubject
{
get { return emailSubject; }
set { emailSubject = value; }
}
//Email Message
public String EmailMessage
{
get { return emailMessage; }
set { emailMessage = value; }
}
//Email Smtp address
public String EmailSmtp
{
get { return emailSmtp; }
set { emailSmtp = value; }
}
}
}
========================
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Business_Logic
{
public sealed class EmailHandler
{
private static char[] charSeparators = new char[] { };
private static String[] result;
private static String[] resultCC;
public static void SendMailMessage(AppHandler pMailApp)
{
try
{
MailMessage mailMsg = new MailMessage();
result = pMailApp.EmailRecipient.ToString().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for (int count = 0; count < result.Length; count++)
{
mailMsg.To.Add(new MailAddress(result[count]));
}
if (pMailApp.EmailRecipientCC != null)
{
if (!string.IsNullOrEmpty(pMailApp.EmailRecipientCC.ToString()))
{
resultCC = pMailApp.EmailRecipientCC.ToString().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for (int count = 0; count < resultCC.Length; count++)
{
mailMsg.CC.Add(new MailAddress(resultCC[count]));
}
}
}
mailMsg.IsBodyHtml = true;
//Email Sender
mailMsg.From = pMailApp.EmailSender;
//Email Subject
mailMsg.Subject = pMailApp.EmailSubject;
//Email Body
mailMsg.Body = pMailApp.EmailMessage;
//Email Priority
switch (pMailApp.EmailPriority.ToString())
{
case "Low" :
mailMsg.Priority = MailPriority.Low;
break;
case "Normal" :
mailMsg.Priority = MailPriority.Normal;
break;
case "High" :
mailMsg.Priority = MailPriority.High;
break;
}
//Attachments
if (pMailApp.AttachedFilePath != null)
{
for (int i = 0; i < pMailApp.AttachedFilePath.Length; i++)
{
Attachment attachFile= new Attachment(pMailApp.AttachedFilePath[i]);
mailMsg.Attachments.Add(attachFile);
}
}
//SMTP address
SmtpClient smtpClient = new SmtpClient(pMailApp.EmailSmtp);
// smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
throw (ex);
}
}
public static void SendMailMessagenewMultiple(AppHandler pMailApp)
{
try
{
MailMessage mailMsg = new MailMessage();
result = pMailApp.EmailTo.ToString().Split(';');
for (int count = 0; count < result.Length; count++)
{
mailMsg.To.Add(new MailAddress(result[count]));
}
if (pMailApp.EmailRecipientCC != null)
{
if (!string.IsNullOrEmpty(pMailApp.EmailRecipientCC.ToString()))
{
resultCC = pMailApp.EmailRecipientCC.ToString().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
for (int count = 0; count < resultCC.Length; count++)
{
mailMsg.CC.Add(new MailAddress(resultCC[count]));
}
}
}
mailMsg.IsBodyHtml = true;
//Email Sender
mailMsg.From = pMailApp.EmailSender;
//Email Subject
mailMsg.Subject = pMailApp.EmailSubject;
//Email Body
mailMsg.Body = pMailApp.EmailMessage;
//Email Priority
switch (pMailApp.EmailPriority.ToString())
{
case "Low":
mailMsg.Priority = MailPriority.Low;
break;
case "Normal":
mailMsg.Priority = MailPriority.Normal;
break;
case "High":
mailMsg.Priority = MailPriority.High;
break;
}
//Attachments
if (pMailApp.AttachedFilePath != null)
{
for (int i = 0; i < pMailApp.AttachedFilePath.Length; i++)
{
Attachment attachFile = new Attachment(pMailApp.AttachedFilePath[i]);
mailMsg.Attachments.Add(attachFile);
}
}
//SMTP address
SmtpClient smtpClient = new SmtpClient(pMailApp.EmailSmtp);
// smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
throw (ex);
}
}
}
}
Wednesday, 16 January 2019
Insert, Update, Delete in List view XML in Asp.net c sharp
==========================Employee.xml=========
<?xml version="1.0" encoding="utf-8"?>
<NewElement>
<Employee>
<ID>1</ID>
<Name>pramod s r</Name>
</Employee>
<Employee>
<ID>2</ID>
<Name>koli</Name>
</Employee>
<Employee>
<ID>3</ID>
<Name>xyz</Name>
</Employee>
<Employee>
<ID>4</ID>
<Name>sdfsdf</Name>
</Employee>
</NewElement>
==============================Design=============================
<asp:ListView ID="lvEmployee" runat="server" InsertItemPosition="LastItem" OnItemInserting="lvEmployee_ItemInserting"
OnItemDeleting="lvEmployee_ItemDeleting" OnItemEditing="lvEmployee_ItemEditing"
OnItemCanceling="lvEmployee_ItemCanceling" >
<LayoutTemplate>
<table id="Table1" runat="server">
<tr id="Tr1" runat="server">
<td id="Td1" runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr id="Tr2" runat="server" style="">
<th id="Th1" runat="server">
</th>
<th id="Th2" runat="server">
ID
</th>
<th id="Th3" runat="server">
Name
</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr id="Tr3" runat="server">
<td id="Td2" runat="server" style="">
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
</td>
<td>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>' />
</td>
<td>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>' />
</td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />
</td>
<td>
</td>
<td>
<asp:TextBox ID="txtID" runat="server" Text='<%# Bind("ID") %>' />
</td>
<td>
<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>' />
</td>
<td>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />
</td>
</tr>
</InsertItemTemplate>
</asp:ListView>
==================================Code======================
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml;
public partial class Listview_XML : System.Web.UI.Page
{
//Global varaiable declaration
string xmlfile = @"E:\Employee.xml";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
//Loading the data from xml file
protected void LoadData()
{
DataSet ds = new DataSet();
DataTable table = new DataTable();
//reading xml file and loading listview.
ds.ReadXml(xmlfile);
lvEmployee.DataSource = ds;
//binding dataset to listview.
lvEmployee.DataBind();
}
// onclick of insert button in listview
protected void lvEmployee_ItemInserting(object sender, ListViewInsertEventArgs e)
{
TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
// loading xml file
XmlDocument xdoc = new XmlDocument();
xdoc.Load(xmlfile);
//Creating childnode to root node using Xmlelement
XmlElement xelement = xdoc.CreateElement("Employee");
//creating subnode to childnode using XmlElement
XmlElement xID = xdoc.CreateElement("ID");
xID.InnerText = txtidTextBox.Text;
xelement.AppendChild(xID);
//creating subnode to childnode using XmlElement
XmlElement xName = xdoc.CreateElement("Name");
xName.InnerText = txtnameTextBox.Text;
xelement.AppendChild(xName);
//Adding childnode to the root node.(in my case "NewElement is root node")
xdoc.DocumentElement.AppendChild(xelement);
xdoc.Save(xmlfile);
LoadData();
}
// onclick of edit button in listview
static Int16 i = 0;// based on the requirement we can change the declaration of variable i.
protected void lvEmployee_ItemEditing(object sender, ListViewEditEventArgs e)
{
//getting the index value of particular row on click of edit button
lvEmployee.EditIndex = e.NewEditIndex;
i = Convert.ToInt16(lvEmployee.EditIndex);
// to get the values from label which is inside listview, we need FindControl
Label lblid = (Label)lvEmployee.EditItem.FindControl("lblID");
Label lblname = (Label)lvEmployee.EditItem.FindControl("lblName");
// to get the values from textbox which is inside listview, we need FindControl
TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
txtidTextBox.Text = lblid.Text;
txtidTextBox.Visible = false;
txtnameTextBox.Text = lblname.Text;
}
protected void lvEmployee_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
// to get the values from label which is inside listview, we need FindControl
Label lbl = (lvEmployee.Items[e.ItemIndex].FindControl("lblID")) as Label;
Label lblName = (lvEmployee.Items[e.ItemIndex].FindControl("lblName")) as Label;
//loading xml file using Xmldocument.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlfile);
XmlNodeList newXMLNodes = xmlDoc.SelectNodes("/NewElement/Employee");
// here i am searching based on id and name.So i am concatenating data into one string variable.
string value = lbl.Text + lblName.Text;
// code to remove child node from xml based on selection(matches all the data in xml file)
//when a match is found removes that childnode from root node.
foreach (XmlNode newXMLNode in newXMLNodes)
{
if (newXMLNode.InnerText == value)
{
newXMLNode.ParentNode.RemoveChild(newXMLNode);
}
}
//saving back xml file and reloading listview.
xmlDoc.Save(xmlfile);
xmlDoc = null;
LoadData();
}
protected void lvEmployee_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
// to clear the textbox data.. (reset)
TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
txtidTextBox.Text = string.Empty;
txtnameTextBox.Text = string.Empty;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
// to get the values from label which is inside listview, we need FindControl
Label lblid = (Label)lvEmployee.EditItem.FindControl("lblID");
Label lblname = (Label)lvEmployee.EditItem.FindControl("lblName");
// to get the values from textbox which is inside listview, we need FindControl
TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
//loading xml file
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xmlfile);
// Index value will be obtained at lvEmployee_ItemEditing ,that index value
//is used here for update.
XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(i);
xmlnode["ID"].InnerText = lblid.Text;
xmlnode["Name"].InnerText = txtnameTextBox.Text;
// save xml file and reload listview.
xmldoc.Save(xmlfile);
LoadData();
}
catch
{
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<NewElement>
<Employee>
<ID>1</ID>
<Name>pramod s r</Name>
</Employee>
<Employee>
<ID>2</ID>
<Name>koli</Name>
</Employee>
<Employee>
<ID>3</ID>
<Name>xyz</Name>
</Employee>
<Employee>
<ID>4</ID>
<Name>sdfsdf</Name>
</Employee>
</NewElement>
==============================Design=============================
<asp:ListView ID="lvEmployee" runat="server" InsertItemPosition="LastItem" OnItemInserting="lvEmployee_ItemInserting"
OnItemDeleting="lvEmployee_ItemDeleting" OnItemEditing="lvEmployee_ItemEditing"
OnItemCanceling="lvEmployee_ItemCanceling" >
<LayoutTemplate>
<table id="Table1" runat="server">
<tr id="Tr1" runat="server">
<td id="Td1" runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr id="Tr2" runat="server" style="">
<th id="Th1" runat="server">
</th>
<th id="Th2" runat="server">
ID
</th>
<th id="Th3" runat="server">
Name
</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr id="Tr3" runat="server">
<td id="Td2" runat="server" style="">
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
</td>
<td>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>' />
</td>
<td>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>' />
</td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />
</td>
<td>
</td>
<td>
<asp:TextBox ID="txtID" runat="server" Text='<%# Bind("ID") %>' />
</td>
<td>
<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>' />
</td>
<td>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />
</td>
</tr>
</InsertItemTemplate>
</asp:ListView>
==================================Code======================
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml;
public partial class Listview_XML : System.Web.UI.Page
{
//Global varaiable declaration
string xmlfile = @"E:\Employee.xml";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
//Loading the data from xml file
protected void LoadData()
{
DataSet ds = new DataSet();
DataTable table = new DataTable();
//reading xml file and loading listview.
ds.ReadXml(xmlfile);
lvEmployee.DataSource = ds;
//binding dataset to listview.
lvEmployee.DataBind();
}
// onclick of insert button in listview
protected void lvEmployee_ItemInserting(object sender, ListViewInsertEventArgs e)
{
TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
// loading xml file
XmlDocument xdoc = new XmlDocument();
xdoc.Load(xmlfile);
//Creating childnode to root node using Xmlelement
XmlElement xelement = xdoc.CreateElement("Employee");
//creating subnode to childnode using XmlElement
XmlElement xID = xdoc.CreateElement("ID");
xID.InnerText = txtidTextBox.Text;
xelement.AppendChild(xID);
//creating subnode to childnode using XmlElement
XmlElement xName = xdoc.CreateElement("Name");
xName.InnerText = txtnameTextBox.Text;
xelement.AppendChild(xName);
//Adding childnode to the root node.(in my case "NewElement is root node")
xdoc.DocumentElement.AppendChild(xelement);
xdoc.Save(xmlfile);
LoadData();
}
// onclick of edit button in listview
static Int16 i = 0;// based on the requirement we can change the declaration of variable i.
protected void lvEmployee_ItemEditing(object sender, ListViewEditEventArgs e)
{
//getting the index value of particular row on click of edit button
lvEmployee.EditIndex = e.NewEditIndex;
i = Convert.ToInt16(lvEmployee.EditIndex);
// to get the values from label which is inside listview, we need FindControl
Label lblid = (Label)lvEmployee.EditItem.FindControl("lblID");
Label lblname = (Label)lvEmployee.EditItem.FindControl("lblName");
// to get the values from textbox which is inside listview, we need FindControl
TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
txtidTextBox.Text = lblid.Text;
txtidTextBox.Visible = false;
txtnameTextBox.Text = lblname.Text;
}
protected void lvEmployee_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
// to get the values from label which is inside listview, we need FindControl
Label lbl = (lvEmployee.Items[e.ItemIndex].FindControl("lblID")) as Label;
Label lblName = (lvEmployee.Items[e.ItemIndex].FindControl("lblName")) as Label;
//loading xml file using Xmldocument.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlfile);
XmlNodeList newXMLNodes = xmlDoc.SelectNodes("/NewElement/Employee");
// here i am searching based on id and name.So i am concatenating data into one string variable.
string value = lbl.Text + lblName.Text;
// code to remove child node from xml based on selection(matches all the data in xml file)
//when a match is found removes that childnode from root node.
foreach (XmlNode newXMLNode in newXMLNodes)
{
if (newXMLNode.InnerText == value)
{
newXMLNode.ParentNode.RemoveChild(newXMLNode);
}
}
//saving back xml file and reloading listview.
xmlDoc.Save(xmlfile);
xmlDoc = null;
LoadData();
}
protected void lvEmployee_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
// to clear the textbox data.. (reset)
TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
txtidTextBox.Text = string.Empty;
txtnameTextBox.Text = string.Empty;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
// to get the values from label which is inside listview, we need FindControl
Label lblid = (Label)lvEmployee.EditItem.FindControl("lblID");
Label lblname = (Label)lvEmployee.EditItem.FindControl("lblName");
// to get the values from textbox which is inside listview, we need FindControl
TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
//loading xml file
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xmlfile);
// Index value will be obtained at lvEmployee_ItemEditing ,that index value
//is used here for update.
XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(i);
xmlnode["ID"].InnerText = lblid.Text;
xmlnode["Name"].InnerText = txtnameTextBox.Text;
// save xml file and reload listview.
xmldoc.Save(xmlfile);
LoadData();
}
catch
{
}
}
}
Paging button more functionality in List View .net c sharp
===================view================
<form id="form1" runat="server">
<div class="StatusMessage">
<asp:ListView ID="lvEmployee" runat="server" OnDataBound="lvEmployee_DataBound">
<LayoutTemplate>
<table id="itemPlaceholderContainer">
<tr runat="server" id="itemPlaceholder">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
Address:<asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Id") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<div id="divpaging" runat="server">
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvEmployee"
OnPreRender="DataPager1_PreRender">
<Fields>
<asp:TemplatePagerField OnPagerCommand="listPages_Click">
<PagerTemplate>
<asp:Button ID="listPages" runat="server" Text="more"></asp:Button>
</PagerTemplate>
</asp:TemplatePagerField>
</Fields>
</asp:DataPager>
</div>
</div>
</form>
================================Code=========================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class listview_paging : System.Web.UI.Page
{
int CurrentPage = 2;
public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
return Convert.ToInt32(ViewState["PageNumber"]);
else
return 0;
}
set
{
ViewState["PageNumber"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PageNumber = 1;
DataPager1.PageSize = 2;
ProductList db = new ProductList();
lvEmployee.DataSource = db.GellAll();
lvEmployee.DataBind();
}
}
protected void lvEmployee_DataBound(object sender, EventArgs e)
{
int PageCount = (DataPager1.TotalRowCount / 2);
if (PageCount * 2 != DataPager1.TotalRowCount)
{
PageCount = PageCount + 1;
}
}
protected void DataPager1_PreRender(object sender, EventArgs e)
{
ProductList db = new ProductList();
lvEmployee.DataSource = db.GellAll();
lvEmployee.DataBind();
}
protected void listPages_Click(object sender, EventArgs e)
{
decimal PageCount = (decimal)((decimal)DataPager1.TotalRowCount / 2);
if (PageNumber < PageCount)
{
PageNumber = PageNumber + 1;
if (PageNumber >= PageCount)
{
divpaging.Attributes["style"] = "display:none;";
}
}
else
{
divpaging.Attributes["style"] = "display:none;";
}
int PageSize = 2 * PageNumber;//CurrentPage
DataPager1.SetPageProperties(0, PageSize, true);
}
}
<form id="form1" runat="server">
<div class="StatusMessage">
<asp:ListView ID="lvEmployee" runat="server" OnDataBound="lvEmployee_DataBound">
<LayoutTemplate>
<table id="itemPlaceholderContainer">
<tr runat="server" id="itemPlaceholder">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
Address:<asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Id") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<div id="divpaging" runat="server">
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvEmployee"
OnPreRender="DataPager1_PreRender">
<Fields>
<asp:TemplatePagerField OnPagerCommand="listPages_Click">
<PagerTemplate>
<asp:Button ID="listPages" runat="server" Text="more"></asp:Button>
</PagerTemplate>
</asp:TemplatePagerField>
</Fields>
</asp:DataPager>
</div>
</div>
</form>
================================Code=========================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class listview_paging : System.Web.UI.Page
{
int CurrentPage = 2;
public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
return Convert.ToInt32(ViewState["PageNumber"]);
else
return 0;
}
set
{
ViewState["PageNumber"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PageNumber = 1;
DataPager1.PageSize = 2;
ProductList db = new ProductList();
lvEmployee.DataSource = db.GellAll();
lvEmployee.DataBind();
}
}
protected void lvEmployee_DataBound(object sender, EventArgs e)
{
int PageCount = (DataPager1.TotalRowCount / 2);
if (PageCount * 2 != DataPager1.TotalRowCount)
{
PageCount = PageCount + 1;
}
}
protected void DataPager1_PreRender(object sender, EventArgs e)
{
ProductList db = new ProductList();
lvEmployee.DataSource = db.GellAll();
lvEmployee.DataBind();
}
protected void listPages_Click(object sender, EventArgs e)
{
decimal PageCount = (decimal)((decimal)DataPager1.TotalRowCount / 2);
if (PageNumber < PageCount)
{
PageNumber = PageNumber + 1;
if (PageNumber >= PageCount)
{
divpaging.Attributes["style"] = "display:none;";
}
}
else
{
divpaging.Attributes["style"] = "display:none;";
}
int PageSize = 2 * PageNumber;//CurrentPage
DataPager1.SetPageProperties(0, PageSize, true);
}
}
Sunday, 6 January 2019
All Table Count and calculate Space in SQL server
SELECT
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
t.Name
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
t.Name
Subscribe to:
Comments (Atom)
