here is my new chat site for developers
http://www.devlobby.net
26 Eylül 2013 Perşembe
3 Temmuz 2013 Çarşamba
how can i connect to webservice from android
hi.
private static String SOAP_ACTION = "http://tempuri.org/HelloWorld";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String METHOD_NAME = "HelloWorld";
private static final String URL = "http://192.168.1.3:80/tryAndoridWebService/serviceTest.asmx?WSDL";
Button btnConnectWebServis;
EditText txtGetData;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnConnectWebServis= (Button)findViewById(R.id.btnConnectWebServis);
txtGetData= (EditText)findViewById(R.id.txtGetData);
btnConnectWebServis.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Use this to add parameters
request.addProperty("param1","my parameter");// send parameter to webservice
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
if (envelope.bodyIn instanceof SoapFault) {
String str= ((SoapFault) envelope.bodyIn).faultstring;
txtGetData.setText(str);
Log.i("", str);
} else {
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
Log.d("WS", String.valueOf(resultsRequestSOAP));
txtGetData.setText(String.valueOf(resultsRequestSOAP.getProperty(0).toString()));
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "hata : "+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
private static String SOAP_ACTION = "http://tempuri.org/HelloWorld";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String METHOD_NAME = "HelloWorld";
private static final String URL = "http://192.168.1.3:80/tryAndoridWebService/serviceTest.asmx?WSDL";
Button btnConnectWebServis;
EditText txtGetData;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnConnectWebServis= (Button)findViewById(R.id.btnConnectWebServis);
txtGetData= (EditText)findViewById(R.id.txtGetData);
btnConnectWebServis.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Use this to add parameters
request.addProperty("param1","my parameter");// send parameter to webservice
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
if (envelope.bodyIn instanceof SoapFault) {
String str= ((SoapFault) envelope.bodyIn).faultstring;
txtGetData.setText(str);
Log.i("", str);
} else {
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
Log.d("WS", String.valueOf(resultsRequestSOAP));
txtGetData.setText(String.valueOf(resultsRequestSOAP.getProperty(0).toString()));
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "hata : "+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
one more thing
add your manifest.xml file
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
AND
run this code on your adb console
adb forward tcp:8080 tcp:8080
Download Picture as .zip file on asp.net mvc
you must download this dll -- Ionic.Zip.dll
public class cPicture
{
public int CID { get; set; }
public int AlbumID { get; set; }
public int DosyaID { get; set; }
public string name { get; set; }
public double size { get; set; }
public string type { get; set; }
public string url { get; set; }
public string delete_url { get; set; }
public string thumbnail_url { get; set; }
public string delete_type { get; set; }
public string Tag { get; set; }
}
///////////////// then we are creating new class ///////////////////////////////////
public class ZipResult : ActionResult
{
private IEnumerable<string> _files;
private string _fileName;
public string FileName
{
get
{
return _fileName ?? "file.zip";
}
set { _fileName = value; }
}
public ZipResult(params string[] files)
{
this._files = files;
}
public ZipResult(IEnumerable<string> files)
{
this._files = files;
}
public override void ExecuteResult(ControllerContext context)
{
using (ZipFile zf = new ZipFile())
{
zf.AddFiles(_files, false, "");
context.HttpContext
.Response.ContentType = "application/zip";
context.HttpContext
.Response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
zf.Save(context.HttpContext.Response.OutputStream);
}
}
}
/// Now we are creating or ActionResult for download/////////////////////
public ActionResult DownloadPicture()
{
IEnumerable<cPicture> pictures = // our cPictureList
string basePath = Server.MapPath("~/UserFiles/");
IEnumerable<string> pp = pictures.Select(a => Path.Combine(basePath, a.name)).ToArray();
return new ZipResult(pp);
}
<a href="/Home/DownloadPicture/" target="_blank">Download File</a>
<a href="/Home/DownloadPicture/" target="_blank">Download File</a>
Yeah That's it.
27 Haziran 2013 Perşembe
Android Socket programming connection failed
if there is connection failed on your app you must run this command from console
adb forward tcp:8080 tcp:8080
each of this tcp:8080 is your server port and client port number.
1 Haziran 2013 Cumartesi
DEVEXPRESS Use Cascade Combobox in İnline Edit Mode
<dx:GridViewDataComboBoxColumn FieldName="Category1ID" VisibleIndex="4">
<PropertiesComboBox DataSourceID="dsCategory1" TextField="Name" ValueField="ID" ValueType="System.Int32">
</PropertiesComboBox>
<EditItemTemplate>
<dxe:ASPxComboBox ID="Cat1" runat="server"
DataSourceID="dsCategory1" TextField="Name" ValueField="ID" Value='<%# Bind("Category1ID") %>'
AutoPostBack="true" OnSelectedIndexChanged="Cat1_SelectedIndexChanged" ValueType="System.Int32">
</dxe:ASPxComboBox>
</EditItemTemplate>
</dx:GridViewDataComboBoxColumn>
------------------------------------------------------------------------------------------------------------
protected void grid_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
{
if ((e.RowType == GridViewRowType.InlineEdit)) {
ASPxComboBox combo2 = ((ASPxComboBox)grid.FindEditRowCellTemplateControl(
grid.Columns["Category2ID"] as GridViewDataComboBoxColumn, "Cat2"));
if (Request.Params[combo2.UniqueID] != null) return;
if (!grid.IsNewRowEditing) {
object[] vals = (object[])grid.GetRowValues(grid.EditingRowVisibleIndex,
new string[] { "Category2ID", "Category3ID", "Category4ID" });
ASPxComboBox combo4 = ((ASPxComboBox)grid.FindEditRowCellTemplateControl(
grid.Columns["Category4ID"] as GridViewDataComboBoxColumn, "Cat4"));
ASPxComboBox combo3 = ((ASPxComboBox)grid.FindEditRowCellTemplateControl(
grid.Columns["Category3ID"] as GridViewDataComboBoxColumn, "Cat3"));
combo2.Value = vals[0];
combo3.Value = vals[1];
combo4.Value = vals[2];
}
}
}
<PropertiesComboBox DataSourceID="dsCategory1" TextField="Name" ValueField="ID" ValueType="System.Int32">
</PropertiesComboBox>
<EditItemTemplate>
<dxe:ASPxComboBox ID="Cat1" runat="server"
DataSourceID="dsCategory1" TextField="Name" ValueField="ID" Value='<%# Bind("Category1ID") %>'
AutoPostBack="true" OnSelectedIndexChanged="Cat1_SelectedIndexChanged" ValueType="System.Int32">
</dxe:ASPxComboBox>
</EditItemTemplate>
</dx:GridViewDataComboBoxColumn>
------------------------------------------------------------------------------------------------------------
protected void grid_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
{
if ((e.RowType == GridViewRowType.InlineEdit)) {
ASPxComboBox combo2 = ((ASPxComboBox)grid.FindEditRowCellTemplateControl(
grid.Columns["Category2ID"] as GridViewDataComboBoxColumn, "Cat2"));
if (Request.Params[combo2.UniqueID] != null) return;
if (!grid.IsNewRowEditing) {
object[] vals = (object[])grid.GetRowValues(grid.EditingRowVisibleIndex,
new string[] { "Category2ID", "Category3ID", "Category4ID" });
ASPxComboBox combo4 = ((ASPxComboBox)grid.FindEditRowCellTemplateControl(
grid.Columns["Category4ID"] as GridViewDataComboBoxColumn, "Cat4"));
ASPxComboBox combo3 = ((ASPxComboBox)grid.FindEditRowCellTemplateControl(
grid.Columns["Category3ID"] as GridViewDataComboBoxColumn, "Cat3"));
combo2.Value = vals[0];
combo3.Value = vals[1];
combo4.Value = vals[2];
}
}
}
31 Mayıs 2013 Cuma
DEVEXPRESS ASPxGridView PropertiesComboBox DataSource On CodeBehind
<dx:ASPxGridView ID="GridViewTRY" runat="server" DataSourceID="SDSGridViewTRY" KeyFieldName="ID" OnInit="GridViewTRY_Init">
<Columns>
<dx:GridViewDataComboBoxColumn FieldName="PersonalFK" Caption="Personel Adı" ShowInCustomizationForm="True" >
<PropertiesComboBox TextField="PersonelName" ValueField="ID"></PropertiesComboBox>
</dx:GridViewDataComboBoxColumn>
</Columns>
</dx:ASPxGridView>
// on CodeBehind //
protected void GridViewTRY_Init(object sender, EventArgs e)
{
ASPxGridView gridView = (ASPxGridView)sender;
((GridViewDataComboBoxColumn)(gridView.Columns["PersonelFK"])).PropertiesComboBox.DataSource = myPersonalList;
}
<Columns>
<dx:GridViewDataComboBoxColumn FieldName="PersonalFK" Caption="Personel Adı" ShowInCustomizationForm="True" >
<PropertiesComboBox TextField="PersonelName" ValueField="ID"></PropertiesComboBox>
</dx:GridViewDataComboBoxColumn>
</Columns>
</dx:ASPxGridView>
// on CodeBehind //
protected void GridViewTRY_Init(object sender, EventArgs e)
{
ASPxGridView gridView = (ASPxGridView)sender;
((GridViewDataComboBoxColumn)(gridView.Columns["PersonelFK"])).PropertiesComboBox.DataSource = myPersonalList;
}
30 Mayıs 2013 Perşembe
pass null parameter if Selectparameter is null
<asp:SqlDataSource ID="SDStry" runat="server" CancelSelectOnNullParameter="false"
SELECTCommand="SELECT * FROM tbFirma WHERE KisiFK=ISNULL(@KisiFK,KisiFK)">
<SelectParameters>
<asp:Parameter Name="KisiFK" ConvertEmptyStringToNull="true" />
</SelectParameters>
</asp:SqlDataSource>
2 Mayıs 2013 Perşembe
create special Sorting with c#
public class SortByNumber : Comparer<object>
{
public override int Compare(object x, object y)
{
var xParts = x.GetType().GetProperty("Code").GetValue(x, null).ToString().Split(new[] { '.' });
var yParts = y.GetType().GetProperty("Code").GetValue(y, null).ToString().Split(new[] { '.' });
xParts = xParts.Select((c) => { return (c == "" ? "0" : c); }).ToArray();
yParts = yParts.Select((c) => { return (c == "" ? "0" : c); }).ToArray();
int index = 0;
while (true)
{
bool xHasValue = xParts.Length > index;
bool yHasValue = yParts.Length > index;
if (xHasValue && !yHasValue)
return 1; // x bigger
if (!xHasValue && yHasValue)
return -1; // y bigger
if (!xHasValue && !yHasValue)
return 0; // no more values -- same
var xValue = int.Parse(xParts[index]);
var yValue = int.Parse(yParts[index]);
if (xValue > yValue)
return 1; // x bigger
if (xValue < yValue)
return -1; // y bigger
index++;
}
}
}
//*******//
public class ctry { public string Code{ get; set; }}
public void tryTest()
{
List<ctry> cList = new List<ctry>();
cList.Add(new ctry() { Code= "1.1" });
cList.Add(new ctry() { Code = "5" });
cList.Add(new ctry() { Code = "1.5" });
cList.Add(new ctry() { Code = "1.2" });
cList.Add(new ctry() { Code = "1.1.2" });
cList.Add(new ctry() { Code = "1" });
cList.Add(new ctry() { Code = "1.1.1" });
cList.Add(new ctry() { Code = "1.11" });
cList.Add(new ctry() { Code = "1.4" });
cList.Add(new ctry() { Code = "6" });
cList.Sort(new SortComparer ());
}
23 Kasım 2012 Cuma
mvc de $.ajax() ile multi delete
function f_MultiDelete()
{
if ($(".chList").size() > 0) {
var IDS = [];
$(".chList").each(function (i) {
if ($(this).attr('checked') == "checked" && $(this).attr('name') == "checkDelete") {
var ID = $(this).attr("vl");
IDS.push(ID);
}
});
if (IDS.length > 0) {
$.ajax({
type: "POST",url: Path, traditional:true, dataType:"json",
data: { 'IDList': IDS },
success: function (data) {
alert(data);
}
});
}
}
}
<input name="checkDelete" class="chList" vl="4" type="checkbox" />
<input name="checkDelete" class="chList" vl="3" type="checkbox" />
<input name="checkDelete" class="chList" vl="2" type="checkbox" />
<input name="checkDelete" class="chList" vl="5" type="checkbox" />
<div onclick="f_MultiDelete('/Admin/AGaleri/MultiDelete/')" class="btn btn-primary">Seçilileri Sil </div>
public ActionResult MultiDelete(IEnumerable<string> IDList)
{
//IDList parametresinden seçili ID lere ulaşabilirsiniz.
}
24 Ekim 2012 Çarşamba
asp.nette web servis kullanımı
Şimdilik .net 3.5 ta web servisi oluşturabiliyoruz. .net4.0 henüz desteklemiyor
Web servisini projemize 'tryWebService' adında ekliyoruz
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public bool firstService(string name,string lastName)
{
// yazmak istediğimiz kodlar
} // webmethod fonksiyonlarımız istediğimiz kadar çoğaltabiliriz.
}
Web servisini projemize 'tryWebService' adında ekliyoruz
var service1 = new tryWebService.Service1SoapClient();
service1.firstService("parametre1", "parametre2");
// yazdığımız tüm methodlara service1 örneğinden ulaşabiliriz.
28 Eylül 2012 Cuma
asp.net te windows service kullanımı
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
string GetUserInfo(int ID);
[OperationContract()]
IEnumerable<User> GetUserList();
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
[DataContract]
public class User
{
public int ID { get; set; }
public string name { get; set; }
public string password { get; set; }
public User() { }
public User(int _ID, string _name, string _password)
{
this.ID = _ID;
this.name = _name;
this.password = _password;
}
}
//**********************************//
servisi projemize ekledikten sonra
ServiceReference1.IService1 service = new ServiceReference1.Service1Client();
service örneğiyle yazdığımız metodlara ulaşabiliriz.
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
string GetUserInfo(int ID);
[OperationContract()]
IEnumerable<User> GetUserList();
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
[DataContract]
public class User
{
public int ID { get; set; }
public string name { get; set; }
public string password { get; set; }
public User() { }
public User(int _ID, string _name, string _password)
{
this.ID = _ID;
this.name = _name;
this.password = _password;
}
}
//**********************************//
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public string GetUserInfo(int ID)
{
string sb = "";
User us = new User() { ID = 3, name = "hakan", password = "passsssssss" };
if (us.ID == ID)
{
sb = us.ID + " : " + us.name + " : " + us.password;
}
return sb;
}
public IEnumerable<User> GetUserList()
{
NSGenel.Genel.MesajGoster("ok");
return new List<User>() { new User() { ID = 3, name = "asdfsdf", password = "psdfsf" } };
//return (List<User>)(us.Add(new User { ID = 3, name = "dfgdfg", password = "passs" }));
}
}
//******************************//servisi projemize ekledikten sonra
ServiceReference1.IService1 service = new ServiceReference1.Service1Client();
service örneğiyle yazdığımız metodlara ulaşabiliriz.
11 Eylül 2012 Salı
asp.net mvc de bot yapımı
sayfadaki tüm <a> ve <a> tagı içerisindeki <img> taglarını çekmek için
//******************************************//
index sayfamız
<h2>Index</h2>
@{
List<string> datas = (List<string>)ViewData["datas"];
foreach(string s in datas.ToList())
{
<hr />
<label>@s.ToString()</label>
}
}
public ActionResult Index()
{
ViewData["datas"] = ss();
return View();
}
List<string> dataList = new List<string>();
private List<string> ss()
{
string Site = "http://shiftdelete.net/";
WebClient client = new WebClient();
Stream data = client.OpenRead(Site);
StreamReader reader = new StreamReader(data, Encoding.GetEncoding("utf-8"));
string datas = reader.ReadToEnd();
string pattern3 = "<a.*?href=.*?>(.*?(<img.*?>).*?)</a>";
MatchCollection mathcollection = System.Text.RegularExpressions.Regex.Matches(datas, pattern3);
foreach (Match match in mathcollection)
{
if (match.Value.ToString().Contains("<img"))
dataList.Add(match.Value);
}
return dataList;
}
//******************************************//
index sayfamız
<h2>Index</h2>
@{
List<string> datas = (List<string>)ViewData["datas"];
foreach(string s in datas.ToList())
{
<hr />
<label>@s.ToString()</label>
}
}
Etiketler:
asp.net,
asp.net mvc,
bot,
c#,
düzenli ifadeler,
regex
9 Eylül 2012 Pazar
asp.net mvc de jQuery.ajax ile UserControl Kullanımı
function f_EditCategory(path) {
$.ajax({
url: path, type: 'POST',
success: function (data) {
$("#divTake").load(data);
},
data: { Mode: ID }
});
jQuery.facebox();
}
<a onclick='f_EditCategory("/AHome/EditCategory/5/"'>Kategori Düzenle </a>
<div id='divTake'></div>
//***************************************//
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditCategory(int? p1)
{
ViewData["ID"] = p1.HasValue ? p1.Value : 0;
return PartialView("UserControl1");
}
//**************************************//
UserControl1 içeriği
<div>
gelen ID @ViewData[ID]
</div>
$.ajax({
url: path, type: 'POST',
success: function (data) {
$("#divTake").load(data);
},
data: { Mode: ID }
});
jQuery.facebox();
}
<a onclick='f_EditCategory("/AHome/EditCategory/5/"'>Kategori Düzenle </a>
<div id='divTake'></div>
//***************************************//
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditCategory(int? p1)
{
ViewData["ID"] = p1.HasValue ? p1.Value : 0;
return PartialView("UserControl1");
}
//**************************************//
UserControl1 içeriği
<div>
gelen ID @ViewData[ID]
</div>
8 Eylül 2012 Cumartesi
asp.net mvc de jQuery.ajax ile Resim,Dosya(multiupload) Ekleme
http://www.uploadify.com/ ilgili dosyaları indirdikten sonra
<link href="@Url.Content("~/Content/uploadify/uploadify.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Content/uploadify/jquery.uploadify.min.js")" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function () {
var inputName = "file";
jQuery("#" + inputName).uploadify({
'hideButton': true,
'wmode': 'transparent',
'buttonText':'Seçiniz',
'swf': '@Url.Content("~/Content/uploadify/uploadify.swf")',
'uploader': '@Url.Action("Upload","Home")',
'script': '@Url.Action("Upload", "Home")',
//'script': '/Home/Upload',
'fileDataName': inputName,
'sizeLimit': 38000000,
'cancelImg': '@Url.Content("~/Content/uploadify/cancel.png")',
'auto': false,
'debug': false,
'multi': true,
'formData': { 'ID': '2', 'KID': '3' },// Extra parametre göndermek isteyenler için..
"onUploadStart":function (file) { $("#" + inputName).uploadify("settings", "ID", 'KID', 2); },// Extra parametre göndermek isteyenler için..
onError: function () { alert('some error occurred. Sorry'); },
onComplete: function (event, queueId, fileObj, response, data) { alert(response); }
});
});
</script>
<p>
<form method="post" enctype="multipart/form-data">
<p>
<input type="file" name="file" id="file" />
<a href="javascript:$('#file').uploadify('upload','*')">Upload Files</a>
</p>
</form>
</p>
[HttpPost]
public JsonResult Upload(int? ID,int? KID)
{
foreach (string file1 in Request.Files)
{
var postedFileBase = Request.Files[file1];
string filename= postedFileBase.FileName;
postedFileBase.SaveAs(HttpContext.Server.MapPath("/UserFiles/") + filename);
}
return Json(true);
}
<link href="@Url.Content("~/Content/uploadify/uploadify.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Content/uploadify/jquery.uploadify.min.js")" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function () {
var inputName = "file";
jQuery("#" + inputName).uploadify({
'hideButton': true,
'wmode': 'transparent',
'buttonText':'Seçiniz',
'swf': '@Url.Content("~/Content/uploadify/uploadify.swf")',
'uploader': '@Url.Action("Upload","Home")',
'script': '@Url.Action("Upload", "Home")',
//'script': '/Home/Upload',
'fileDataName': inputName,
'sizeLimit': 38000000,
'cancelImg': '@Url.Content("~/Content/uploadify/cancel.png")',
'auto': false,
'debug': false,
'multi': true,
'formData': { 'ID': '2', 'KID': '3' },// Extra parametre göndermek isteyenler için..
"onUploadStart":function (file) { $("#" + inputName).uploadify("settings", "ID", 'KID', 2); },// Extra parametre göndermek isteyenler için..
onError: function () { alert('some error occurred. Sorry'); },
onComplete: function (event, queueId, fileObj, response, data) { alert(response); }
});
});
</script>
<p>
<form method="post" enctype="multipart/form-data">
<p>
<input type="file" name="file" id="file" />
<a href="javascript:$('#file').uploadify('upload','*')">Upload Files</a>
</p>
</form>
</p>
[HttpPost]
public JsonResult Upload(int? ID,int? KID)
{
foreach (string file1 in Request.Files)
{
var postedFileBase = Request.Files[file1];
string filename= postedFileBase.FileName;
postedFileBase.SaveAs(HttpContext.Server.MapPath("/UserFiles/") + filename);
}
return Json(true);
}
Etiketler:
asp.net mvc,
ekleme,
jquery,
multiupload,
Upload
UserControl da Event Tanımlama
UserControldaki buttonumuz için click event
public delegate void UserControlbtnClikcHandler(object sender, EventArgs e);
public event UserControlbtnClikcHandler btnLoginClick;
private void btnLogin_Click(object sender, EventArgs e)
{
if (this.btnLoginClick != null)
this.btnLoginClick(sender, e);
}
UserControlu kullandığımız formdan erişmek için
private void ucLogin1_btnLoginClick(object sender, EventArgs e)
{
MessageBox.Show(""); //usercontroldeki tüm controllere ucLogin1. şeklinde ulaşabiliriz..
}
Etiketler:
asp.net,
c#,
event,
eventHandler,
UserControl
6 Eylül 2012 Perşembe
base64 encode,read byte
public static string base64Encode(string data)
{
try
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception e)
{
throw new Exception("Error in base64Encode" + e.Message);
}
}
public static string base64Decode(string data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch (Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}
//*****************//
public static byte[] getBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
4 Eylül 2012 Salı
asp.net mvc de döviz kurlarını alma
public ActionResult Index()
{
XmlTextReader oku = new XmlTextReader("http://www.tcmb.gov.tr/kurlar/today.xml");
XmlDocument dok = new XmlDocument();
dok.Load(oku);
XmlNode xdollar = dok.SelectSingleNode("/Tarih_Date/Currency[CurrencyName='US DOLLAR']");
XmlNode xeuro = dok.SelectSingleNode("/Tarih_Date/Currency[CurrencyName='EURO']");
XmlNode xsterling = dok.SelectSingleNode("/Tarih_Date/Currency[CurrencyName='POUND STERLING']");
double dolar = double.Parse(xdollar.ChildNodes[4].InnerText);
double euro = double.Parse(xeuro.ChildNodes[4].InnerText);
double sterling = double.Parse(xsterling.ChildNodes[4].InnerText);
ViewData["dolar"] = dolar;
ViewData["euro"] = euro;
ViewData["sterling"] = sterling;
//ya da
Func<XmlNode, double> fnc = delegate(XmlNode x) {
return double.Parse(x.ChildNodes[4].InnerText);
};
ViewData["dolar"] = fnc(xdollar);
ViewData["euro"] = fnc(xeuro);
ViewData["sterling"] = fnc(xsterling);
//ya da
Func<XmlNode, double> fnc = delegate(XmlNode x) {
return double.Parse(x.ChildNodes[4].InnerText);
};
ViewData["dolar"] = fnc(xdollar);
ViewData["euro"] = fnc(xeuro);
ViewData["sterling"] = fnc(xsterling);
return View();
}
//*************************************//
<h2>Index</h2>
Dolar: @ViewData["dolar"]<hr />
Euro: @ViewData["euro"]<hr />
Sterling: @ViewData["sterling"]
3 Eylül 2012 Pazartesi
asp.net mvc de jQuery ajax ile post işlemi
var path='/Home/Update';
function (path, ID) {
$.ajax({
url: path, type: 'POST',
success: function (msg) { alert(msg); },
data: { param1: ID} });
}
//************************//
public JsonResult Update(int? param1)
{
//işlemler
return Json("ok");
}
1 Eylül 2012 Cumartesi
jQuery sayfalama kodlarım
<div class="pagination" id="divPager"></div>
<div style=" display:none;">
<label id="lblTotalRecord">50</label>// taoplam kayıt sayısı
<label id="lblRecordSize">15 </label>// sayfada kaç adet
<label id="lblNumSize">10 </label>// numarator sayısı
<label id="lblCurrentPage">2 </label>// geçerli sayfa
</div>
<script type="text/javascript">
$(document).ready(function () {
f_GetPage("/AHome/Hizmet/Sayfa/");
});
$(document).ready(function () {
f_GetPage("/AHome/Hizmet/Sayfa/");
});
function
f_GetPage (path) {
var TotalRecord, RecordSize, NumSize, CurrentPage;
TotalRecord = jQuery("#lblTotalRecord").text(); RecordSize = jQuery("#lblRecordSize").text(); NumSize = jQuery("#lblNumSize").text(); CurrentPage = jQuery("#lblCurrentPage").text();
jQuery("#divPager > ul ").html(f_Page(path, TotalRecord, RecordSize, NumSize, CurrentPage));
}
function f_Page(Path, TotalRecord, RecordSize, NumSize, CurrentPage) {
var sb = "0";
TotalRecord = parseInt(TotalRecord);RecordSize = parseInt(RecordSize);CurrentPage = parseInt(CurrentPage);
if (TotalRecord > RecordSize) {
sb = "<span class='spnc' id='spnc" + NumSize + "'></span>";
var TotalNum;
TotalNum = TotalRecord % RecordSize ? Math.floor(TotalRecord / RecordSize + 1) : TotalRecord / RecordSize;
if (TotalNum >= CurrentPage) {
var startindex = CurrentPage % NumSize ? Math.floor(CurrentPage / NumSize) : CurrentPage / NumSize - 1;
startindex = startindex * NumSize;
var finishindex = parseInt(startindex) + parseInt(NumSize);
var tfi = TotalRecord % RecordSize ? Math.floor(TotalRecord / RecordSize) + 1 : TotalRecord / RecordSize;
if (finishindex > tfi) finishindex = tfi;
if (startindex >= NumSize) sb += "<li><a href=" + startindex + "> Önceki </a></li>"; else sb += "<li><a href='#'> Önceki </a></li>";
for (var i = startindex + 1; i <= finishindex; i++) {
if (i == CurrentPage) sb += "<li class='active'><a href='#'>" + i + "</a></li>";
else sb += "<li><a href='" + Path + i + "'>" + i + "</a><li>";
}
var r = CurrentPage % NumSize ? (parseInt(Math.floor(CurrentPage / NumSize)) * NumSize + parseInt(NumSize)) : ((parseInt(CurrentPage / NumSize) - 1) * NumSize + parseInt(NumSize));
if (r < TotalNum) sb += "<li><a href='" + i + "'> :right</a></li>"; else sb += "<li><a href='#'>Sonraki</a></li>"
}
}
return sb;
}
</script>
1 Temmuz 2012 Pazar
notlar
var el = $('input[type=text], textarea');
el.focus(function (e) { if (e.target.value == e.target.defaultValue) e.target.value = ''; });
el.blur(function (e) { if (e.target.value == '') e.target.value = e.target.defaultValue; });
Response.Redirect(Url.RouteUrl(new { controller = "Home", action = "Index" }));
Kaydol:
Kayıtlar (Atom)
