Wednesday, April 11, 2012

Retrieve the contents of DataSource form the ComboBox

I have a combobox that I bind with a list of objects with three properties, int a, int b, string x. When bound I set DataTextField to x and DataValue Field to a. What I want to do is get the value of b in the codebehind after the collection has been bound to the list. I do not want to use viewstate. Can I possibly use reflection? something like this?


var dataSource = ddlTest.GetDataSource();
 var newDataSource = dataSource.GetType().GetProperty("_dataSource", BindingFlags.NonPublic | BindingFlags.Instance);
 



Answer:


I'm not sure about this, but you might be able to add b as a custom attribute to the ListItem. Try something like this and see if it works:
var table = new DataTable("TableName"); 
//bind the dropdown to the result set
dropDownList.DataSource = table;
dropDownList.DataBind();
//iterate through the datasource and add custom attributes for each item in the list
table.AsEnumerable().ToList().ForEach(r => 
    dropDownList.Items.FindByValue(r.Field<int>("a").ToString()).Attributes["data-field"] = r.Field<int>("b").ToString());    
If you'd prefer to use a regular foreach loop:
foreach (DataRow row in table.Rows)
{
    var item = dropDownList.FindByValue(row.Field<int>("a").ToString());
    if (item != null)
    {
        item.Attributes["data-value"] = row.Field<int>("b").ToString();
    }
}
If adding custom attributes doesn't work and you don't want to use ViewState, you might have to store both a and b in the value field, separated by a delimeter. This can be a pain because you'll have to parse the items to get the values, but given your requirements that might be the best option if the custom attributes don't work.

Advance Python Scheduler and SQLAlchemyJobStore

I am using sqlalchemy job store in APS . Jobs are added too cron using the function add_cron_job. But no entry is made in database table. Pls help me out: following is the code



import time
import logging
from threading import Timer
from threading import Lock
from gadgetplatform.classes.utils.utilities import import_module
from apscheduler.scheduler import Scheduler

from apscheduler.jobstores.sqlalchemy_store import SQLAlchemyJobStore

class SchedulerManager(object):
_instance = None
_initialised = False
lock = Lock()
log = logging.getLogger(__name__)
jobDict=[]

def __new__(cls):

if not cls._instance or not cls._initialised:
cls.lock.acquire()
if not cls._instance:
cls.log.info("creating instance")
cls._instance = super(SchedulerManager, cls).__new__(cls)
cls._initialised = True
cls._instance.init()
cls.log.info("instance created")
cls.lock.release()
cls.log.info("lock released")
cls.log.info("returning instance")
return cls._instance

def init(self):
self.sched=Scheduler()
self.sched.add_jobstore(SQLAlchemyJobStore('mysql://root@localhost/mygola?charset=utf8&use_unicode=0'), 'apschedulerJobs')

def addToCron(self,source,time):
self.log.info("called to add schedular")

time = time.split(' ')

m=str(time[0])
h=str(time[1])
d=str(time[2])
mnth=str(time[3])
yr=str(time[4])

func=self.convertStringToFunction(source)
self.sched.add_cron_job(func, year=yr, month=mnth, day=d, hour=h, minute=m)
self.jobDict.append(source)

self.log.info("added with the time")

def removeFromCron(self,source):
func=self.convertStringToFunction(source)
self.sched.unschedule_func(func)

def start(self):
self.sched.start()
self.log.info("Schedular Started")

def stop(self):
self.sched.shutdown()

def getRunningJobs(self):
return self.jobDict

def convertStringToFunction(self,source):
strArr = source.rsplit('.',1)
mod = import_module(strArr[0])
func = getattr(mod, strArr[1])
return func




Creating/updating an xml file from a mysql database table with php

I have a javascript image gallery which is getting data from an XML file. Im in the process of building a backend function in order for someone else to easy update the gallery. All the data required in the XML file, is available to me from a table in my database.



<?xml version="1.0" encoding="UTF-8"?>
<portfolio>
<items>
<item>
<thumbnail>images/banner001.jpg</thumbnail>
<preview>images/preview.jpg</preview>
<category>banner</category>
<description>Swatch MTV </description>
</item>
<item>
<thumbnail>images/banner002.jpg</thumbnail>
<preview>images/preview.jpg</preview>
<category>banner,campaign</category>
<description>Nike iD</description>
</item>
<item>
<thumbnail>images/banner003.jpg</thumbnail>
<preview>images/preview.jpg</preview>
<category>banner</category>
<description>Sony Handycam</description>
</item>
<item>
<thumbnail>images/banner006.jpg</thumbnail>
<preview>images/preview.jpg</preview>
<category>banner</category>
<description>Statoil App kampagne</description>
</item>
<item>
<thumbnail>images/design006.jpg</thumbnail>
<preview>images/preview.jpg</preview>
<category>web</category>
<description>Hempel Website design</description>
</item>

</items>
</portfolio>


In this regard I have a couple of questions (please keep in mind that im fairly new to php):




  1. which is the better/easier option: update the existing xml file or simply overwrite the entire xml file with newer/updated data?

  2. how do I create the same xml format using php?

  3. I have been looking at both SimpleXML and the DOMDocument. Which one is better/easier to use in my case?



I would be grateful for any help you guys can give me. If posting code, please include a short description/explanation.



Please let me know if you need anything clarified.





Android create fragment more than one time

Using this android sample: http://developer.android.com/resources/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentTabsPager.html I have make my own Fragment that holds tabhost and tab content:



    public class TabsFragment extends Fragment
{
private static final String EXTRA_TAB = "EXTRA_TAB";

private TabHost tabHost;
private TabManager tabManager;
private MaptrixFragmentActivity activity;
private Context context;

@Override
public void onAttach(Activity activity)
{
this.activity = (MaptrixFragmentActivity) activity;
this.context = activity;
super.onAttach(activity);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_tabs, container, false);
tabHost = (TabHost)view.findViewById(android.R.id.tabhost);
tabHost.setup();
tabManager = new TabManager(activity, tabHost, R.id.realtabcontent);

initTabs();

if (savedInstanceState != null)
{
tabHost.setCurrentTabByTag(savedInstanceState.getString(EXTRA_TAB));
}
return view;
}

private void initTabs()
{
// tab one
addTab(Fragment.class, null, R.drawable.icon1, Res.S(R.string.tab1));

// I have not implement the tab fragment yet!

// tab two
addTab(Fragment.class, null, R.drawable.icon2, Res.S(R.string.tab2));
}

private void addTab(Class<?> fragmenClass, Bundle bundle, int drawableId, String tag)
{
TabHost.TabSpec spec = tabHost.newTabSpec(tag);
View tabIndicator = LayoutInflater.from(context).inflate(R.layout.item_tab, tabHost.getTabWidget(), false);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.tab_image);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
tabManager.addTab(spec, fragmenClass, bundle);
}

@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putString(EXTRA_TAB, tabHost.getCurrentTabTag());
}

public static class TabManager implements TabHost.OnTabChangeListener
{
private final FragmentActivity activity;
private final TabHost tabHost;
private final int containerID;
private final HashMap<String, TabInfo> tabs = new HashMap<String, TabInfo>();
TabInfo lastTab;
TabFactory factory;

public TabManager(FragmentActivity activity, TabHost tabHost, int containerID)
{
this.activity = activity;
this.tabHost = tabHost;
this.containerID = containerID;
factory = new TabFactory(activity);
tabHost.setOnTabChangedListener(this);
}

public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args)
{
tabSpec.setContent(factory);
String tag = tabSpec.getTag();

TabInfo info = new TabInfo(tag, clss, args);

info.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);

if (info.fragment != null && !info.fragment.isDetached())
{
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.detach(info.fragment);
ft.commit();
}

tabs.put(tag, info);
tabHost.addTab(tabSpec);
}

@Override
public void onTabChanged(String tabId)
{
TabInfo newTab = tabs.get(tabId);
if (lastTab != newTab)
{
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
if (lastTab != null) {
if (lastTab.fragment != null)
{
ft.detach(lastTab.fragment);
}
}
if (newTab != null)
{
if (newTab.fragment == null)
{
newTab.fragment = Fragment.instantiate(activity, newTab.clss.getName(), newTab.args);
ft.add(containerID, newTab.fragment, newTab.tag);
}
else
{
ft.attach(newTab.fragment);
}
}

lastTab = newTab;
ft.commit();
}
}
}

private static class TabInfo
{
private final String tag;
private final Class<?> clss;
private final Bundle args;
private Fragment fragment;

TabInfo(String _tag, Class<?> _class, Bundle _args)
{
tag = _tag;
clss = _class;
args = _args;
}
}

private static class TabFactory implements TabHost.TabContentFactory
{
private final Context mContext;

public TabFactory(Context context)
{
mContext = context;
}

@Override
public View createTabContent(String tag)
{
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
}


But onCreateView method calls two or more times when device changes orientation.



My FragmentActivity is:



    public class MaptrixFragmentActivity extends FragmentActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.factivity);

replace(R.id.factivity_content, new TabsFragment(), false, false);
}

@Override
protected void onResume()
{
super.onResume();
}

@Override
protected void onPause()
{
super.onPause();
}

public void replace(int rootView, Fragment fragment)
{
replace(rootView, fragment, true, true);
}

public void replace(int rootView, Fragment fragment, boolean backStack)
{
replace(rootView, fragment, backStack, true);
}

public void replace(int rootView, Fragment fragment, boolean backStack, boolean animation)
{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (animation) transaction.setCustomAnimations(R.anim.fragment_open, R.anim.fragment_close, R.anim.fragment_open_stack, R.anim.fragment_close_stack);
if (backStack) transaction.addToBackStack(null);
transaction.replace(R.id.factivity_maptrix_content, fragment);
transaction.commit();
}
}


Why i have this bug?